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/MathExtras.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Target/TargetLowering.h" 39 #include "llvm/Target/TargetOptions.h" 40 #include "llvm/Target/TargetRegisterInfo.h" 41 #include "llvm/Target/TargetSubtargetInfo.h" 42 #include <algorithm> 43 using namespace llvm; 44 45 #define DEBUG_TYPE "dagcombine" 46 47 STATISTIC(NodesCombined , "Number of dag nodes combined"); 48 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 49 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 50 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 51 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 52 STATISTIC(SlicedLoads, "Number of load sliced"); 53 54 namespace { 55 static cl::opt<bool> 56 CombinerAA("combiner-alias-analysis", cl::Hidden, 57 cl::desc("Enable DAG combiner alias-analysis heuristics")); 58 59 static cl::opt<bool> 60 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 61 cl::desc("Enable DAG combiner's use of IR alias analysis")); 62 63 static cl::opt<bool> 64 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 65 cl::desc("Enable DAG combiner's use of TBAA")); 66 67 #ifndef NDEBUG 68 static cl::opt<std::string> 69 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 70 cl::desc("Only use DAG-combiner alias analysis in this" 71 " function")); 72 #endif 73 74 /// Hidden option to stress test load slicing, i.e., when this option 75 /// is enabled, load slicing bypasses most of its profitability guards. 76 static cl::opt<bool> 77 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 78 cl::desc("Bypass the profitability model of load " 79 "slicing"), 80 cl::init(false)); 81 82 static cl::opt<bool> 83 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 84 cl::desc("DAG combiner may split indexing from loads")); 85 86 //------------------------------ DAGCombiner ---------------------------------// 87 88 class DAGCombiner { 89 SelectionDAG &DAG; 90 const TargetLowering &TLI; 91 CombineLevel Level; 92 CodeGenOpt::Level OptLevel; 93 bool LegalOperations; 94 bool LegalTypes; 95 bool ForCodeSize; 96 97 /// \brief Worklist of all of the nodes that need to be simplified. 98 /// 99 /// This must behave as a stack -- new nodes to process are pushed onto the 100 /// back and when processing we pop off of the back. 101 /// 102 /// The worklist will not contain duplicates but may contain null entries 103 /// due to nodes being deleted from the underlying DAG. 104 SmallVector<SDNode *, 64> Worklist; 105 106 /// \brief Mapping from an SDNode to its position on the worklist. 107 /// 108 /// This is used to find and remove nodes from the worklist (by nulling 109 /// them) when they are deleted from the underlying DAG. It relies on 110 /// stable indices of nodes within the worklist. 111 DenseMap<SDNode *, unsigned> WorklistMap; 112 113 /// \brief Set of nodes which have been combined (at least once). 114 /// 115 /// This is used to allow us to reliably add any operands of a DAG node 116 /// which have not yet been combined to the worklist. 117 SmallPtrSet<SDNode *, 32> CombinedNodes; 118 119 // AA - Used for DAG load/store alias analysis. 120 AliasAnalysis &AA; 121 122 /// When an instruction is simplified, add all users of the instruction to 123 /// the work lists because they might get more simplified now. 124 void AddUsersToWorklist(SDNode *N) { 125 for (SDNode *Node : N->uses()) 126 AddToWorklist(Node); 127 } 128 129 /// Call the node-specific routine that folds each particular type of node. 130 SDValue visit(SDNode *N); 131 132 public: 133 /// Add to the worklist making sure its instance is at the back (next to be 134 /// processed.) 135 void AddToWorklist(SDNode *N) { 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 181 /// Check the specified integer node value to see if it can be simplified or 182 /// if things it uses can be simplified by bit propagation. 183 /// If so, return true. 184 bool SimplifyDemandedBits(SDValue Op) { 185 unsigned BitWidth = Op.getScalarValueSizeInBits(); 186 APInt Demanded = APInt::getAllOnesValue(BitWidth); 187 return SimplifyDemandedBits(Op, Demanded); 188 } 189 190 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 191 192 bool CombineToPreIndexedLoadStore(SDNode *N); 193 bool CombineToPostIndexedLoadStore(SDNode *N); 194 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 195 bool SliceUpLoad(SDNode *N); 196 197 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 198 /// load. 199 /// 200 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 201 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 202 /// \param EltNo index of the vector element to load. 203 /// \param OriginalLoad load that EVE came from to be replaced. 204 /// \returns EVE on success SDValue() on failure. 205 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 206 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 207 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 208 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 209 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 210 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 211 SDValue PromoteIntBinOp(SDValue Op); 212 SDValue PromoteIntShiftOp(SDValue Op); 213 SDValue PromoteExtend(SDValue Op); 214 bool PromoteLoad(SDValue Op); 215 216 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 217 SDValue ExtLoad, const SDLoc &DL, 218 ISD::NodeType ExtType); 219 220 /// Call the node-specific routine that knows how to fold each 221 /// particular type of node. If that doesn't do anything, try the 222 /// target-specific DAG combines. 223 SDValue combine(SDNode *N); 224 225 // Visitation implementation - Implement dag node combining for different 226 // node types. The semantics are as follows: 227 // Return Value: 228 // SDValue.getNode() == 0 - No change was made 229 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 230 // otherwise - N should be replaced by the returned Operand. 231 // 232 SDValue visitTokenFactor(SDNode *N); 233 SDValue visitMERGE_VALUES(SDNode *N); 234 SDValue visitADD(SDNode *N); 235 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 236 SDValue visitSUB(SDNode *N); 237 SDValue visitADDC(SDNode *N); 238 SDValue visitSUBC(SDNode *N); 239 SDValue visitADDE(SDNode *N); 240 SDValue visitSUBE(SDNode *N); 241 SDValue visitMUL(SDNode *N); 242 SDValue useDivRem(SDNode *N); 243 SDValue visitSDIV(SDNode *N); 244 SDValue visitUDIV(SDNode *N); 245 SDValue visitREM(SDNode *N); 246 SDValue visitMULHU(SDNode *N); 247 SDValue visitMULHS(SDNode *N); 248 SDValue visitSMUL_LOHI(SDNode *N); 249 SDValue visitUMUL_LOHI(SDNode *N); 250 SDValue visitSMULO(SDNode *N); 251 SDValue visitUMULO(SDNode *N); 252 SDValue visitIMINMAX(SDNode *N); 253 SDValue visitAND(SDNode *N); 254 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 255 SDValue visitOR(SDNode *N); 256 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 257 SDValue visitXOR(SDNode *N); 258 SDValue SimplifyVBinOp(SDNode *N); 259 SDValue visitSHL(SDNode *N); 260 SDValue visitSRA(SDNode *N); 261 SDValue visitSRL(SDNode *N); 262 SDValue visitRotate(SDNode *N); 263 SDValue visitBSWAP(SDNode *N); 264 SDValue visitBITREVERSE(SDNode *N); 265 SDValue visitCTLZ(SDNode *N); 266 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 267 SDValue visitCTTZ(SDNode *N); 268 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 269 SDValue visitCTPOP(SDNode *N); 270 SDValue visitSELECT(SDNode *N); 271 SDValue visitVSELECT(SDNode *N); 272 SDValue visitSELECT_CC(SDNode *N); 273 SDValue visitSETCC(SDNode *N); 274 SDValue visitSETCCE(SDNode *N); 275 SDValue visitSIGN_EXTEND(SDNode *N); 276 SDValue visitZERO_EXTEND(SDNode *N); 277 SDValue visitANY_EXTEND(SDNode *N); 278 SDValue visitAssertZext(SDNode *N); 279 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 280 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 281 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 282 SDValue visitTRUNCATE(SDNode *N); 283 SDValue visitBITCAST(SDNode *N); 284 SDValue visitBUILD_PAIR(SDNode *N); 285 SDValue visitFADD(SDNode *N); 286 SDValue visitFSUB(SDNode *N); 287 SDValue visitFMUL(SDNode *N); 288 SDValue visitFMA(SDNode *N); 289 SDValue visitFDIV(SDNode *N); 290 SDValue visitFREM(SDNode *N); 291 SDValue visitFSQRT(SDNode *N); 292 SDValue visitFCOPYSIGN(SDNode *N); 293 SDValue visitSINT_TO_FP(SDNode *N); 294 SDValue visitUINT_TO_FP(SDNode *N); 295 SDValue visitFP_TO_SINT(SDNode *N); 296 SDValue visitFP_TO_UINT(SDNode *N); 297 SDValue visitFP_ROUND(SDNode *N); 298 SDValue visitFP_ROUND_INREG(SDNode *N); 299 SDValue visitFP_EXTEND(SDNode *N); 300 SDValue visitFNEG(SDNode *N); 301 SDValue visitFABS(SDNode *N); 302 SDValue visitFCEIL(SDNode *N); 303 SDValue visitFTRUNC(SDNode *N); 304 SDValue visitFFLOOR(SDNode *N); 305 SDValue visitFMINNUM(SDNode *N); 306 SDValue visitFMAXNUM(SDNode *N); 307 SDValue visitBRCOND(SDNode *N); 308 SDValue visitBR_CC(SDNode *N); 309 SDValue visitLOAD(SDNode *N); 310 311 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 312 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 313 314 SDValue visitSTORE(SDNode *N); 315 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 316 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 317 SDValue visitBUILD_VECTOR(SDNode *N); 318 SDValue visitCONCAT_VECTORS(SDNode *N); 319 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 320 SDValue visitVECTOR_SHUFFLE(SDNode *N); 321 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 322 SDValue visitINSERT_SUBVECTOR(SDNode *N); 323 SDValue visitMLOAD(SDNode *N); 324 SDValue visitMSTORE(SDNode *N); 325 SDValue visitMGATHER(SDNode *N); 326 SDValue visitMSCATTER(SDNode *N); 327 SDValue visitFP_TO_FP16(SDNode *N); 328 SDValue visitFP16_TO_FP(SDNode *N); 329 330 SDValue visitFADDForFMACombine(SDNode *N); 331 SDValue visitFSUBForFMACombine(SDNode *N); 332 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 333 334 SDValue XformToShuffleWithZero(SDNode *N); 335 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 336 SDValue RHS); 337 338 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 339 340 SDValue foldSelectOfConstants(SDNode *N); 341 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 342 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 343 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 344 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 345 SDValue N2, SDValue N3, ISD::CondCode CC, 346 bool NotExtCompare = false); 347 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 348 SDValue N2, SDValue N3, ISD::CondCode CC); 349 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 350 const SDLoc &DL, bool foldBooleans = true); 351 352 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 353 SDValue &CC) const; 354 bool isOneUseSetCC(SDValue N) const; 355 356 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 357 unsigned HiOp); 358 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 359 SDValue CombineExtLoad(SDNode *N); 360 SDValue combineRepeatedFPDivisors(SDNode *N); 361 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 362 SDValue BuildSDIV(SDNode *N); 363 SDValue BuildSDIVPow2(SDNode *N); 364 SDValue BuildUDIV(SDNode *N); 365 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 366 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 367 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 368 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags); 369 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip); 370 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 371 SDNodeFlags *Flags, bool Reciprocal); 372 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 373 SDNodeFlags *Flags, bool Reciprocal); 374 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 375 bool DemandHighBits = true); 376 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 377 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 378 SDValue InnerPos, SDValue InnerNeg, 379 unsigned PosOpcode, unsigned NegOpcode, 380 const SDLoc &DL); 381 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 382 SDValue MatchLoadCombine(SDNode *N); 383 SDValue ReduceLoadWidth(SDNode *N); 384 SDValue ReduceLoadOpStoreWidth(SDNode *N); 385 SDValue splitMergedValStore(StoreSDNode *ST); 386 SDValue TransformFPLoadStorePair(SDNode *N); 387 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 388 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 389 SDValue reduceBuildVecToShuffle(SDNode *N); 390 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 391 ArrayRef<int> VectorMask, SDValue VecIn1, 392 SDValue VecIn2, unsigned LeftIdx); 393 394 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 395 396 /// Walk up chain skipping non-aliasing memory nodes, 397 /// looking for aliasing nodes and adding them to the Aliases vector. 398 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 399 SmallVectorImpl<SDValue> &Aliases); 400 401 /// Return true if there is any possibility that the two addresses overlap. 402 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 403 404 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 405 /// chain (aliasing node.) 406 SDValue FindBetterChain(SDNode *N, SDValue Chain); 407 408 /// Try to replace a store and any possibly adjacent stores on 409 /// consecutive chains with better chains. Return true only if St is 410 /// replaced. 411 /// 412 /// Notice that other chains may still be replaced even if the function 413 /// returns false. 414 bool findBetterNeighborChains(StoreSDNode *St); 415 416 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 417 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 418 419 /// Holds a pointer to an LSBaseSDNode as well as information on where it 420 /// is located in a sequence of memory operations connected by a chain. 421 struct MemOpLink { 422 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 423 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 424 // Ptr to the mem node. 425 LSBaseSDNode *MemNode; 426 // Offset from the base ptr. 427 int64_t OffsetFromBase; 428 // What is the sequence number of this mem node. 429 // Lowest mem operand in the DAG starts at zero. 430 unsigned SequenceNum; 431 }; 432 433 /// This is a helper function for visitMUL to check the profitability 434 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 435 /// MulNode is the original multiply, AddNode is (add x, c1), 436 /// and ConstNode is c2. 437 bool isMulAddWithConstProfitable(SDNode *MulNode, 438 SDValue &AddNode, 439 SDValue &ConstNode); 440 441 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 442 /// constant build_vector of the stored constant values in Stores. 443 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL, 444 ArrayRef<MemOpLink> Stores, 445 SmallVectorImpl<SDValue> &Chains, 446 EVT Ty) const; 447 448 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 449 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 450 /// the type of the loaded value to be extended. LoadedVT returns the type 451 /// of the original loaded value. NarrowLoad returns whether the load would 452 /// need to be narrowed in order to match. 453 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 454 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 455 bool &NarrowLoad); 456 457 /// This is a helper function for MergeConsecutiveStores. When the source 458 /// elements of the consecutive stores are all constants or all extracted 459 /// vector elements, try to merge them into one larger store. 460 /// \return number of stores that were merged into a merged store (always 461 /// a prefix of \p StoreNode). 462 bool MergeStoresOfConstantsOrVecElts( 463 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 464 bool IsConstantSrc, bool UseVector); 465 466 /// This is a helper function for MergeConsecutiveStores. 467 /// Stores that may be merged are placed in StoreNodes. 468 /// Loads that may alias with those stores are placed in AliasLoadNodes. 469 void getStoreMergeAndAliasCandidates( 470 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 471 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 472 473 /// Helper function for MergeConsecutiveStores. Checks if 474 /// Candidate stores have indirect dependency through their 475 /// operands. \return True if safe to merge 476 bool checkMergeStoreCandidatesForDependencies( 477 SmallVectorImpl<MemOpLink> &StoreNodes); 478 479 /// Merge consecutive store operations into a wide store. 480 /// This optimization uses wide integers or vectors when possible. 481 /// \return number of stores that were merged into a merged store (the 482 /// affected nodes are stored as a prefix in \p StoreNodes). 483 bool MergeConsecutiveStores(StoreSDNode *N, 484 SmallVectorImpl<MemOpLink> &StoreNodes); 485 486 /// \brief Try to transform a truncation where C is a constant: 487 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 488 /// 489 /// \p N needs to be a truncation and its first operand an AND. Other 490 /// requirements are checked by the function (e.g. that trunc is 491 /// single-use) and if missed an empty SDValue is returned. 492 SDValue distributeTruncateThroughAnd(SDNode *N); 493 494 public: 495 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 496 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 497 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 498 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 499 } 500 501 /// Runs the dag combiner on all nodes in the work list 502 void Run(CombineLevel AtLevel); 503 504 SelectionDAG &getDAG() const { return DAG; } 505 506 /// Returns a type large enough to hold any valid shift amount - before type 507 /// legalization these can be huge. 508 EVT getShiftAmountTy(EVT LHSTy) { 509 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 510 if (LHSTy.isVector()) 511 return LHSTy; 512 auto &DL = DAG.getDataLayout(); 513 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 514 : TLI.getPointerTy(DL); 515 } 516 517 /// This method returns true if we are running before type legalization or 518 /// if the specified VT is legal. 519 bool isTypeLegal(const EVT &VT) { 520 if (!LegalTypes) return true; 521 return TLI.isTypeLegal(VT); 522 } 523 524 /// Convenience wrapper around TargetLowering::getSetCCResultType 525 EVT getSetCCResultType(EVT VT) const { 526 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 527 } 528 }; 529 } 530 531 532 namespace { 533 /// This class is a DAGUpdateListener that removes any deleted 534 /// nodes from the worklist. 535 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 536 DAGCombiner &DC; 537 public: 538 explicit WorklistRemover(DAGCombiner &dc) 539 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 540 541 void NodeDeleted(SDNode *N, SDNode *E) override { 542 DC.removeFromWorklist(N); 543 } 544 }; 545 } 546 547 //===----------------------------------------------------------------------===// 548 // TargetLowering::DAGCombinerInfo implementation 549 //===----------------------------------------------------------------------===// 550 551 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 552 ((DAGCombiner*)DC)->AddToWorklist(N); 553 } 554 555 SDValue TargetLowering::DAGCombinerInfo:: 556 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 557 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 558 } 559 560 SDValue TargetLowering::DAGCombinerInfo:: 561 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 562 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 563 } 564 565 566 SDValue TargetLowering::DAGCombinerInfo:: 567 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 568 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 569 } 570 571 void TargetLowering::DAGCombinerInfo:: 572 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 573 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 574 } 575 576 //===----------------------------------------------------------------------===// 577 // Helper Functions 578 //===----------------------------------------------------------------------===// 579 580 void DAGCombiner::deleteAndRecombine(SDNode *N) { 581 removeFromWorklist(N); 582 583 // If the operands of this node are only used by the node, they will now be 584 // dead. Make sure to re-visit them and recursively delete dead nodes. 585 for (const SDValue &Op : N->ops()) 586 // For an operand generating multiple values, one of the values may 587 // become dead allowing further simplification (e.g. split index 588 // arithmetic from an indexed load). 589 if (Op->hasOneUse() || Op->getNumValues() > 1) 590 AddToWorklist(Op.getNode()); 591 592 DAG.DeleteNode(N); 593 } 594 595 /// Return 1 if we can compute the negated form of the specified expression for 596 /// the same cost as the expression itself, or 2 if we can compute the negated 597 /// form more cheaply than the expression itself. 598 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 599 const TargetLowering &TLI, 600 const TargetOptions *Options, 601 unsigned Depth = 0) { 602 // fneg is removable even if it has multiple uses. 603 if (Op.getOpcode() == ISD::FNEG) return 2; 604 605 // Don't allow anything with multiple uses. 606 if (!Op.hasOneUse()) return 0; 607 608 // Don't recurse exponentially. 609 if (Depth > 6) return 0; 610 611 switch (Op.getOpcode()) { 612 default: return false; 613 case ISD::ConstantFP: { 614 if (!LegalOperations) 615 return 1; 616 617 // Don't invert constant FP values after legalization unless the target says 618 // the negated constant is legal. 619 EVT VT = Op.getValueType(); 620 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 621 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 622 } 623 case ISD::FADD: 624 // FIXME: determine better conditions for this xform. 625 if (!Options->UnsafeFPMath) return 0; 626 627 // After operation legalization, it might not be legal to create new FSUBs. 628 if (LegalOperations && 629 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 630 return 0; 631 632 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 633 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 634 Options, Depth + 1)) 635 return V; 636 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 637 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 638 Depth + 1); 639 case ISD::FSUB: 640 // We can't turn -(A-B) into B-A when we honor signed zeros. 641 if (!Options->NoSignedZerosFPMath && 642 !Op.getNode()->getFlags()->hasNoSignedZeros()) 643 return 0; 644 645 // fold (fneg (fsub A, B)) -> (fsub B, A) 646 return 1; 647 648 case ISD::FMUL: 649 case ISD::FDIV: 650 if (Options->HonorSignDependentRoundingFPMath()) return 0; 651 652 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 653 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 654 Options, Depth + 1)) 655 return V; 656 657 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 658 Depth + 1); 659 660 case ISD::FP_EXTEND: 661 case ISD::FP_ROUND: 662 case ISD::FSIN: 663 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 664 Depth + 1); 665 } 666 } 667 668 /// If isNegatibleForFree returns true, return the newly negated expression. 669 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 670 bool LegalOperations, unsigned Depth = 0) { 671 const TargetOptions &Options = DAG.getTarget().Options; 672 // fneg is removable even if it has multiple uses. 673 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 674 675 // Don't allow anything with multiple uses. 676 assert(Op.hasOneUse() && "Unknown reuse!"); 677 678 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 679 680 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 681 682 switch (Op.getOpcode()) { 683 default: llvm_unreachable("Unknown code"); 684 case ISD::ConstantFP: { 685 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 686 V.changeSign(); 687 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 688 } 689 case ISD::FADD: 690 // FIXME: determine better conditions for this xform. 691 assert(Options.UnsafeFPMath); 692 693 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 694 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 695 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 696 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 697 GetNegatedExpression(Op.getOperand(0), DAG, 698 LegalOperations, Depth+1), 699 Op.getOperand(1), Flags); 700 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 701 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 702 GetNegatedExpression(Op.getOperand(1), DAG, 703 LegalOperations, Depth+1), 704 Op.getOperand(0), Flags); 705 case ISD::FSUB: 706 // fold (fneg (fsub 0, B)) -> B 707 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 708 if (N0CFP->isZero()) 709 return Op.getOperand(1); 710 711 // fold (fneg (fsub A, B)) -> (fsub B, A) 712 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 713 Op.getOperand(1), Op.getOperand(0), Flags); 714 715 case ISD::FMUL: 716 case ISD::FDIV: 717 assert(!Options.HonorSignDependentRoundingFPMath()); 718 719 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 720 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 721 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 722 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 723 GetNegatedExpression(Op.getOperand(0), DAG, 724 LegalOperations, Depth+1), 725 Op.getOperand(1), Flags); 726 727 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 728 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 729 Op.getOperand(0), 730 GetNegatedExpression(Op.getOperand(1), DAG, 731 LegalOperations, Depth+1), Flags); 732 733 case ISD::FP_EXTEND: 734 case ISD::FSIN: 735 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 736 GetNegatedExpression(Op.getOperand(0), DAG, 737 LegalOperations, Depth+1)); 738 case ISD::FP_ROUND: 739 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 740 GetNegatedExpression(Op.getOperand(0), DAG, 741 LegalOperations, Depth+1), 742 Op.getOperand(1)); 743 } 744 } 745 746 // APInts must be the same size for most operations, this helper 747 // function zero extends the shorter of the pair so that they match. 748 // We provide an Offset so that we can create bitwidths that won't overflow. 749 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 750 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 751 LHS = LHS.zextOrSelf(Bits); 752 RHS = RHS.zextOrSelf(Bits); 753 } 754 755 // Return true if this node is a setcc, or is a select_cc 756 // that selects between the target values used for true and false, making it 757 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 758 // the appropriate nodes based on the type of node we are checking. This 759 // simplifies life a bit for the callers. 760 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 761 SDValue &CC) const { 762 if (N.getOpcode() == ISD::SETCC) { 763 LHS = N.getOperand(0); 764 RHS = N.getOperand(1); 765 CC = N.getOperand(2); 766 return true; 767 } 768 769 if (N.getOpcode() != ISD::SELECT_CC || 770 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 771 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 772 return false; 773 774 if (TLI.getBooleanContents(N.getValueType()) == 775 TargetLowering::UndefinedBooleanContent) 776 return false; 777 778 LHS = N.getOperand(0); 779 RHS = N.getOperand(1); 780 CC = N.getOperand(4); 781 return true; 782 } 783 784 /// Return true if this is a SetCC-equivalent operation with only one use. 785 /// If this is true, it allows the users to invert the operation for free when 786 /// it is profitable to do so. 787 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 788 SDValue N0, N1, N2; 789 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 790 return true; 791 return false; 792 } 793 794 // \brief Returns the SDNode if it is a constant float BuildVector 795 // or constant float. 796 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 797 if (isa<ConstantFPSDNode>(N)) 798 return N.getNode(); 799 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 800 return N.getNode(); 801 return nullptr; 802 } 803 804 // Determines if it is a constant integer or a build vector of constant 805 // integers (and undefs). 806 // Do not permit build vector implicit truncation. 807 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 808 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 809 return !(Const->isOpaque() && NoOpaques); 810 if (N.getOpcode() != ISD::BUILD_VECTOR) 811 return false; 812 unsigned BitWidth = N.getScalarValueSizeInBits(); 813 for (const SDValue &Op : N->op_values()) { 814 if (Op.isUndef()) 815 continue; 816 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 817 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 818 (Const->isOpaque() && NoOpaques)) 819 return false; 820 } 821 return true; 822 } 823 824 // Determines if it is a constant null integer or a splatted vector of a 825 // constant null integer (with no undefs). 826 // Build vector implicit truncation is not an issue for null values. 827 static bool isNullConstantOrNullSplatConstant(SDValue N) { 828 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 829 return Splat->isNullValue(); 830 return false; 831 } 832 833 // Determines if it is a constant integer of one or a splatted vector of a 834 // constant integer of one (with no undefs). 835 // Do not permit build vector implicit truncation. 836 static bool isOneConstantOrOneSplatConstant(SDValue N) { 837 unsigned BitWidth = N.getScalarValueSizeInBits(); 838 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 839 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 840 return false; 841 } 842 843 // Determines if it is a constant integer of all ones or a splatted vector of a 844 // constant integer of all ones (with no undefs). 845 // Do not permit build vector implicit truncation. 846 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 847 unsigned BitWidth = N.getScalarValueSizeInBits(); 848 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 849 return Splat->isAllOnesValue() && 850 Splat->getAPIntValue().getBitWidth() == BitWidth; 851 return false; 852 } 853 854 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 855 // undef's. 856 static bool isAnyConstantBuildVector(const SDNode *N) { 857 return ISD::isBuildVectorOfConstantSDNodes(N) || 858 ISD::isBuildVectorOfConstantFPSDNodes(N); 859 } 860 861 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 862 SDValue N1) { 863 EVT VT = N0.getValueType(); 864 if (N0.getOpcode() == Opc) { 865 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 866 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 867 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 868 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 869 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 870 return SDValue(); 871 } 872 if (N0.hasOneUse()) { 873 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 874 // use 875 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 876 if (!OpNode.getNode()) 877 return SDValue(); 878 AddToWorklist(OpNode.getNode()); 879 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 880 } 881 } 882 } 883 884 if (N1.getOpcode() == Opc) { 885 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 886 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 887 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 888 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 889 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 890 return SDValue(); 891 } 892 if (N1.hasOneUse()) { 893 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 894 // use 895 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 896 if (!OpNode.getNode()) 897 return SDValue(); 898 AddToWorklist(OpNode.getNode()); 899 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 900 } 901 } 902 } 903 904 return SDValue(); 905 } 906 907 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 908 bool AddTo) { 909 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 910 ++NodesCombined; 911 DEBUG(dbgs() << "\nReplacing.1 "; 912 N->dump(&DAG); 913 dbgs() << "\nWith: "; 914 To[0].getNode()->dump(&DAG); 915 dbgs() << " and " << NumTo-1 << " other values\n"); 916 for (unsigned i = 0, e = NumTo; i != e; ++i) 917 assert((!To[i].getNode() || 918 N->getValueType(i) == To[i].getValueType()) && 919 "Cannot combine value to value of different type!"); 920 921 WorklistRemover DeadNodes(*this); 922 DAG.ReplaceAllUsesWith(N, To); 923 if (AddTo) { 924 // Push the new nodes and any users onto the worklist 925 for (unsigned i = 0, e = NumTo; i != e; ++i) { 926 if (To[i].getNode()) { 927 AddToWorklist(To[i].getNode()); 928 AddUsersToWorklist(To[i].getNode()); 929 } 930 } 931 } 932 933 // Finally, if the node is now dead, remove it from the graph. The node 934 // may not be dead if the replacement process recursively simplified to 935 // something else needing this node. 936 if (N->use_empty()) 937 deleteAndRecombine(N); 938 return SDValue(N, 0); 939 } 940 941 void DAGCombiner:: 942 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 943 // Replace all uses. If any nodes become isomorphic to other nodes and 944 // are deleted, make sure to remove them from our worklist. 945 WorklistRemover DeadNodes(*this); 946 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 947 948 // Push the new node and any (possibly new) users onto the worklist. 949 AddToWorklist(TLO.New.getNode()); 950 AddUsersToWorklist(TLO.New.getNode()); 951 952 // Finally, if the node is now dead, remove it from the graph. The node 953 // may not be dead if the replacement process recursively simplified to 954 // something else needing this node. 955 if (TLO.Old.getNode()->use_empty()) 956 deleteAndRecombine(TLO.Old.getNode()); 957 } 958 959 /// Check the specified integer node value to see if it can be simplified or if 960 /// things it uses can be simplified by bit propagation. If so, return true. 961 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 962 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 963 APInt KnownZero, KnownOne; 964 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 965 return false; 966 967 // Revisit the node. 968 AddToWorklist(Op.getNode()); 969 970 // Replace the old value with the new one. 971 ++NodesCombined; 972 DEBUG(dbgs() << "\nReplacing.2 "; 973 TLO.Old.getNode()->dump(&DAG); 974 dbgs() << "\nWith: "; 975 TLO.New.getNode()->dump(&DAG); 976 dbgs() << '\n'); 977 978 CommitTargetLoweringOpt(TLO); 979 return true; 980 } 981 982 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 983 SDLoc DL(Load); 984 EVT VT = Load->getValueType(0); 985 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 986 987 DEBUG(dbgs() << "\nReplacing.9 "; 988 Load->dump(&DAG); 989 dbgs() << "\nWith: "; 990 Trunc.getNode()->dump(&DAG); 991 dbgs() << '\n'); 992 WorklistRemover DeadNodes(*this); 993 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 994 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 995 deleteAndRecombine(Load); 996 AddToWorklist(Trunc.getNode()); 997 } 998 999 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1000 Replace = false; 1001 SDLoc DL(Op); 1002 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1003 LoadSDNode *LD = cast<LoadSDNode>(Op); 1004 EVT MemVT = LD->getMemoryVT(); 1005 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1006 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1007 : ISD::EXTLOAD) 1008 : LD->getExtensionType(); 1009 Replace = true; 1010 return DAG.getExtLoad(ExtType, DL, PVT, 1011 LD->getChain(), LD->getBasePtr(), 1012 MemVT, LD->getMemOperand()); 1013 } 1014 1015 unsigned Opc = Op.getOpcode(); 1016 switch (Opc) { 1017 default: break; 1018 case ISD::AssertSext: 1019 return DAG.getNode(ISD::AssertSext, DL, PVT, 1020 SExtPromoteOperand(Op.getOperand(0), PVT), 1021 Op.getOperand(1)); 1022 case ISD::AssertZext: 1023 return DAG.getNode(ISD::AssertZext, DL, PVT, 1024 ZExtPromoteOperand(Op.getOperand(0), PVT), 1025 Op.getOperand(1)); 1026 case ISD::Constant: { 1027 unsigned ExtOpc = 1028 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1029 return DAG.getNode(ExtOpc, DL, PVT, Op); 1030 } 1031 } 1032 1033 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1034 return SDValue(); 1035 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1036 } 1037 1038 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1039 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1040 return SDValue(); 1041 EVT OldVT = Op.getValueType(); 1042 SDLoc DL(Op); 1043 bool Replace = false; 1044 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1045 if (!NewOp.getNode()) 1046 return SDValue(); 1047 AddToWorklist(NewOp.getNode()); 1048 1049 if (Replace) 1050 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1051 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1052 DAG.getValueType(OldVT)); 1053 } 1054 1055 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1056 EVT OldVT = Op.getValueType(); 1057 SDLoc DL(Op); 1058 bool Replace = false; 1059 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1060 if (!NewOp.getNode()) 1061 return SDValue(); 1062 AddToWorklist(NewOp.getNode()); 1063 1064 if (Replace) 1065 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1066 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1067 } 1068 1069 /// Promote the specified integer binary operation if the target indicates it is 1070 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1071 /// i32 since i16 instructions are longer. 1072 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1073 if (!LegalOperations) 1074 return SDValue(); 1075 1076 EVT VT = Op.getValueType(); 1077 if (VT.isVector() || !VT.isInteger()) 1078 return SDValue(); 1079 1080 // If operation type is 'undesirable', e.g. i16 on x86, consider 1081 // promoting it. 1082 unsigned Opc = Op.getOpcode(); 1083 if (TLI.isTypeDesirableForOp(Opc, VT)) 1084 return SDValue(); 1085 1086 EVT PVT = VT; 1087 // Consult target whether it is a good idea to promote this operation and 1088 // what's the right type to promote it to. 1089 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1090 assert(PVT != VT && "Don't know what type to promote to!"); 1091 1092 bool Replace0 = false; 1093 SDValue N0 = Op.getOperand(0); 1094 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1095 if (!NN0.getNode()) 1096 return SDValue(); 1097 1098 bool Replace1 = false; 1099 SDValue N1 = Op.getOperand(1); 1100 SDValue NN1; 1101 if (N0 == N1) 1102 NN1 = NN0; 1103 else { 1104 NN1 = PromoteOperand(N1, PVT, Replace1); 1105 if (!NN1.getNode()) 1106 return SDValue(); 1107 } 1108 1109 AddToWorklist(NN0.getNode()); 1110 if (NN1.getNode()) 1111 AddToWorklist(NN1.getNode()); 1112 1113 if (Replace0) 1114 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1115 if (Replace1) 1116 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1117 1118 DEBUG(dbgs() << "\nPromoting "; 1119 Op.getNode()->dump(&DAG)); 1120 SDLoc DL(Op); 1121 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1122 DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1123 } 1124 return SDValue(); 1125 } 1126 1127 /// Promote the specified integer shift operation if the target indicates it is 1128 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1129 /// i32 since i16 instructions are longer. 1130 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1131 if (!LegalOperations) 1132 return SDValue(); 1133 1134 EVT VT = Op.getValueType(); 1135 if (VT.isVector() || !VT.isInteger()) 1136 return SDValue(); 1137 1138 // If operation type is 'undesirable', e.g. i16 on x86, consider 1139 // promoting it. 1140 unsigned Opc = Op.getOpcode(); 1141 if (TLI.isTypeDesirableForOp(Opc, VT)) 1142 return SDValue(); 1143 1144 EVT PVT = VT; 1145 // Consult target whether it is a good idea to promote this operation and 1146 // what's the right type to promote it to. 1147 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1148 assert(PVT != VT && "Don't know what type to promote to!"); 1149 1150 bool Replace = false; 1151 SDValue N0 = Op.getOperand(0); 1152 if (Opc == ISD::SRA) 1153 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1154 else if (Opc == ISD::SRL) 1155 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1156 else 1157 N0 = PromoteOperand(N0, PVT, Replace); 1158 if (!N0.getNode()) 1159 return SDValue(); 1160 1161 AddToWorklist(N0.getNode()); 1162 if (Replace) 1163 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1164 1165 DEBUG(dbgs() << "\nPromoting "; 1166 Op.getNode()->dump(&DAG)); 1167 SDLoc DL(Op); 1168 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1169 DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1))); 1170 } 1171 return SDValue(); 1172 } 1173 1174 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1175 if (!LegalOperations) 1176 return SDValue(); 1177 1178 EVT VT = Op.getValueType(); 1179 if (VT.isVector() || !VT.isInteger()) 1180 return SDValue(); 1181 1182 // If operation type is 'undesirable', e.g. i16 on x86, consider 1183 // promoting it. 1184 unsigned Opc = Op.getOpcode(); 1185 if (TLI.isTypeDesirableForOp(Opc, VT)) 1186 return SDValue(); 1187 1188 EVT PVT = VT; 1189 // Consult target whether it is a good idea to promote this operation and 1190 // what's the right type to promote it to. 1191 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1192 assert(PVT != VT && "Don't know what type to promote to!"); 1193 // fold (aext (aext x)) -> (aext x) 1194 // fold (aext (zext x)) -> (zext x) 1195 // fold (aext (sext x)) -> (sext x) 1196 DEBUG(dbgs() << "\nPromoting "; 1197 Op.getNode()->dump(&DAG)); 1198 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1199 } 1200 return SDValue(); 1201 } 1202 1203 bool DAGCombiner::PromoteLoad(SDValue Op) { 1204 if (!LegalOperations) 1205 return false; 1206 1207 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1208 return false; 1209 1210 EVT VT = Op.getValueType(); 1211 if (VT.isVector() || !VT.isInteger()) 1212 return false; 1213 1214 // If operation type is 'undesirable', e.g. i16 on x86, consider 1215 // promoting it. 1216 unsigned Opc = Op.getOpcode(); 1217 if (TLI.isTypeDesirableForOp(Opc, VT)) 1218 return false; 1219 1220 EVT PVT = VT; 1221 // Consult target whether it is a good idea to promote this operation and 1222 // what's the right type to promote it to. 1223 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1224 assert(PVT != VT && "Don't know what type to promote to!"); 1225 1226 SDLoc DL(Op); 1227 SDNode *N = Op.getNode(); 1228 LoadSDNode *LD = cast<LoadSDNode>(N); 1229 EVT MemVT = LD->getMemoryVT(); 1230 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1231 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1232 : ISD::EXTLOAD) 1233 : LD->getExtensionType(); 1234 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1235 LD->getChain(), LD->getBasePtr(), 1236 MemVT, LD->getMemOperand()); 1237 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1238 1239 DEBUG(dbgs() << "\nPromoting "; 1240 N->dump(&DAG); 1241 dbgs() << "\nTo: "; 1242 Result.getNode()->dump(&DAG); 1243 dbgs() << '\n'); 1244 WorklistRemover DeadNodes(*this); 1245 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1246 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1247 deleteAndRecombine(N); 1248 AddToWorklist(Result.getNode()); 1249 return true; 1250 } 1251 return false; 1252 } 1253 1254 /// \brief Recursively delete a node which has no uses and any operands for 1255 /// which it is the only use. 1256 /// 1257 /// Note that this both deletes the nodes and removes them from the worklist. 1258 /// It also adds any nodes who have had a user deleted to the worklist as they 1259 /// may now have only one use and subject to other combines. 1260 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1261 if (!N->use_empty()) 1262 return false; 1263 1264 SmallSetVector<SDNode *, 16> Nodes; 1265 Nodes.insert(N); 1266 do { 1267 N = Nodes.pop_back_val(); 1268 if (!N) 1269 continue; 1270 1271 if (N->use_empty()) { 1272 for (const SDValue &ChildN : N->op_values()) 1273 Nodes.insert(ChildN.getNode()); 1274 1275 removeFromWorklist(N); 1276 DAG.DeleteNode(N); 1277 } else { 1278 AddToWorklist(N); 1279 } 1280 } while (!Nodes.empty()); 1281 return true; 1282 } 1283 1284 //===----------------------------------------------------------------------===// 1285 // Main DAG Combiner implementation 1286 //===----------------------------------------------------------------------===// 1287 1288 void DAGCombiner::Run(CombineLevel AtLevel) { 1289 // set the instance variables, so that the various visit routines may use it. 1290 Level = AtLevel; 1291 LegalOperations = Level >= AfterLegalizeVectorOps; 1292 LegalTypes = Level >= AfterLegalizeTypes; 1293 1294 // Add all the dag nodes to the worklist. 1295 for (SDNode &Node : DAG.allnodes()) 1296 AddToWorklist(&Node); 1297 1298 // Create a dummy node (which is not added to allnodes), that adds a reference 1299 // to the root node, preventing it from being deleted, and tracking any 1300 // changes of the root. 1301 HandleSDNode Dummy(DAG.getRoot()); 1302 1303 // While the worklist isn't empty, find a node and try to combine it. 1304 while (!WorklistMap.empty()) { 1305 SDNode *N; 1306 // The Worklist holds the SDNodes in order, but it may contain null entries. 1307 do { 1308 N = Worklist.pop_back_val(); 1309 } while (!N); 1310 1311 bool GoodWorklistEntry = WorklistMap.erase(N); 1312 (void)GoodWorklistEntry; 1313 assert(GoodWorklistEntry && 1314 "Found a worklist entry without a corresponding map entry!"); 1315 1316 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1317 // N is deleted from the DAG, since they too may now be dead or may have a 1318 // reduced number of uses, allowing other xforms. 1319 if (recursivelyDeleteUnusedNodes(N)) 1320 continue; 1321 1322 WorklistRemover DeadNodes(*this); 1323 1324 // If this combine is running after legalizing the DAG, re-legalize any 1325 // nodes pulled off the worklist. 1326 if (Level == AfterLegalizeDAG) { 1327 SmallSetVector<SDNode *, 16> UpdatedNodes; 1328 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1329 1330 for (SDNode *LN : UpdatedNodes) { 1331 AddToWorklist(LN); 1332 AddUsersToWorklist(LN); 1333 } 1334 if (!NIsValid) 1335 continue; 1336 } 1337 1338 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1339 1340 // Add any operands of the new node which have not yet been combined to the 1341 // worklist as well. Because the worklist uniques things already, this 1342 // won't repeatedly process the same operand. 1343 CombinedNodes.insert(N); 1344 for (const SDValue &ChildN : N->op_values()) 1345 if (!CombinedNodes.count(ChildN.getNode())) 1346 AddToWorklist(ChildN.getNode()); 1347 1348 SDValue RV = combine(N); 1349 1350 if (!RV.getNode()) 1351 continue; 1352 1353 ++NodesCombined; 1354 1355 // If we get back the same node we passed in, rather than a new node or 1356 // zero, we know that the node must have defined multiple values and 1357 // CombineTo was used. Since CombineTo takes care of the worklist 1358 // mechanics for us, we have no work to do in this case. 1359 if (RV.getNode() == N) 1360 continue; 1361 1362 assert(N->getOpcode() != ISD::DELETED_NODE && 1363 RV.getOpcode() != ISD::DELETED_NODE && 1364 "Node was deleted but visit returned new node!"); 1365 1366 DEBUG(dbgs() << " ... into: "; 1367 RV.getNode()->dump(&DAG)); 1368 1369 if (N->getNumValues() == RV.getNode()->getNumValues()) 1370 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1371 else { 1372 assert(N->getValueType(0) == RV.getValueType() && 1373 N->getNumValues() == 1 && "Type mismatch"); 1374 DAG.ReplaceAllUsesWith(N, &RV); 1375 } 1376 1377 // Push the new node and any users onto the worklist 1378 AddToWorklist(RV.getNode()); 1379 AddUsersToWorklist(RV.getNode()); 1380 1381 // Finally, if the node is now dead, remove it from the graph. The node 1382 // may not be dead if the replacement process recursively simplified to 1383 // something else needing this node. This will also take care of adding any 1384 // operands which have lost a user to the worklist. 1385 recursivelyDeleteUnusedNodes(N); 1386 } 1387 1388 // If the root changed (e.g. it was a dead load, update the root). 1389 DAG.setRoot(Dummy.getValue()); 1390 DAG.RemoveDeadNodes(); 1391 } 1392 1393 SDValue DAGCombiner::visit(SDNode *N) { 1394 switch (N->getOpcode()) { 1395 default: break; 1396 case ISD::TokenFactor: return visitTokenFactor(N); 1397 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1398 case ISD::ADD: return visitADD(N); 1399 case ISD::SUB: return visitSUB(N); 1400 case ISD::ADDC: return visitADDC(N); 1401 case ISD::SUBC: return visitSUBC(N); 1402 case ISD::ADDE: return visitADDE(N); 1403 case ISD::SUBE: return visitSUBE(N); 1404 case ISD::MUL: return visitMUL(N); 1405 case ISD::SDIV: return visitSDIV(N); 1406 case ISD::UDIV: return visitUDIV(N); 1407 case ISD::SREM: 1408 case ISD::UREM: return visitREM(N); 1409 case ISD::MULHU: return visitMULHU(N); 1410 case ISD::MULHS: return visitMULHS(N); 1411 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1412 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1413 case ISD::SMULO: return visitSMULO(N); 1414 case ISD::UMULO: return visitUMULO(N); 1415 case ISD::SMIN: 1416 case ISD::SMAX: 1417 case ISD::UMIN: 1418 case ISD::UMAX: return visitIMINMAX(N); 1419 case ISD::AND: return visitAND(N); 1420 case ISD::OR: return visitOR(N); 1421 case ISD::XOR: return visitXOR(N); 1422 case ISD::SHL: return visitSHL(N); 1423 case ISD::SRA: return visitSRA(N); 1424 case ISD::SRL: return visitSRL(N); 1425 case ISD::ROTR: 1426 case ISD::ROTL: return visitRotate(N); 1427 case ISD::BSWAP: return visitBSWAP(N); 1428 case ISD::BITREVERSE: return visitBITREVERSE(N); 1429 case ISD::CTLZ: return visitCTLZ(N); 1430 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1431 case ISD::CTTZ: return visitCTTZ(N); 1432 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1433 case ISD::CTPOP: return visitCTPOP(N); 1434 case ISD::SELECT: return visitSELECT(N); 1435 case ISD::VSELECT: return visitVSELECT(N); 1436 case ISD::SELECT_CC: return visitSELECT_CC(N); 1437 case ISD::SETCC: return visitSETCC(N); 1438 case ISD::SETCCE: return visitSETCCE(N); 1439 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1440 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1441 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1442 case ISD::AssertZext: return visitAssertZext(N); 1443 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1444 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1445 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1446 case ISD::TRUNCATE: return visitTRUNCATE(N); 1447 case ISD::BITCAST: return visitBITCAST(N); 1448 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1449 case ISD::FADD: return visitFADD(N); 1450 case ISD::FSUB: return visitFSUB(N); 1451 case ISD::FMUL: return visitFMUL(N); 1452 case ISD::FMA: return visitFMA(N); 1453 case ISD::FDIV: return visitFDIV(N); 1454 case ISD::FREM: return visitFREM(N); 1455 case ISD::FSQRT: return visitFSQRT(N); 1456 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1457 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1458 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1459 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1460 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1461 case ISD::FP_ROUND: return visitFP_ROUND(N); 1462 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1463 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1464 case ISD::FNEG: return visitFNEG(N); 1465 case ISD::FABS: return visitFABS(N); 1466 case ISD::FFLOOR: return visitFFLOOR(N); 1467 case ISD::FMINNUM: return visitFMINNUM(N); 1468 case ISD::FMAXNUM: return visitFMAXNUM(N); 1469 case ISD::FCEIL: return visitFCEIL(N); 1470 case ISD::FTRUNC: return visitFTRUNC(N); 1471 case ISD::BRCOND: return visitBRCOND(N); 1472 case ISD::BR_CC: return visitBR_CC(N); 1473 case ISD::LOAD: return visitLOAD(N); 1474 case ISD::STORE: return visitSTORE(N); 1475 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1476 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1477 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1478 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1479 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1480 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1481 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1482 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1483 case ISD::MGATHER: return visitMGATHER(N); 1484 case ISD::MLOAD: return visitMLOAD(N); 1485 case ISD::MSCATTER: return visitMSCATTER(N); 1486 case ISD::MSTORE: return visitMSTORE(N); 1487 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1488 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1489 } 1490 return SDValue(); 1491 } 1492 1493 SDValue DAGCombiner::combine(SDNode *N) { 1494 SDValue RV = visit(N); 1495 1496 // If nothing happened, try a target-specific DAG combine. 1497 if (!RV.getNode()) { 1498 assert(N->getOpcode() != ISD::DELETED_NODE && 1499 "Node was deleted but visit returned NULL!"); 1500 1501 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1502 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1503 1504 // Expose the DAG combiner to the target combiner impls. 1505 TargetLowering::DAGCombinerInfo 1506 DagCombineInfo(DAG, Level, false, this); 1507 1508 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1509 } 1510 } 1511 1512 // If nothing happened still, try promoting the operation. 1513 if (!RV.getNode()) { 1514 switch (N->getOpcode()) { 1515 default: break; 1516 case ISD::ADD: 1517 case ISD::SUB: 1518 case ISD::MUL: 1519 case ISD::AND: 1520 case ISD::OR: 1521 case ISD::XOR: 1522 RV = PromoteIntBinOp(SDValue(N, 0)); 1523 break; 1524 case ISD::SHL: 1525 case ISD::SRA: 1526 case ISD::SRL: 1527 RV = PromoteIntShiftOp(SDValue(N, 0)); 1528 break; 1529 case ISD::SIGN_EXTEND: 1530 case ISD::ZERO_EXTEND: 1531 case ISD::ANY_EXTEND: 1532 RV = PromoteExtend(SDValue(N, 0)); 1533 break; 1534 case ISD::LOAD: 1535 if (PromoteLoad(SDValue(N, 0))) 1536 RV = SDValue(N, 0); 1537 break; 1538 } 1539 } 1540 1541 // If N is a commutative binary node, try commuting it to enable more 1542 // sdisel CSE. 1543 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1544 N->getNumValues() == 1) { 1545 SDValue N0 = N->getOperand(0); 1546 SDValue N1 = N->getOperand(1); 1547 1548 // Constant operands are canonicalized to RHS. 1549 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1550 SDValue Ops[] = {N1, N0}; 1551 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1552 N->getFlags()); 1553 if (CSENode) 1554 return SDValue(CSENode, 0); 1555 } 1556 } 1557 1558 return RV; 1559 } 1560 1561 /// Given a node, return its input chain if it has one, otherwise return a null 1562 /// sd operand. 1563 static SDValue getInputChainForNode(SDNode *N) { 1564 if (unsigned NumOps = N->getNumOperands()) { 1565 if (N->getOperand(0).getValueType() == MVT::Other) 1566 return N->getOperand(0); 1567 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1568 return N->getOperand(NumOps-1); 1569 for (unsigned i = 1; i < NumOps-1; ++i) 1570 if (N->getOperand(i).getValueType() == MVT::Other) 1571 return N->getOperand(i); 1572 } 1573 return SDValue(); 1574 } 1575 1576 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1577 // If N has two operands, where one has an input chain equal to the other, 1578 // the 'other' chain is redundant. 1579 if (N->getNumOperands() == 2) { 1580 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1581 return N->getOperand(0); 1582 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1583 return N->getOperand(1); 1584 } 1585 1586 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1587 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1588 SmallPtrSet<SDNode*, 16> SeenOps; 1589 bool Changed = false; // If we should replace this token factor. 1590 1591 // Start out with this token factor. 1592 TFs.push_back(N); 1593 1594 // Iterate through token factors. The TFs grows when new token factors are 1595 // encountered. 1596 for (unsigned i = 0; i < TFs.size(); ++i) { 1597 SDNode *TF = TFs[i]; 1598 1599 // Check each of the operands. 1600 for (const SDValue &Op : TF->op_values()) { 1601 1602 switch (Op.getOpcode()) { 1603 case ISD::EntryToken: 1604 // Entry tokens don't need to be added to the list. They are 1605 // redundant. 1606 Changed = true; 1607 break; 1608 1609 case ISD::TokenFactor: 1610 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1611 // Queue up for processing. 1612 TFs.push_back(Op.getNode()); 1613 // Clean up in case the token factor is removed. 1614 AddToWorklist(Op.getNode()); 1615 Changed = true; 1616 break; 1617 } 1618 LLVM_FALLTHROUGH; 1619 1620 default: 1621 // Only add if it isn't already in the list. 1622 if (SeenOps.insert(Op.getNode()).second) 1623 Ops.push_back(Op); 1624 else 1625 Changed = true; 1626 break; 1627 } 1628 } 1629 } 1630 1631 SDValue Result; 1632 1633 // If we've changed things around then replace token factor. 1634 if (Changed) { 1635 if (Ops.empty()) { 1636 // The entry token is the only possible outcome. 1637 Result = DAG.getEntryNode(); 1638 } else { 1639 // New and improved token factor. 1640 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1641 } 1642 1643 // Add users to worklist if AA is enabled, since it may introduce 1644 // a lot of new chained token factors while removing memory deps. 1645 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1646 : DAG.getSubtarget().useAA(); 1647 return CombineTo(N, Result, UseAA /*add to worklist*/); 1648 } 1649 1650 return Result; 1651 } 1652 1653 /// MERGE_VALUES can always be eliminated. 1654 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1655 WorklistRemover DeadNodes(*this); 1656 // Replacing results may cause a different MERGE_VALUES to suddenly 1657 // be CSE'd with N, and carry its uses with it. Iterate until no 1658 // uses remain, to ensure that the node can be safely deleted. 1659 // First add the users of this node to the work list so that they 1660 // can be tried again once they have new operands. 1661 AddUsersToWorklist(N); 1662 do { 1663 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1664 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1665 } while (!N->use_empty()); 1666 deleteAndRecombine(N); 1667 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1668 } 1669 1670 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1671 /// ConstantSDNode pointer else nullptr. 1672 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1673 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1674 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1675 } 1676 1677 SDValue DAGCombiner::visitADD(SDNode *N) { 1678 SDValue N0 = N->getOperand(0); 1679 SDValue N1 = N->getOperand(1); 1680 EVT VT = N0.getValueType(); 1681 SDLoc DL(N); 1682 1683 // fold vector ops 1684 if (VT.isVector()) { 1685 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1686 return FoldedVOp; 1687 1688 // fold (add x, 0) -> x, vector edition 1689 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1690 return N0; 1691 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1692 return N1; 1693 } 1694 1695 // fold (add x, undef) -> undef 1696 if (N0.isUndef()) 1697 return N0; 1698 1699 if (N1.isUndef()) 1700 return N1; 1701 1702 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1703 // canonicalize constant to RHS 1704 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1705 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1706 // fold (add c1, c2) -> c1+c2 1707 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1708 N1.getNode()); 1709 } 1710 1711 // fold (add x, 0) -> x 1712 if (isNullConstant(N1)) 1713 return N0; 1714 1715 // fold ((c1-A)+c2) -> (c1+c2)-A 1716 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1717 if (N0.getOpcode() == ISD::SUB) 1718 if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1719 return DAG.getNode(ISD::SUB, DL, VT, 1720 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1721 N0.getOperand(1)); 1722 } 1723 } 1724 1725 // reassociate add 1726 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1727 return RADD; 1728 1729 // fold ((0-A) + B) -> B-A 1730 if (N0.getOpcode() == ISD::SUB && 1731 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1732 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1733 1734 // fold (A + (0-B)) -> A-B 1735 if (N1.getOpcode() == ISD::SUB && 1736 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1737 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1738 1739 // fold (A+(B-A)) -> B 1740 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1741 return N1.getOperand(0); 1742 1743 // fold ((B-A)+A) -> B 1744 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1745 return N0.getOperand(0); 1746 1747 // fold (A+(B-(A+C))) to (B-C) 1748 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1749 N0 == N1.getOperand(1).getOperand(0)) 1750 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1751 N1.getOperand(1).getOperand(1)); 1752 1753 // fold (A+(B-(C+A))) to (B-C) 1754 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1755 N0 == N1.getOperand(1).getOperand(1)) 1756 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1757 N1.getOperand(1).getOperand(0)); 1758 1759 // fold (A+((B-A)+or-C)) to (B+or-C) 1760 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1761 N1.getOperand(0).getOpcode() == ISD::SUB && 1762 N0 == N1.getOperand(0).getOperand(1)) 1763 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1764 N1.getOperand(1)); 1765 1766 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1767 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1768 SDValue N00 = N0.getOperand(0); 1769 SDValue N01 = N0.getOperand(1); 1770 SDValue N10 = N1.getOperand(0); 1771 SDValue N11 = N1.getOperand(1); 1772 1773 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 1774 return DAG.getNode(ISD::SUB, DL, VT, 1775 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1776 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1777 } 1778 1779 if (SimplifyDemandedBits(SDValue(N, 0))) 1780 return SDValue(N, 0); 1781 1782 // fold (a+b) -> (a|b) iff a and b share no bits. 1783 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1784 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1)) 1785 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 1786 1787 if (SDValue Combined = visitADDLike(N0, N1, N)) 1788 return Combined; 1789 1790 if (SDValue Combined = visitADDLike(N1, N0, N)) 1791 return Combined; 1792 1793 return SDValue(); 1794 } 1795 1796 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 1797 EVT VT = N0.getValueType(); 1798 SDLoc DL(LocReference); 1799 1800 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1801 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1802 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 1803 return DAG.getNode(ISD::SUB, DL, VT, N0, 1804 DAG.getNode(ISD::SHL, DL, VT, 1805 N1.getOperand(0).getOperand(1), 1806 N1.getOperand(1))); 1807 1808 if (N1.getOpcode() == ISD::AND) { 1809 SDValue AndOp0 = N1.getOperand(0); 1810 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1811 unsigned DestBits = VT.getScalarSizeInBits(); 1812 1813 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1814 // and similar xforms where the inner op is either ~0 or 0. 1815 if (NumSignBits == DestBits && 1816 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 1817 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 1818 } 1819 1820 // add (sext i1), X -> sub X, (zext i1) 1821 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1822 N0.getOperand(0).getValueType() == MVT::i1 && 1823 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1824 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1825 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1826 } 1827 1828 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1829 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1830 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1831 if (TN->getVT() == MVT::i1) { 1832 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1833 DAG.getConstant(1, DL, VT)); 1834 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1835 } 1836 } 1837 1838 return SDValue(); 1839 } 1840 1841 SDValue DAGCombiner::visitADDC(SDNode *N) { 1842 SDValue N0 = N->getOperand(0); 1843 SDValue N1 = N->getOperand(1); 1844 EVT VT = N0.getValueType(); 1845 SDLoc DL(N); 1846 1847 // If the flag result is dead, turn this into an ADD. 1848 if (!N->hasAnyUseOfValue(1)) 1849 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 1850 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1851 1852 // canonicalize constant to RHS. 1853 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1854 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1855 if (N0C && !N1C) 1856 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 1857 1858 // fold (addc x, 0) -> x + no carry out 1859 if (isNullConstant(N1)) 1860 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1861 DL, MVT::Glue)); 1862 1863 // If it cannot overflow, transform into an add. 1864 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 1865 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 1866 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1867 1868 return SDValue(); 1869 } 1870 1871 SDValue DAGCombiner::visitADDE(SDNode *N) { 1872 SDValue N0 = N->getOperand(0); 1873 SDValue N1 = N->getOperand(1); 1874 SDValue CarryIn = N->getOperand(2); 1875 1876 // canonicalize constant to RHS 1877 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1878 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1879 if (N0C && !N1C) 1880 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1881 N1, N0, CarryIn); 1882 1883 // fold (adde x, y, false) -> (addc x, y) 1884 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1885 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1886 1887 return SDValue(); 1888 } 1889 1890 // Since it may not be valid to emit a fold to zero for vector initializers 1891 // check if we can before folding. 1892 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 1893 SelectionDAG &DAG, bool LegalOperations, 1894 bool LegalTypes) { 1895 if (!VT.isVector()) 1896 return DAG.getConstant(0, DL, VT); 1897 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1898 return DAG.getConstant(0, DL, VT); 1899 return SDValue(); 1900 } 1901 1902 SDValue DAGCombiner::visitSUB(SDNode *N) { 1903 SDValue N0 = N->getOperand(0); 1904 SDValue N1 = N->getOperand(1); 1905 EVT VT = N0.getValueType(); 1906 SDLoc DL(N); 1907 1908 // fold vector ops 1909 if (VT.isVector()) { 1910 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1911 return FoldedVOp; 1912 1913 // fold (sub x, 0) -> x, vector edition 1914 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1915 return N0; 1916 } 1917 1918 // fold (sub x, x) -> 0 1919 // FIXME: Refactor this and xor and other similar operations together. 1920 if (N0 == N1) 1921 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 1922 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1923 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1924 // fold (sub c1, c2) -> c1-c2 1925 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 1926 N1.getNode()); 1927 } 1928 1929 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1930 1931 // fold (sub x, c) -> (add x, -c) 1932 if (N1C) { 1933 return DAG.getNode(ISD::ADD, DL, VT, N0, 1934 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1935 } 1936 1937 if (isNullConstantOrNullSplatConstant(N0)) { 1938 unsigned BitWidth = VT.getScalarSizeInBits(); 1939 // Right-shifting everything out but the sign bit followed by negation is 1940 // the same as flipping arithmetic/logical shift type without the negation: 1941 // -(X >>u 31) -> (X >>s 31) 1942 // -(X >>s 31) -> (X >>u 31) 1943 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 1944 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 1945 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 1946 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 1947 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 1948 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 1949 } 1950 } 1951 1952 // 0 - X --> 0 if the sub is NUW. 1953 if (N->getFlags()->hasNoUnsignedWrap()) 1954 return N0; 1955 1956 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) { 1957 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 1958 // N1 must be 0 because negating the minimum signed value is undefined. 1959 if (N->getFlags()->hasNoSignedWrap()) 1960 return N0; 1961 1962 // 0 - X --> X if X is 0 or the minimum signed value. 1963 return N1; 1964 } 1965 } 1966 1967 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1968 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 1969 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 1970 1971 // fold A-(A-B) -> B 1972 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1973 return N1.getOperand(1); 1974 1975 // fold (A+B)-A -> B 1976 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1977 return N0.getOperand(1); 1978 1979 // fold (A+B)-B -> A 1980 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1981 return N0.getOperand(0); 1982 1983 // fold C2-(A+C1) -> (C2-C1)-A 1984 if (N1.getOpcode() == ISD::ADD) { 1985 SDValue N11 = N1.getOperand(1); 1986 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 1987 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 1988 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 1989 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 1990 } 1991 } 1992 1993 // fold ((A+(B+or-C))-B) -> A+or-C 1994 if (N0.getOpcode() == ISD::ADD && 1995 (N0.getOperand(1).getOpcode() == ISD::SUB || 1996 N0.getOperand(1).getOpcode() == ISD::ADD) && 1997 N0.getOperand(1).getOperand(0) == N1) 1998 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 1999 N0.getOperand(1).getOperand(1)); 2000 2001 // fold ((A+(C+B))-B) -> A+C 2002 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2003 N0.getOperand(1).getOperand(1) == N1) 2004 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2005 N0.getOperand(1).getOperand(0)); 2006 2007 // fold ((A-(B-C))-C) -> A-B 2008 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2009 N0.getOperand(1).getOperand(1) == N1) 2010 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2011 N0.getOperand(1).getOperand(0)); 2012 2013 // If either operand of a sub is undef, the result is undef 2014 if (N0.isUndef()) 2015 return N0; 2016 if (N1.isUndef()) 2017 return N1; 2018 2019 // If the relocation model supports it, consider symbol offsets. 2020 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2021 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2022 // fold (sub Sym, c) -> Sym-c 2023 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2024 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2025 GA->getOffset() - 2026 (uint64_t)N1C->getSExtValue()); 2027 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2028 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2029 if (GA->getGlobal() == GB->getGlobal()) 2030 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2031 DL, VT); 2032 } 2033 2034 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2035 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2036 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2037 if (TN->getVT() == MVT::i1) { 2038 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2039 DAG.getConstant(1, DL, VT)); 2040 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2041 } 2042 } 2043 2044 return SDValue(); 2045 } 2046 2047 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2048 SDValue N0 = N->getOperand(0); 2049 SDValue N1 = N->getOperand(1); 2050 EVT VT = N0.getValueType(); 2051 SDLoc DL(N); 2052 2053 // If the flag result is dead, turn this into an SUB. 2054 if (!N->hasAnyUseOfValue(1)) 2055 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2056 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2057 2058 // fold (subc x, x) -> 0 + no borrow 2059 if (N0 == N1) 2060 return CombineTo(N, DAG.getConstant(0, DL, VT), 2061 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2062 2063 // fold (subc x, 0) -> x + no borrow 2064 if (isNullConstant(N1)) 2065 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2066 2067 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2068 if (isAllOnesConstant(N0)) 2069 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2070 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2071 2072 return SDValue(); 2073 } 2074 2075 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2076 SDValue N0 = N->getOperand(0); 2077 SDValue N1 = N->getOperand(1); 2078 SDValue CarryIn = N->getOperand(2); 2079 2080 // fold (sube x, y, false) -> (subc x, y) 2081 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2082 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2083 2084 return SDValue(); 2085 } 2086 2087 SDValue DAGCombiner::visitMUL(SDNode *N) { 2088 SDValue N0 = N->getOperand(0); 2089 SDValue N1 = N->getOperand(1); 2090 EVT VT = N0.getValueType(); 2091 2092 // fold (mul x, undef) -> 0 2093 if (N0.isUndef() || N1.isUndef()) 2094 return DAG.getConstant(0, SDLoc(N), VT); 2095 2096 bool N0IsConst = false; 2097 bool N1IsConst = false; 2098 bool N1IsOpaqueConst = false; 2099 bool N0IsOpaqueConst = false; 2100 APInt ConstValue0, ConstValue1; 2101 // fold vector ops 2102 if (VT.isVector()) { 2103 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2104 return FoldedVOp; 2105 2106 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2107 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2108 } else { 2109 N0IsConst = isa<ConstantSDNode>(N0); 2110 if (N0IsConst) { 2111 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2112 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2113 } 2114 N1IsConst = isa<ConstantSDNode>(N1); 2115 if (N1IsConst) { 2116 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2117 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2118 } 2119 } 2120 2121 // fold (mul c1, c2) -> c1*c2 2122 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2123 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2124 N0.getNode(), N1.getNode()); 2125 2126 // canonicalize constant to RHS (vector doesn't have to splat) 2127 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2128 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2129 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2130 // fold (mul x, 0) -> 0 2131 if (N1IsConst && ConstValue1 == 0) 2132 return N1; 2133 // We require a splat of the entire scalar bit width for non-contiguous 2134 // bit patterns. 2135 bool IsFullSplat = 2136 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2137 // fold (mul x, 1) -> x 2138 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2139 return N0; 2140 // fold (mul x, -1) -> 0-x 2141 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2142 SDLoc DL(N); 2143 return DAG.getNode(ISD::SUB, DL, VT, 2144 DAG.getConstant(0, DL, VT), N0); 2145 } 2146 // fold (mul x, (1 << c)) -> x << c 2147 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2148 IsFullSplat) { 2149 SDLoc DL(N); 2150 return DAG.getNode(ISD::SHL, DL, VT, N0, 2151 DAG.getConstant(ConstValue1.logBase2(), DL, 2152 getShiftAmountTy(N0.getValueType()))); 2153 } 2154 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2155 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2156 IsFullSplat) { 2157 unsigned Log2Val = (-ConstValue1).logBase2(); 2158 SDLoc DL(N); 2159 // FIXME: If the input is something that is easily negated (e.g. a 2160 // single-use add), we should put the negate there. 2161 return DAG.getNode(ISD::SUB, DL, VT, 2162 DAG.getConstant(0, DL, VT), 2163 DAG.getNode(ISD::SHL, DL, VT, N0, 2164 DAG.getConstant(Log2Val, DL, 2165 getShiftAmountTy(N0.getValueType())))); 2166 } 2167 2168 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2169 if (N0.getOpcode() == ISD::SHL && 2170 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2171 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2172 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2173 if (isConstantOrConstantVector(C3)) 2174 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2175 } 2176 2177 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2178 // use. 2179 { 2180 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2181 2182 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2183 if (N0.getOpcode() == ISD::SHL && 2184 isConstantOrConstantVector(N0.getOperand(1)) && 2185 N0.getNode()->hasOneUse()) { 2186 Sh = N0; Y = N1; 2187 } else if (N1.getOpcode() == ISD::SHL && 2188 isConstantOrConstantVector(N1.getOperand(1)) && 2189 N1.getNode()->hasOneUse()) { 2190 Sh = N1; Y = N0; 2191 } 2192 2193 if (Sh.getNode()) { 2194 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2195 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2196 } 2197 } 2198 2199 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2200 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2201 N0.getOpcode() == ISD::ADD && 2202 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2203 isMulAddWithConstProfitable(N, N0, N1)) 2204 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2205 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2206 N0.getOperand(0), N1), 2207 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2208 N0.getOperand(1), N1)); 2209 2210 // reassociate mul 2211 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2212 return RMUL; 2213 2214 return SDValue(); 2215 } 2216 2217 /// Return true if divmod libcall is available. 2218 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2219 const TargetLowering &TLI) { 2220 RTLIB::Libcall LC; 2221 EVT NodeType = Node->getValueType(0); 2222 if (!NodeType.isSimple()) 2223 return false; 2224 switch (NodeType.getSimpleVT().SimpleTy) { 2225 default: return false; // No libcall for vector types. 2226 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2227 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2228 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2229 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2230 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2231 } 2232 2233 return TLI.getLibcallName(LC) != nullptr; 2234 } 2235 2236 /// Issue divrem if both quotient and remainder are needed. 2237 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2238 if (Node->use_empty()) 2239 return SDValue(); // This is a dead node, leave it alone. 2240 2241 unsigned Opcode = Node->getOpcode(); 2242 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2243 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2244 2245 // DivMod lib calls can still work on non-legal types if using lib-calls. 2246 EVT VT = Node->getValueType(0); 2247 if (VT.isVector() || !VT.isInteger()) 2248 return SDValue(); 2249 2250 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2251 return SDValue(); 2252 2253 // If DIVREM is going to get expanded into a libcall, 2254 // but there is no libcall available, then don't combine. 2255 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2256 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2257 return SDValue(); 2258 2259 // If div is legal, it's better to do the normal expansion 2260 unsigned OtherOpcode = 0; 2261 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2262 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2263 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2264 return SDValue(); 2265 } else { 2266 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2267 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2268 return SDValue(); 2269 } 2270 2271 SDValue Op0 = Node->getOperand(0); 2272 SDValue Op1 = Node->getOperand(1); 2273 SDValue combined; 2274 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2275 UE = Op0.getNode()->use_end(); UI != UE;) { 2276 SDNode *User = *UI++; 2277 if (User == Node || User->use_empty()) 2278 continue; 2279 // Convert the other matching node(s), too; 2280 // otherwise, the DIVREM may get target-legalized into something 2281 // target-specific that we won't be able to recognize. 2282 unsigned UserOpc = User->getOpcode(); 2283 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2284 User->getOperand(0) == Op0 && 2285 User->getOperand(1) == Op1) { 2286 if (!combined) { 2287 if (UserOpc == OtherOpcode) { 2288 SDVTList VTs = DAG.getVTList(VT, VT); 2289 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2290 } else if (UserOpc == DivRemOpc) { 2291 combined = SDValue(User, 0); 2292 } else { 2293 assert(UserOpc == Opcode); 2294 continue; 2295 } 2296 } 2297 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2298 CombineTo(User, combined); 2299 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2300 CombineTo(User, combined.getValue(1)); 2301 } 2302 } 2303 return combined; 2304 } 2305 2306 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2307 SDValue N0 = N->getOperand(0); 2308 SDValue N1 = N->getOperand(1); 2309 EVT VT = N->getValueType(0); 2310 2311 // fold vector ops 2312 if (VT.isVector()) 2313 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2314 return FoldedVOp; 2315 2316 SDLoc DL(N); 2317 2318 // fold (sdiv c1, c2) -> c1/c2 2319 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2320 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2321 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2322 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2323 // fold (sdiv X, 1) -> X 2324 if (N1C && N1C->isOne()) 2325 return N0; 2326 // fold (sdiv X, -1) -> 0-X 2327 if (N1C && N1C->isAllOnesValue()) 2328 return DAG.getNode(ISD::SUB, DL, VT, 2329 DAG.getConstant(0, DL, VT), N0); 2330 2331 // If we know the sign bits of both operands are zero, strength reduce to a 2332 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2333 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2334 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2335 2336 // fold (sdiv X, pow2) -> simple ops after legalize 2337 // FIXME: We check for the exact bit here because the generic lowering gives 2338 // better results in that case. The target-specific lowering should learn how 2339 // to handle exact sdivs efficiently. 2340 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2341 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2342 (N1C->getAPIntValue().isPowerOf2() || 2343 (-N1C->getAPIntValue()).isPowerOf2())) { 2344 // Target-specific implementation of sdiv x, pow2. 2345 if (SDValue Res = BuildSDIVPow2(N)) 2346 return Res; 2347 2348 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2349 2350 // Splat the sign bit into the register 2351 SDValue SGN = 2352 DAG.getNode(ISD::SRA, DL, VT, N0, 2353 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2354 getShiftAmountTy(N0.getValueType()))); 2355 AddToWorklist(SGN.getNode()); 2356 2357 // Add (N0 < 0) ? abs2 - 1 : 0; 2358 SDValue SRL = 2359 DAG.getNode(ISD::SRL, DL, VT, SGN, 2360 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2361 getShiftAmountTy(SGN.getValueType()))); 2362 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2363 AddToWorklist(SRL.getNode()); 2364 AddToWorklist(ADD.getNode()); // Divide by pow2 2365 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2366 DAG.getConstant(lg2, DL, 2367 getShiftAmountTy(ADD.getValueType()))); 2368 2369 // If we're dividing by a positive value, we're done. Otherwise, we must 2370 // negate the result. 2371 if (N1C->getAPIntValue().isNonNegative()) 2372 return SRA; 2373 2374 AddToWorklist(SRA.getNode()); 2375 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2376 } 2377 2378 // If integer divide is expensive and we satisfy the requirements, emit an 2379 // alternate sequence. Targets may check function attributes for size/speed 2380 // trade-offs. 2381 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2382 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2383 if (SDValue Op = BuildSDIV(N)) 2384 return Op; 2385 2386 // sdiv, srem -> sdivrem 2387 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2388 // true. Otherwise, we break the simplification logic in visitREM(). 2389 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2390 if (SDValue DivRem = useDivRem(N)) 2391 return DivRem; 2392 2393 // undef / X -> 0 2394 if (N0.isUndef()) 2395 return DAG.getConstant(0, DL, VT); 2396 // X / undef -> undef 2397 if (N1.isUndef()) 2398 return N1; 2399 2400 return SDValue(); 2401 } 2402 2403 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2404 SDValue N0 = N->getOperand(0); 2405 SDValue N1 = N->getOperand(1); 2406 EVT VT = N->getValueType(0); 2407 2408 // fold vector ops 2409 if (VT.isVector()) 2410 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2411 return FoldedVOp; 2412 2413 SDLoc DL(N); 2414 2415 // fold (udiv c1, c2) -> c1/c2 2416 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2417 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2418 if (N0C && N1C) 2419 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2420 N0C, N1C)) 2421 return Folded; 2422 2423 // fold (udiv x, (1 << c)) -> x >>u c 2424 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2425 DAG.isKnownToBeAPowerOfTwo(N1)) { 2426 SDValue LogBase2 = BuildLogBase2(N1, DL); 2427 AddToWorklist(LogBase2.getNode()); 2428 2429 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2430 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2431 AddToWorklist(Trunc.getNode()); 2432 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2433 } 2434 2435 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2436 if (N1.getOpcode() == ISD::SHL) { 2437 SDValue N10 = N1.getOperand(0); 2438 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2439 DAG.isKnownToBeAPowerOfTwo(N10)) { 2440 SDValue LogBase2 = BuildLogBase2(N10, DL); 2441 AddToWorklist(LogBase2.getNode()); 2442 2443 EVT ADDVT = N1.getOperand(1).getValueType(); 2444 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2445 AddToWorklist(Trunc.getNode()); 2446 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2447 AddToWorklist(Add.getNode()); 2448 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2449 } 2450 } 2451 2452 // fold (udiv x, c) -> alternate 2453 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2454 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2455 if (SDValue Op = BuildUDIV(N)) 2456 return Op; 2457 2458 // sdiv, srem -> sdivrem 2459 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2460 // true. Otherwise, we break the simplification logic in visitREM(). 2461 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2462 if (SDValue DivRem = useDivRem(N)) 2463 return DivRem; 2464 2465 // undef / X -> 0 2466 if (N0.isUndef()) 2467 return DAG.getConstant(0, DL, VT); 2468 // X / undef -> undef 2469 if (N1.isUndef()) 2470 return N1; 2471 2472 return SDValue(); 2473 } 2474 2475 // handles ISD::SREM and ISD::UREM 2476 SDValue DAGCombiner::visitREM(SDNode *N) { 2477 unsigned Opcode = N->getOpcode(); 2478 SDValue N0 = N->getOperand(0); 2479 SDValue N1 = N->getOperand(1); 2480 EVT VT = N->getValueType(0); 2481 bool isSigned = (Opcode == ISD::SREM); 2482 SDLoc DL(N); 2483 2484 // fold (rem c1, c2) -> c1%c2 2485 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2486 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2487 if (N0C && N1C) 2488 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2489 return Folded; 2490 2491 if (isSigned) { 2492 // If we know the sign bits of both operands are zero, strength reduce to a 2493 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2494 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2495 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2496 } else { 2497 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 2498 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 2499 // fold (urem x, pow2) -> (and x, pow2-1) 2500 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2501 AddToWorklist(Add.getNode()); 2502 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2503 } 2504 if (N1.getOpcode() == ISD::SHL && 2505 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 2506 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2507 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2508 AddToWorklist(Add.getNode()); 2509 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2510 } 2511 } 2512 2513 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2514 2515 // If X/C can be simplified by the division-by-constant logic, lower 2516 // X%C to the equivalent of X-X/C*C. 2517 // To avoid mangling nodes, this simplification requires that the combine() 2518 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2519 // against this by skipping the simplification if isIntDivCheap(). When 2520 // div is not cheap, combine will not return a DIVREM. Regardless, 2521 // checking cheapness here makes sense since the simplification results in 2522 // fatter code. 2523 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2524 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2525 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2526 AddToWorklist(Div.getNode()); 2527 SDValue OptimizedDiv = combine(Div.getNode()); 2528 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2529 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2530 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2531 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2532 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2533 AddToWorklist(Mul.getNode()); 2534 return Sub; 2535 } 2536 } 2537 2538 // sdiv, srem -> sdivrem 2539 if (SDValue DivRem = useDivRem(N)) 2540 return DivRem.getValue(1); 2541 2542 // undef % X -> 0 2543 if (N0.isUndef()) 2544 return DAG.getConstant(0, DL, VT); 2545 // X % undef -> undef 2546 if (N1.isUndef()) 2547 return N1; 2548 2549 return SDValue(); 2550 } 2551 2552 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2553 SDValue N0 = N->getOperand(0); 2554 SDValue N1 = N->getOperand(1); 2555 EVT VT = N->getValueType(0); 2556 SDLoc DL(N); 2557 2558 // fold (mulhs x, 0) -> 0 2559 if (isNullConstant(N1)) 2560 return N1; 2561 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2562 if (isOneConstant(N1)) { 2563 SDLoc DL(N); 2564 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2565 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 2566 getShiftAmountTy(N0.getValueType()))); 2567 } 2568 // fold (mulhs x, undef) -> 0 2569 if (N0.isUndef() || N1.isUndef()) 2570 return DAG.getConstant(0, SDLoc(N), VT); 2571 2572 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2573 // plus a shift. 2574 if (VT.isSimple() && !VT.isVector()) { 2575 MVT Simple = VT.getSimpleVT(); 2576 unsigned SimpleSize = Simple.getSizeInBits(); 2577 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2578 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2579 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2580 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2581 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2582 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2583 DAG.getConstant(SimpleSize, DL, 2584 getShiftAmountTy(N1.getValueType()))); 2585 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2586 } 2587 } 2588 2589 return SDValue(); 2590 } 2591 2592 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2593 SDValue N0 = N->getOperand(0); 2594 SDValue N1 = N->getOperand(1); 2595 EVT VT = N->getValueType(0); 2596 SDLoc DL(N); 2597 2598 // fold (mulhu x, 0) -> 0 2599 if (isNullConstant(N1)) 2600 return N1; 2601 // fold (mulhu x, 1) -> 0 2602 if (isOneConstant(N1)) 2603 return DAG.getConstant(0, DL, N0.getValueType()); 2604 // fold (mulhu x, undef) -> 0 2605 if (N0.isUndef() || N1.isUndef()) 2606 return DAG.getConstant(0, DL, VT); 2607 2608 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2609 // plus a shift. 2610 if (VT.isSimple() && !VT.isVector()) { 2611 MVT Simple = VT.getSimpleVT(); 2612 unsigned SimpleSize = Simple.getSizeInBits(); 2613 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2614 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2615 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2616 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2617 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2618 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2619 DAG.getConstant(SimpleSize, DL, 2620 getShiftAmountTy(N1.getValueType()))); 2621 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2622 } 2623 } 2624 2625 return SDValue(); 2626 } 2627 2628 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2629 /// give the opcodes for the two computations that are being performed. Return 2630 /// true if a simplification was made. 2631 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2632 unsigned HiOp) { 2633 // If the high half is not needed, just compute the low half. 2634 bool HiExists = N->hasAnyUseOfValue(1); 2635 if (!HiExists && 2636 (!LegalOperations || 2637 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2638 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2639 return CombineTo(N, Res, Res); 2640 } 2641 2642 // If the low half is not needed, just compute the high half. 2643 bool LoExists = N->hasAnyUseOfValue(0); 2644 if (!LoExists && 2645 (!LegalOperations || 2646 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2647 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2648 return CombineTo(N, Res, Res); 2649 } 2650 2651 // If both halves are used, return as it is. 2652 if (LoExists && HiExists) 2653 return SDValue(); 2654 2655 // If the two computed results can be simplified separately, separate them. 2656 if (LoExists) { 2657 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2658 AddToWorklist(Lo.getNode()); 2659 SDValue LoOpt = combine(Lo.getNode()); 2660 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2661 (!LegalOperations || 2662 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2663 return CombineTo(N, LoOpt, LoOpt); 2664 } 2665 2666 if (HiExists) { 2667 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2668 AddToWorklist(Hi.getNode()); 2669 SDValue HiOpt = combine(Hi.getNode()); 2670 if (HiOpt.getNode() && HiOpt != Hi && 2671 (!LegalOperations || 2672 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2673 return CombineTo(N, HiOpt, HiOpt); 2674 } 2675 2676 return SDValue(); 2677 } 2678 2679 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2680 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2681 return Res; 2682 2683 EVT VT = N->getValueType(0); 2684 SDLoc DL(N); 2685 2686 // If the type is twice as wide is legal, transform the mulhu to a wider 2687 // multiply plus a shift. 2688 if (VT.isSimple() && !VT.isVector()) { 2689 MVT Simple = VT.getSimpleVT(); 2690 unsigned SimpleSize = Simple.getSizeInBits(); 2691 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2692 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2693 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2694 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2695 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2696 // Compute the high part as N1. 2697 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2698 DAG.getConstant(SimpleSize, DL, 2699 getShiftAmountTy(Lo.getValueType()))); 2700 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2701 // Compute the low part as N0. 2702 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2703 return CombineTo(N, Lo, Hi); 2704 } 2705 } 2706 2707 return SDValue(); 2708 } 2709 2710 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2711 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2712 return Res; 2713 2714 EVT VT = N->getValueType(0); 2715 SDLoc DL(N); 2716 2717 // If the type is twice as wide is legal, transform the mulhu to a wider 2718 // multiply plus a shift. 2719 if (VT.isSimple() && !VT.isVector()) { 2720 MVT Simple = VT.getSimpleVT(); 2721 unsigned SimpleSize = Simple.getSizeInBits(); 2722 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2723 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2724 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2725 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2726 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2727 // Compute the high part as N1. 2728 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2729 DAG.getConstant(SimpleSize, DL, 2730 getShiftAmountTy(Lo.getValueType()))); 2731 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2732 // Compute the low part as N0. 2733 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2734 return CombineTo(N, Lo, Hi); 2735 } 2736 } 2737 2738 return SDValue(); 2739 } 2740 2741 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2742 // (smulo x, 2) -> (saddo x, x) 2743 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2744 if (C2->getAPIntValue() == 2) 2745 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2746 N->getOperand(0), N->getOperand(0)); 2747 2748 return SDValue(); 2749 } 2750 2751 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2752 // (umulo x, 2) -> (uaddo x, x) 2753 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2754 if (C2->getAPIntValue() == 2) 2755 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2756 N->getOperand(0), N->getOperand(0)); 2757 2758 return SDValue(); 2759 } 2760 2761 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2762 SDValue N0 = N->getOperand(0); 2763 SDValue N1 = N->getOperand(1); 2764 EVT VT = N0.getValueType(); 2765 2766 // fold vector ops 2767 if (VT.isVector()) 2768 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2769 return FoldedVOp; 2770 2771 // fold (add c1, c2) -> c1+c2 2772 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2773 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2774 if (N0C && N1C) 2775 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2776 2777 // canonicalize constant to RHS 2778 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2779 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2780 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2781 2782 return SDValue(); 2783 } 2784 2785 /// If this is a binary operator with two operands of the same opcode, try to 2786 /// simplify it. 2787 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2788 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2789 EVT VT = N0.getValueType(); 2790 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2791 2792 // Bail early if none of these transforms apply. 2793 if (N0.getNumOperands() == 0) return SDValue(); 2794 2795 // For each of OP in AND/OR/XOR: 2796 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2797 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2798 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2799 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2800 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2801 // 2802 // do not sink logical op inside of a vector extend, since it may combine 2803 // into a vsetcc. 2804 EVT Op0VT = N0.getOperand(0).getValueType(); 2805 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2806 N0.getOpcode() == ISD::SIGN_EXTEND || 2807 N0.getOpcode() == ISD::BSWAP || 2808 // Avoid infinite looping with PromoteIntBinOp. 2809 (N0.getOpcode() == ISD::ANY_EXTEND && 2810 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2811 (N0.getOpcode() == ISD::TRUNCATE && 2812 (!TLI.isZExtFree(VT, Op0VT) || 2813 !TLI.isTruncateFree(Op0VT, VT)) && 2814 TLI.isTypeLegal(Op0VT))) && 2815 !VT.isVector() && 2816 Op0VT == N1.getOperand(0).getValueType() && 2817 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2818 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2819 N0.getOperand(0).getValueType(), 2820 N0.getOperand(0), N1.getOperand(0)); 2821 AddToWorklist(ORNode.getNode()); 2822 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2823 } 2824 2825 // For each of OP in SHL/SRL/SRA/AND... 2826 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2827 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2828 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2829 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2830 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2831 N0.getOperand(1) == N1.getOperand(1)) { 2832 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2833 N0.getOperand(0).getValueType(), 2834 N0.getOperand(0), N1.getOperand(0)); 2835 AddToWorklist(ORNode.getNode()); 2836 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2837 ORNode, N0.getOperand(1)); 2838 } 2839 2840 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2841 // Only perform this optimization up until type legalization, before 2842 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2843 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2844 // we don't want to undo this promotion. 2845 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2846 // on scalars. 2847 if ((N0.getOpcode() == ISD::BITCAST || 2848 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2849 Level <= AfterLegalizeTypes) { 2850 SDValue In0 = N0.getOperand(0); 2851 SDValue In1 = N1.getOperand(0); 2852 EVT In0Ty = In0.getValueType(); 2853 EVT In1Ty = In1.getValueType(); 2854 SDLoc DL(N); 2855 // If both incoming values are integers, and the original types are the 2856 // same. 2857 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2858 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2859 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2860 AddToWorklist(Op.getNode()); 2861 return BC; 2862 } 2863 } 2864 2865 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2866 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2867 // If both shuffles use the same mask, and both shuffle within a single 2868 // vector, then it is worthwhile to move the swizzle after the operation. 2869 // The type-legalizer generates this pattern when loading illegal 2870 // vector types from memory. In many cases this allows additional shuffle 2871 // optimizations. 2872 // There are other cases where moving the shuffle after the xor/and/or 2873 // is profitable even if shuffles don't perform a swizzle. 2874 // If both shuffles use the same mask, and both shuffles have the same first 2875 // or second operand, then it might still be profitable to move the shuffle 2876 // after the xor/and/or operation. 2877 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2878 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2879 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2880 2881 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2882 "Inputs to shuffles are not the same type"); 2883 2884 // Check that both shuffles use the same mask. The masks are known to be of 2885 // the same length because the result vector type is the same. 2886 // Check also that shuffles have only one use to avoid introducing extra 2887 // instructions. 2888 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2889 SVN0->getMask().equals(SVN1->getMask())) { 2890 SDValue ShOp = N0->getOperand(1); 2891 2892 // Don't try to fold this node if it requires introducing a 2893 // build vector of all zeros that might be illegal at this stage. 2894 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2895 if (!LegalTypes) 2896 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2897 else 2898 ShOp = SDValue(); 2899 } 2900 2901 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2902 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2903 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2904 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2905 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2906 N0->getOperand(0), N1->getOperand(0)); 2907 AddToWorklist(NewNode.getNode()); 2908 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2909 SVN0->getMask()); 2910 } 2911 2912 // Don't try to fold this node if it requires introducing a 2913 // build vector of all zeros that might be illegal at this stage. 2914 ShOp = N0->getOperand(0); 2915 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2916 if (!LegalTypes) 2917 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2918 else 2919 ShOp = SDValue(); 2920 } 2921 2922 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2923 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2924 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2925 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2926 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2927 N0->getOperand(1), N1->getOperand(1)); 2928 AddToWorklist(NewNode.getNode()); 2929 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2930 SVN0->getMask()); 2931 } 2932 } 2933 } 2934 2935 return SDValue(); 2936 } 2937 2938 /// This contains all DAGCombine rules which reduce two values combined by 2939 /// an And operation to a single value. This makes them reusable in the context 2940 /// of visitSELECT(). Rules involving constants are not included as 2941 /// visitSELECT() already handles those cases. 2942 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2943 SDNode *LocReference) { 2944 EVT VT = N1.getValueType(); 2945 2946 // fold (and x, undef) -> 0 2947 if (N0.isUndef() || N1.isUndef()) 2948 return DAG.getConstant(0, SDLoc(LocReference), VT); 2949 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2950 SDValue LL, LR, RL, RR, CC0, CC1; 2951 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2952 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2953 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2954 2955 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2956 LL.getValueType().isInteger()) { 2957 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2958 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2959 EVT CCVT = getSetCCResultType(LR.getValueType()); 2960 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2961 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2962 LR.getValueType(), LL, RL); 2963 AddToWorklist(ORNode.getNode()); 2964 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2965 } 2966 } 2967 if (isAllOnesConstant(LR)) { 2968 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2969 if (Op1 == ISD::SETEQ) { 2970 EVT CCVT = getSetCCResultType(LR.getValueType()); 2971 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2972 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2973 LR.getValueType(), LL, RL); 2974 AddToWorklist(ANDNode.getNode()); 2975 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2976 } 2977 } 2978 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2979 if (Op1 == ISD::SETGT) { 2980 EVT CCVT = getSetCCResultType(LR.getValueType()); 2981 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2982 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2983 LR.getValueType(), LL, RL); 2984 AddToWorklist(ORNode.getNode()); 2985 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2986 } 2987 } 2988 } 2989 } 2990 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2991 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2992 Op0 == Op1 && LL.getValueType().isInteger() && 2993 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2994 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2995 EVT CCVT = getSetCCResultType(LL.getValueType()); 2996 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2997 SDLoc DL(N0); 2998 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2999 LL, DAG.getConstant(1, DL, 3000 LL.getValueType())); 3001 AddToWorklist(ADDNode.getNode()); 3002 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 3003 DAG.getConstant(2, DL, LL.getValueType()), 3004 ISD::SETUGE); 3005 } 3006 } 3007 // canonicalize equivalent to ll == rl 3008 if (LL == RR && LR == RL) { 3009 Op1 = ISD::getSetCCSwappedOperands(Op1); 3010 std::swap(RL, RR); 3011 } 3012 if (LL == RL && LR == RR) { 3013 bool isInteger = LL.getValueType().isInteger(); 3014 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 3015 if (Result != ISD::SETCC_INVALID && 3016 (!LegalOperations || 3017 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3018 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3019 EVT CCVT = getSetCCResultType(LL.getValueType()); 3020 if (N0.getValueType() == CCVT || 3021 (!LegalOperations && N0.getValueType() == MVT::i1)) 3022 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3023 LL, LR, Result); 3024 } 3025 } 3026 } 3027 3028 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3029 VT.getSizeInBits() <= 64) { 3030 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3031 APInt ADDC = ADDI->getAPIntValue(); 3032 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3033 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3034 // immediate for an add, but it is legal if its top c2 bits are set, 3035 // transform the ADD so the immediate doesn't need to be materialized 3036 // in a register. 3037 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3038 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3039 SRLI->getZExtValue()); 3040 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3041 ADDC |= Mask; 3042 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3043 SDLoc DL(N0); 3044 SDValue NewAdd = 3045 DAG.getNode(ISD::ADD, DL, VT, 3046 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3047 CombineTo(N0.getNode(), NewAdd); 3048 // Return N so it doesn't get rechecked! 3049 return SDValue(LocReference, 0); 3050 } 3051 } 3052 } 3053 } 3054 } 3055 } 3056 3057 // Reduce bit extract of low half of an integer to the narrower type. 3058 // (and (srl i64:x, K), KMask) -> 3059 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3060 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3061 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3062 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3063 unsigned Size = VT.getSizeInBits(); 3064 const APInt &AndMask = CAnd->getAPIntValue(); 3065 unsigned ShiftBits = CShift->getZExtValue(); 3066 3067 // Bail out, this node will probably disappear anyway. 3068 if (ShiftBits == 0) 3069 return SDValue(); 3070 3071 unsigned MaskBits = AndMask.countTrailingOnes(); 3072 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3073 3074 if (APIntOps::isMask(AndMask) && 3075 // Required bits must not span the two halves of the integer and 3076 // must fit in the half size type. 3077 (ShiftBits + MaskBits <= Size / 2) && 3078 TLI.isNarrowingProfitable(VT, HalfVT) && 3079 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3080 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3081 TLI.isTruncateFree(VT, HalfVT) && 3082 TLI.isZExtFree(HalfVT, VT)) { 3083 // The isNarrowingProfitable is to avoid regressions on PPC and 3084 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3085 // on downstream users of this. Those patterns could probably be 3086 // extended to handle extensions mixed in. 3087 3088 SDValue SL(N0); 3089 assert(MaskBits <= Size); 3090 3091 // Extracting the highest bit of the low half. 3092 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3093 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3094 N0.getOperand(0)); 3095 3096 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3097 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3098 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3099 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3100 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3101 } 3102 } 3103 } 3104 } 3105 3106 return SDValue(); 3107 } 3108 3109 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3110 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3111 bool &NarrowLoad) { 3112 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3113 3114 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3115 return false; 3116 3117 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3118 LoadedVT = LoadN->getMemoryVT(); 3119 3120 if (ExtVT == LoadedVT && 3121 (!LegalOperations || 3122 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3123 // ZEXTLOAD will match without needing to change the size of the value being 3124 // loaded. 3125 NarrowLoad = false; 3126 return true; 3127 } 3128 3129 // Do not change the width of a volatile load. 3130 if (LoadN->isVolatile()) 3131 return false; 3132 3133 // Do not generate loads of non-round integer types since these can 3134 // be expensive (and would be wrong if the type is not byte sized). 3135 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3136 return false; 3137 3138 if (LegalOperations && 3139 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3140 return false; 3141 3142 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3143 return false; 3144 3145 NarrowLoad = true; 3146 return true; 3147 } 3148 3149 SDValue DAGCombiner::visitAND(SDNode *N) { 3150 SDValue N0 = N->getOperand(0); 3151 SDValue N1 = N->getOperand(1); 3152 EVT VT = N1.getValueType(); 3153 3154 // x & x --> x 3155 if (N0 == N1) 3156 return N0; 3157 3158 // fold vector ops 3159 if (VT.isVector()) { 3160 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3161 return FoldedVOp; 3162 3163 // fold (and x, 0) -> 0, vector edition 3164 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3165 // do not return N0, because undef node may exist in N0 3166 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3167 SDLoc(N), N0.getValueType()); 3168 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3169 // do not return N1, because undef node may exist in N1 3170 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3171 SDLoc(N), N1.getValueType()); 3172 3173 // fold (and x, -1) -> x, vector edition 3174 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3175 return N1; 3176 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3177 return N0; 3178 } 3179 3180 // fold (and c1, c2) -> c1&c2 3181 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3182 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3183 if (N0C && N1C && !N1C->isOpaque()) 3184 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3185 // canonicalize constant to RHS 3186 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3187 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3188 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3189 // fold (and x, -1) -> x 3190 if (isAllOnesConstant(N1)) 3191 return N0; 3192 // if (and x, c) is known to be zero, return 0 3193 unsigned BitWidth = VT.getScalarSizeInBits(); 3194 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3195 APInt::getAllOnesValue(BitWidth))) 3196 return DAG.getConstant(0, SDLoc(N), VT); 3197 // reassociate and 3198 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3199 return RAND; 3200 // fold (and (or x, C), D) -> D if (C & D) == D 3201 if (N1C && N0.getOpcode() == ISD::OR) 3202 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3203 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3204 return N1; 3205 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3206 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3207 SDValue N0Op0 = N0.getOperand(0); 3208 APInt Mask = ~N1C->getAPIntValue(); 3209 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3210 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3211 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3212 N0.getValueType(), N0Op0); 3213 3214 // Replace uses of the AND with uses of the Zero extend node. 3215 CombineTo(N, Zext); 3216 3217 // We actually want to replace all uses of the any_extend with the 3218 // zero_extend, to avoid duplicating things. This will later cause this 3219 // AND to be folded. 3220 CombineTo(N0.getNode(), Zext); 3221 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3222 } 3223 } 3224 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3225 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3226 // already be zero by virtue of the width of the base type of the load. 3227 // 3228 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3229 // more cases. 3230 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3231 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3232 N0.getOperand(0).getOpcode() == ISD::LOAD && 3233 N0.getOperand(0).getResNo() == 0) || 3234 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3235 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3236 N0 : N0.getOperand(0) ); 3237 3238 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3239 // This can be a pure constant or a vector splat, in which case we treat the 3240 // vector as a scalar and use the splat value. 3241 APInt Constant = APInt::getNullValue(1); 3242 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3243 Constant = C->getAPIntValue(); 3244 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3245 APInt SplatValue, SplatUndef; 3246 unsigned SplatBitSize; 3247 bool HasAnyUndefs; 3248 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3249 SplatBitSize, HasAnyUndefs); 3250 if (IsSplat) { 3251 // Undef bits can contribute to a possible optimisation if set, so 3252 // set them. 3253 SplatValue |= SplatUndef; 3254 3255 // The splat value may be something like "0x00FFFFFF", which means 0 for 3256 // the first vector value and FF for the rest, repeating. We need a mask 3257 // that will apply equally to all members of the vector, so AND all the 3258 // lanes of the constant together. 3259 EVT VT = Vector->getValueType(0); 3260 unsigned BitWidth = VT.getScalarSizeInBits(); 3261 3262 // If the splat value has been compressed to a bitlength lower 3263 // than the size of the vector lane, we need to re-expand it to 3264 // the lane size. 3265 if (BitWidth > SplatBitSize) 3266 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3267 SplatBitSize < BitWidth; 3268 SplatBitSize = SplatBitSize * 2) 3269 SplatValue |= SplatValue.shl(SplatBitSize); 3270 3271 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3272 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3273 if (SplatBitSize % BitWidth == 0) { 3274 Constant = APInt::getAllOnesValue(BitWidth); 3275 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3276 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3277 } 3278 } 3279 } 3280 3281 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3282 // actually legal and isn't going to get expanded, else this is a false 3283 // optimisation. 3284 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3285 Load->getValueType(0), 3286 Load->getMemoryVT()); 3287 3288 // Resize the constant to the same size as the original memory access before 3289 // extension. If it is still the AllOnesValue then this AND is completely 3290 // unneeded. 3291 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3292 3293 bool B; 3294 switch (Load->getExtensionType()) { 3295 default: B = false; break; 3296 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3297 case ISD::ZEXTLOAD: 3298 case ISD::NON_EXTLOAD: B = true; break; 3299 } 3300 3301 if (B && Constant.isAllOnesValue()) { 3302 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3303 // preserve semantics once we get rid of the AND. 3304 SDValue NewLoad(Load, 0); 3305 if (Load->getExtensionType() == ISD::EXTLOAD) { 3306 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3307 Load->getValueType(0), SDLoc(Load), 3308 Load->getChain(), Load->getBasePtr(), 3309 Load->getOffset(), Load->getMemoryVT(), 3310 Load->getMemOperand()); 3311 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3312 if (Load->getNumValues() == 3) { 3313 // PRE/POST_INC loads have 3 values. 3314 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3315 NewLoad.getValue(2) }; 3316 CombineTo(Load, To, 3, true); 3317 } else { 3318 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3319 } 3320 } 3321 3322 // Fold the AND away, taking care not to fold to the old load node if we 3323 // replaced it. 3324 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3325 3326 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3327 } 3328 } 3329 3330 // fold (and (load x), 255) -> (zextload x, i8) 3331 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3332 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3333 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3334 (N0.getOpcode() == ISD::ANY_EXTEND && 3335 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3336 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3337 LoadSDNode *LN0 = HasAnyExt 3338 ? cast<LoadSDNode>(N0.getOperand(0)) 3339 : cast<LoadSDNode>(N0); 3340 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3341 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3342 auto NarrowLoad = false; 3343 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3344 EVT ExtVT, LoadedVT; 3345 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3346 NarrowLoad)) { 3347 if (!NarrowLoad) { 3348 SDValue NewLoad = 3349 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3350 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3351 LN0->getMemOperand()); 3352 AddToWorklist(N); 3353 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3354 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3355 } else { 3356 EVT PtrType = LN0->getOperand(1).getValueType(); 3357 3358 unsigned Alignment = LN0->getAlignment(); 3359 SDValue NewPtr = LN0->getBasePtr(); 3360 3361 // For big endian targets, we need to add an offset to the pointer 3362 // to load the correct bytes. For little endian systems, we merely 3363 // need to read fewer bytes from the same pointer. 3364 if (DAG.getDataLayout().isBigEndian()) { 3365 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3366 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3367 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3368 SDLoc DL(LN0); 3369 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3370 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3371 Alignment = MinAlign(Alignment, PtrOff); 3372 } 3373 3374 AddToWorklist(NewPtr.getNode()); 3375 3376 SDValue Load = DAG.getExtLoad( 3377 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3378 LN0->getPointerInfo(), ExtVT, Alignment, 3379 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3380 AddToWorklist(N); 3381 CombineTo(LN0, Load, Load.getValue(1)); 3382 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3383 } 3384 } 3385 } 3386 } 3387 3388 if (SDValue Combined = visitANDLike(N0, N1, N)) 3389 return Combined; 3390 3391 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3392 if (N0.getOpcode() == N1.getOpcode()) 3393 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3394 return Tmp; 3395 3396 // Masking the negated extension of a boolean is just the zero-extended 3397 // boolean: 3398 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3399 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3400 // 3401 // Note: the SimplifyDemandedBits fold below can make an information-losing 3402 // transform, and then we have no way to find this better fold. 3403 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3404 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0)); 3405 SDValue SubRHS = N0.getOperand(1); 3406 if (SubLHS && SubLHS->isNullValue()) { 3407 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3408 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3409 return SubRHS; 3410 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3411 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3412 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3413 } 3414 } 3415 3416 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3417 // fold (and (sra)) -> (and (srl)) when possible. 3418 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 3419 return SDValue(N, 0); 3420 3421 // fold (zext_inreg (extload x)) -> (zextload x) 3422 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3423 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3424 EVT MemVT = LN0->getMemoryVT(); 3425 // If we zero all the possible extended bits, then we can turn this into 3426 // a zextload if we are running before legalize or the operation is legal. 3427 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3428 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3429 BitWidth - MemVT.getScalarSizeInBits())) && 3430 ((!LegalOperations && !LN0->isVolatile()) || 3431 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3432 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3433 LN0->getChain(), LN0->getBasePtr(), 3434 MemVT, LN0->getMemOperand()); 3435 AddToWorklist(N); 3436 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3437 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3438 } 3439 } 3440 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3441 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3442 N0.hasOneUse()) { 3443 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3444 EVT MemVT = LN0->getMemoryVT(); 3445 // If we zero all the possible extended bits, then we can turn this into 3446 // a zextload if we are running before legalize or the operation is legal. 3447 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3448 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3449 BitWidth - MemVT.getScalarSizeInBits())) && 3450 ((!LegalOperations && !LN0->isVolatile()) || 3451 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3452 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3453 LN0->getChain(), LN0->getBasePtr(), 3454 MemVT, LN0->getMemOperand()); 3455 AddToWorklist(N); 3456 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3457 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3458 } 3459 } 3460 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3461 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3462 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3463 N0.getOperand(1), false)) 3464 return BSwap; 3465 } 3466 3467 return SDValue(); 3468 } 3469 3470 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3471 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3472 bool DemandHighBits) { 3473 if (!LegalOperations) 3474 return SDValue(); 3475 3476 EVT VT = N->getValueType(0); 3477 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3478 return SDValue(); 3479 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3480 return SDValue(); 3481 3482 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3483 bool LookPassAnd0 = false; 3484 bool LookPassAnd1 = false; 3485 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3486 std::swap(N0, N1); 3487 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3488 std::swap(N0, N1); 3489 if (N0.getOpcode() == ISD::AND) { 3490 if (!N0.getNode()->hasOneUse()) 3491 return SDValue(); 3492 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3493 if (!N01C || N01C->getZExtValue() != 0xFF00) 3494 return SDValue(); 3495 N0 = N0.getOperand(0); 3496 LookPassAnd0 = true; 3497 } 3498 3499 if (N1.getOpcode() == ISD::AND) { 3500 if (!N1.getNode()->hasOneUse()) 3501 return SDValue(); 3502 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3503 if (!N11C || N11C->getZExtValue() != 0xFF) 3504 return SDValue(); 3505 N1 = N1.getOperand(0); 3506 LookPassAnd1 = true; 3507 } 3508 3509 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3510 std::swap(N0, N1); 3511 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3512 return SDValue(); 3513 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 3514 return SDValue(); 3515 3516 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3517 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3518 if (!N01C || !N11C) 3519 return SDValue(); 3520 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3521 return SDValue(); 3522 3523 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3524 SDValue N00 = N0->getOperand(0); 3525 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3526 if (!N00.getNode()->hasOneUse()) 3527 return SDValue(); 3528 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3529 if (!N001C || N001C->getZExtValue() != 0xFF) 3530 return SDValue(); 3531 N00 = N00.getOperand(0); 3532 LookPassAnd0 = true; 3533 } 3534 3535 SDValue N10 = N1->getOperand(0); 3536 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3537 if (!N10.getNode()->hasOneUse()) 3538 return SDValue(); 3539 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3540 if (!N101C || N101C->getZExtValue() != 0xFF00) 3541 return SDValue(); 3542 N10 = N10.getOperand(0); 3543 LookPassAnd1 = true; 3544 } 3545 3546 if (N00 != N10) 3547 return SDValue(); 3548 3549 // Make sure everything beyond the low halfword gets set to zero since the SRL 3550 // 16 will clear the top bits. 3551 unsigned OpSizeInBits = VT.getSizeInBits(); 3552 if (DemandHighBits && OpSizeInBits > 16) { 3553 // If the left-shift isn't masked out then the only way this is a bswap is 3554 // if all bits beyond the low 8 are 0. In that case the entire pattern 3555 // reduces to a left shift anyway: leave it for other parts of the combiner. 3556 if (!LookPassAnd0) 3557 return SDValue(); 3558 3559 // However, if the right shift isn't masked out then it might be because 3560 // it's not needed. See if we can spot that too. 3561 if (!LookPassAnd1 && 3562 !DAG.MaskedValueIsZero( 3563 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3564 return SDValue(); 3565 } 3566 3567 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3568 if (OpSizeInBits > 16) { 3569 SDLoc DL(N); 3570 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3571 DAG.getConstant(OpSizeInBits - 16, DL, 3572 getShiftAmountTy(VT))); 3573 } 3574 return Res; 3575 } 3576 3577 /// Return true if the specified node is an element that makes up a 32-bit 3578 /// packed halfword byteswap. 3579 /// ((x & 0x000000ff) << 8) | 3580 /// ((x & 0x0000ff00) >> 8) | 3581 /// ((x & 0x00ff0000) << 8) | 3582 /// ((x & 0xff000000) >> 8) 3583 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3584 if (!N.getNode()->hasOneUse()) 3585 return false; 3586 3587 unsigned Opc = N.getOpcode(); 3588 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3589 return false; 3590 3591 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3592 if (!N1C) 3593 return false; 3594 3595 unsigned Num; 3596 switch (N1C->getZExtValue()) { 3597 default: 3598 return false; 3599 case 0xFF: Num = 0; break; 3600 case 0xFF00: Num = 1; break; 3601 case 0xFF0000: Num = 2; break; 3602 case 0xFF000000: Num = 3; break; 3603 } 3604 3605 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3606 SDValue N0 = N.getOperand(0); 3607 if (Opc == ISD::AND) { 3608 if (Num == 0 || Num == 2) { 3609 // (x >> 8) & 0xff 3610 // (x >> 8) & 0xff0000 3611 if (N0.getOpcode() != ISD::SRL) 3612 return false; 3613 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3614 if (!C || C->getZExtValue() != 8) 3615 return false; 3616 } else { 3617 // (x << 8) & 0xff00 3618 // (x << 8) & 0xff000000 3619 if (N0.getOpcode() != ISD::SHL) 3620 return false; 3621 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3622 if (!C || C->getZExtValue() != 8) 3623 return false; 3624 } 3625 } else if (Opc == ISD::SHL) { 3626 // (x & 0xff) << 8 3627 // (x & 0xff0000) << 8 3628 if (Num != 0 && Num != 2) 3629 return false; 3630 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3631 if (!C || C->getZExtValue() != 8) 3632 return false; 3633 } else { // Opc == ISD::SRL 3634 // (x & 0xff00) >> 8 3635 // (x & 0xff000000) >> 8 3636 if (Num != 1 && Num != 3) 3637 return false; 3638 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3639 if (!C || C->getZExtValue() != 8) 3640 return false; 3641 } 3642 3643 if (Parts[Num]) 3644 return false; 3645 3646 Parts[Num] = N0.getOperand(0).getNode(); 3647 return true; 3648 } 3649 3650 /// Match a 32-bit packed halfword bswap. That is 3651 /// ((x & 0x000000ff) << 8) | 3652 /// ((x & 0x0000ff00) >> 8) | 3653 /// ((x & 0x00ff0000) << 8) | 3654 /// ((x & 0xff000000) >> 8) 3655 /// => (rotl (bswap x), 16) 3656 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3657 if (!LegalOperations) 3658 return SDValue(); 3659 3660 EVT VT = N->getValueType(0); 3661 if (VT != MVT::i32) 3662 return SDValue(); 3663 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3664 return SDValue(); 3665 3666 // Look for either 3667 // (or (or (and), (and)), (or (and), (and))) 3668 // (or (or (or (and), (and)), (and)), (and)) 3669 if (N0.getOpcode() != ISD::OR) 3670 return SDValue(); 3671 SDValue N00 = N0.getOperand(0); 3672 SDValue N01 = N0.getOperand(1); 3673 SDNode *Parts[4] = {}; 3674 3675 if (N1.getOpcode() == ISD::OR && 3676 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3677 // (or (or (and), (and)), (or (and), (and))) 3678 SDValue N000 = N00.getOperand(0); 3679 if (!isBSwapHWordElement(N000, Parts)) 3680 return SDValue(); 3681 3682 SDValue N001 = N00.getOperand(1); 3683 if (!isBSwapHWordElement(N001, Parts)) 3684 return SDValue(); 3685 SDValue N010 = N01.getOperand(0); 3686 if (!isBSwapHWordElement(N010, Parts)) 3687 return SDValue(); 3688 SDValue N011 = N01.getOperand(1); 3689 if (!isBSwapHWordElement(N011, Parts)) 3690 return SDValue(); 3691 } else { 3692 // (or (or (or (and), (and)), (and)), (and)) 3693 if (!isBSwapHWordElement(N1, Parts)) 3694 return SDValue(); 3695 if (!isBSwapHWordElement(N01, Parts)) 3696 return SDValue(); 3697 if (N00.getOpcode() != ISD::OR) 3698 return SDValue(); 3699 SDValue N000 = N00.getOperand(0); 3700 if (!isBSwapHWordElement(N000, Parts)) 3701 return SDValue(); 3702 SDValue N001 = N00.getOperand(1); 3703 if (!isBSwapHWordElement(N001, Parts)) 3704 return SDValue(); 3705 } 3706 3707 // Make sure the parts are all coming from the same node. 3708 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3709 return SDValue(); 3710 3711 SDLoc DL(N); 3712 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3713 SDValue(Parts[0], 0)); 3714 3715 // Result of the bswap should be rotated by 16. If it's not legal, then 3716 // do (x << 16) | (x >> 16). 3717 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3718 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3719 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3720 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3721 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3722 return DAG.getNode(ISD::OR, DL, VT, 3723 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3724 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3725 } 3726 3727 /// This contains all DAGCombine rules which reduce two values combined by 3728 /// an Or operation to a single value \see visitANDLike(). 3729 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3730 EVT VT = N1.getValueType(); 3731 // fold (or x, undef) -> -1 3732 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 3733 return DAG.getAllOnesConstant(SDLoc(LocReference), VT); 3734 3735 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3736 SDValue LL, LR, RL, RR, CC0, CC1; 3737 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3738 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3739 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3740 3741 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3742 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3743 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3744 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3745 EVT CCVT = getSetCCResultType(LR.getValueType()); 3746 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3747 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3748 LR.getValueType(), LL, RL); 3749 AddToWorklist(ORNode.getNode()); 3750 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3751 } 3752 } 3753 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3754 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3755 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3756 EVT CCVT = getSetCCResultType(LR.getValueType()); 3757 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3758 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3759 LR.getValueType(), LL, RL); 3760 AddToWorklist(ANDNode.getNode()); 3761 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3762 } 3763 } 3764 } 3765 // canonicalize equivalent to ll == rl 3766 if (LL == RR && LR == RL) { 3767 Op1 = ISD::getSetCCSwappedOperands(Op1); 3768 std::swap(RL, RR); 3769 } 3770 if (LL == RL && LR == RR) { 3771 bool isInteger = LL.getValueType().isInteger(); 3772 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3773 if (Result != ISD::SETCC_INVALID && 3774 (!LegalOperations || 3775 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3776 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3777 EVT CCVT = getSetCCResultType(LL.getValueType()); 3778 if (N0.getValueType() == CCVT || 3779 (!LegalOperations && N0.getValueType() == MVT::i1)) 3780 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3781 LL, LR, Result); 3782 } 3783 } 3784 } 3785 3786 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3787 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3788 // Don't increase # computations. 3789 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3790 // We can only do this xform if we know that bits from X that are set in C2 3791 // but not in C1 are already zero. Likewise for Y. 3792 if (const ConstantSDNode *N0O1C = 3793 getAsNonOpaqueConstant(N0.getOperand(1))) { 3794 if (const ConstantSDNode *N1O1C = 3795 getAsNonOpaqueConstant(N1.getOperand(1))) { 3796 // We can only do this xform if we know that bits from X that are set in 3797 // C2 but not in C1 are already zero. Likewise for Y. 3798 const APInt &LHSMask = N0O1C->getAPIntValue(); 3799 const APInt &RHSMask = N1O1C->getAPIntValue(); 3800 3801 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3802 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3803 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3804 N0.getOperand(0), N1.getOperand(0)); 3805 SDLoc DL(LocReference); 3806 return DAG.getNode(ISD::AND, DL, VT, X, 3807 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3808 } 3809 } 3810 } 3811 } 3812 3813 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3814 if (N0.getOpcode() == ISD::AND && 3815 N1.getOpcode() == ISD::AND && 3816 N0.getOperand(0) == N1.getOperand(0) && 3817 // Don't increase # computations. 3818 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3819 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3820 N0.getOperand(1), N1.getOperand(1)); 3821 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3822 } 3823 3824 return SDValue(); 3825 } 3826 3827 SDValue DAGCombiner::visitOR(SDNode *N) { 3828 SDValue N0 = N->getOperand(0); 3829 SDValue N1 = N->getOperand(1); 3830 EVT VT = N1.getValueType(); 3831 3832 // x | x --> x 3833 if (N0 == N1) 3834 return N0; 3835 3836 // fold vector ops 3837 if (VT.isVector()) { 3838 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3839 return FoldedVOp; 3840 3841 // fold (or x, 0) -> x, vector edition 3842 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3843 return N1; 3844 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3845 return N0; 3846 3847 // fold (or x, -1) -> -1, vector edition 3848 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3849 // do not return N0, because undef node may exist in N0 3850 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 3851 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3852 // do not return N1, because undef node may exist in N1 3853 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 3854 3855 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 3856 // Do this only if the resulting shuffle is legal. 3857 if (isa<ShuffleVectorSDNode>(N0) && 3858 isa<ShuffleVectorSDNode>(N1) && 3859 // Avoid folding a node with illegal type. 3860 TLI.isTypeLegal(VT)) { 3861 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 3862 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 3863 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 3864 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 3865 // Ensure both shuffles have a zero input. 3866 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 3867 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 3868 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 3869 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3870 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3871 bool CanFold = true; 3872 int NumElts = VT.getVectorNumElements(); 3873 SmallVector<int, 4> Mask(NumElts); 3874 3875 for (int i = 0; i != NumElts; ++i) { 3876 int M0 = SV0->getMaskElt(i); 3877 int M1 = SV1->getMaskElt(i); 3878 3879 // Determine if either index is pointing to a zero vector. 3880 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 3881 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 3882 3883 // If one element is zero and the otherside is undef, keep undef. 3884 // This also handles the case that both are undef. 3885 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 3886 Mask[i] = -1; 3887 continue; 3888 } 3889 3890 // Make sure only one of the elements is zero. 3891 if (M0Zero == M1Zero) { 3892 CanFold = false; 3893 break; 3894 } 3895 3896 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 3897 3898 // We have a zero and non-zero element. If the non-zero came from 3899 // SV0 make the index a LHS index. If it came from SV1, make it 3900 // a RHS index. We need to mod by NumElts because we don't care 3901 // which operand it came from in the original shuffles. 3902 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 3903 } 3904 3905 if (CanFold) { 3906 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 3907 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 3908 3909 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3910 if (!LegalMask) { 3911 std::swap(NewLHS, NewRHS); 3912 ShuffleVectorSDNode::commuteMask(Mask); 3913 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3914 } 3915 3916 if (LegalMask) 3917 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 3918 } 3919 } 3920 } 3921 } 3922 3923 // fold (or c1, c2) -> c1|c2 3924 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3925 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3926 if (N0C && N1C && !N1C->isOpaque()) 3927 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3928 // canonicalize constant to RHS 3929 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3930 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3931 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3932 // fold (or x, 0) -> x 3933 if (isNullConstant(N1)) 3934 return N0; 3935 // fold (or x, -1) -> -1 3936 if (isAllOnesConstant(N1)) 3937 return N1; 3938 // fold (or x, c) -> c iff (x & ~c) == 0 3939 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3940 return N1; 3941 3942 if (SDValue Combined = visitORLike(N0, N1, N)) 3943 return Combined; 3944 3945 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3946 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3947 return BSwap; 3948 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3949 return BSwap; 3950 3951 // reassociate or 3952 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3953 return ROR; 3954 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3955 // iff (c1 & c2) == 0. 3956 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3957 isa<ConstantSDNode>(N0.getOperand(1))) { 3958 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3959 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3960 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3961 N1C, C1)) 3962 return DAG.getNode( 3963 ISD::AND, SDLoc(N), VT, 3964 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3965 return SDValue(); 3966 } 3967 } 3968 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3969 if (N0.getOpcode() == N1.getOpcode()) 3970 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3971 return Tmp; 3972 3973 // See if this is some rotate idiom. 3974 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3975 return SDValue(Rot, 0); 3976 3977 if (SDValue Load = MatchLoadCombine(N)) 3978 return Load; 3979 3980 // Simplify the operands using demanded-bits information. 3981 if (!VT.isVector() && 3982 SimplifyDemandedBits(SDValue(N, 0))) 3983 return SDValue(N, 0); 3984 3985 return SDValue(); 3986 } 3987 3988 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3989 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3990 if (Op.getOpcode() == ISD::AND) { 3991 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3992 Mask = Op.getOperand(1); 3993 Op = Op.getOperand(0); 3994 } else { 3995 return false; 3996 } 3997 } 3998 3999 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4000 Shift = Op; 4001 return true; 4002 } 4003 4004 return false; 4005 } 4006 4007 // Return true if we can prove that, whenever Neg and Pos are both in the 4008 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4009 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4010 // 4011 // (or (shift1 X, Neg), (shift2 X, Pos)) 4012 // 4013 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4014 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4015 // to consider shift amounts with defined behavior. 4016 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4017 // If EltSize is a power of 2 then: 4018 // 4019 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4020 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4021 // 4022 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4023 // for the stronger condition: 4024 // 4025 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4026 // 4027 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4028 // we can just replace Neg with Neg' for the rest of the function. 4029 // 4030 // In other cases we check for the even stronger condition: 4031 // 4032 // Neg == EltSize - Pos [B] 4033 // 4034 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4035 // behavior if Pos == 0 (and consequently Neg == EltSize). 4036 // 4037 // We could actually use [A] whenever EltSize is a power of 2, but the 4038 // only extra cases that it would match are those uninteresting ones 4039 // where Neg and Pos are never in range at the same time. E.g. for 4040 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4041 // as well as (sub 32, Pos), but: 4042 // 4043 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4044 // 4045 // always invokes undefined behavior for 32-bit X. 4046 // 4047 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4048 unsigned MaskLoBits = 0; 4049 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4050 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4051 if (NegC->getAPIntValue() == EltSize - 1) { 4052 Neg = Neg.getOperand(0); 4053 MaskLoBits = Log2_64(EltSize); 4054 } 4055 } 4056 } 4057 4058 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4059 if (Neg.getOpcode() != ISD::SUB) 4060 return false; 4061 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4062 if (!NegC) 4063 return false; 4064 SDValue NegOp1 = Neg.getOperand(1); 4065 4066 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4067 // Pos'. The truncation is redundant for the purpose of the equality. 4068 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4069 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4070 if (PosC->getAPIntValue() == EltSize - 1) 4071 Pos = Pos.getOperand(0); 4072 4073 // The condition we need is now: 4074 // 4075 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4076 // 4077 // If NegOp1 == Pos then we need: 4078 // 4079 // EltSize & Mask == NegC & Mask 4080 // 4081 // (because "x & Mask" is a truncation and distributes through subtraction). 4082 APInt Width; 4083 if (Pos == NegOp1) 4084 Width = NegC->getAPIntValue(); 4085 4086 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4087 // Then the condition we want to prove becomes: 4088 // 4089 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4090 // 4091 // which, again because "x & Mask" is a truncation, becomes: 4092 // 4093 // NegC & Mask == (EltSize - PosC) & Mask 4094 // EltSize & Mask == (NegC + PosC) & Mask 4095 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4096 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4097 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4098 else 4099 return false; 4100 } else 4101 return false; 4102 4103 // Now we just need to check that EltSize & Mask == Width & Mask. 4104 if (MaskLoBits) 4105 // EltSize & Mask is 0 since Mask is EltSize - 1. 4106 return Width.getLoBits(MaskLoBits) == 0; 4107 return Width == EltSize; 4108 } 4109 4110 // A subroutine of MatchRotate used once we have found an OR of two opposite 4111 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4112 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4113 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4114 // Neg with outer conversions stripped away. 4115 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4116 SDValue Neg, SDValue InnerPos, 4117 SDValue InnerNeg, unsigned PosOpcode, 4118 unsigned NegOpcode, const SDLoc &DL) { 4119 // fold (or (shl x, (*ext y)), 4120 // (srl x, (*ext (sub 32, y)))) -> 4121 // (rotl x, y) or (rotr x, (sub 32, y)) 4122 // 4123 // fold (or (shl x, (*ext (sub 32, y))), 4124 // (srl x, (*ext y))) -> 4125 // (rotr x, y) or (rotl x, (sub 32, y)) 4126 EVT VT = Shifted.getValueType(); 4127 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4128 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4129 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4130 HasPos ? Pos : Neg).getNode(); 4131 } 4132 4133 return nullptr; 4134 } 4135 4136 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4137 // idioms for rotate, and if the target supports rotation instructions, generate 4138 // a rot[lr]. 4139 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4140 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4141 EVT VT = LHS.getValueType(); 4142 if (!TLI.isTypeLegal(VT)) return nullptr; 4143 4144 // The target must have at least one rotate flavor. 4145 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4146 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4147 if (!HasROTL && !HasROTR) return nullptr; 4148 4149 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4150 SDValue LHSShift; // The shift. 4151 SDValue LHSMask; // AND value if any. 4152 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4153 return nullptr; // Not part of a rotate. 4154 4155 SDValue RHSShift; // The shift. 4156 SDValue RHSMask; // AND value if any. 4157 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4158 return nullptr; // Not part of a rotate. 4159 4160 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4161 return nullptr; // Not shifting the same value. 4162 4163 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4164 return nullptr; // Shifts must disagree. 4165 4166 // Canonicalize shl to left side in a shl/srl pair. 4167 if (RHSShift.getOpcode() == ISD::SHL) { 4168 std::swap(LHS, RHS); 4169 std::swap(LHSShift, RHSShift); 4170 std::swap(LHSMask, RHSMask); 4171 } 4172 4173 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4174 SDValue LHSShiftArg = LHSShift.getOperand(0); 4175 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4176 SDValue RHSShiftArg = RHSShift.getOperand(0); 4177 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4178 4179 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4180 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4181 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4182 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4183 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4184 if ((LShVal + RShVal) != EltSizeInBits) 4185 return nullptr; 4186 4187 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4188 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4189 4190 // If there is an AND of either shifted operand, apply it to the result. 4191 if (LHSMask.getNode() || RHSMask.getNode()) { 4192 SDValue Mask = DAG.getAllOnesConstant(DL, VT); 4193 4194 if (LHSMask.getNode()) { 4195 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4196 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4197 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4198 DAG.getConstant(RHSBits, DL, VT))); 4199 } 4200 if (RHSMask.getNode()) { 4201 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4202 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4203 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4204 DAG.getConstant(LHSBits, DL, VT))); 4205 } 4206 4207 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4208 } 4209 4210 return Rot.getNode(); 4211 } 4212 4213 // If there is a mask here, and we have a variable shift, we can't be sure 4214 // that we're masking out the right stuff. 4215 if (LHSMask.getNode() || RHSMask.getNode()) 4216 return nullptr; 4217 4218 // If the shift amount is sign/zext/any-extended just peel it off. 4219 SDValue LExtOp0 = LHSShiftAmt; 4220 SDValue RExtOp0 = RHSShiftAmt; 4221 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4222 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4223 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4224 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4225 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4226 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4227 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4228 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4229 LExtOp0 = LHSShiftAmt.getOperand(0); 4230 RExtOp0 = RHSShiftAmt.getOperand(0); 4231 } 4232 4233 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4234 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4235 if (TryL) 4236 return TryL; 4237 4238 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4239 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4240 if (TryR) 4241 return TryR; 4242 4243 return nullptr; 4244 } 4245 4246 namespace { 4247 /// Helper struct to parse and store a memory address as base + index + offset. 4248 /// We ignore sign extensions when it is safe to do so. 4249 /// The following two expressions are not equivalent. To differentiate we need 4250 /// to store whether there was a sign extension involved in the index 4251 /// computation. 4252 /// (load (i64 add (i64 copyfromreg %c) 4253 /// (i64 signextend (add (i8 load %index) 4254 /// (i8 1)))) 4255 /// vs 4256 /// 4257 /// (load (i64 add (i64 copyfromreg %c) 4258 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 4259 /// (i32 1))))) 4260 struct BaseIndexOffset { 4261 SDValue Base; 4262 SDValue Index; 4263 int64_t Offset; 4264 bool IsIndexSignExt; 4265 4266 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 4267 4268 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 4269 bool IsIndexSignExt) : 4270 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 4271 4272 bool equalBaseIndex(const BaseIndexOffset &Other) { 4273 return Other.Base == Base && Other.Index == Index && 4274 Other.IsIndexSignExt == IsIndexSignExt; 4275 } 4276 4277 /// Parses tree in Ptr for base, index, offset addresses. 4278 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG, 4279 int64_t PartialOffset = 0) { 4280 bool IsIndexSignExt = false; 4281 4282 // Split up a folded GlobalAddress+Offset into its component parts. 4283 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 4284 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 4285 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 4286 SDLoc(GA), 4287 GA->getValueType(0), 4288 /*Offset=*/PartialOffset, 4289 /*isTargetGA=*/false, 4290 GA->getTargetFlags()), 4291 SDValue(), 4292 GA->getOffset(), 4293 IsIndexSignExt); 4294 } 4295 4296 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 4297 // instruction, then it could be just the BASE or everything else we don't 4298 // know how to handle. Just use Ptr as BASE and give up. 4299 if (Ptr->getOpcode() != ISD::ADD) 4300 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4301 4302 // We know that we have at least an ADD instruction. Try to pattern match 4303 // the simple case of BASE + OFFSET. 4304 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 4305 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 4306 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset); 4307 } 4308 4309 // Inside a loop the current BASE pointer is calculated using an ADD and a 4310 // MUL instruction. In this case Ptr is the actual BASE pointer. 4311 // (i64 add (i64 %array_ptr) 4312 // (i64 mul (i64 %induction_var) 4313 // (i64 %element_size))) 4314 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 4315 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4316 4317 // Look at Base + Index + Offset cases. 4318 SDValue Base = Ptr->getOperand(0); 4319 SDValue IndexOffset = Ptr->getOperand(1); 4320 4321 // Skip signextends. 4322 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 4323 IndexOffset = IndexOffset->getOperand(0); 4324 IsIndexSignExt = true; 4325 } 4326 4327 // Either the case of Base + Index (no offset) or something else. 4328 if (IndexOffset->getOpcode() != ISD::ADD) 4329 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt); 4330 4331 // Now we have the case of Base + Index + offset. 4332 SDValue Index = IndexOffset->getOperand(0); 4333 SDValue Offset = IndexOffset->getOperand(1); 4334 4335 if (!isa<ConstantSDNode>(Offset)) 4336 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4337 4338 // Ignore signextends. 4339 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 4340 Index = Index->getOperand(0); 4341 IsIndexSignExt = true; 4342 } else IsIndexSignExt = false; 4343 4344 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 4345 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt); 4346 } 4347 }; 4348 } // namespace 4349 4350 namespace { 4351 /// Represents known origin of an individual byte in load combine pattern. The 4352 /// value of the byte is either constant zero or comes from memory. 4353 struct ByteProvider { 4354 // For constant zero providers Load is set to nullptr. For memory providers 4355 // Load represents the node which loads the byte from memory. 4356 // ByteOffset is the offset of the byte in the value produced by the load. 4357 LoadSDNode *Load; 4358 unsigned ByteOffset; 4359 4360 ByteProvider() : Load(nullptr), ByteOffset(0) {} 4361 4362 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4363 return ByteProvider(Load, ByteOffset); 4364 } 4365 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4366 4367 bool isConstantZero() const { return !Load; } 4368 bool isMemory() const { return Load; } 4369 4370 bool operator==(const ByteProvider &Other) const { 4371 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4372 } 4373 4374 private: 4375 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4376 : Load(Load), ByteOffset(ByteOffset) {} 4377 }; 4378 4379 /// Recursively traverses the expression calculating the origin of the requested 4380 /// byte of the given value. Returns None if the provider can't be calculated. 4381 /// 4382 /// For all the values except the root of the expression verifies that the value 4383 /// has exactly one use and if it's not true return None. This way if the origin 4384 /// of the byte is returned it's guaranteed that the values which contribute to 4385 /// the byte are not used outside of this expression. 4386 /// 4387 /// Because the parts of the expression are not allowed to have more than one 4388 /// use this function iterates over trees, not DAGs. So it never visits the same 4389 /// node more than once. 4390 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index, 4391 unsigned Depth, 4392 bool Root = false) { 4393 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4394 if (Depth == 10) 4395 return None; 4396 4397 if (!Root && !Op.hasOneUse()) 4398 return None; 4399 4400 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4401 unsigned BitWidth = Op.getValueSizeInBits(); 4402 if (BitWidth % 8 != 0) 4403 return None; 4404 unsigned ByteWidth = BitWidth / 8; 4405 assert(Index < ByteWidth && "invalid index requested"); 4406 (void) ByteWidth; 4407 4408 switch (Op.getOpcode()) { 4409 case ISD::OR: { 4410 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4411 if (!LHS) 4412 return None; 4413 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4414 if (!RHS) 4415 return None; 4416 4417 if (LHS->isConstantZero()) 4418 return RHS; 4419 else if (RHS->isConstantZero()) 4420 return LHS; 4421 else 4422 return None; 4423 } 4424 case ISD::SHL: { 4425 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4426 if (!ShiftOp) 4427 return None; 4428 4429 uint64_t BitShift = ShiftOp->getZExtValue(); 4430 if (BitShift % 8 != 0) 4431 return None; 4432 uint64_t ByteShift = BitShift / 8; 4433 4434 return Index < ByteShift 4435 ? ByteProvider::getConstantZero() 4436 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4437 Depth + 1); 4438 } 4439 case ISD::ZERO_EXTEND: { 4440 SDValue NarrowOp = Op->getOperand(0); 4441 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4442 if (NarrowBitWidth % 8 != 0) 4443 return None; 4444 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4445 4446 return Index >= NarrowByteWidth 4447 ? ByteProvider::getConstantZero() 4448 : calculateByteProvider(NarrowOp, Index, Depth + 1); 4449 } 4450 case ISD::BSWAP: 4451 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4452 Depth + 1); 4453 case ISD::LOAD: { 4454 auto L = cast<LoadSDNode>(Op.getNode()); 4455 4456 // TODO: support ext loads 4457 if (L->isVolatile() || L->isIndexed() || 4458 L->getExtensionType() != ISD::NON_EXTLOAD) 4459 return None; 4460 4461 return ByteProvider::getMemory(L, Index); 4462 } 4463 } 4464 4465 return None; 4466 } 4467 } // namespace 4468 4469 /// Match a pattern where a wide type scalar value is loaded by several narrow 4470 /// loads and combined by shifts and ors. Fold it into a single load or a load 4471 /// and a BSWAP if the targets supports it. 4472 /// 4473 /// Assuming little endian target: 4474 /// i8 *a = ... 4475 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4476 /// => 4477 /// i32 val = *((i32)a) 4478 /// 4479 /// i8 *a = ... 4480 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4481 /// => 4482 /// i32 val = BSWAP(*((i32)a)) 4483 /// 4484 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4485 /// interact well with the worklist mechanism. When a part of the pattern is 4486 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4487 /// but the root node of the pattern which triggers the load combine is not 4488 /// necessarily a direct user of the changed node. For example, once the address 4489 /// of t28 load is reassociated load combine won't be triggered: 4490 /// t25: i32 = add t4, Constant:i32<2> 4491 /// t26: i64 = sign_extend t25 4492 /// t27: i64 = add t2, t26 4493 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4494 /// t29: i32 = zero_extend t28 4495 /// t32: i32 = shl t29, Constant:i8<8> 4496 /// t33: i32 = or t23, t32 4497 /// As a possible fix visitLoad can check if the load can be a part of a load 4498 /// combine pattern and add corresponding OR roots to the worklist. 4499 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4500 assert(N->getOpcode() == ISD::OR && 4501 "Can only match load combining against OR nodes"); 4502 4503 // Handles simple types only 4504 EVT VT = N->getValueType(0); 4505 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4506 return SDValue(); 4507 unsigned ByteWidth = VT.getSizeInBits() / 8; 4508 4509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4510 // Before legalize we can introduce too wide illegal loads which will be later 4511 // split into legal sized loads. This enables us to combine i64 load by i8 4512 // patterns to a couple of i32 loads on 32 bit targets. 4513 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4514 return SDValue(); 4515 4516 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4517 unsigned BW, unsigned i) { return i; }; 4518 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4519 unsigned BW, unsigned i) { return BW - i - 1; }; 4520 4521 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4522 auto MemoryByteOffset = [&] (ByteProvider P) { 4523 assert(P.isMemory() && "Must be a memory byte provider"); 4524 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4525 assert(LoadBitWidth % 8 == 0 && 4526 "can only analyze providers for individual bytes not bit"); 4527 unsigned LoadByteWidth = LoadBitWidth / 8; 4528 return IsBigEndianTarget 4529 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4530 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4531 }; 4532 4533 Optional<BaseIndexOffset> Base; 4534 SDValue Chain; 4535 4536 SmallSet<LoadSDNode *, 8> Loads; 4537 Optional<ByteProvider> FirstByteProvider; 4538 int64_t FirstOffset = INT64_MAX; 4539 4540 // Check if all the bytes of the OR we are looking at are loaded from the same 4541 // base address. Collect bytes offsets from Base address in ByteOffsets. 4542 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 4543 for (unsigned i = 0; i < ByteWidth; i++) { 4544 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 4545 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 4546 return SDValue(); 4547 4548 LoadSDNode *L = P->Load; 4549 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 4550 (L->getExtensionType() == ISD::NON_EXTLOAD) && 4551 "Must be enforced by calculateByteProvider"); 4552 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 4553 4554 // All loads must share the same chain 4555 SDValue LChain = L->getChain(); 4556 if (!Chain) 4557 Chain = LChain; 4558 else if (Chain != LChain) 4559 return SDValue(); 4560 4561 // Loads must share the same base address 4562 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 4563 if (!Base) 4564 Base = Ptr; 4565 else if (!Base->equalBaseIndex(Ptr)) 4566 return SDValue(); 4567 4568 // Calculate the offset of the current byte from the base address 4569 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P); 4570 ByteOffsets[i] = ByteOffsetFromBase; 4571 4572 // Remember the first byte load 4573 if (ByteOffsetFromBase < FirstOffset) { 4574 FirstByteProvider = P; 4575 FirstOffset = ByteOffsetFromBase; 4576 } 4577 4578 Loads.insert(L); 4579 } 4580 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from " 4581 "memory, so there must be at least one load which produces the value"); 4582 assert(Base && "Base address of the accessed memory location must be set"); 4583 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 4584 4585 // Check if the bytes of the OR we are looking at match with either big or 4586 // little endian value load 4587 bool BigEndian = true, LittleEndian = true; 4588 for (unsigned i = 0; i < ByteWidth; i++) { 4589 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 4590 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 4591 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 4592 if (!BigEndian && !LittleEndian) 4593 return SDValue(); 4594 } 4595 assert((BigEndian != LittleEndian) && "should be either or"); 4596 assert(FirstByteProvider && "must be set"); 4597 4598 // Ensure that the first byte is loaded from zero offset of the first load. 4599 // So the combined value can be loaded from the first load address. 4600 if (MemoryByteOffset(*FirstByteProvider) != 0) 4601 return SDValue(); 4602 LoadSDNode *FirstLoad = FirstByteProvider->Load; 4603 4604 // The node we are looking at matches with the pattern, check if we can 4605 // replace it with a single load and bswap if needed. 4606 4607 // If the load needs byte swap check if the target supports it 4608 bool NeedsBswap = IsBigEndianTarget != BigEndian; 4609 4610 // Before legalize we can introduce illegal bswaps which will be later 4611 // converted to an explicit bswap sequence. This way we end up with a single 4612 // load and byte shuffling instead of several loads and byte shuffling. 4613 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 4614 return SDValue(); 4615 4616 // Check that a load of the wide type is both allowed and fast on the target 4617 bool Fast = false; 4618 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 4619 VT, FirstLoad->getAddressSpace(), 4620 FirstLoad->getAlignment(), &Fast); 4621 if (!Allowed || !Fast) 4622 return SDValue(); 4623 4624 SDValue NewLoad = 4625 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 4626 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 4627 4628 // Transfer chain users from old loads to the new load. 4629 for (LoadSDNode *L : Loads) 4630 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 4631 4632 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 4633 } 4634 4635 SDValue DAGCombiner::visitXOR(SDNode *N) { 4636 SDValue N0 = N->getOperand(0); 4637 SDValue N1 = N->getOperand(1); 4638 EVT VT = N0.getValueType(); 4639 4640 // fold vector ops 4641 if (VT.isVector()) { 4642 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4643 return FoldedVOp; 4644 4645 // fold (xor x, 0) -> x, vector edition 4646 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4647 return N1; 4648 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4649 return N0; 4650 } 4651 4652 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4653 if (N0.isUndef() && N1.isUndef()) 4654 return DAG.getConstant(0, SDLoc(N), VT); 4655 // fold (xor x, undef) -> undef 4656 if (N0.isUndef()) 4657 return N0; 4658 if (N1.isUndef()) 4659 return N1; 4660 // fold (xor c1, c2) -> c1^c2 4661 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4662 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4663 if (N0C && N1C) 4664 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4665 // canonicalize constant to RHS 4666 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4667 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4668 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4669 // fold (xor x, 0) -> x 4670 if (isNullConstant(N1)) 4671 return N0; 4672 // reassociate xor 4673 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4674 return RXOR; 4675 4676 // fold !(x cc y) -> (x !cc y) 4677 SDValue LHS, RHS, CC; 4678 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4679 bool isInt = LHS.getValueType().isInteger(); 4680 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4681 isInt); 4682 4683 if (!LegalOperations || 4684 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4685 switch (N0.getOpcode()) { 4686 default: 4687 llvm_unreachable("Unhandled SetCC Equivalent!"); 4688 case ISD::SETCC: 4689 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4690 case ISD::SELECT_CC: 4691 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4692 N0.getOperand(3), NotCC); 4693 } 4694 } 4695 } 4696 4697 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4698 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4699 N0.getNode()->hasOneUse() && 4700 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4701 SDValue V = N0.getOperand(0); 4702 SDLoc DL(N0); 4703 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4704 DAG.getConstant(1, DL, V.getValueType())); 4705 AddToWorklist(V.getNode()); 4706 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4707 } 4708 4709 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4710 if (isOneConstant(N1) && VT == MVT::i1 && 4711 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4712 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4713 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4714 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4715 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4716 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4717 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4718 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4719 } 4720 } 4721 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4722 if (isAllOnesConstant(N1) && 4723 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4724 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4725 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4726 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4727 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4728 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4729 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4730 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4731 } 4732 } 4733 // fold (xor (and x, y), y) -> (and (not x), y) 4734 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4735 N0->getOperand(1) == N1) { 4736 SDValue X = N0->getOperand(0); 4737 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4738 AddToWorklist(NotX.getNode()); 4739 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4740 } 4741 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4742 if (N1C && N0.getOpcode() == ISD::XOR) { 4743 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4744 SDLoc DL(N); 4745 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4746 DAG.getConstant(N1C->getAPIntValue() ^ 4747 N00C->getAPIntValue(), DL, VT)); 4748 } 4749 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4750 SDLoc DL(N); 4751 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4752 DAG.getConstant(N1C->getAPIntValue() ^ 4753 N01C->getAPIntValue(), DL, VT)); 4754 } 4755 } 4756 // fold (xor x, x) -> 0 4757 if (N0 == N1) 4758 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4759 4760 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4761 // Here is a concrete example of this equivalence: 4762 // i16 x == 14 4763 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4764 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4765 // 4766 // => 4767 // 4768 // i16 ~1 == 0b1111111111111110 4769 // i16 rol(~1, 14) == 0b1011111111111111 4770 // 4771 // Some additional tips to help conceptualize this transform: 4772 // - Try to see the operation as placing a single zero in a value of all ones. 4773 // - There exists no value for x which would allow the result to contain zero. 4774 // - Values of x larger than the bitwidth are undefined and do not require a 4775 // consistent result. 4776 // - Pushing the zero left requires shifting one bits in from the right. 4777 // A rotate left of ~1 is a nice way of achieving the desired result. 4778 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4779 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4780 SDLoc DL(N); 4781 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4782 N0.getOperand(1)); 4783 } 4784 4785 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4786 if (N0.getOpcode() == N1.getOpcode()) 4787 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4788 return Tmp; 4789 4790 // Simplify the expression using non-local knowledge. 4791 if (!VT.isVector() && 4792 SimplifyDemandedBits(SDValue(N, 0))) 4793 return SDValue(N, 0); 4794 4795 return SDValue(); 4796 } 4797 4798 /// Handle transforms common to the three shifts, when the shift amount is a 4799 /// constant. 4800 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4801 SDNode *LHS = N->getOperand(0).getNode(); 4802 if (!LHS->hasOneUse()) return SDValue(); 4803 4804 // We want to pull some binops through shifts, so that we have (and (shift)) 4805 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4806 // thing happens with address calculations, so it's important to canonicalize 4807 // it. 4808 bool HighBitSet = false; // Can we transform this if the high bit is set? 4809 4810 switch (LHS->getOpcode()) { 4811 default: return SDValue(); 4812 case ISD::OR: 4813 case ISD::XOR: 4814 HighBitSet = false; // We can only transform sra if the high bit is clear. 4815 break; 4816 case ISD::AND: 4817 HighBitSet = true; // We can only transform sra if the high bit is set. 4818 break; 4819 case ISD::ADD: 4820 if (N->getOpcode() != ISD::SHL) 4821 return SDValue(); // only shl(add) not sr[al](add). 4822 HighBitSet = false; // We can only transform sra if the high bit is clear. 4823 break; 4824 } 4825 4826 // We require the RHS of the binop to be a constant and not opaque as well. 4827 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4828 if (!BinOpCst) return SDValue(); 4829 4830 // FIXME: disable this unless the input to the binop is a shift by a constant 4831 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 4832 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4833 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 4834 BinOpLHSVal->getOpcode() == ISD::SRA || 4835 BinOpLHSVal->getOpcode() == ISD::SRL; 4836 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 4837 BinOpLHSVal->getOpcode() == ISD::SELECT; 4838 4839 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 4840 !isCopyOrSelect) 4841 return SDValue(); 4842 4843 if (isCopyOrSelect && N->hasOneUse()) 4844 return SDValue(); 4845 4846 EVT VT = N->getValueType(0); 4847 4848 // If this is a signed shift right, and the high bit is modified by the 4849 // logical operation, do not perform the transformation. The highBitSet 4850 // boolean indicates the value of the high bit of the constant which would 4851 // cause it to be modified for this operation. 4852 if (N->getOpcode() == ISD::SRA) { 4853 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4854 if (BinOpRHSSignSet != HighBitSet) 4855 return SDValue(); 4856 } 4857 4858 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4859 return SDValue(); 4860 4861 // Fold the constants, shifting the binop RHS by the shift amount. 4862 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4863 N->getValueType(0), 4864 LHS->getOperand(1), N->getOperand(1)); 4865 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4866 4867 // Create the new shift. 4868 SDValue NewShift = DAG.getNode(N->getOpcode(), 4869 SDLoc(LHS->getOperand(0)), 4870 VT, LHS->getOperand(0), N->getOperand(1)); 4871 4872 // Create the new binop. 4873 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4874 } 4875 4876 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4877 assert(N->getOpcode() == ISD::TRUNCATE); 4878 assert(N->getOperand(0).getOpcode() == ISD::AND); 4879 4880 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4881 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4882 SDValue N01 = N->getOperand(0).getOperand(1); 4883 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 4884 SDLoc DL(N); 4885 EVT TruncVT = N->getValueType(0); 4886 SDValue N00 = N->getOperand(0).getOperand(0); 4887 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 4888 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 4889 AddToWorklist(Trunc00.getNode()); 4890 AddToWorklist(Trunc01.getNode()); 4891 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 4892 } 4893 } 4894 4895 return SDValue(); 4896 } 4897 4898 SDValue DAGCombiner::visitRotate(SDNode *N) { 4899 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4900 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4901 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4902 if (SDValue NewOp1 = 4903 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4904 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4905 N->getOperand(0), NewOp1); 4906 } 4907 return SDValue(); 4908 } 4909 4910 SDValue DAGCombiner::visitSHL(SDNode *N) { 4911 SDValue N0 = N->getOperand(0); 4912 SDValue N1 = N->getOperand(1); 4913 EVT VT = N0.getValueType(); 4914 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4915 4916 // fold vector ops 4917 if (VT.isVector()) { 4918 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4919 return FoldedVOp; 4920 4921 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4922 // If setcc produces all-one true value then: 4923 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4924 if (N1CV && N1CV->isConstant()) { 4925 if (N0.getOpcode() == ISD::AND) { 4926 SDValue N00 = N0->getOperand(0); 4927 SDValue N01 = N0->getOperand(1); 4928 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4929 4930 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4931 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4932 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4933 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4934 N01CV, N1CV)) 4935 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4936 } 4937 } 4938 } 4939 } 4940 4941 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4942 4943 // fold (shl c1, c2) -> c1<<c2 4944 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4945 if (N0C && N1C && !N1C->isOpaque()) 4946 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4947 // fold (shl 0, x) -> 0 4948 if (isNullConstant(N0)) 4949 return N0; 4950 // fold (shl x, c >= size(x)) -> undef 4951 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4952 return DAG.getUNDEF(VT); 4953 // fold (shl x, 0) -> x 4954 if (N1C && N1C->isNullValue()) 4955 return N0; 4956 // fold (shl undef, x) -> 0 4957 if (N0.isUndef()) 4958 return DAG.getConstant(0, SDLoc(N), VT); 4959 // if (shl x, c) is known to be zero, return 0 4960 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4961 APInt::getAllOnesValue(OpSizeInBits))) 4962 return DAG.getConstant(0, SDLoc(N), VT); 4963 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4964 if (N1.getOpcode() == ISD::TRUNCATE && 4965 N1.getOperand(0).getOpcode() == ISD::AND) { 4966 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4967 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4968 } 4969 4970 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4971 return SDValue(N, 0); 4972 4973 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4974 if (N1C && N0.getOpcode() == ISD::SHL) { 4975 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4976 SDLoc DL(N); 4977 APInt c1 = N0C1->getAPIntValue(); 4978 APInt c2 = N1C->getAPIntValue(); 4979 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4980 4981 APInt Sum = c1 + c2; 4982 if (Sum.uge(OpSizeInBits)) 4983 return DAG.getConstant(0, DL, VT); 4984 4985 return DAG.getNode( 4986 ISD::SHL, DL, VT, N0.getOperand(0), 4987 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4988 } 4989 } 4990 4991 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4992 // For this to be valid, the second form must not preserve any of the bits 4993 // that are shifted out by the inner shift in the first form. This means 4994 // the outer shift size must be >= the number of bits added by the ext. 4995 // As a corollary, we don't care what kind of ext it is. 4996 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4997 N0.getOpcode() == ISD::ANY_EXTEND || 4998 N0.getOpcode() == ISD::SIGN_EXTEND) && 4999 N0.getOperand(0).getOpcode() == ISD::SHL) { 5000 SDValue N0Op0 = N0.getOperand(0); 5001 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5002 APInt c1 = N0Op0C1->getAPIntValue(); 5003 APInt c2 = N1C->getAPIntValue(); 5004 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5005 5006 EVT InnerShiftVT = N0Op0.getValueType(); 5007 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5008 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5009 SDLoc DL(N0); 5010 APInt Sum = c1 + c2; 5011 if (Sum.uge(OpSizeInBits)) 5012 return DAG.getConstant(0, DL, VT); 5013 5014 return DAG.getNode( 5015 ISD::SHL, DL, VT, 5016 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5017 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5018 } 5019 } 5020 } 5021 5022 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5023 // Only fold this if the inner zext has no other uses to avoid increasing 5024 // the total number of instructions. 5025 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5026 N0.getOperand(0).getOpcode() == ISD::SRL) { 5027 SDValue N0Op0 = N0.getOperand(0); 5028 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5029 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5030 uint64_t c1 = N0Op0C1->getZExtValue(); 5031 uint64_t c2 = N1C->getZExtValue(); 5032 if (c1 == c2) { 5033 SDValue NewOp0 = N0.getOperand(0); 5034 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5035 SDLoc DL(N); 5036 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5037 NewOp0, 5038 DAG.getConstant(c2, DL, CountVT)); 5039 AddToWorklist(NewSHL.getNode()); 5040 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5041 } 5042 } 5043 } 5044 } 5045 5046 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5047 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5048 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5049 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 5050 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5051 uint64_t C1 = N0C1->getZExtValue(); 5052 uint64_t C2 = N1C->getZExtValue(); 5053 SDLoc DL(N); 5054 if (C1 <= C2) 5055 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5056 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5057 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5058 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5059 } 5060 } 5061 5062 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5063 // (and (srl x, (sub c1, c2), MASK) 5064 // Only fold this if the inner shift has no other uses -- if it does, folding 5065 // this will increase the total number of instructions. 5066 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5067 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5068 uint64_t c1 = N0C1->getZExtValue(); 5069 if (c1 < OpSizeInBits) { 5070 uint64_t c2 = N1C->getZExtValue(); 5071 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5072 SDValue Shift; 5073 if (c2 > c1) { 5074 Mask = Mask.shl(c2 - c1); 5075 SDLoc DL(N); 5076 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5077 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5078 } else { 5079 Mask = Mask.lshr(c1 - c2); 5080 SDLoc DL(N); 5081 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5082 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5083 } 5084 SDLoc DL(N0); 5085 return DAG.getNode(ISD::AND, DL, VT, Shift, 5086 DAG.getConstant(Mask, DL, VT)); 5087 } 5088 } 5089 } 5090 5091 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5092 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5093 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5094 SDLoc DL(N); 5095 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5096 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5097 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5098 } 5099 5100 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5101 // Variant of version done on multiply, except mul by a power of 2 is turned 5102 // into a shift. 5103 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 5104 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5105 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5106 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5107 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5108 AddToWorklist(Shl0.getNode()); 5109 AddToWorklist(Shl1.getNode()); 5110 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 5111 } 5112 5113 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5114 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5115 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5116 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5117 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5118 if (isConstantOrConstantVector(Shl)) 5119 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5120 } 5121 5122 if (N1C && !N1C->isOpaque()) 5123 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5124 return NewSHL; 5125 5126 return SDValue(); 5127 } 5128 5129 SDValue DAGCombiner::visitSRA(SDNode *N) { 5130 SDValue N0 = N->getOperand(0); 5131 SDValue N1 = N->getOperand(1); 5132 EVT VT = N0.getValueType(); 5133 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5134 5135 // Arithmetic shifting an all-sign-bit value is a no-op. 5136 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5137 return N0; 5138 5139 // fold vector ops 5140 if (VT.isVector()) 5141 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5142 return FoldedVOp; 5143 5144 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5145 5146 // fold (sra c1, c2) -> (sra c1, c2) 5147 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5148 if (N0C && N1C && !N1C->isOpaque()) 5149 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5150 // fold (sra 0, x) -> 0 5151 if (isNullConstant(N0)) 5152 return N0; 5153 // fold (sra -1, x) -> -1 5154 if (isAllOnesConstant(N0)) 5155 return N0; 5156 // fold (sra x, c >= size(x)) -> undef 5157 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5158 return DAG.getUNDEF(VT); 5159 // fold (sra x, 0) -> x 5160 if (N1C && N1C->isNullValue()) 5161 return N0; 5162 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5163 // sext_inreg. 5164 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5165 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5166 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5167 if (VT.isVector()) 5168 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5169 ExtVT, VT.getVectorNumElements()); 5170 if ((!LegalOperations || 5171 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5172 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5173 N0.getOperand(0), DAG.getValueType(ExtVT)); 5174 } 5175 5176 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5177 if (N1C && N0.getOpcode() == ISD::SRA) { 5178 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5179 SDLoc DL(N); 5180 APInt c1 = N0C1->getAPIntValue(); 5181 APInt c2 = N1C->getAPIntValue(); 5182 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5183 5184 APInt Sum = c1 + c2; 5185 if (Sum.uge(OpSizeInBits)) 5186 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 5187 5188 return DAG.getNode( 5189 ISD::SRA, DL, VT, N0.getOperand(0), 5190 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5191 } 5192 } 5193 5194 // fold (sra (shl X, m), (sub result_size, n)) 5195 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5196 // result_size - n != m. 5197 // If truncate is free for the target sext(shl) is likely to result in better 5198 // code. 5199 if (N0.getOpcode() == ISD::SHL && N1C) { 5200 // Get the two constanst of the shifts, CN0 = m, CN = n. 5201 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5202 if (N01C) { 5203 LLVMContext &Ctx = *DAG.getContext(); 5204 // Determine what the truncate's result bitsize and type would be. 5205 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5206 5207 if (VT.isVector()) 5208 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5209 5210 // Determine the residual right-shift amount. 5211 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5212 5213 // If the shift is not a no-op (in which case this should be just a sign 5214 // extend already), the truncated to type is legal, sign_extend is legal 5215 // on that type, and the truncate to that type is both legal and free, 5216 // perform the transform. 5217 if ((ShiftAmt > 0) && 5218 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5219 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5220 TLI.isTruncateFree(VT, TruncVT)) { 5221 5222 SDLoc DL(N); 5223 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5224 getShiftAmountTy(N0.getOperand(0).getValueType())); 5225 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5226 N0.getOperand(0), Amt); 5227 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5228 Shift); 5229 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5230 N->getValueType(0), Trunc); 5231 } 5232 } 5233 } 5234 5235 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5236 if (N1.getOpcode() == ISD::TRUNCATE && 5237 N1.getOperand(0).getOpcode() == ISD::AND) { 5238 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5239 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5240 } 5241 5242 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5243 // if c1 is equal to the number of bits the trunc removes 5244 if (N0.getOpcode() == ISD::TRUNCATE && 5245 (N0.getOperand(0).getOpcode() == ISD::SRL || 5246 N0.getOperand(0).getOpcode() == ISD::SRA) && 5247 N0.getOperand(0).hasOneUse() && 5248 N0.getOperand(0).getOperand(1).hasOneUse() && 5249 N1C) { 5250 SDValue N0Op0 = N0.getOperand(0); 5251 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5252 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5253 EVT LargeVT = N0Op0.getValueType(); 5254 5255 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5256 SDLoc DL(N); 5257 SDValue Amt = 5258 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5259 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5260 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5261 N0Op0.getOperand(0), Amt); 5262 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5263 } 5264 } 5265 } 5266 5267 // Simplify, based on bits shifted out of the LHS. 5268 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5269 return SDValue(N, 0); 5270 5271 5272 // If the sign bit is known to be zero, switch this to a SRL. 5273 if (DAG.SignBitIsZero(N0)) 5274 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5275 5276 if (N1C && !N1C->isOpaque()) 5277 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5278 return NewSRA; 5279 5280 return SDValue(); 5281 } 5282 5283 SDValue DAGCombiner::visitSRL(SDNode *N) { 5284 SDValue N0 = N->getOperand(0); 5285 SDValue N1 = N->getOperand(1); 5286 EVT VT = N0.getValueType(); 5287 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5288 5289 // fold vector ops 5290 if (VT.isVector()) 5291 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5292 return FoldedVOp; 5293 5294 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5295 5296 // fold (srl c1, c2) -> c1 >>u c2 5297 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5298 if (N0C && N1C && !N1C->isOpaque()) 5299 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5300 // fold (srl 0, x) -> 0 5301 if (isNullConstant(N0)) 5302 return N0; 5303 // fold (srl x, c >= size(x)) -> undef 5304 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5305 return DAG.getUNDEF(VT); 5306 // fold (srl x, 0) -> x 5307 if (N1C && N1C->isNullValue()) 5308 return N0; 5309 // if (srl x, c) is known to be zero, return 0 5310 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5311 APInt::getAllOnesValue(OpSizeInBits))) 5312 return DAG.getConstant(0, SDLoc(N), VT); 5313 5314 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5315 if (N1C && N0.getOpcode() == ISD::SRL) { 5316 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5317 SDLoc DL(N); 5318 APInt c1 = N0C1->getAPIntValue(); 5319 APInt c2 = N1C->getAPIntValue(); 5320 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5321 5322 APInt Sum = c1 + c2; 5323 if (Sum.uge(OpSizeInBits)) 5324 return DAG.getConstant(0, DL, VT); 5325 5326 return DAG.getNode( 5327 ISD::SRL, DL, VT, N0.getOperand(0), 5328 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5329 } 5330 } 5331 5332 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5333 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5334 N0.getOperand(0).getOpcode() == ISD::SRL && 5335 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 5336 uint64_t c1 = 5337 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 5338 uint64_t c2 = N1C->getZExtValue(); 5339 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5340 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 5341 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5342 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5343 if (c1 + OpSizeInBits == InnerShiftSize) { 5344 SDLoc DL(N0); 5345 if (c1 + c2 >= InnerShiftSize) 5346 return DAG.getConstant(0, DL, VT); 5347 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5348 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5349 N0.getOperand(0)->getOperand(0), 5350 DAG.getConstant(c1 + c2, DL, 5351 ShiftCountVT))); 5352 } 5353 } 5354 5355 // fold (srl (shl x, c), c) -> (and x, cst2) 5356 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5357 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5358 SDLoc DL(N); 5359 SDValue Mask = 5360 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5361 AddToWorklist(Mask.getNode()); 5362 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5363 } 5364 5365 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5366 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5367 // Shifting in all undef bits? 5368 EVT SmallVT = N0.getOperand(0).getValueType(); 5369 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5370 if (N1C->getZExtValue() >= BitSize) 5371 return DAG.getUNDEF(VT); 5372 5373 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5374 uint64_t ShiftAmt = N1C->getZExtValue(); 5375 SDLoc DL0(N0); 5376 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5377 N0.getOperand(0), 5378 DAG.getConstant(ShiftAmt, DL0, 5379 getShiftAmountTy(SmallVT))); 5380 AddToWorklist(SmallShift.getNode()); 5381 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 5382 SDLoc DL(N); 5383 return DAG.getNode(ISD::AND, DL, VT, 5384 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5385 DAG.getConstant(Mask, DL, VT)); 5386 } 5387 } 5388 5389 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5390 // bit, which is unmodified by sra. 5391 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5392 if (N0.getOpcode() == ISD::SRA) 5393 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5394 } 5395 5396 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5397 if (N1C && N0.getOpcode() == ISD::CTLZ && 5398 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5399 APInt KnownZero, KnownOne; 5400 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 5401 5402 // If any of the input bits are KnownOne, then the input couldn't be all 5403 // zeros, thus the result of the srl will always be zero. 5404 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5405 5406 // If all of the bits input the to ctlz node are known to be zero, then 5407 // the result of the ctlz is "32" and the result of the shift is one. 5408 APInt UnknownBits = ~KnownZero; 5409 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5410 5411 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5412 if ((UnknownBits & (UnknownBits - 1)) == 0) { 5413 // Okay, we know that only that the single bit specified by UnknownBits 5414 // could be set on input to the CTLZ node. If this bit is set, the SRL 5415 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5416 // to an SRL/XOR pair, which is likely to simplify more. 5417 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5418 SDValue Op = N0.getOperand(0); 5419 5420 if (ShAmt) { 5421 SDLoc DL(N0); 5422 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5423 DAG.getConstant(ShAmt, DL, 5424 getShiftAmountTy(Op.getValueType()))); 5425 AddToWorklist(Op.getNode()); 5426 } 5427 5428 SDLoc DL(N); 5429 return DAG.getNode(ISD::XOR, DL, VT, 5430 Op, DAG.getConstant(1, DL, VT)); 5431 } 5432 } 5433 5434 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5435 if (N1.getOpcode() == ISD::TRUNCATE && 5436 N1.getOperand(0).getOpcode() == ISD::AND) { 5437 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5438 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5439 } 5440 5441 // fold operands of srl based on knowledge that the low bits are not 5442 // demanded. 5443 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5444 return SDValue(N, 0); 5445 5446 if (N1C && !N1C->isOpaque()) 5447 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5448 return NewSRL; 5449 5450 // Attempt to convert a srl of a load into a narrower zero-extending load. 5451 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5452 return NarrowLoad; 5453 5454 // Here is a common situation. We want to optimize: 5455 // 5456 // %a = ... 5457 // %b = and i32 %a, 2 5458 // %c = srl i32 %b, 1 5459 // brcond i32 %c ... 5460 // 5461 // into 5462 // 5463 // %a = ... 5464 // %b = and %a, 2 5465 // %c = setcc eq %b, 0 5466 // brcond %c ... 5467 // 5468 // However when after the source operand of SRL is optimized into AND, the SRL 5469 // itself may not be optimized further. Look for it and add the BRCOND into 5470 // the worklist. 5471 if (N->hasOneUse()) { 5472 SDNode *Use = *N->use_begin(); 5473 if (Use->getOpcode() == ISD::BRCOND) 5474 AddToWorklist(Use); 5475 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5476 // Also look pass the truncate. 5477 Use = *Use->use_begin(); 5478 if (Use->getOpcode() == ISD::BRCOND) 5479 AddToWorklist(Use); 5480 } 5481 } 5482 5483 return SDValue(); 5484 } 5485 5486 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5487 SDValue N0 = N->getOperand(0); 5488 EVT VT = N->getValueType(0); 5489 5490 // fold (bswap c1) -> c2 5491 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5492 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5493 // fold (bswap (bswap x)) -> x 5494 if (N0.getOpcode() == ISD::BSWAP) 5495 return N0->getOperand(0); 5496 return SDValue(); 5497 } 5498 5499 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5500 SDValue N0 = N->getOperand(0); 5501 EVT VT = N->getValueType(0); 5502 5503 // fold (bitreverse c1) -> c2 5504 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5505 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 5506 // fold (bitreverse (bitreverse x)) -> x 5507 if (N0.getOpcode() == ISD::BITREVERSE) 5508 return N0.getOperand(0); 5509 return SDValue(); 5510 } 5511 5512 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5513 SDValue N0 = N->getOperand(0); 5514 EVT VT = N->getValueType(0); 5515 5516 // fold (ctlz c1) -> c2 5517 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5518 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5519 return SDValue(); 5520 } 5521 5522 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5523 SDValue N0 = N->getOperand(0); 5524 EVT VT = N->getValueType(0); 5525 5526 // fold (ctlz_zero_undef c1) -> c2 5527 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5528 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5529 return SDValue(); 5530 } 5531 5532 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5533 SDValue N0 = N->getOperand(0); 5534 EVT VT = N->getValueType(0); 5535 5536 // fold (cttz c1) -> c2 5537 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5538 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5539 return SDValue(); 5540 } 5541 5542 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5543 SDValue N0 = N->getOperand(0); 5544 EVT VT = N->getValueType(0); 5545 5546 // fold (cttz_zero_undef c1) -> c2 5547 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5548 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5549 return SDValue(); 5550 } 5551 5552 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5553 SDValue N0 = N->getOperand(0); 5554 EVT VT = N->getValueType(0); 5555 5556 // fold (ctpop c1) -> c2 5557 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5558 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5559 return SDValue(); 5560 } 5561 5562 5563 /// \brief Generate Min/Max node 5564 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5565 SDValue RHS, SDValue True, SDValue False, 5566 ISD::CondCode CC, const TargetLowering &TLI, 5567 SelectionDAG &DAG) { 5568 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5569 return SDValue(); 5570 5571 switch (CC) { 5572 case ISD::SETOLT: 5573 case ISD::SETOLE: 5574 case ISD::SETLT: 5575 case ISD::SETLE: 5576 case ISD::SETULT: 5577 case ISD::SETULE: { 5578 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5579 if (TLI.isOperationLegal(Opcode, VT)) 5580 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5581 return SDValue(); 5582 } 5583 case ISD::SETOGT: 5584 case ISD::SETOGE: 5585 case ISD::SETGT: 5586 case ISD::SETGE: 5587 case ISD::SETUGT: 5588 case ISD::SETUGE: { 5589 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5590 if (TLI.isOperationLegal(Opcode, VT)) 5591 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5592 return SDValue(); 5593 } 5594 default: 5595 return SDValue(); 5596 } 5597 } 5598 5599 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 5600 SDValue Cond = N->getOperand(0); 5601 SDValue N1 = N->getOperand(1); 5602 SDValue N2 = N->getOperand(2); 5603 EVT VT = N->getValueType(0); 5604 EVT CondVT = Cond.getValueType(); 5605 SDLoc DL(N); 5606 5607 if (!VT.isInteger()) 5608 return SDValue(); 5609 5610 if (!isa<ConstantSDNode>(N1) || !isa<ConstantSDNode>(N2)) 5611 return SDValue(); 5612 5613 // Only do this before legalization to avoid conflicting with target-specific 5614 // transforms in the other direction (create a select from a zext/sext). There 5615 // is also a target-independent combine here in DAGCombiner in the other 5616 // direction for (select Cond, -1, 0) when the condition is not i1. 5617 // TODO: This could be generalized for any 2 constants that differ by 1: 5618 // add ({s/z}ext Cond), C 5619 if (CondVT == MVT::i1 && !LegalOperations) { 5620 if (isNullConstant(N1) && isOneConstant(N2)) { 5621 // select Cond, 0, 1 --> zext (!Cond) 5622 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 5623 if (VT != MVT::i1) 5624 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 5625 return NotCond; 5626 } 5627 if (isNullConstant(N1) && isAllOnesConstant(N2)) { 5628 // select Cond, 0, -1 --> sext (!Cond) 5629 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 5630 if (VT != MVT::i1) 5631 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 5632 return NotCond; 5633 } 5634 if (isOneConstant(N1) && isNullConstant(N2)) { 5635 // select Cond, 1, 0 --> zext (Cond) 5636 if (VT != MVT::i1) 5637 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 5638 return Cond; 5639 } 5640 if (isAllOnesConstant(N1) && isNullConstant(N2)) { 5641 // select Cond, -1, 0 --> sext (Cond) 5642 if (VT != MVT::i1) 5643 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 5644 return Cond; 5645 } 5646 return SDValue(); 5647 } 5648 5649 // fold (select Cond, 0, 1) -> (xor Cond, 1) 5650 // We can't do this reliably if integer based booleans have different contents 5651 // to floating point based booleans. This is because we can't tell whether we 5652 // have an integer-based boolean or a floating-point-based boolean unless we 5653 // can find the SETCC that produced it and inspect its operands. This is 5654 // fairly easy if C is the SETCC node, but it can potentially be 5655 // undiscoverable (or not reasonably discoverable). For example, it could be 5656 // in another basic block or it could require searching a complicated 5657 // expression. 5658 if (CondVT.isInteger() && 5659 TLI.getBooleanContents(false, true) == 5660 TargetLowering::ZeroOrOneBooleanContent && 5661 TLI.getBooleanContents(false, false) == 5662 TargetLowering::ZeroOrOneBooleanContent && 5663 isNullConstant(N1) && isOneConstant(N2)) { 5664 SDValue NotCond = 5665 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 5666 if (VT.bitsEq(CondVT)) 5667 return NotCond; 5668 return DAG.getZExtOrTrunc(NotCond, DL, VT); 5669 } 5670 5671 return SDValue(); 5672 } 5673 5674 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5675 SDValue N0 = N->getOperand(0); 5676 SDValue N1 = N->getOperand(1); 5677 SDValue N2 = N->getOperand(2); 5678 EVT VT = N->getValueType(0); 5679 EVT VT0 = N0.getValueType(); 5680 5681 // fold (select C, X, X) -> X 5682 if (N1 == N2) 5683 return N1; 5684 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5685 // fold (select true, X, Y) -> X 5686 // fold (select false, X, Y) -> Y 5687 return !N0C->isNullValue() ? N1 : N2; 5688 } 5689 // fold (select X, X, Y) -> (or X, Y) 5690 // fold (select X, 1, Y) -> (or C, Y) 5691 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5692 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5693 5694 if (SDValue V = foldSelectOfConstants(N)) 5695 return V; 5696 5697 // fold (select C, 0, X) -> (and (not C), X) 5698 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5699 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5700 AddToWorklist(NOTNode.getNode()); 5701 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5702 } 5703 // fold (select C, X, 1) -> (or (not C), X) 5704 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5705 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5706 AddToWorklist(NOTNode.getNode()); 5707 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5708 } 5709 // fold (select X, Y, X) -> (and X, Y) 5710 // fold (select X, Y, 0) -> (and X, Y) 5711 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5712 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5713 5714 // If we can fold this based on the true/false value, do so. 5715 if (SimplifySelectOps(N, N1, N2)) 5716 return SDValue(N, 0); // Don't revisit N. 5717 5718 if (VT0 == MVT::i1) { 5719 // The code in this block deals with the following 2 equivalences: 5720 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5721 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5722 // The target can specify its preferred form with the 5723 // shouldNormalizeToSelectSequence() callback. However we always transform 5724 // to the right anyway if we find the inner select exists in the DAG anyway 5725 // and we always transform to the left side if we know that we can further 5726 // optimize the combination of the conditions. 5727 bool normalizeToSequence 5728 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5729 // select (and Cond0, Cond1), X, Y 5730 // -> select Cond0, (select Cond1, X, Y), Y 5731 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5732 SDValue Cond0 = N0->getOperand(0); 5733 SDValue Cond1 = N0->getOperand(1); 5734 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5735 N1.getValueType(), Cond1, N1, N2); 5736 if (normalizeToSequence || !InnerSelect.use_empty()) 5737 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5738 InnerSelect, N2); 5739 } 5740 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5741 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5742 SDValue Cond0 = N0->getOperand(0); 5743 SDValue Cond1 = N0->getOperand(1); 5744 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5745 N1.getValueType(), Cond1, N1, N2); 5746 if (normalizeToSequence || !InnerSelect.use_empty()) 5747 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5748 InnerSelect); 5749 } 5750 5751 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5752 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5753 SDValue N1_0 = N1->getOperand(0); 5754 SDValue N1_1 = N1->getOperand(1); 5755 SDValue N1_2 = N1->getOperand(2); 5756 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5757 // Create the actual and node if we can generate good code for it. 5758 if (!normalizeToSequence) { 5759 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5760 N0, N1_0); 5761 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5762 N1_1, N2); 5763 } 5764 // Otherwise see if we can optimize the "and" to a better pattern. 5765 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5766 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5767 N1_1, N2); 5768 } 5769 } 5770 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5771 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5772 SDValue N2_0 = N2->getOperand(0); 5773 SDValue N2_1 = N2->getOperand(1); 5774 SDValue N2_2 = N2->getOperand(2); 5775 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5776 // Create the actual or node if we can generate good code for it. 5777 if (!normalizeToSequence) { 5778 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5779 N0, N2_0); 5780 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5781 N1, N2_2); 5782 } 5783 // Otherwise see if we can optimize to a better pattern. 5784 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5785 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5786 N1, N2_2); 5787 } 5788 } 5789 } 5790 5791 // select (xor Cond, 1), X, Y -> select Cond, Y, X 5792 if (VT0 == MVT::i1) { 5793 if (N0->getOpcode() == ISD::XOR) { 5794 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 5795 SDValue Cond0 = N0->getOperand(0); 5796 if (C->isOne()) 5797 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 5798 Cond0, N2, N1); 5799 } 5800 } 5801 } 5802 5803 // fold selects based on a setcc into other things, such as min/max/abs 5804 if (N0.getOpcode() == ISD::SETCC) { 5805 // select x, y (fcmp lt x, y) -> fminnum x, y 5806 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5807 // 5808 // This is OK if we don't care about what happens if either operand is a 5809 // NaN. 5810 // 5811 5812 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5813 // no signed zeros as well as no nans. 5814 const TargetOptions &Options = DAG.getTarget().Options; 5815 if (Options.UnsafeFPMath && 5816 VT.isFloatingPoint() && N0.hasOneUse() && 5817 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5818 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5819 5820 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5821 N0.getOperand(1), N1, N2, CC, 5822 TLI, DAG)) 5823 return FMinMax; 5824 } 5825 5826 if ((!LegalOperations && 5827 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5828 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5829 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5830 N0.getOperand(0), N0.getOperand(1), 5831 N1, N2, N0.getOperand(2)); 5832 return SimplifySelect(SDLoc(N), N0, N1, N2); 5833 } 5834 5835 return SDValue(); 5836 } 5837 5838 static 5839 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5840 SDLoc DL(N); 5841 EVT LoVT, HiVT; 5842 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5843 5844 // Split the inputs. 5845 SDValue Lo, Hi, LL, LH, RL, RH; 5846 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5847 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5848 5849 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5850 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5851 5852 return std::make_pair(Lo, Hi); 5853 } 5854 5855 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5856 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5857 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5858 SDLoc DL(N); 5859 SDValue Cond = N->getOperand(0); 5860 SDValue LHS = N->getOperand(1); 5861 SDValue RHS = N->getOperand(2); 5862 EVT VT = N->getValueType(0); 5863 int NumElems = VT.getVectorNumElements(); 5864 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5865 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5866 Cond.getOpcode() == ISD::BUILD_VECTOR); 5867 5868 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5869 // binary ones here. 5870 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5871 return SDValue(); 5872 5873 // We're sure we have an even number of elements due to the 5874 // concat_vectors we have as arguments to vselect. 5875 // Skip BV elements until we find one that's not an UNDEF 5876 // After we find an UNDEF element, keep looping until we get to half the 5877 // length of the BV and see if all the non-undef nodes are the same. 5878 ConstantSDNode *BottomHalf = nullptr; 5879 for (int i = 0; i < NumElems / 2; ++i) { 5880 if (Cond->getOperand(i)->isUndef()) 5881 continue; 5882 5883 if (BottomHalf == nullptr) 5884 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5885 else if (Cond->getOperand(i).getNode() != BottomHalf) 5886 return SDValue(); 5887 } 5888 5889 // Do the same for the second half of the BuildVector 5890 ConstantSDNode *TopHalf = nullptr; 5891 for (int i = NumElems / 2; i < NumElems; ++i) { 5892 if (Cond->getOperand(i)->isUndef()) 5893 continue; 5894 5895 if (TopHalf == nullptr) 5896 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5897 else if (Cond->getOperand(i).getNode() != TopHalf) 5898 return SDValue(); 5899 } 5900 5901 assert(TopHalf && BottomHalf && 5902 "One half of the selector was all UNDEFs and the other was all the " 5903 "same value. This should have been addressed before this function."); 5904 return DAG.getNode( 5905 ISD::CONCAT_VECTORS, DL, VT, 5906 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5907 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5908 } 5909 5910 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5911 5912 if (Level >= AfterLegalizeTypes) 5913 return SDValue(); 5914 5915 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5916 SDValue Mask = MSC->getMask(); 5917 SDValue Data = MSC->getValue(); 5918 SDLoc DL(N); 5919 5920 // If the MSCATTER data type requires splitting and the mask is provided by a 5921 // SETCC, then split both nodes and its operands before legalization. This 5922 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5923 // and enables future optimizations (e.g. min/max pattern matching on X86). 5924 if (Mask.getOpcode() != ISD::SETCC) 5925 return SDValue(); 5926 5927 // Check if any splitting is required. 5928 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5929 TargetLowering::TypeSplitVector) 5930 return SDValue(); 5931 SDValue MaskLo, MaskHi, Lo, Hi; 5932 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5933 5934 EVT LoVT, HiVT; 5935 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5936 5937 SDValue Chain = MSC->getChain(); 5938 5939 EVT MemoryVT = MSC->getMemoryVT(); 5940 unsigned Alignment = MSC->getOriginalAlignment(); 5941 5942 EVT LoMemVT, HiMemVT; 5943 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5944 5945 SDValue DataLo, DataHi; 5946 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5947 5948 SDValue BasePtr = MSC->getBasePtr(); 5949 SDValue IndexLo, IndexHi; 5950 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5951 5952 MachineMemOperand *MMO = DAG.getMachineFunction(). 5953 getMachineMemOperand(MSC->getPointerInfo(), 5954 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5955 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5956 5957 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5958 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5959 DL, OpsLo, MMO); 5960 5961 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5962 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5963 DL, OpsHi, MMO); 5964 5965 AddToWorklist(Lo.getNode()); 5966 AddToWorklist(Hi.getNode()); 5967 5968 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5969 } 5970 5971 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5972 5973 if (Level >= AfterLegalizeTypes) 5974 return SDValue(); 5975 5976 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5977 SDValue Mask = MST->getMask(); 5978 SDValue Data = MST->getValue(); 5979 EVT VT = Data.getValueType(); 5980 SDLoc DL(N); 5981 5982 // If the MSTORE data type requires splitting and the mask is provided by a 5983 // SETCC, then split both nodes and its operands before legalization. This 5984 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5985 // and enables future optimizations (e.g. min/max pattern matching on X86). 5986 if (Mask.getOpcode() == ISD::SETCC) { 5987 5988 // Check if any splitting is required. 5989 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5990 TargetLowering::TypeSplitVector) 5991 return SDValue(); 5992 5993 SDValue MaskLo, MaskHi, Lo, Hi; 5994 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5995 5996 SDValue Chain = MST->getChain(); 5997 SDValue Ptr = MST->getBasePtr(); 5998 5999 EVT MemoryVT = MST->getMemoryVT(); 6000 unsigned Alignment = MST->getOriginalAlignment(); 6001 6002 // if Alignment is equal to the vector size, 6003 // take the half of it for the second part 6004 unsigned SecondHalfAlignment = 6005 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6006 6007 EVT LoMemVT, HiMemVT; 6008 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6009 6010 SDValue DataLo, DataHi; 6011 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6012 6013 MachineMemOperand *MMO = DAG.getMachineFunction(). 6014 getMachineMemOperand(MST->getPointerInfo(), 6015 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6016 Alignment, MST->getAAInfo(), MST->getRanges()); 6017 6018 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6019 MST->isTruncatingStore(), 6020 MST->isCompressingStore()); 6021 6022 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6023 MST->isCompressingStore()); 6024 6025 MMO = DAG.getMachineFunction(). 6026 getMachineMemOperand(MST->getPointerInfo(), 6027 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6028 SecondHalfAlignment, MST->getAAInfo(), 6029 MST->getRanges()); 6030 6031 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6032 MST->isTruncatingStore(), 6033 MST->isCompressingStore()); 6034 6035 AddToWorklist(Lo.getNode()); 6036 AddToWorklist(Hi.getNode()); 6037 6038 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6039 } 6040 return SDValue(); 6041 } 6042 6043 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6044 6045 if (Level >= AfterLegalizeTypes) 6046 return SDValue(); 6047 6048 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 6049 SDValue Mask = MGT->getMask(); 6050 SDLoc DL(N); 6051 6052 // If the MGATHER result requires splitting and the mask is provided by a 6053 // SETCC, then split both nodes and its operands before legalization. This 6054 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6055 // and enables future optimizations (e.g. min/max pattern matching on X86). 6056 6057 if (Mask.getOpcode() != ISD::SETCC) 6058 return SDValue(); 6059 6060 EVT VT = N->getValueType(0); 6061 6062 // Check if any splitting is required. 6063 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6064 TargetLowering::TypeSplitVector) 6065 return SDValue(); 6066 6067 SDValue MaskLo, MaskHi, Lo, Hi; 6068 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6069 6070 SDValue Src0 = MGT->getValue(); 6071 SDValue Src0Lo, Src0Hi; 6072 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6073 6074 EVT LoVT, HiVT; 6075 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6076 6077 SDValue Chain = MGT->getChain(); 6078 EVT MemoryVT = MGT->getMemoryVT(); 6079 unsigned Alignment = MGT->getOriginalAlignment(); 6080 6081 EVT LoMemVT, HiMemVT; 6082 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6083 6084 SDValue BasePtr = MGT->getBasePtr(); 6085 SDValue Index = MGT->getIndex(); 6086 SDValue IndexLo, IndexHi; 6087 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6088 6089 MachineMemOperand *MMO = DAG.getMachineFunction(). 6090 getMachineMemOperand(MGT->getPointerInfo(), 6091 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6092 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6093 6094 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6095 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6096 MMO); 6097 6098 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6099 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6100 MMO); 6101 6102 AddToWorklist(Lo.getNode()); 6103 AddToWorklist(Hi.getNode()); 6104 6105 // Build a factor node to remember that this load is independent of the 6106 // other one. 6107 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6108 Hi.getValue(1)); 6109 6110 // Legalized the chain result - switch anything that used the old chain to 6111 // use the new one. 6112 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6113 6114 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6115 6116 SDValue RetOps[] = { GatherRes, Chain }; 6117 return DAG.getMergeValues(RetOps, DL); 6118 } 6119 6120 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6121 6122 if (Level >= AfterLegalizeTypes) 6123 return SDValue(); 6124 6125 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6126 SDValue Mask = MLD->getMask(); 6127 SDLoc DL(N); 6128 6129 // If the MLOAD result requires splitting and the mask is provided by a 6130 // SETCC, then split both nodes and its operands before legalization. This 6131 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6132 // and enables future optimizations (e.g. min/max pattern matching on X86). 6133 6134 if (Mask.getOpcode() == ISD::SETCC) { 6135 EVT VT = N->getValueType(0); 6136 6137 // Check if any splitting is required. 6138 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6139 TargetLowering::TypeSplitVector) 6140 return SDValue(); 6141 6142 SDValue MaskLo, MaskHi, Lo, Hi; 6143 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6144 6145 SDValue Src0 = MLD->getSrc0(); 6146 SDValue Src0Lo, Src0Hi; 6147 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6148 6149 EVT LoVT, HiVT; 6150 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6151 6152 SDValue Chain = MLD->getChain(); 6153 SDValue Ptr = MLD->getBasePtr(); 6154 EVT MemoryVT = MLD->getMemoryVT(); 6155 unsigned Alignment = MLD->getOriginalAlignment(); 6156 6157 // if Alignment is equal to the vector size, 6158 // take the half of it for the second part 6159 unsigned SecondHalfAlignment = 6160 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6161 Alignment/2 : Alignment; 6162 6163 EVT LoMemVT, HiMemVT; 6164 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6165 6166 MachineMemOperand *MMO = DAG.getMachineFunction(). 6167 getMachineMemOperand(MLD->getPointerInfo(), 6168 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6169 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6170 6171 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6172 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6173 6174 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6175 MLD->isExpandingLoad()); 6176 6177 MMO = DAG.getMachineFunction(). 6178 getMachineMemOperand(MLD->getPointerInfo(), 6179 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6180 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6181 6182 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6183 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6184 6185 AddToWorklist(Lo.getNode()); 6186 AddToWorklist(Hi.getNode()); 6187 6188 // Build a factor node to remember that this load is independent of the 6189 // other one. 6190 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6191 Hi.getValue(1)); 6192 6193 // Legalized the chain result - switch anything that used the old chain to 6194 // use the new one. 6195 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6196 6197 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6198 6199 SDValue RetOps[] = { LoadRes, Chain }; 6200 return DAG.getMergeValues(RetOps, DL); 6201 } 6202 return SDValue(); 6203 } 6204 6205 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6206 SDValue N0 = N->getOperand(0); 6207 SDValue N1 = N->getOperand(1); 6208 SDValue N2 = N->getOperand(2); 6209 SDLoc DL(N); 6210 6211 // fold (vselect C, X, X) -> X 6212 if (N1 == N2) 6213 return N1; 6214 6215 // Canonicalize integer abs. 6216 // vselect (setg[te] X, 0), X, -X -> 6217 // vselect (setgt X, -1), X, -X -> 6218 // vselect (setl[te] X, 0), -X, X -> 6219 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6220 if (N0.getOpcode() == ISD::SETCC) { 6221 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6222 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6223 bool isAbs = false; 6224 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6225 6226 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6227 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6228 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6229 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6230 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6231 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6232 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6233 6234 if (isAbs) { 6235 EVT VT = LHS.getValueType(); 6236 SDValue Shift = DAG.getNode( 6237 ISD::SRA, DL, VT, LHS, 6238 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6239 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6240 AddToWorklist(Shift.getNode()); 6241 AddToWorklist(Add.getNode()); 6242 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6243 } 6244 } 6245 6246 if (SimplifySelectOps(N, N1, N2)) 6247 return SDValue(N, 0); // Don't revisit N. 6248 6249 // If the VSELECT result requires splitting and the mask is provided by a 6250 // SETCC, then split both nodes and its operands before legalization. This 6251 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6252 // and enables future optimizations (e.g. min/max pattern matching on X86). 6253 if (N0.getOpcode() == ISD::SETCC) { 6254 EVT VT = N->getValueType(0); 6255 6256 // Check if any splitting is required. 6257 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6258 TargetLowering::TypeSplitVector) 6259 return SDValue(); 6260 6261 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 6262 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 6263 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 6264 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 6265 6266 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 6267 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 6268 6269 // Add the new VSELECT nodes to the work list in case they need to be split 6270 // again. 6271 AddToWorklist(Lo.getNode()); 6272 AddToWorklist(Hi.getNode()); 6273 6274 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6275 } 6276 6277 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6278 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6279 return N1; 6280 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6281 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6282 return N2; 6283 6284 // The ConvertSelectToConcatVector function is assuming both the above 6285 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6286 // and addressed. 6287 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6288 N2.getOpcode() == ISD::CONCAT_VECTORS && 6289 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6290 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6291 return CV; 6292 } 6293 6294 return SDValue(); 6295 } 6296 6297 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6298 SDValue N0 = N->getOperand(0); 6299 SDValue N1 = N->getOperand(1); 6300 SDValue N2 = N->getOperand(2); 6301 SDValue N3 = N->getOperand(3); 6302 SDValue N4 = N->getOperand(4); 6303 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6304 6305 // fold select_cc lhs, rhs, x, x, cc -> x 6306 if (N2 == N3) 6307 return N2; 6308 6309 // Determine if the condition we're dealing with is constant 6310 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6311 CC, SDLoc(N), false)) { 6312 AddToWorklist(SCC.getNode()); 6313 6314 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6315 if (!SCCC->isNullValue()) 6316 return N2; // cond always true -> true val 6317 else 6318 return N3; // cond always false -> false val 6319 } else if (SCC->isUndef()) { 6320 // When the condition is UNDEF, just return the first operand. This is 6321 // coherent the DAG creation, no setcc node is created in this case 6322 return N2; 6323 } else if (SCC.getOpcode() == ISD::SETCC) { 6324 // Fold to a simpler select_cc 6325 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6326 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6327 SCC.getOperand(2)); 6328 } 6329 } 6330 6331 // If we can fold this based on the true/false value, do so. 6332 if (SimplifySelectOps(N, N2, N3)) 6333 return SDValue(N, 0); // Don't revisit N. 6334 6335 // fold select_cc into other things, such as min/max/abs 6336 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6337 } 6338 6339 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6340 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6341 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6342 SDLoc(N)); 6343 } 6344 6345 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6346 SDValue LHS = N->getOperand(0); 6347 SDValue RHS = N->getOperand(1); 6348 SDValue Carry = N->getOperand(2); 6349 SDValue Cond = N->getOperand(3); 6350 6351 // If Carry is false, fold to a regular SETCC. 6352 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6353 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6354 6355 return SDValue(); 6356 } 6357 6358 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6359 /// a build_vector of constants. 6360 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6361 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6362 /// Vector extends are not folded if operations are legal; this is to 6363 /// avoid introducing illegal build_vector dag nodes. 6364 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6365 SelectionDAG &DAG, bool LegalTypes, 6366 bool LegalOperations) { 6367 unsigned Opcode = N->getOpcode(); 6368 SDValue N0 = N->getOperand(0); 6369 EVT VT = N->getValueType(0); 6370 6371 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6372 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6373 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6374 && "Expected EXTEND dag node in input!"); 6375 6376 // fold (sext c1) -> c1 6377 // fold (zext c1) -> c1 6378 // fold (aext c1) -> c1 6379 if (isa<ConstantSDNode>(N0)) 6380 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6381 6382 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6383 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6384 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6385 EVT SVT = VT.getScalarType(); 6386 if (!(VT.isVector() && 6387 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6388 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6389 return nullptr; 6390 6391 // We can fold this node into a build_vector. 6392 unsigned VTBits = SVT.getSizeInBits(); 6393 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6394 SmallVector<SDValue, 8> Elts; 6395 unsigned NumElts = VT.getVectorNumElements(); 6396 SDLoc DL(N); 6397 6398 for (unsigned i=0; i != NumElts; ++i) { 6399 SDValue Op = N0->getOperand(i); 6400 if (Op->isUndef()) { 6401 Elts.push_back(DAG.getUNDEF(SVT)); 6402 continue; 6403 } 6404 6405 SDLoc DL(Op); 6406 // Get the constant value and if needed trunc it to the size of the type. 6407 // Nodes like build_vector might have constants wider than the scalar type. 6408 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6409 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6410 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6411 else 6412 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6413 } 6414 6415 return DAG.getBuildVector(VT, DL, Elts).getNode(); 6416 } 6417 6418 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 6419 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 6420 // transformation. Returns true if extension are possible and the above 6421 // mentioned transformation is profitable. 6422 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 6423 unsigned ExtOpc, 6424 SmallVectorImpl<SDNode *> &ExtendNodes, 6425 const TargetLowering &TLI) { 6426 bool HasCopyToRegUses = false; 6427 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 6428 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 6429 UE = N0.getNode()->use_end(); 6430 UI != UE; ++UI) { 6431 SDNode *User = *UI; 6432 if (User == N) 6433 continue; 6434 if (UI.getUse().getResNo() != N0.getResNo()) 6435 continue; 6436 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6437 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6438 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6439 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6440 // Sign bits will be lost after a zext. 6441 return false; 6442 bool Add = false; 6443 for (unsigned i = 0; i != 2; ++i) { 6444 SDValue UseOp = User->getOperand(i); 6445 if (UseOp == N0) 6446 continue; 6447 if (!isa<ConstantSDNode>(UseOp)) 6448 return false; 6449 Add = true; 6450 } 6451 if (Add) 6452 ExtendNodes.push_back(User); 6453 continue; 6454 } 6455 // If truncates aren't free and there are users we can't 6456 // extend, it isn't worthwhile. 6457 if (!isTruncFree) 6458 return false; 6459 // Remember if this value is live-out. 6460 if (User->getOpcode() == ISD::CopyToReg) 6461 HasCopyToRegUses = true; 6462 } 6463 6464 if (HasCopyToRegUses) { 6465 bool BothLiveOut = false; 6466 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6467 UI != UE; ++UI) { 6468 SDUse &Use = UI.getUse(); 6469 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6470 BothLiveOut = true; 6471 break; 6472 } 6473 } 6474 if (BothLiveOut) 6475 // Both unextended and extended values are live out. There had better be 6476 // a good reason for the transformation. 6477 return ExtendNodes.size(); 6478 } 6479 return true; 6480 } 6481 6482 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 6483 SDValue Trunc, SDValue ExtLoad, 6484 const SDLoc &DL, ISD::NodeType ExtType) { 6485 // Extend SetCC uses if necessary. 6486 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 6487 SDNode *SetCC = SetCCs[i]; 6488 SmallVector<SDValue, 4> Ops; 6489 6490 for (unsigned j = 0; j != 2; ++j) { 6491 SDValue SOp = SetCC->getOperand(j); 6492 if (SOp == Trunc) 6493 Ops.push_back(ExtLoad); 6494 else 6495 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 6496 } 6497 6498 Ops.push_back(SetCC->getOperand(2)); 6499 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6500 } 6501 } 6502 6503 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 6504 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 6505 SDValue N0 = N->getOperand(0); 6506 EVT DstVT = N->getValueType(0); 6507 EVT SrcVT = N0.getValueType(); 6508 6509 assert((N->getOpcode() == ISD::SIGN_EXTEND || 6510 N->getOpcode() == ISD::ZERO_EXTEND) && 6511 "Unexpected node type (not an extend)!"); 6512 6513 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 6514 // For example, on a target with legal v4i32, but illegal v8i32, turn: 6515 // (v8i32 (sext (v8i16 (load x)))) 6516 // into: 6517 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6518 // (v4i32 (sextload (x + 16))))) 6519 // Where uses of the original load, i.e.: 6520 // (v8i16 (load x)) 6521 // are replaced with: 6522 // (v8i16 (truncate 6523 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6524 // (v4i32 (sextload (x + 16))))))) 6525 // 6526 // This combine is only applicable to illegal, but splittable, vectors. 6527 // All legal types, and illegal non-vector types, are handled elsewhere. 6528 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 6529 // 6530 if (N0->getOpcode() != ISD::LOAD) 6531 return SDValue(); 6532 6533 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6534 6535 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 6536 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 6537 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 6538 return SDValue(); 6539 6540 SmallVector<SDNode *, 4> SetCCs; 6541 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 6542 return SDValue(); 6543 6544 ISD::LoadExtType ExtType = 6545 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 6546 6547 // Try to split the vector types to get down to legal types. 6548 EVT SplitSrcVT = SrcVT; 6549 EVT SplitDstVT = DstVT; 6550 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 6551 SplitSrcVT.getVectorNumElements() > 1) { 6552 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 6553 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 6554 } 6555 6556 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 6557 return SDValue(); 6558 6559 SDLoc DL(N); 6560 const unsigned NumSplits = 6561 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 6562 const unsigned Stride = SplitSrcVT.getStoreSize(); 6563 SmallVector<SDValue, 4> Loads; 6564 SmallVector<SDValue, 4> Chains; 6565 6566 SDValue BasePtr = LN0->getBasePtr(); 6567 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6568 const unsigned Offset = Idx * Stride; 6569 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 6570 6571 SDValue SplitLoad = DAG.getExtLoad( 6572 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 6573 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 6574 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6575 6576 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6577 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6578 6579 Loads.push_back(SplitLoad.getValue(0)); 6580 Chains.push_back(SplitLoad.getValue(1)); 6581 } 6582 6583 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6584 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6585 6586 CombineTo(N, NewValue); 6587 6588 // Replace uses of the original load (before extension) 6589 // with a truncate of the concatenated sextloaded vectors. 6590 SDValue Trunc = 6591 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6592 CombineTo(N0.getNode(), Trunc, NewChain); 6593 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6594 (ISD::NodeType)N->getOpcode()); 6595 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6596 } 6597 6598 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6599 SDValue N0 = N->getOperand(0); 6600 EVT VT = N->getValueType(0); 6601 SDLoc DL(N); 6602 6603 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6604 LegalOperations)) 6605 return SDValue(Res, 0); 6606 6607 // fold (sext (sext x)) -> (sext x) 6608 // fold (sext (aext x)) -> (sext x) 6609 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6610 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 6611 6612 if (N0.getOpcode() == ISD::TRUNCATE) { 6613 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6614 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6615 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6616 SDNode *oye = N0.getOperand(0).getNode(); 6617 if (NarrowLoad.getNode() != N0.getNode()) { 6618 CombineTo(N0.getNode(), NarrowLoad); 6619 // CombineTo deleted the truncate, if needed, but not what's under it. 6620 AddToWorklist(oye); 6621 } 6622 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6623 } 6624 6625 // See if the value being truncated is already sign extended. If so, just 6626 // eliminate the trunc/sext pair. 6627 SDValue Op = N0.getOperand(0); 6628 unsigned OpBits = Op.getScalarValueSizeInBits(); 6629 unsigned MidBits = N0.getScalarValueSizeInBits(); 6630 unsigned DestBits = VT.getScalarSizeInBits(); 6631 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6632 6633 if (OpBits == DestBits) { 6634 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6635 // bits, it is already ready. 6636 if (NumSignBits > DestBits-MidBits) 6637 return Op; 6638 } else if (OpBits < DestBits) { 6639 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6640 // bits, just sext from i32. 6641 if (NumSignBits > OpBits-MidBits) 6642 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 6643 } else { 6644 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6645 // bits, just truncate to i32. 6646 if (NumSignBits > OpBits-MidBits) 6647 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 6648 } 6649 6650 // fold (sext (truncate x)) -> (sextinreg x). 6651 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6652 N0.getValueType())) { 6653 if (OpBits < DestBits) 6654 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6655 else if (OpBits > DestBits) 6656 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6657 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 6658 DAG.getValueType(N0.getValueType())); 6659 } 6660 } 6661 6662 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6663 // Only generate vector extloads when 1) they're legal, and 2) they are 6664 // deemed desirable by the target. 6665 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6666 ((!LegalOperations && !VT.isVector() && 6667 !cast<LoadSDNode>(N0)->isVolatile()) || 6668 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6669 bool DoXform = true; 6670 SmallVector<SDNode*, 4> SetCCs; 6671 if (!N0.hasOneUse()) 6672 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6673 if (VT.isVector()) 6674 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6675 if (DoXform) { 6676 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6677 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 6678 LN0->getBasePtr(), N0.getValueType(), 6679 LN0->getMemOperand()); 6680 CombineTo(N, ExtLoad); 6681 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6682 N0.getValueType(), ExtLoad); 6683 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6684 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 6685 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6686 } 6687 } 6688 6689 // fold (sext (load x)) to multiple smaller sextloads. 6690 // Only on illegal but splittable vectors. 6691 if (SDValue ExtLoad = CombineExtLoad(N)) 6692 return ExtLoad; 6693 6694 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6695 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6696 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6697 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6698 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6699 EVT MemVT = LN0->getMemoryVT(); 6700 if ((!LegalOperations && !LN0->isVolatile()) || 6701 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6702 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 6703 LN0->getBasePtr(), MemVT, 6704 LN0->getMemOperand()); 6705 CombineTo(N, ExtLoad); 6706 CombineTo(N0.getNode(), 6707 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6708 N0.getValueType(), ExtLoad), 6709 ExtLoad.getValue(1)); 6710 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6711 } 6712 } 6713 6714 // fold (sext (and/or/xor (load x), cst)) -> 6715 // (and/or/xor (sextload x), (sext cst)) 6716 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6717 N0.getOpcode() == ISD::XOR) && 6718 isa<LoadSDNode>(N0.getOperand(0)) && 6719 N0.getOperand(1).getOpcode() == ISD::Constant && 6720 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6721 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6722 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6723 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6724 bool DoXform = true; 6725 SmallVector<SDNode*, 4> SetCCs; 6726 if (!N0.hasOneUse()) 6727 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6728 SetCCs, TLI); 6729 if (DoXform) { 6730 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6731 LN0->getChain(), LN0->getBasePtr(), 6732 LN0->getMemoryVT(), 6733 LN0->getMemOperand()); 6734 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6735 Mask = Mask.sext(VT.getSizeInBits()); 6736 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6737 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6738 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6739 SDLoc(N0.getOperand(0)), 6740 N0.getOperand(0).getValueType(), ExtLoad); 6741 CombineTo(N, And); 6742 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6743 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 6744 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6745 } 6746 } 6747 } 6748 6749 if (N0.getOpcode() == ISD::SETCC) { 6750 SDValue N00 = N0.getOperand(0); 6751 SDValue N01 = N0.getOperand(1); 6752 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6753 EVT N00VT = N0.getOperand(0).getValueType(); 6754 6755 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6756 // Only do this before legalize for now. 6757 if (VT.isVector() && !LegalOperations && 6758 TLI.getBooleanContents(N00VT) == 6759 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6760 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6761 // of the same size as the compared operands. Only optimize sext(setcc()) 6762 // if this is the case. 6763 EVT SVT = getSetCCResultType(N00VT); 6764 6765 // We know that the # elements of the results is the same as the 6766 // # elements of the compare (and the # elements of the compare result 6767 // for that matter). Check to see that they are the same size. If so, 6768 // we know that the element size of the sext'd result matches the 6769 // element size of the compare operands. 6770 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6771 return DAG.getSetCC(DL, VT, N00, N01, CC); 6772 6773 // If the desired elements are smaller or larger than the source 6774 // elements, we can use a matching integer vector type and then 6775 // truncate/sign extend. 6776 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 6777 if (SVT == MatchingVecType) { 6778 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 6779 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 6780 } 6781 } 6782 6783 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 6784 // Here, T can be 1 or -1, depending on the type of the setcc and 6785 // getBooleanContents(). 6786 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 6787 6788 // To determine the "true" side of the select, we need to know the high bit 6789 // of the value returned by the setcc if it evaluates to true. 6790 // If the type of the setcc is i1, then the true case of the select is just 6791 // sext(i1 1), that is, -1. 6792 // If the type of the setcc is larger (say, i8) then the value of the high 6793 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 6794 // of the appropriate width. 6795 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 6796 : TLI.getConstTrueVal(DAG, VT, DL); 6797 SDValue Zero = DAG.getConstant(0, DL, VT); 6798 if (SDValue SCC = 6799 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 6800 return SCC; 6801 6802 if (!VT.isVector()) { 6803 EVT SetCCVT = getSetCCResultType(N00VT); 6804 // Don't do this transform for i1 because there's a select transform 6805 // that would reverse it. 6806 // TODO: We should not do this transform at all without a target hook 6807 // because a sext is likely cheaper than a select? 6808 if (SetCCVT.getScalarSizeInBits() != 1 && 6809 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 6810 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 6811 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 6812 } 6813 } 6814 } 6815 6816 // fold (sext x) -> (zext x) if the sign bit is known zero. 6817 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6818 DAG.SignBitIsZero(N0)) 6819 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 6820 6821 return SDValue(); 6822 } 6823 6824 // isTruncateOf - If N is a truncate of some other value, return true, record 6825 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6826 // This function computes KnownZero to avoid a duplicated call to 6827 // computeKnownBits in the caller. 6828 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6829 APInt &KnownZero) { 6830 APInt KnownOne; 6831 if (N->getOpcode() == ISD::TRUNCATE) { 6832 Op = N->getOperand(0); 6833 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6834 return true; 6835 } 6836 6837 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6838 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6839 return false; 6840 6841 SDValue Op0 = N->getOperand(0); 6842 SDValue Op1 = N->getOperand(1); 6843 assert(Op0.getValueType() == Op1.getValueType()); 6844 6845 if (isNullConstant(Op0)) 6846 Op = Op1; 6847 else if (isNullConstant(Op1)) 6848 Op = Op0; 6849 else 6850 return false; 6851 6852 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6853 6854 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6855 return false; 6856 6857 return true; 6858 } 6859 6860 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6861 SDValue N0 = N->getOperand(0); 6862 EVT VT = N->getValueType(0); 6863 6864 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6865 LegalOperations)) 6866 return SDValue(Res, 0); 6867 6868 // fold (zext (zext x)) -> (zext x) 6869 // fold (zext (aext x)) -> (zext x) 6870 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6871 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6872 N0.getOperand(0)); 6873 6874 // fold (zext (truncate x)) -> (zext x) or 6875 // (zext (truncate x)) -> (truncate x) 6876 // This is valid when the truncated bits of x are already zero. 6877 // FIXME: We should extend this to work for vectors too. 6878 SDValue Op; 6879 APInt KnownZero; 6880 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6881 APInt TruncatedBits = 6882 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6883 APInt(Op.getValueSizeInBits(), 0) : 6884 APInt::getBitsSet(Op.getValueSizeInBits(), 6885 N0.getValueSizeInBits(), 6886 std::min(Op.getValueSizeInBits(), 6887 VT.getSizeInBits())); 6888 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6889 if (VT.bitsGT(Op.getValueType())) 6890 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6891 if (VT.bitsLT(Op.getValueType())) 6892 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6893 6894 return Op; 6895 } 6896 } 6897 6898 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6899 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6900 if (N0.getOpcode() == ISD::TRUNCATE) { 6901 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6902 SDNode *oye = N0.getOperand(0).getNode(); 6903 if (NarrowLoad.getNode() != N0.getNode()) { 6904 CombineTo(N0.getNode(), NarrowLoad); 6905 // CombineTo deleted the truncate, if needed, but not what's under it. 6906 AddToWorklist(oye); 6907 } 6908 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6909 } 6910 } 6911 6912 // fold (zext (truncate x)) -> (and x, mask) 6913 if (N0.getOpcode() == ISD::TRUNCATE) { 6914 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6915 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6916 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6917 SDNode *oye = N0.getOperand(0).getNode(); 6918 if (NarrowLoad.getNode() != N0.getNode()) { 6919 CombineTo(N0.getNode(), NarrowLoad); 6920 // CombineTo deleted the truncate, if needed, but not what's under it. 6921 AddToWorklist(oye); 6922 } 6923 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6924 } 6925 6926 EVT SrcVT = N0.getOperand(0).getValueType(); 6927 EVT MinVT = N0.getValueType(); 6928 6929 // Try to mask before the extension to avoid having to generate a larger mask, 6930 // possibly over several sub-vectors. 6931 if (SrcVT.bitsLT(VT)) { 6932 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6933 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6934 SDValue Op = N0.getOperand(0); 6935 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6936 AddToWorklist(Op.getNode()); 6937 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6938 } 6939 } 6940 6941 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6942 SDValue Op = N0.getOperand(0); 6943 if (SrcVT.bitsLT(VT)) { 6944 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6945 AddToWorklist(Op.getNode()); 6946 } else if (SrcVT.bitsGT(VT)) { 6947 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6948 AddToWorklist(Op.getNode()); 6949 } 6950 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6951 } 6952 } 6953 6954 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6955 // if either of the casts is not free. 6956 if (N0.getOpcode() == ISD::AND && 6957 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6958 N0.getOperand(1).getOpcode() == ISD::Constant && 6959 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6960 N0.getValueType()) || 6961 !TLI.isZExtFree(N0.getValueType(), VT))) { 6962 SDValue X = N0.getOperand(0).getOperand(0); 6963 if (X.getValueType().bitsLT(VT)) { 6964 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6965 } else if (X.getValueType().bitsGT(VT)) { 6966 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6967 } 6968 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6969 Mask = Mask.zext(VT.getSizeInBits()); 6970 SDLoc DL(N); 6971 return DAG.getNode(ISD::AND, DL, VT, 6972 X, DAG.getConstant(Mask, DL, VT)); 6973 } 6974 6975 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6976 // Only generate vector extloads when 1) they're legal, and 2) they are 6977 // deemed desirable by the target. 6978 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6979 ((!LegalOperations && !VT.isVector() && 6980 !cast<LoadSDNode>(N0)->isVolatile()) || 6981 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6982 bool DoXform = true; 6983 SmallVector<SDNode*, 4> SetCCs; 6984 if (!N0.hasOneUse()) 6985 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6986 if (VT.isVector()) 6987 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6988 if (DoXform) { 6989 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6990 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6991 LN0->getChain(), 6992 LN0->getBasePtr(), N0.getValueType(), 6993 LN0->getMemOperand()); 6994 CombineTo(N, ExtLoad); 6995 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6996 N0.getValueType(), ExtLoad); 6997 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6998 6999 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7000 ISD::ZERO_EXTEND); 7001 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7002 } 7003 } 7004 7005 // fold (zext (load x)) to multiple smaller zextloads. 7006 // Only on illegal but splittable vectors. 7007 if (SDValue ExtLoad = CombineExtLoad(N)) 7008 return ExtLoad; 7009 7010 // fold (zext (and/or/xor (load x), cst)) -> 7011 // (and/or/xor (zextload x), (zext cst)) 7012 // Unless (and (load x) cst) will match as a zextload already and has 7013 // additional users. 7014 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7015 N0.getOpcode() == ISD::XOR) && 7016 isa<LoadSDNode>(N0.getOperand(0)) && 7017 N0.getOperand(1).getOpcode() == ISD::Constant && 7018 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7019 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7020 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7021 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7022 bool DoXform = true; 7023 SmallVector<SDNode*, 4> SetCCs; 7024 if (!N0.hasOneUse()) { 7025 if (N0.getOpcode() == ISD::AND) { 7026 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7027 auto NarrowLoad = false; 7028 EVT LoadResultTy = AndC->getValueType(0); 7029 EVT ExtVT, LoadedVT; 7030 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7031 NarrowLoad)) 7032 DoXform = false; 7033 } 7034 if (DoXform) 7035 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7036 ISD::ZERO_EXTEND, SetCCs, TLI); 7037 } 7038 if (DoXform) { 7039 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7040 LN0->getChain(), LN0->getBasePtr(), 7041 LN0->getMemoryVT(), 7042 LN0->getMemOperand()); 7043 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7044 Mask = Mask.zext(VT.getSizeInBits()); 7045 SDLoc DL(N); 7046 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7047 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7048 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7049 SDLoc(N0.getOperand(0)), 7050 N0.getOperand(0).getValueType(), ExtLoad); 7051 CombineTo(N, And); 7052 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7053 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 7054 ISD::ZERO_EXTEND); 7055 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7056 } 7057 } 7058 } 7059 7060 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7061 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7062 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7063 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7064 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7065 EVT MemVT = LN0->getMemoryVT(); 7066 if ((!LegalOperations && !LN0->isVolatile()) || 7067 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7068 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7069 LN0->getChain(), 7070 LN0->getBasePtr(), MemVT, 7071 LN0->getMemOperand()); 7072 CombineTo(N, ExtLoad); 7073 CombineTo(N0.getNode(), 7074 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7075 ExtLoad), 7076 ExtLoad.getValue(1)); 7077 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7078 } 7079 } 7080 7081 if (N0.getOpcode() == ISD::SETCC) { 7082 // Only do this before legalize for now. 7083 if (!LegalOperations && VT.isVector() && 7084 N0.getValueType().getVectorElementType() == MVT::i1) { 7085 EVT N00VT = N0.getOperand(0).getValueType(); 7086 if (getSetCCResultType(N00VT) == N0.getValueType()) 7087 return SDValue(); 7088 7089 // We know that the # elements of the results is the same as the # 7090 // elements of the compare (and the # elements of the compare result for 7091 // that matter). Check to see that they are the same size. If so, we know 7092 // that the element size of the sext'd result matches the element size of 7093 // the compare operands. 7094 SDLoc DL(N); 7095 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7096 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7097 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7098 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7099 N0.getOperand(1), N0.getOperand(2)); 7100 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7101 } 7102 7103 // If the desired elements are smaller or larger than the source 7104 // elements we can use a matching integer vector type and then 7105 // truncate/sign extend. 7106 EVT MatchingElementType = EVT::getIntegerVT( 7107 *DAG.getContext(), N00VT.getScalarSizeInBits()); 7108 EVT MatchingVectorType = EVT::getVectorVT( 7109 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 7110 SDValue VsetCC = 7111 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7112 N0.getOperand(1), N0.getOperand(2)); 7113 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7114 VecOnes); 7115 } 7116 7117 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7118 SDLoc DL(N); 7119 if (SDValue SCC = SimplifySelectCC( 7120 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7121 DAG.getConstant(0, DL, VT), 7122 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7123 return SCC; 7124 } 7125 7126 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7127 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7128 isa<ConstantSDNode>(N0.getOperand(1)) && 7129 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7130 N0.hasOneUse()) { 7131 SDValue ShAmt = N0.getOperand(1); 7132 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7133 if (N0.getOpcode() == ISD::SHL) { 7134 SDValue InnerZExt = N0.getOperand(0); 7135 // If the original shl may be shifting out bits, do not perform this 7136 // transformation. 7137 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7138 InnerZExt.getOperand(0).getValueSizeInBits(); 7139 if (ShAmtVal > KnownZeroBits) 7140 return SDValue(); 7141 } 7142 7143 SDLoc DL(N); 7144 7145 // Ensure that the shift amount is wide enough for the shifted value. 7146 if (VT.getSizeInBits() >= 256) 7147 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7148 7149 return DAG.getNode(N0.getOpcode(), DL, VT, 7150 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7151 ShAmt); 7152 } 7153 7154 return SDValue(); 7155 } 7156 7157 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7158 SDValue N0 = N->getOperand(0); 7159 EVT VT = N->getValueType(0); 7160 7161 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7162 LegalOperations)) 7163 return SDValue(Res, 0); 7164 7165 // fold (aext (aext x)) -> (aext x) 7166 // fold (aext (zext x)) -> (zext x) 7167 // fold (aext (sext x)) -> (sext x) 7168 if (N0.getOpcode() == ISD::ANY_EXTEND || 7169 N0.getOpcode() == ISD::ZERO_EXTEND || 7170 N0.getOpcode() == ISD::SIGN_EXTEND) 7171 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7172 7173 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7174 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7175 if (N0.getOpcode() == ISD::TRUNCATE) { 7176 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7177 SDNode *oye = N0.getOperand(0).getNode(); 7178 if (NarrowLoad.getNode() != N0.getNode()) { 7179 CombineTo(N0.getNode(), NarrowLoad); 7180 // CombineTo deleted the truncate, if needed, but not what's under it. 7181 AddToWorklist(oye); 7182 } 7183 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7184 } 7185 } 7186 7187 // fold (aext (truncate x)) 7188 if (N0.getOpcode() == ISD::TRUNCATE) { 7189 SDValue TruncOp = N0.getOperand(0); 7190 if (TruncOp.getValueType() == VT) 7191 return TruncOp; // x iff x size == zext size. 7192 if (TruncOp.getValueType().bitsGT(VT)) 7193 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 7194 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 7195 } 7196 7197 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7198 // if the trunc is not free. 7199 if (N0.getOpcode() == ISD::AND && 7200 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7201 N0.getOperand(1).getOpcode() == ISD::Constant && 7202 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7203 N0.getValueType())) { 7204 SDLoc DL(N); 7205 SDValue X = N0.getOperand(0).getOperand(0); 7206 if (X.getValueType().bitsLT(VT)) { 7207 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); 7208 } else if (X.getValueType().bitsGT(VT)) { 7209 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X); 7210 } 7211 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7212 Mask = Mask.zext(VT.getSizeInBits()); 7213 return DAG.getNode(ISD::AND, DL, VT, 7214 X, DAG.getConstant(Mask, DL, VT)); 7215 } 7216 7217 // fold (aext (load x)) -> (aext (truncate (extload x))) 7218 // None of the supported targets knows how to perform load and any_ext 7219 // on vectors in one instruction. We only perform this transformation on 7220 // scalars. 7221 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7222 ISD::isUNINDEXEDLoad(N0.getNode()) && 7223 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7224 bool DoXform = true; 7225 SmallVector<SDNode*, 4> SetCCs; 7226 if (!N0.hasOneUse()) 7227 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7228 if (DoXform) { 7229 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7230 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7231 LN0->getChain(), 7232 LN0->getBasePtr(), N0.getValueType(), 7233 LN0->getMemOperand()); 7234 CombineTo(N, ExtLoad); 7235 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7236 N0.getValueType(), ExtLoad); 7237 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7238 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7239 ISD::ANY_EXTEND); 7240 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7241 } 7242 } 7243 7244 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7245 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7246 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7247 if (N0.getOpcode() == ISD::LOAD && 7248 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7249 N0.hasOneUse()) { 7250 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7251 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7252 EVT MemVT = LN0->getMemoryVT(); 7253 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7254 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7255 VT, LN0->getChain(), LN0->getBasePtr(), 7256 MemVT, LN0->getMemOperand()); 7257 CombineTo(N, ExtLoad); 7258 CombineTo(N0.getNode(), 7259 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7260 N0.getValueType(), ExtLoad), 7261 ExtLoad.getValue(1)); 7262 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7263 } 7264 } 7265 7266 if (N0.getOpcode() == ISD::SETCC) { 7267 // For vectors: 7268 // aext(setcc) -> vsetcc 7269 // aext(setcc) -> truncate(vsetcc) 7270 // aext(setcc) -> aext(vsetcc) 7271 // Only do this before legalize for now. 7272 if (VT.isVector() && !LegalOperations) { 7273 EVT N0VT = N0.getOperand(0).getValueType(); 7274 // We know that the # elements of the results is the same as the 7275 // # elements of the compare (and the # elements of the compare result 7276 // for that matter). Check to see that they are the same size. If so, 7277 // we know that the element size of the sext'd result matches the 7278 // element size of the compare operands. 7279 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 7280 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7281 N0.getOperand(1), 7282 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7283 // If the desired elements are smaller or larger than the source 7284 // elements we can use a matching integer vector type and then 7285 // truncate/any extend 7286 else { 7287 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 7288 SDValue VsetCC = 7289 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7290 N0.getOperand(1), 7291 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7292 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7293 } 7294 } 7295 7296 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7297 SDLoc DL(N); 7298 if (SDValue SCC = SimplifySelectCC( 7299 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7300 DAG.getConstant(0, DL, VT), 7301 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7302 return SCC; 7303 } 7304 7305 return SDValue(); 7306 } 7307 7308 SDValue DAGCombiner::visitAssertZext(SDNode *N) { 7309 SDValue N0 = N->getOperand(0); 7310 SDValue N1 = N->getOperand(1); 7311 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7312 7313 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt) 7314 if (N0.getOpcode() == ISD::AssertZext && 7315 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7316 return N0; 7317 7318 return SDValue(); 7319 } 7320 7321 /// See if the specified operand can be simplified with the knowledge that only 7322 /// the bits specified by Mask are used. If so, return the simpler operand, 7323 /// otherwise return a null SDValue. 7324 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 7325 switch (V.getOpcode()) { 7326 default: break; 7327 case ISD::Constant: { 7328 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 7329 assert(CV && "Const value should be ConstSDNode."); 7330 const APInt &CVal = CV->getAPIntValue(); 7331 APInt NewVal = CVal & Mask; 7332 if (NewVal != CVal) 7333 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 7334 break; 7335 } 7336 case ISD::OR: 7337 case ISD::XOR: 7338 // If the LHS or RHS don't contribute bits to the or, drop them. 7339 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 7340 return V.getOperand(1); 7341 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 7342 return V.getOperand(0); 7343 break; 7344 case ISD::SRL: 7345 // Only look at single-use SRLs. 7346 if (!V.getNode()->hasOneUse()) 7347 break; 7348 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 7349 // See if we can recursively simplify the LHS. 7350 unsigned Amt = RHSC->getZExtValue(); 7351 7352 // Watch out for shift count overflow though. 7353 if (Amt >= Mask.getBitWidth()) break; 7354 APInt NewMask = Mask << Amt; 7355 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 7356 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 7357 SimplifyLHS, V.getOperand(1)); 7358 } 7359 } 7360 return SDValue(); 7361 } 7362 7363 /// If the result of a wider load is shifted to right of N bits and then 7364 /// truncated to a narrower type and where N is a multiple of number of bits of 7365 /// the narrower type, transform it to a narrower load from address + N / num of 7366 /// bits of new type. If the result is to be extended, also fold the extension 7367 /// to form a extending load. 7368 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7369 unsigned Opc = N->getOpcode(); 7370 7371 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7372 SDValue N0 = N->getOperand(0); 7373 EVT VT = N->getValueType(0); 7374 EVT ExtVT = VT; 7375 7376 // This transformation isn't valid for vector loads. 7377 if (VT.isVector()) 7378 return SDValue(); 7379 7380 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7381 // extended to VT. 7382 if (Opc == ISD::SIGN_EXTEND_INREG) { 7383 ExtType = ISD::SEXTLOAD; 7384 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7385 } else if (Opc == ISD::SRL) { 7386 // Another special-case: SRL is basically zero-extending a narrower value. 7387 ExtType = ISD::ZEXTLOAD; 7388 N0 = SDValue(N, 0); 7389 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7390 if (!N01) return SDValue(); 7391 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 7392 VT.getSizeInBits() - N01->getZExtValue()); 7393 } 7394 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 7395 return SDValue(); 7396 7397 unsigned EVTBits = ExtVT.getSizeInBits(); 7398 7399 // Do not generate loads of non-round integer types since these can 7400 // be expensive (and would be wrong if the type is not byte sized). 7401 if (!ExtVT.isRound()) 7402 return SDValue(); 7403 7404 unsigned ShAmt = 0; 7405 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 7406 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7407 ShAmt = N01->getZExtValue(); 7408 // Is the shift amount a multiple of size of VT? 7409 if ((ShAmt & (EVTBits-1)) == 0) { 7410 N0 = N0.getOperand(0); 7411 // Is the load width a multiple of size of VT? 7412 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 7413 return SDValue(); 7414 } 7415 7416 // At this point, we must have a load or else we can't do the transform. 7417 if (!isa<LoadSDNode>(N0)) return SDValue(); 7418 7419 // Because a SRL must be assumed to *need* to zero-extend the high bits 7420 // (as opposed to anyext the high bits), we can't combine the zextload 7421 // lowering of SRL and an sextload. 7422 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 7423 return SDValue(); 7424 7425 // If the shift amount is larger than the input type then we're not 7426 // accessing any of the loaded bytes. If the load was a zextload/extload 7427 // then the result of the shift+trunc is zero/undef (handled elsewhere). 7428 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 7429 return SDValue(); 7430 } 7431 } 7432 7433 // If the load is shifted left (and the result isn't shifted back right), 7434 // we can fold the truncate through the shift. 7435 unsigned ShLeftAmt = 0; 7436 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7437 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 7438 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7439 ShLeftAmt = N01->getZExtValue(); 7440 N0 = N0.getOperand(0); 7441 } 7442 } 7443 7444 // If we haven't found a load, we can't narrow it. Don't transform one with 7445 // multiple uses, this would require adding a new load. 7446 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 7447 return SDValue(); 7448 7449 // Don't change the width of a volatile load. 7450 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7451 if (LN0->isVolatile()) 7452 return SDValue(); 7453 7454 // Verify that we are actually reducing a load width here. 7455 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 7456 return SDValue(); 7457 7458 // For the transform to be legal, the load must produce only two values 7459 // (the value loaded and the chain). Don't transform a pre-increment 7460 // load, for example, which produces an extra value. Otherwise the 7461 // transformation is not equivalent, and the downstream logic to replace 7462 // uses gets things wrong. 7463 if (LN0->getNumValues() > 2) 7464 return SDValue(); 7465 7466 // If the load that we're shrinking is an extload and we're not just 7467 // discarding the extension we can't simply shrink the load. Bail. 7468 // TODO: It would be possible to merge the extensions in some cases. 7469 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 7470 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 7471 return SDValue(); 7472 7473 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 7474 return SDValue(); 7475 7476 EVT PtrType = N0.getOperand(1).getValueType(); 7477 7478 if (PtrType == MVT::Untyped || PtrType.isExtended()) 7479 // It's not possible to generate a constant of extended or untyped type. 7480 return SDValue(); 7481 7482 // For big endian targets, we need to adjust the offset to the pointer to 7483 // load the correct bytes. 7484 if (DAG.getDataLayout().isBigEndian()) { 7485 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 7486 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 7487 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 7488 } 7489 7490 uint64_t PtrOff = ShAmt / 8; 7491 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 7492 SDLoc DL(LN0); 7493 // The original load itself didn't wrap, so an offset within it doesn't. 7494 SDNodeFlags Flags; 7495 Flags.setNoUnsignedWrap(true); 7496 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 7497 PtrType, LN0->getBasePtr(), 7498 DAG.getConstant(PtrOff, DL, PtrType), 7499 &Flags); 7500 AddToWorklist(NewPtr.getNode()); 7501 7502 SDValue Load; 7503 if (ExtType == ISD::NON_EXTLOAD) 7504 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 7505 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 7506 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7507 else 7508 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 7509 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 7510 NewAlign, LN0->getMemOperand()->getFlags(), 7511 LN0->getAAInfo()); 7512 7513 // Replace the old load's chain with the new load's chain. 7514 WorklistRemover DeadNodes(*this); 7515 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7516 7517 // Shift the result left, if we've swallowed a left shift. 7518 SDValue Result = Load; 7519 if (ShLeftAmt != 0) { 7520 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 7521 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 7522 ShImmTy = VT; 7523 // If the shift amount is as large as the result size (but, presumably, 7524 // no larger than the source) then the useful bits of the result are 7525 // zero; we can't simply return the shortened shift, because the result 7526 // of that operation is undefined. 7527 SDLoc DL(N0); 7528 if (ShLeftAmt >= VT.getSizeInBits()) 7529 Result = DAG.getConstant(0, DL, VT); 7530 else 7531 Result = DAG.getNode(ISD::SHL, DL, VT, 7532 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 7533 } 7534 7535 // Return the new loaded value. 7536 return Result; 7537 } 7538 7539 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 7540 SDValue N0 = N->getOperand(0); 7541 SDValue N1 = N->getOperand(1); 7542 EVT VT = N->getValueType(0); 7543 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7544 unsigned VTBits = VT.getScalarSizeInBits(); 7545 unsigned EVTBits = EVT.getScalarSizeInBits(); 7546 7547 if (N0.isUndef()) 7548 return DAG.getUNDEF(VT); 7549 7550 // fold (sext_in_reg c1) -> c1 7551 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7552 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 7553 7554 // If the input is already sign extended, just drop the extension. 7555 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 7556 return N0; 7557 7558 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 7559 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 7560 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 7561 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7562 N0.getOperand(0), N1); 7563 7564 // fold (sext_in_reg (sext x)) -> (sext x) 7565 // fold (sext_in_reg (aext x)) -> (sext x) 7566 // if x is small enough. 7567 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 7568 SDValue N00 = N0.getOperand(0); 7569 if (N00.getScalarValueSizeInBits() <= EVTBits && 7570 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7571 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7572 } 7573 7574 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 7575 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 7576 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 7577 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 7578 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 7579 if (!LegalOperations || 7580 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 7581 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 7582 } 7583 7584 // fold (sext_in_reg (zext x)) -> (sext x) 7585 // iff we are extending the source sign bit. 7586 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 7587 SDValue N00 = N0.getOperand(0); 7588 if (N00.getScalarValueSizeInBits() == EVTBits && 7589 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7590 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7591 } 7592 7593 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 7594 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 7595 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 7596 7597 // fold operands of sext_in_reg based on knowledge that the top bits are not 7598 // demanded. 7599 if (SimplifyDemandedBits(SDValue(N, 0))) 7600 return SDValue(N, 0); 7601 7602 // fold (sext_in_reg (load x)) -> (smaller sextload x) 7603 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 7604 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 7605 return NarrowLoad; 7606 7607 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7608 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7609 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7610 if (N0.getOpcode() == ISD::SRL) { 7611 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7612 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7613 // We can turn this into an SRA iff the input to the SRL is already sign 7614 // extended enough. 7615 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7616 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7617 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7618 N0.getOperand(0), N0.getOperand(1)); 7619 } 7620 } 7621 7622 // fold (sext_inreg (extload x)) -> (sextload x) 7623 if (ISD::isEXTLoad(N0.getNode()) && 7624 ISD::isUNINDEXEDLoad(N0.getNode()) && 7625 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7626 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7627 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7628 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7629 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7630 LN0->getChain(), 7631 LN0->getBasePtr(), EVT, 7632 LN0->getMemOperand()); 7633 CombineTo(N, ExtLoad); 7634 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7635 AddToWorklist(ExtLoad.getNode()); 7636 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7637 } 7638 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7639 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7640 N0.hasOneUse() && 7641 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7642 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7643 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7644 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7645 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7646 LN0->getChain(), 7647 LN0->getBasePtr(), EVT, 7648 LN0->getMemOperand()); 7649 CombineTo(N, ExtLoad); 7650 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7651 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7652 } 7653 7654 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7655 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7656 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7657 N0.getOperand(1), false)) 7658 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7659 BSwap, N1); 7660 } 7661 7662 return SDValue(); 7663 } 7664 7665 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7666 SDValue N0 = N->getOperand(0); 7667 EVT VT = N->getValueType(0); 7668 7669 if (N0.isUndef()) 7670 return DAG.getUNDEF(VT); 7671 7672 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7673 LegalOperations)) 7674 return SDValue(Res, 0); 7675 7676 return SDValue(); 7677 } 7678 7679 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7680 SDValue N0 = N->getOperand(0); 7681 EVT VT = N->getValueType(0); 7682 7683 if (N0.isUndef()) 7684 return DAG.getUNDEF(VT); 7685 7686 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7687 LegalOperations)) 7688 return SDValue(Res, 0); 7689 7690 return SDValue(); 7691 } 7692 7693 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7694 SDValue N0 = N->getOperand(0); 7695 EVT VT = N->getValueType(0); 7696 bool isLE = DAG.getDataLayout().isLittleEndian(); 7697 7698 // noop truncate 7699 if (N0.getValueType() == N->getValueType(0)) 7700 return N0; 7701 // fold (truncate c1) -> c1 7702 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7703 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7704 // fold (truncate (truncate x)) -> (truncate x) 7705 if (N0.getOpcode() == ISD::TRUNCATE) 7706 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7707 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7708 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7709 N0.getOpcode() == ISD::SIGN_EXTEND || 7710 N0.getOpcode() == ISD::ANY_EXTEND) { 7711 // if the source is smaller than the dest, we still need an extend. 7712 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7713 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7714 // if the source is larger than the dest, than we just need the truncate. 7715 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7716 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7717 // if the source and dest are the same type, we can drop both the extend 7718 // and the truncate. 7719 return N0.getOperand(0); 7720 } 7721 7722 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 7723 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 7724 return SDValue(); 7725 7726 // Fold extract-and-trunc into a narrow extract. For example: 7727 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7728 // i32 y = TRUNCATE(i64 x) 7729 // -- becomes -- 7730 // v16i8 b = BITCAST (v2i64 val) 7731 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7732 // 7733 // Note: We only run this optimization after type legalization (which often 7734 // creates this pattern) and before operation legalization after which 7735 // we need to be more careful about the vector instructions that we generate. 7736 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7737 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7738 7739 EVT VecTy = N0.getOperand(0).getValueType(); 7740 EVT ExTy = N0.getValueType(); 7741 EVT TrTy = N->getValueType(0); 7742 7743 unsigned NumElem = VecTy.getVectorNumElements(); 7744 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7745 7746 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7747 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7748 7749 SDValue EltNo = N0->getOperand(1); 7750 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7751 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7752 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7753 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7754 7755 SDLoc DL(N); 7756 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7757 DAG.getBitcast(NVT, N0.getOperand(0)), 7758 DAG.getConstant(Index, DL, IndexTy)); 7759 } 7760 } 7761 7762 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7763 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 7764 EVT SrcVT = N0.getValueType(); 7765 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7766 TLI.isTruncateFree(SrcVT, VT)) { 7767 SDLoc SL(N0); 7768 SDValue Cond = N0.getOperand(0); 7769 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7770 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7771 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7772 } 7773 } 7774 7775 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 7776 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7777 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7778 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7779 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7780 uint64_t Amt = CAmt->getZExtValue(); 7781 unsigned Size = VT.getScalarSizeInBits(); 7782 7783 if (Amt < Size) { 7784 SDLoc SL(N); 7785 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7786 7787 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7788 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7789 DAG.getConstant(Amt, SL, AmtVT)); 7790 } 7791 } 7792 } 7793 7794 // Fold a series of buildvector, bitcast, and truncate if possible. 7795 // For example fold 7796 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7797 // (2xi32 (buildvector x, y)). 7798 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7799 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7800 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7801 N0.getOperand(0).hasOneUse()) { 7802 7803 SDValue BuildVect = N0.getOperand(0); 7804 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7805 EVT TruncVecEltTy = VT.getVectorElementType(); 7806 7807 // Check that the element types match. 7808 if (BuildVectEltTy == TruncVecEltTy) { 7809 // Now we only need to compute the offset of the truncated elements. 7810 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7811 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7812 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7813 7814 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7815 "Invalid number of elements"); 7816 7817 SmallVector<SDValue, 8> Opnds; 7818 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7819 Opnds.push_back(BuildVect.getOperand(i)); 7820 7821 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7822 } 7823 } 7824 7825 // See if we can simplify the input to this truncate through knowledge that 7826 // only the low bits are being used. 7827 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7828 // Currently we only perform this optimization on scalars because vectors 7829 // may have different active low bits. 7830 if (!VT.isVector()) { 7831 if (SDValue Shorter = 7832 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7833 VT.getSizeInBits()))) 7834 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7835 } 7836 7837 // fold (truncate (load x)) -> (smaller load x) 7838 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7839 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7840 if (SDValue Reduced = ReduceLoadWidth(N)) 7841 return Reduced; 7842 7843 // Handle the case where the load remains an extending load even 7844 // after truncation. 7845 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7846 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7847 if (!LN0->isVolatile() && 7848 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7849 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7850 VT, LN0->getChain(), LN0->getBasePtr(), 7851 LN0->getMemoryVT(), 7852 LN0->getMemOperand()); 7853 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7854 return NewLoad; 7855 } 7856 } 7857 } 7858 7859 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7860 // where ... are all 'undef'. 7861 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7862 SmallVector<EVT, 8> VTs; 7863 SDValue V; 7864 unsigned Idx = 0; 7865 unsigned NumDefs = 0; 7866 7867 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7868 SDValue X = N0.getOperand(i); 7869 if (!X.isUndef()) { 7870 V = X; 7871 Idx = i; 7872 NumDefs++; 7873 } 7874 // Stop if more than one members are non-undef. 7875 if (NumDefs > 1) 7876 break; 7877 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7878 VT.getVectorElementType(), 7879 X.getValueType().getVectorNumElements())); 7880 } 7881 7882 if (NumDefs == 0) 7883 return DAG.getUNDEF(VT); 7884 7885 if (NumDefs == 1) { 7886 assert(V.getNode() && "The single defined operand is empty!"); 7887 SmallVector<SDValue, 8> Opnds; 7888 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7889 if (i != Idx) { 7890 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7891 continue; 7892 } 7893 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7894 AddToWorklist(NV.getNode()); 7895 Opnds.push_back(NV); 7896 } 7897 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7898 } 7899 } 7900 7901 // Fold truncate of a bitcast of a vector to an extract of the low vector 7902 // element. 7903 // 7904 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7905 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7906 SDValue VecSrc = N0.getOperand(0); 7907 EVT SrcVT = VecSrc.getValueType(); 7908 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7909 (!LegalOperations || 7910 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7911 SDLoc SL(N); 7912 7913 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7914 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7915 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7916 } 7917 } 7918 7919 // Simplify the operands using demanded-bits information. 7920 if (!VT.isVector() && 7921 SimplifyDemandedBits(SDValue(N, 0))) 7922 return SDValue(N, 0); 7923 7924 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 7925 // When the adde's carry is not used. 7926 if (N0.getOpcode() == ISD::ADDE && N0.hasOneUse() && 7927 !N0.getNode()->hasAnyUseOfValue(1) && 7928 (!LegalOperations || TLI.isOperationLegal(ISD::ADDE, VT))) { 7929 SDLoc SL(N); 7930 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7931 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7932 return DAG.getNode(ISD::ADDE, SL, DAG.getVTList(VT, MVT::Glue), 7933 X, Y, N0.getOperand(2)); 7934 } 7935 7936 return SDValue(); 7937 } 7938 7939 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7940 SDValue Elt = N->getOperand(i); 7941 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7942 return Elt.getNode(); 7943 return Elt.getOperand(Elt.getResNo()).getNode(); 7944 } 7945 7946 /// build_pair (load, load) -> load 7947 /// if load locations are consecutive. 7948 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7949 assert(N->getOpcode() == ISD::BUILD_PAIR); 7950 7951 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7952 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7953 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7954 LD1->getAddressSpace() != LD2->getAddressSpace()) 7955 return SDValue(); 7956 EVT LD1VT = LD1->getValueType(0); 7957 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7958 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7959 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7960 unsigned Align = LD1->getAlignment(); 7961 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7962 VT.getTypeForEVT(*DAG.getContext())); 7963 7964 if (NewAlign <= Align && 7965 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7966 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 7967 LD1->getPointerInfo(), Align); 7968 } 7969 7970 return SDValue(); 7971 } 7972 7973 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7974 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7975 // and Lo parts; on big-endian machines it doesn't. 7976 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7977 } 7978 7979 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 7980 const TargetLowering &TLI) { 7981 // If this is not a bitcast to an FP type or if the target doesn't have 7982 // IEEE754-compliant FP logic, we're done. 7983 EVT VT = N->getValueType(0); 7984 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 7985 return SDValue(); 7986 7987 // TODO: Use splat values for the constant-checking below and remove this 7988 // restriction. 7989 SDValue N0 = N->getOperand(0); 7990 EVT SourceVT = N0.getValueType(); 7991 if (SourceVT.isVector()) 7992 return SDValue(); 7993 7994 unsigned FPOpcode; 7995 APInt SignMask; 7996 switch (N0.getOpcode()) { 7997 case ISD::AND: 7998 FPOpcode = ISD::FABS; 7999 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 8000 break; 8001 case ISD::XOR: 8002 FPOpcode = ISD::FNEG; 8003 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 8004 break; 8005 // TODO: ISD::OR --> ISD::FNABS? 8006 default: 8007 return SDValue(); 8008 } 8009 8010 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8011 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8012 SDValue LogicOp0 = N0.getOperand(0); 8013 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8014 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8015 LogicOp0.getOpcode() == ISD::BITCAST && 8016 LogicOp0->getOperand(0).getValueType() == VT) 8017 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8018 8019 return SDValue(); 8020 } 8021 8022 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8023 SDValue N0 = N->getOperand(0); 8024 EVT VT = N->getValueType(0); 8025 8026 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8027 // Only do this before legalize, since afterward the target may be depending 8028 // on the bitconvert. 8029 // First check to see if this is all constant. 8030 if (!LegalTypes && 8031 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8032 VT.isVector()) { 8033 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8034 8035 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8036 assert(!DestEltVT.isVector() && 8037 "Element type of vector ValueType must not be vector!"); 8038 if (isSimple) 8039 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8040 } 8041 8042 // If the input is a constant, let getNode fold it. 8043 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8044 // If we can't allow illegal operations, we need to check that this is just 8045 // a fp -> int or int -> conversion and that the resulting operation will 8046 // be legal. 8047 if (!LegalOperations || 8048 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8049 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8050 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8051 TLI.isOperationLegal(ISD::Constant, VT))) 8052 return DAG.getBitcast(VT, N0); 8053 } 8054 8055 // (conv (conv x, t1), t2) -> (conv x, t2) 8056 if (N0.getOpcode() == ISD::BITCAST) 8057 return DAG.getBitcast(VT, N0.getOperand(0)); 8058 8059 // fold (conv (load x)) -> (load (conv*)x) 8060 // If the resultant load doesn't need a higher alignment than the original! 8061 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8062 // Do not change the width of a volatile load. 8063 !cast<LoadSDNode>(N0)->isVolatile() && 8064 // Do not remove the cast if the types differ in endian layout. 8065 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8066 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8067 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8068 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8069 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8070 unsigned OrigAlign = LN0->getAlignment(); 8071 8072 bool Fast = false; 8073 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8074 LN0->getAddressSpace(), OrigAlign, &Fast) && 8075 Fast) { 8076 SDValue Load = 8077 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8078 LN0->getPointerInfo(), OrigAlign, 8079 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8080 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8081 return Load; 8082 } 8083 } 8084 8085 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8086 return V; 8087 8088 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8089 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8090 // 8091 // For ppc_fp128: 8092 // fold (bitcast (fneg x)) -> 8093 // flipbit = signbit 8094 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8095 // 8096 // fold (bitcast (fabs x)) -> 8097 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8098 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8099 // This often reduces constant pool loads. 8100 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8101 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8102 N0.getNode()->hasOneUse() && VT.isInteger() && 8103 !VT.isVector() && !N0.getValueType().isVector()) { 8104 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8105 AddToWorklist(NewConv.getNode()); 8106 8107 SDLoc DL(N); 8108 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8109 assert(VT.getSizeInBits() == 128); 8110 SDValue SignBit = DAG.getConstant( 8111 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8112 SDValue FlipBit; 8113 if (N0.getOpcode() == ISD::FNEG) { 8114 FlipBit = SignBit; 8115 AddToWorklist(FlipBit.getNode()); 8116 } else { 8117 assert(N0.getOpcode() == ISD::FABS); 8118 SDValue Hi = 8119 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8120 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8121 SDLoc(NewConv))); 8122 AddToWorklist(Hi.getNode()); 8123 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8124 AddToWorklist(FlipBit.getNode()); 8125 } 8126 SDValue FlipBits = 8127 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8128 AddToWorklist(FlipBits.getNode()); 8129 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8130 } 8131 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 8132 if (N0.getOpcode() == ISD::FNEG) 8133 return DAG.getNode(ISD::XOR, DL, VT, 8134 NewConv, DAG.getConstant(SignBit, DL, VT)); 8135 assert(N0.getOpcode() == ISD::FABS); 8136 return DAG.getNode(ISD::AND, DL, VT, 8137 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8138 } 8139 8140 // fold (bitconvert (fcopysign cst, x)) -> 8141 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8142 // Note that we don't handle (copysign x, cst) because this can always be 8143 // folded to an fneg or fabs. 8144 // 8145 // For ppc_fp128: 8146 // fold (bitcast (fcopysign cst, x)) -> 8147 // flipbit = (and (extract_element 8148 // (xor (bitcast cst), (bitcast x)), 0), 8149 // signbit) 8150 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8151 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8152 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8153 VT.isInteger() && !VT.isVector()) { 8154 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8155 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8156 if (isTypeLegal(IntXVT)) { 8157 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8158 AddToWorklist(X.getNode()); 8159 8160 // If X has a different width than the result/lhs, sext it or truncate it. 8161 unsigned VTWidth = VT.getSizeInBits(); 8162 if (OrigXWidth < VTWidth) { 8163 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8164 AddToWorklist(X.getNode()); 8165 } else if (OrigXWidth > VTWidth) { 8166 // To get the sign bit in the right place, we have to shift it right 8167 // before truncating. 8168 SDLoc DL(X); 8169 X = DAG.getNode(ISD::SRL, DL, 8170 X.getValueType(), X, 8171 DAG.getConstant(OrigXWidth-VTWidth, DL, 8172 X.getValueType())); 8173 AddToWorklist(X.getNode()); 8174 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8175 AddToWorklist(X.getNode()); 8176 } 8177 8178 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8179 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 8180 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8181 AddToWorklist(Cst.getNode()); 8182 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8183 AddToWorklist(X.getNode()); 8184 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8185 AddToWorklist(XorResult.getNode()); 8186 SDValue XorResult64 = DAG.getNode( 8187 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8188 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8189 SDLoc(XorResult))); 8190 AddToWorklist(XorResult64.getNode()); 8191 SDValue FlipBit = 8192 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8193 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8194 AddToWorklist(FlipBit.getNode()); 8195 SDValue FlipBits = 8196 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8197 AddToWorklist(FlipBits.getNode()); 8198 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8199 } 8200 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 8201 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8202 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8203 AddToWorklist(X.getNode()); 8204 8205 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8206 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8207 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8208 AddToWorklist(Cst.getNode()); 8209 8210 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8211 } 8212 } 8213 8214 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8215 if (N0.getOpcode() == ISD::BUILD_PAIR) 8216 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8217 return CombineLD; 8218 8219 // Remove double bitcasts from shuffles - this is often a legacy of 8220 // XformToShuffleWithZero being used to combine bitmaskings (of 8221 // float vectors bitcast to integer vectors) into shuffles. 8222 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8223 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8224 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8225 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8226 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8227 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8228 8229 // If operands are a bitcast, peek through if it casts the original VT. 8230 // If operands are a constant, just bitcast back to original VT. 8231 auto PeekThroughBitcast = [&](SDValue Op) { 8232 if (Op.getOpcode() == ISD::BITCAST && 8233 Op.getOperand(0).getValueType() == VT) 8234 return SDValue(Op.getOperand(0)); 8235 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8236 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8237 return DAG.getBitcast(VT, Op); 8238 return SDValue(); 8239 }; 8240 8241 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8242 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8243 if (!(SV0 && SV1)) 8244 return SDValue(); 8245 8246 int MaskScale = 8247 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8248 SmallVector<int, 8> NewMask; 8249 for (int M : SVN->getMask()) 8250 for (int i = 0; i != MaskScale; ++i) 8251 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8252 8253 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8254 if (!LegalMask) { 8255 std::swap(SV0, SV1); 8256 ShuffleVectorSDNode::commuteMask(NewMask); 8257 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8258 } 8259 8260 if (LegalMask) 8261 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8262 } 8263 8264 return SDValue(); 8265 } 8266 8267 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8268 EVT VT = N->getValueType(0); 8269 return CombineConsecutiveLoads(N, VT); 8270 } 8271 8272 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8273 /// operands. DstEltVT indicates the destination element value type. 8274 SDValue DAGCombiner:: 8275 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8276 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8277 8278 // If this is already the right type, we're done. 8279 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8280 8281 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8282 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8283 8284 // If this is a conversion of N elements of one type to N elements of another 8285 // type, convert each element. This handles FP<->INT cases. 8286 if (SrcBitSize == DstBitSize) { 8287 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8288 BV->getValueType(0).getVectorNumElements()); 8289 8290 // Due to the FP element handling below calling this routine recursively, 8291 // we can end up with a scalar-to-vector node here. 8292 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8293 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8294 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8295 8296 SmallVector<SDValue, 8> Ops; 8297 for (SDValue Op : BV->op_values()) { 8298 // If the vector element type is not legal, the BUILD_VECTOR operands 8299 // are promoted and implicitly truncated. Make that explicit here. 8300 if (Op.getValueType() != SrcEltVT) 8301 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8302 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8303 AddToWorklist(Ops.back().getNode()); 8304 } 8305 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8306 } 8307 8308 // Otherwise, we're growing or shrinking the elements. To avoid having to 8309 // handle annoying details of growing/shrinking FP values, we convert them to 8310 // int first. 8311 if (SrcEltVT.isFloatingPoint()) { 8312 // Convert the input float vector to a int vector where the elements are the 8313 // same sizes. 8314 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8315 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8316 SrcEltVT = IntVT; 8317 } 8318 8319 // Now we know the input is an integer vector. If the output is a FP type, 8320 // convert to integer first, then to FP of the right size. 8321 if (DstEltVT.isFloatingPoint()) { 8322 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8323 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8324 8325 // Next, convert to FP elements of the same size. 8326 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 8327 } 8328 8329 SDLoc DL(BV); 8330 8331 // Okay, we know the src/dst types are both integers of differing types. 8332 // Handling growing first. 8333 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 8334 if (SrcBitSize < DstBitSize) { 8335 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 8336 8337 SmallVector<SDValue, 8> Ops; 8338 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 8339 i += NumInputsPerOutput) { 8340 bool isLE = DAG.getDataLayout().isLittleEndian(); 8341 APInt NewBits = APInt(DstBitSize, 0); 8342 bool EltIsUndef = true; 8343 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 8344 // Shift the previously computed bits over. 8345 NewBits <<= SrcBitSize; 8346 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 8347 if (Op.isUndef()) continue; 8348 EltIsUndef = false; 8349 8350 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 8351 zextOrTrunc(SrcBitSize).zext(DstBitSize); 8352 } 8353 8354 if (EltIsUndef) 8355 Ops.push_back(DAG.getUNDEF(DstEltVT)); 8356 else 8357 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 8358 } 8359 8360 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 8361 return DAG.getBuildVector(VT, DL, Ops); 8362 } 8363 8364 // Finally, this must be the case where we are shrinking elements: each input 8365 // turns into multiple outputs. 8366 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 8367 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8368 NumOutputsPerInput*BV->getNumOperands()); 8369 SmallVector<SDValue, 8> Ops; 8370 8371 for (const SDValue &Op : BV->op_values()) { 8372 if (Op.isUndef()) { 8373 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 8374 continue; 8375 } 8376 8377 APInt OpVal = cast<ConstantSDNode>(Op)-> 8378 getAPIntValue().zextOrTrunc(SrcBitSize); 8379 8380 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 8381 APInt ThisVal = OpVal.trunc(DstBitSize); 8382 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 8383 OpVal = OpVal.lshr(DstBitSize); 8384 } 8385 8386 // For big endian targets, swap the order of the pieces of each element. 8387 if (DAG.getDataLayout().isBigEndian()) 8388 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 8389 } 8390 8391 return DAG.getBuildVector(VT, DL, Ops); 8392 } 8393 8394 /// Try to perform FMA combining on a given FADD node. 8395 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 8396 SDValue N0 = N->getOperand(0); 8397 SDValue N1 = N->getOperand(1); 8398 EVT VT = N->getValueType(0); 8399 SDLoc SL(N); 8400 8401 const TargetOptions &Options = DAG.getTarget().Options; 8402 bool AllowFusion = 8403 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8404 8405 // Floating-point multiply-add with intermediate rounding. 8406 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8407 8408 // Floating-point multiply-add without intermediate rounding. 8409 bool HasFMA = 8410 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8411 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8412 8413 // No valid opcode, do not combine. 8414 if (!HasFMAD && !HasFMA) 8415 return SDValue(); 8416 8417 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8418 ; 8419 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8420 return SDValue(); 8421 8422 // Always prefer FMAD to FMA for precision. 8423 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8424 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8425 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8426 8427 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 8428 // prefer to fold the multiply with fewer uses. 8429 if (Aggressive && N0.getOpcode() == ISD::FMUL && 8430 N1.getOpcode() == ISD::FMUL) { 8431 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 8432 std::swap(N0, N1); 8433 } 8434 8435 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 8436 if (N0.getOpcode() == ISD::FMUL && 8437 (Aggressive || N0->hasOneUse())) { 8438 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8439 N0.getOperand(0), N0.getOperand(1), N1); 8440 } 8441 8442 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 8443 // Note: Commutes FADD operands. 8444 if (N1.getOpcode() == ISD::FMUL && 8445 (Aggressive || N1->hasOneUse())) { 8446 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8447 N1.getOperand(0), N1.getOperand(1), N0); 8448 } 8449 8450 // Look through FP_EXTEND nodes to do more combining. 8451 if (AllowFusion && LookThroughFPExt) { 8452 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 8453 if (N0.getOpcode() == ISD::FP_EXTEND) { 8454 SDValue N00 = N0.getOperand(0); 8455 if (N00.getOpcode() == ISD::FMUL) 8456 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8457 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8458 N00.getOperand(0)), 8459 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8460 N00.getOperand(1)), N1); 8461 } 8462 8463 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 8464 // Note: Commutes FADD operands. 8465 if (N1.getOpcode() == ISD::FP_EXTEND) { 8466 SDValue N10 = N1.getOperand(0); 8467 if (N10.getOpcode() == ISD::FMUL) 8468 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8469 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8470 N10.getOperand(0)), 8471 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8472 N10.getOperand(1)), N0); 8473 } 8474 } 8475 8476 // More folding opportunities when target permits. 8477 if (Aggressive) { 8478 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 8479 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8480 // are currently only supported on binary nodes. 8481 if (Options.UnsafeFPMath && 8482 N0.getOpcode() == PreferredFusedOpcode && 8483 N0.getOperand(2).getOpcode() == ISD::FMUL && 8484 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8485 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8486 N0.getOperand(0), N0.getOperand(1), 8487 DAG.getNode(PreferredFusedOpcode, SL, VT, 8488 N0.getOperand(2).getOperand(0), 8489 N0.getOperand(2).getOperand(1), 8490 N1)); 8491 } 8492 8493 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 8494 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8495 // are currently only supported on binary nodes. 8496 if (Options.UnsafeFPMath && 8497 N1->getOpcode() == PreferredFusedOpcode && 8498 N1.getOperand(2).getOpcode() == ISD::FMUL && 8499 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 8500 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8501 N1.getOperand(0), N1.getOperand(1), 8502 DAG.getNode(PreferredFusedOpcode, SL, VT, 8503 N1.getOperand(2).getOperand(0), 8504 N1.getOperand(2).getOperand(1), 8505 N0)); 8506 } 8507 8508 if (AllowFusion && LookThroughFPExt) { 8509 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 8510 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 8511 auto FoldFAddFMAFPExtFMul = [&] ( 8512 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8513 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 8514 DAG.getNode(PreferredFusedOpcode, SL, VT, 8515 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8516 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8517 Z)); 8518 }; 8519 if (N0.getOpcode() == PreferredFusedOpcode) { 8520 SDValue N02 = N0.getOperand(2); 8521 if (N02.getOpcode() == ISD::FP_EXTEND) { 8522 SDValue N020 = N02.getOperand(0); 8523 if (N020.getOpcode() == ISD::FMUL) 8524 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 8525 N020.getOperand(0), N020.getOperand(1), 8526 N1); 8527 } 8528 } 8529 8530 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 8531 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 8532 // FIXME: This turns two single-precision and one double-precision 8533 // operation into two double-precision operations, which might not be 8534 // interesting for all targets, especially GPUs. 8535 auto FoldFAddFPExtFMAFMul = [&] ( 8536 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8537 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8538 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 8539 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 8540 DAG.getNode(PreferredFusedOpcode, SL, VT, 8541 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8542 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8543 Z)); 8544 }; 8545 if (N0.getOpcode() == ISD::FP_EXTEND) { 8546 SDValue N00 = N0.getOperand(0); 8547 if (N00.getOpcode() == PreferredFusedOpcode) { 8548 SDValue N002 = N00.getOperand(2); 8549 if (N002.getOpcode() == ISD::FMUL) 8550 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 8551 N002.getOperand(0), N002.getOperand(1), 8552 N1); 8553 } 8554 } 8555 8556 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 8557 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 8558 if (N1.getOpcode() == PreferredFusedOpcode) { 8559 SDValue N12 = N1.getOperand(2); 8560 if (N12.getOpcode() == ISD::FP_EXTEND) { 8561 SDValue N120 = N12.getOperand(0); 8562 if (N120.getOpcode() == ISD::FMUL) 8563 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 8564 N120.getOperand(0), N120.getOperand(1), 8565 N0); 8566 } 8567 } 8568 8569 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 8570 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 8571 // FIXME: This turns two single-precision and one double-precision 8572 // operation into two double-precision operations, which might not be 8573 // interesting for all targets, especially GPUs. 8574 if (N1.getOpcode() == ISD::FP_EXTEND) { 8575 SDValue N10 = N1.getOperand(0); 8576 if (N10.getOpcode() == PreferredFusedOpcode) { 8577 SDValue N102 = N10.getOperand(2); 8578 if (N102.getOpcode() == ISD::FMUL) 8579 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 8580 N102.getOperand(0), N102.getOperand(1), 8581 N0); 8582 } 8583 } 8584 } 8585 } 8586 8587 return SDValue(); 8588 } 8589 8590 /// Try to perform FMA combining on a given FSUB node. 8591 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 8592 SDValue N0 = N->getOperand(0); 8593 SDValue N1 = N->getOperand(1); 8594 EVT VT = N->getValueType(0); 8595 SDLoc SL(N); 8596 8597 const TargetOptions &Options = DAG.getTarget().Options; 8598 bool AllowFusion = 8599 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8600 8601 // Floating-point multiply-add with intermediate rounding. 8602 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8603 8604 // Floating-point multiply-add without intermediate rounding. 8605 bool HasFMA = 8606 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8607 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8608 8609 // No valid opcode, do not combine. 8610 if (!HasFMAD && !HasFMA) 8611 return SDValue(); 8612 8613 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8614 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8615 return SDValue(); 8616 8617 // Always prefer FMAD to FMA for precision. 8618 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8619 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8620 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8621 8622 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 8623 if (N0.getOpcode() == ISD::FMUL && 8624 (Aggressive || N0->hasOneUse())) { 8625 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8626 N0.getOperand(0), N0.getOperand(1), 8627 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8628 } 8629 8630 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 8631 // Note: Commutes FSUB operands. 8632 if (N1.getOpcode() == ISD::FMUL && 8633 (Aggressive || N1->hasOneUse())) 8634 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8635 DAG.getNode(ISD::FNEG, SL, VT, 8636 N1.getOperand(0)), 8637 N1.getOperand(1), N0); 8638 8639 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 8640 if (N0.getOpcode() == ISD::FNEG && 8641 N0.getOperand(0).getOpcode() == ISD::FMUL && 8642 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 8643 SDValue N00 = N0.getOperand(0).getOperand(0); 8644 SDValue N01 = N0.getOperand(0).getOperand(1); 8645 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8646 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 8647 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8648 } 8649 8650 // Look through FP_EXTEND nodes to do more combining. 8651 if (AllowFusion && LookThroughFPExt) { 8652 // fold (fsub (fpext (fmul x, y)), z) 8653 // -> (fma (fpext x), (fpext y), (fneg z)) 8654 if (N0.getOpcode() == ISD::FP_EXTEND) { 8655 SDValue N00 = N0.getOperand(0); 8656 if (N00.getOpcode() == ISD::FMUL) 8657 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8658 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8659 N00.getOperand(0)), 8660 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8661 N00.getOperand(1)), 8662 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8663 } 8664 8665 // fold (fsub x, (fpext (fmul y, z))) 8666 // -> (fma (fneg (fpext y)), (fpext z), x) 8667 // Note: Commutes FSUB operands. 8668 if (N1.getOpcode() == ISD::FP_EXTEND) { 8669 SDValue N10 = N1.getOperand(0); 8670 if (N10.getOpcode() == ISD::FMUL) 8671 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8672 DAG.getNode(ISD::FNEG, SL, VT, 8673 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8674 N10.getOperand(0))), 8675 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8676 N10.getOperand(1)), 8677 N0); 8678 } 8679 8680 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8681 // -> (fneg (fma (fpext x), (fpext y), z)) 8682 // Note: This could be removed with appropriate canonicalization of the 8683 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8684 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8685 // from implementing the canonicalization in visitFSUB. 8686 if (N0.getOpcode() == ISD::FP_EXTEND) { 8687 SDValue N00 = N0.getOperand(0); 8688 if (N00.getOpcode() == ISD::FNEG) { 8689 SDValue N000 = N00.getOperand(0); 8690 if (N000.getOpcode() == ISD::FMUL) { 8691 return DAG.getNode(ISD::FNEG, SL, VT, 8692 DAG.getNode(PreferredFusedOpcode, SL, VT, 8693 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8694 N000.getOperand(0)), 8695 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8696 N000.getOperand(1)), 8697 N1)); 8698 } 8699 } 8700 } 8701 8702 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8703 // -> (fneg (fma (fpext x)), (fpext y), z) 8704 // Note: This could be removed with appropriate canonicalization of the 8705 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8706 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8707 // from implementing the canonicalization in visitFSUB. 8708 if (N0.getOpcode() == ISD::FNEG) { 8709 SDValue N00 = N0.getOperand(0); 8710 if (N00.getOpcode() == ISD::FP_EXTEND) { 8711 SDValue N000 = N00.getOperand(0); 8712 if (N000.getOpcode() == ISD::FMUL) { 8713 return DAG.getNode(ISD::FNEG, SL, VT, 8714 DAG.getNode(PreferredFusedOpcode, SL, VT, 8715 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8716 N000.getOperand(0)), 8717 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8718 N000.getOperand(1)), 8719 N1)); 8720 } 8721 } 8722 } 8723 8724 } 8725 8726 // More folding opportunities when target permits. 8727 if (Aggressive) { 8728 // fold (fsub (fma x, y, (fmul u, v)), z) 8729 // -> (fma x, y (fma u, v, (fneg z))) 8730 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8731 // are currently only supported on binary nodes. 8732 if (Options.UnsafeFPMath && 8733 N0.getOpcode() == PreferredFusedOpcode && 8734 N0.getOperand(2).getOpcode() == ISD::FMUL && 8735 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8736 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8737 N0.getOperand(0), N0.getOperand(1), 8738 DAG.getNode(PreferredFusedOpcode, SL, VT, 8739 N0.getOperand(2).getOperand(0), 8740 N0.getOperand(2).getOperand(1), 8741 DAG.getNode(ISD::FNEG, SL, VT, 8742 N1))); 8743 } 8744 8745 // fold (fsub x, (fma y, z, (fmul u, v))) 8746 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8747 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8748 // are currently only supported on binary nodes. 8749 if (Options.UnsafeFPMath && 8750 N1.getOpcode() == PreferredFusedOpcode && 8751 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8752 SDValue N20 = N1.getOperand(2).getOperand(0); 8753 SDValue N21 = N1.getOperand(2).getOperand(1); 8754 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8755 DAG.getNode(ISD::FNEG, SL, VT, 8756 N1.getOperand(0)), 8757 N1.getOperand(1), 8758 DAG.getNode(PreferredFusedOpcode, SL, VT, 8759 DAG.getNode(ISD::FNEG, SL, VT, N20), 8760 8761 N21, N0)); 8762 } 8763 8764 if (AllowFusion && LookThroughFPExt) { 8765 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8766 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8767 if (N0.getOpcode() == PreferredFusedOpcode) { 8768 SDValue N02 = N0.getOperand(2); 8769 if (N02.getOpcode() == ISD::FP_EXTEND) { 8770 SDValue N020 = N02.getOperand(0); 8771 if (N020.getOpcode() == ISD::FMUL) 8772 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8773 N0.getOperand(0), N0.getOperand(1), 8774 DAG.getNode(PreferredFusedOpcode, SL, VT, 8775 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8776 N020.getOperand(0)), 8777 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8778 N020.getOperand(1)), 8779 DAG.getNode(ISD::FNEG, SL, VT, 8780 N1))); 8781 } 8782 } 8783 8784 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8785 // -> (fma (fpext x), (fpext y), 8786 // (fma (fpext u), (fpext v), (fneg z))) 8787 // FIXME: This turns two single-precision and one double-precision 8788 // operation into two double-precision operations, which might not be 8789 // interesting for all targets, especially GPUs. 8790 if (N0.getOpcode() == ISD::FP_EXTEND) { 8791 SDValue N00 = N0.getOperand(0); 8792 if (N00.getOpcode() == PreferredFusedOpcode) { 8793 SDValue N002 = N00.getOperand(2); 8794 if (N002.getOpcode() == ISD::FMUL) 8795 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8796 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8797 N00.getOperand(0)), 8798 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8799 N00.getOperand(1)), 8800 DAG.getNode(PreferredFusedOpcode, SL, VT, 8801 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8802 N002.getOperand(0)), 8803 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8804 N002.getOperand(1)), 8805 DAG.getNode(ISD::FNEG, SL, VT, 8806 N1))); 8807 } 8808 } 8809 8810 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8811 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8812 if (N1.getOpcode() == PreferredFusedOpcode && 8813 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8814 SDValue N120 = N1.getOperand(2).getOperand(0); 8815 if (N120.getOpcode() == ISD::FMUL) { 8816 SDValue N1200 = N120.getOperand(0); 8817 SDValue N1201 = N120.getOperand(1); 8818 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8819 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8820 N1.getOperand(1), 8821 DAG.getNode(PreferredFusedOpcode, SL, VT, 8822 DAG.getNode(ISD::FNEG, SL, VT, 8823 DAG.getNode(ISD::FP_EXTEND, SL, 8824 VT, N1200)), 8825 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8826 N1201), 8827 N0)); 8828 } 8829 } 8830 8831 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8832 // -> (fma (fneg (fpext y)), (fpext z), 8833 // (fma (fneg (fpext u)), (fpext v), x)) 8834 // FIXME: This turns two single-precision and one double-precision 8835 // operation into two double-precision operations, which might not be 8836 // interesting for all targets, especially GPUs. 8837 if (N1.getOpcode() == ISD::FP_EXTEND && 8838 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8839 SDValue N100 = N1.getOperand(0).getOperand(0); 8840 SDValue N101 = N1.getOperand(0).getOperand(1); 8841 SDValue N102 = N1.getOperand(0).getOperand(2); 8842 if (N102.getOpcode() == ISD::FMUL) { 8843 SDValue N1020 = N102.getOperand(0); 8844 SDValue N1021 = N102.getOperand(1); 8845 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8846 DAG.getNode(ISD::FNEG, SL, VT, 8847 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8848 N100)), 8849 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8850 DAG.getNode(PreferredFusedOpcode, SL, VT, 8851 DAG.getNode(ISD::FNEG, SL, VT, 8852 DAG.getNode(ISD::FP_EXTEND, SL, 8853 VT, N1020)), 8854 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8855 N1021), 8856 N0)); 8857 } 8858 } 8859 } 8860 } 8861 8862 return SDValue(); 8863 } 8864 8865 /// Try to perform FMA combining on a given FMUL node based on the distributive 8866 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 8867 /// subtraction instead of addition). 8868 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 8869 SDValue N0 = N->getOperand(0); 8870 SDValue N1 = N->getOperand(1); 8871 EVT VT = N->getValueType(0); 8872 SDLoc SL(N); 8873 8874 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8875 8876 const TargetOptions &Options = DAG.getTarget().Options; 8877 8878 // The transforms below are incorrect when x == 0 and y == inf, because the 8879 // intermediate multiplication produces a nan. 8880 if (!Options.NoInfsFPMath) 8881 return SDValue(); 8882 8883 // Floating-point multiply-add without intermediate rounding. 8884 bool HasFMA = 8885 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 8886 TLI.isFMAFasterThanFMulAndFAdd(VT) && 8887 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8888 8889 // Floating-point multiply-add with intermediate rounding. This can result 8890 // in a less precise result due to the changed rounding order. 8891 bool HasFMAD = Options.UnsafeFPMath && 8892 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8893 8894 // No valid opcode, do not combine. 8895 if (!HasFMAD && !HasFMA) 8896 return SDValue(); 8897 8898 // Always prefer FMAD to FMA for precision. 8899 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8900 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8901 8902 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8903 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8904 auto FuseFADD = [&](SDValue X, SDValue Y) { 8905 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8906 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8907 if (XC1 && XC1->isExactlyValue(+1.0)) 8908 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8909 if (XC1 && XC1->isExactlyValue(-1.0)) 8910 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8911 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8912 } 8913 return SDValue(); 8914 }; 8915 8916 if (SDValue FMA = FuseFADD(N0, N1)) 8917 return FMA; 8918 if (SDValue FMA = FuseFADD(N1, N0)) 8919 return FMA; 8920 8921 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8922 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8923 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8924 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8925 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8926 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8927 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8928 if (XC0 && XC0->isExactlyValue(+1.0)) 8929 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8930 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8931 Y); 8932 if (XC0 && XC0->isExactlyValue(-1.0)) 8933 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8934 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8935 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8936 8937 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8938 if (XC1 && XC1->isExactlyValue(+1.0)) 8939 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8940 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8941 if (XC1 && XC1->isExactlyValue(-1.0)) 8942 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8943 } 8944 return SDValue(); 8945 }; 8946 8947 if (SDValue FMA = FuseFSUB(N0, N1)) 8948 return FMA; 8949 if (SDValue FMA = FuseFSUB(N1, N0)) 8950 return FMA; 8951 8952 return SDValue(); 8953 } 8954 8955 SDValue DAGCombiner::visitFADD(SDNode *N) { 8956 SDValue N0 = N->getOperand(0); 8957 SDValue N1 = N->getOperand(1); 8958 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8959 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8960 EVT VT = N->getValueType(0); 8961 SDLoc DL(N); 8962 const TargetOptions &Options = DAG.getTarget().Options; 8963 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8964 8965 // fold vector ops 8966 if (VT.isVector()) 8967 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8968 return FoldedVOp; 8969 8970 // fold (fadd c1, c2) -> c1 + c2 8971 if (N0CFP && N1CFP) 8972 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8973 8974 // canonicalize constant to RHS 8975 if (N0CFP && !N1CFP) 8976 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8977 8978 // fold (fadd A, (fneg B)) -> (fsub A, B) 8979 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8980 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8981 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8982 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8983 8984 // fold (fadd (fneg A), B) -> (fsub B, A) 8985 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8986 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8987 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8988 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8989 8990 // FIXME: Auto-upgrade the target/function-level option. 8991 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 8992 // fold (fadd A, 0) -> A 8993 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8994 if (N1C->isZero()) 8995 return N0; 8996 } 8997 8998 // If 'unsafe math' is enabled, fold lots of things. 8999 if (Options.UnsafeFPMath) { 9000 // No FP constant should be created after legalization as Instruction 9001 // Selection pass has a hard time dealing with FP constants. 9002 bool AllowNewConst = (Level < AfterLegalizeDAG); 9003 9004 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9005 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9006 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9007 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9008 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9009 Flags), 9010 Flags); 9011 9012 // If allowed, fold (fadd (fneg x), x) -> 0.0 9013 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9014 return DAG.getConstantFP(0.0, DL, VT); 9015 9016 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9017 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9018 return DAG.getConstantFP(0.0, DL, VT); 9019 9020 // We can fold chains of FADD's of the same value into multiplications. 9021 // This transform is not safe in general because we are reducing the number 9022 // of rounding steps. 9023 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9024 if (N0.getOpcode() == ISD::FMUL) { 9025 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9026 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9027 9028 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9029 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9030 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9031 DAG.getConstantFP(1.0, DL, VT), Flags); 9032 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9033 } 9034 9035 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9036 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9037 N1.getOperand(0) == N1.getOperand(1) && 9038 N0.getOperand(0) == N1.getOperand(0)) { 9039 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9040 DAG.getConstantFP(2.0, DL, VT), Flags); 9041 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9042 } 9043 } 9044 9045 if (N1.getOpcode() == ISD::FMUL) { 9046 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9047 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9048 9049 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9050 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9051 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9052 DAG.getConstantFP(1.0, DL, VT), Flags); 9053 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9054 } 9055 9056 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9057 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9058 N0.getOperand(0) == N0.getOperand(1) && 9059 N1.getOperand(0) == N0.getOperand(0)) { 9060 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9061 DAG.getConstantFP(2.0, DL, VT), Flags); 9062 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9063 } 9064 } 9065 9066 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9067 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9068 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9069 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9070 (N0.getOperand(0) == N1)) { 9071 return DAG.getNode(ISD::FMUL, DL, VT, 9072 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9073 } 9074 } 9075 9076 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9077 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9078 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9079 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9080 N1.getOperand(0) == N0) { 9081 return DAG.getNode(ISD::FMUL, DL, VT, 9082 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9083 } 9084 } 9085 9086 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9087 if (AllowNewConst && 9088 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9089 N0.getOperand(0) == N0.getOperand(1) && 9090 N1.getOperand(0) == N1.getOperand(1) && 9091 N0.getOperand(0) == N1.getOperand(0)) { 9092 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9093 DAG.getConstantFP(4.0, DL, VT), Flags); 9094 } 9095 } 9096 } // enable-unsafe-fp-math 9097 9098 // FADD -> FMA combines: 9099 if (SDValue Fused = visitFADDForFMACombine(N)) { 9100 AddToWorklist(Fused.getNode()); 9101 return Fused; 9102 } 9103 return SDValue(); 9104 } 9105 9106 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9107 SDValue N0 = N->getOperand(0); 9108 SDValue N1 = N->getOperand(1); 9109 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9110 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9111 EVT VT = N->getValueType(0); 9112 SDLoc DL(N); 9113 const TargetOptions &Options = DAG.getTarget().Options; 9114 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9115 9116 // fold vector ops 9117 if (VT.isVector()) 9118 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9119 return FoldedVOp; 9120 9121 // fold (fsub c1, c2) -> c1-c2 9122 if (N0CFP && N1CFP) 9123 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9124 9125 // fold (fsub A, (fneg B)) -> (fadd A, B) 9126 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9127 return DAG.getNode(ISD::FADD, DL, VT, N0, 9128 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9129 9130 // FIXME: Auto-upgrade the target/function-level option. 9131 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 9132 // (fsub 0, B) -> -B 9133 if (N0CFP && N0CFP->isZero()) { 9134 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9135 return GetNegatedExpression(N1, DAG, LegalOperations); 9136 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9137 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9138 } 9139 } 9140 9141 // If 'unsafe math' is enabled, fold lots of things. 9142 if (Options.UnsafeFPMath) { 9143 // (fsub A, 0) -> A 9144 if (N1CFP && N1CFP->isZero()) 9145 return N0; 9146 9147 // (fsub x, x) -> 0.0 9148 if (N0 == N1) 9149 return DAG.getConstantFP(0.0f, DL, VT); 9150 9151 // (fsub x, (fadd x, y)) -> (fneg y) 9152 // (fsub x, (fadd y, x)) -> (fneg y) 9153 if (N1.getOpcode() == ISD::FADD) { 9154 SDValue N10 = N1->getOperand(0); 9155 SDValue N11 = N1->getOperand(1); 9156 9157 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9158 return GetNegatedExpression(N11, DAG, LegalOperations); 9159 9160 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9161 return GetNegatedExpression(N10, DAG, LegalOperations); 9162 } 9163 } 9164 9165 // FSUB -> FMA combines: 9166 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9167 AddToWorklist(Fused.getNode()); 9168 return Fused; 9169 } 9170 9171 return SDValue(); 9172 } 9173 9174 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9175 SDValue N0 = N->getOperand(0); 9176 SDValue N1 = N->getOperand(1); 9177 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9178 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9179 EVT VT = N->getValueType(0); 9180 SDLoc DL(N); 9181 const TargetOptions &Options = DAG.getTarget().Options; 9182 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9183 9184 // fold vector ops 9185 if (VT.isVector()) { 9186 // This just handles C1 * C2 for vectors. Other vector folds are below. 9187 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9188 return FoldedVOp; 9189 } 9190 9191 // fold (fmul c1, c2) -> c1*c2 9192 if (N0CFP && N1CFP) 9193 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9194 9195 // canonicalize constant to RHS 9196 if (isConstantFPBuildVectorOrConstantFP(N0) && 9197 !isConstantFPBuildVectorOrConstantFP(N1)) 9198 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9199 9200 // fold (fmul A, 1.0) -> A 9201 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9202 return N0; 9203 9204 if (Options.UnsafeFPMath) { 9205 // fold (fmul A, 0) -> 0 9206 if (N1CFP && N1CFP->isZero()) 9207 return N1; 9208 9209 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9210 if (N0.getOpcode() == ISD::FMUL) { 9211 // Fold scalars or any vector constants (not just splats). 9212 // This fold is done in general by InstCombine, but extra fmul insts 9213 // may have been generated during lowering. 9214 SDValue N00 = N0.getOperand(0); 9215 SDValue N01 = N0.getOperand(1); 9216 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9217 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9218 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9219 9220 // Check 1: Make sure that the first operand of the inner multiply is NOT 9221 // a constant. Otherwise, we may induce infinite looping. 9222 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9223 // Check 2: Make sure that the second operand of the inner multiply and 9224 // the second operand of the outer multiply are constants. 9225 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9226 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9227 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9228 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9229 } 9230 } 9231 } 9232 9233 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9234 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9235 // during an early run of DAGCombiner can prevent folding with fmuls 9236 // inserted during lowering. 9237 if (N0.getOpcode() == ISD::FADD && 9238 (N0.getOperand(0) == N0.getOperand(1)) && 9239 N0.hasOneUse()) { 9240 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9241 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9242 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9243 } 9244 } 9245 9246 // fold (fmul X, 2.0) -> (fadd X, X) 9247 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9248 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9249 9250 // fold (fmul X, -1.0) -> (fneg X) 9251 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9252 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9253 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9254 9255 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9256 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9257 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9258 // Both can be negated for free, check to see if at least one is cheaper 9259 // negated. 9260 if (LHSNeg == 2 || RHSNeg == 2) 9261 return DAG.getNode(ISD::FMUL, DL, VT, 9262 GetNegatedExpression(N0, DAG, LegalOperations), 9263 GetNegatedExpression(N1, DAG, LegalOperations), 9264 Flags); 9265 } 9266 } 9267 9268 // FMUL -> FMA combines: 9269 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 9270 AddToWorklist(Fused.getNode()); 9271 return Fused; 9272 } 9273 9274 return SDValue(); 9275 } 9276 9277 SDValue DAGCombiner::visitFMA(SDNode *N) { 9278 SDValue N0 = N->getOperand(0); 9279 SDValue N1 = N->getOperand(1); 9280 SDValue N2 = N->getOperand(2); 9281 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9282 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9283 EVT VT = N->getValueType(0); 9284 SDLoc DL(N); 9285 const TargetOptions &Options = DAG.getTarget().Options; 9286 9287 // Constant fold FMA. 9288 if (isa<ConstantFPSDNode>(N0) && 9289 isa<ConstantFPSDNode>(N1) && 9290 isa<ConstantFPSDNode>(N2)) { 9291 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 9292 } 9293 9294 if (Options.UnsafeFPMath) { 9295 if (N0CFP && N0CFP->isZero()) 9296 return N2; 9297 if (N1CFP && N1CFP->isZero()) 9298 return N2; 9299 } 9300 // TODO: The FMA node should have flags that propagate to these nodes. 9301 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9302 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 9303 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9304 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 9305 9306 // Canonicalize (fma c, x, y) -> (fma x, c, y) 9307 if (isConstantFPBuildVectorOrConstantFP(N0) && 9308 !isConstantFPBuildVectorOrConstantFP(N1)) 9309 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 9310 9311 // TODO: FMA nodes should have flags that propagate to the created nodes. 9312 // For now, create a Flags object for use with all unsafe math transforms. 9313 SDNodeFlags Flags; 9314 Flags.setUnsafeAlgebra(true); 9315 9316 if (Options.UnsafeFPMath) { 9317 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 9318 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 9319 isConstantFPBuildVectorOrConstantFP(N1) && 9320 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 9321 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9322 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 9323 &Flags), &Flags); 9324 } 9325 9326 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 9327 if (N0.getOpcode() == ISD::FMUL && 9328 isConstantFPBuildVectorOrConstantFP(N1) && 9329 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 9330 return DAG.getNode(ISD::FMA, DL, VT, 9331 N0.getOperand(0), 9332 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 9333 &Flags), 9334 N2); 9335 } 9336 } 9337 9338 // (fma x, 1, y) -> (fadd x, y) 9339 // (fma x, -1, y) -> (fadd (fneg x), y) 9340 if (N1CFP) { 9341 if (N1CFP->isExactlyValue(1.0)) 9342 // TODO: The FMA node should have flags that propagate to this node. 9343 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 9344 9345 if (N1CFP->isExactlyValue(-1.0) && 9346 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 9347 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 9348 AddToWorklist(RHSNeg.getNode()); 9349 // TODO: The FMA node should have flags that propagate to this node. 9350 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 9351 } 9352 } 9353 9354 if (Options.UnsafeFPMath) { 9355 // (fma x, c, x) -> (fmul x, (c+1)) 9356 if (N1CFP && N0 == N2) { 9357 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9358 DAG.getNode(ISD::FADD, DL, VT, N1, 9359 DAG.getConstantFP(1.0, DL, VT), &Flags), 9360 &Flags); 9361 } 9362 9363 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 9364 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 9365 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9366 DAG.getNode(ISD::FADD, DL, VT, N1, 9367 DAG.getConstantFP(-1.0, DL, VT), &Flags), 9368 &Flags); 9369 } 9370 } 9371 9372 return SDValue(); 9373 } 9374 9375 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9376 // reciprocal. 9377 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 9378 // Notice that this is not always beneficial. One reason is different targets 9379 // may have different costs for FDIV and FMUL, so sometimes the cost of two 9380 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 9381 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 9382 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 9383 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 9384 const SDNodeFlags *Flags = N->getFlags(); 9385 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 9386 return SDValue(); 9387 9388 // Skip if current node is a reciprocal. 9389 SDValue N0 = N->getOperand(0); 9390 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9391 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9392 return SDValue(); 9393 9394 // Exit early if the target does not want this transform or if there can't 9395 // possibly be enough uses of the divisor to make the transform worthwhile. 9396 SDValue N1 = N->getOperand(1); 9397 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 9398 if (!MinUses || N1->use_size() < MinUses) 9399 return SDValue(); 9400 9401 // Find all FDIV users of the same divisor. 9402 // Use a set because duplicates may be present in the user list. 9403 SetVector<SDNode *> Users; 9404 for (auto *U : N1->uses()) { 9405 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 9406 // This division is eligible for optimization only if global unsafe math 9407 // is enabled or if this division allows reciprocal formation. 9408 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 9409 Users.insert(U); 9410 } 9411 } 9412 9413 // Now that we have the actual number of divisor uses, make sure it meets 9414 // the minimum threshold specified by the target. 9415 if (Users.size() < MinUses) 9416 return SDValue(); 9417 9418 EVT VT = N->getValueType(0); 9419 SDLoc DL(N); 9420 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 9421 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 9422 9423 // Dividend / Divisor -> Dividend * Reciprocal 9424 for (auto *U : Users) { 9425 SDValue Dividend = U->getOperand(0); 9426 if (Dividend != FPOne) { 9427 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 9428 Reciprocal, Flags); 9429 CombineTo(U, NewNode); 9430 } else if (U != Reciprocal.getNode()) { 9431 // In the absence of fast-math-flags, this user node is always the 9432 // same node as Reciprocal, but with FMF they may be different nodes. 9433 CombineTo(U, Reciprocal); 9434 } 9435 } 9436 return SDValue(N, 0); // N was replaced. 9437 } 9438 9439 SDValue DAGCombiner::visitFDIV(SDNode *N) { 9440 SDValue N0 = N->getOperand(0); 9441 SDValue N1 = N->getOperand(1); 9442 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9443 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9444 EVT VT = N->getValueType(0); 9445 SDLoc DL(N); 9446 const TargetOptions &Options = DAG.getTarget().Options; 9447 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9448 9449 // fold vector ops 9450 if (VT.isVector()) 9451 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9452 return FoldedVOp; 9453 9454 // fold (fdiv c1, c2) -> c1/c2 9455 if (N0CFP && N1CFP) 9456 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 9457 9458 if (Options.UnsafeFPMath) { 9459 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 9460 if (N1CFP) { 9461 // Compute the reciprocal 1.0 / c2. 9462 const APFloat &N1APF = N1CFP->getValueAPF(); 9463 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 9464 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 9465 // Only do the transform if the reciprocal is a legal fp immediate that 9466 // isn't too nasty (eg NaN, denormal, ...). 9467 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 9468 (!LegalOperations || 9469 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 9470 // backend)... we should handle this gracefully after Legalize. 9471 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 9472 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 9473 TLI.isFPImmLegal(Recip, VT))) 9474 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9475 DAG.getConstantFP(Recip, DL, VT), Flags); 9476 } 9477 9478 // If this FDIV is part of a reciprocal square root, it may be folded 9479 // into a target-specific square root estimate instruction. 9480 if (N1.getOpcode() == ISD::FSQRT) { 9481 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 9482 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9483 } 9484 } else if (N1.getOpcode() == ISD::FP_EXTEND && 9485 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9486 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9487 Flags)) { 9488 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 9489 AddToWorklist(RV.getNode()); 9490 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9491 } 9492 } else if (N1.getOpcode() == ISD::FP_ROUND && 9493 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9494 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9495 Flags)) { 9496 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 9497 AddToWorklist(RV.getNode()); 9498 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9499 } 9500 } else if (N1.getOpcode() == ISD::FMUL) { 9501 // Look through an FMUL. Even though this won't remove the FDIV directly, 9502 // it's still worthwhile to get rid of the FSQRT if possible. 9503 SDValue SqrtOp; 9504 SDValue OtherOp; 9505 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9506 SqrtOp = N1.getOperand(0); 9507 OtherOp = N1.getOperand(1); 9508 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 9509 SqrtOp = N1.getOperand(1); 9510 OtherOp = N1.getOperand(0); 9511 } 9512 if (SqrtOp.getNode()) { 9513 // We found a FSQRT, so try to make this fold: 9514 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 9515 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 9516 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 9517 AddToWorklist(RV.getNode()); 9518 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9519 } 9520 } 9521 } 9522 9523 // Fold into a reciprocal estimate and multiply instead of a real divide. 9524 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 9525 AddToWorklist(RV.getNode()); 9526 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9527 } 9528 } 9529 9530 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 9531 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9532 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9533 // Both can be negated for free, check to see if at least one is cheaper 9534 // negated. 9535 if (LHSNeg == 2 || RHSNeg == 2) 9536 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 9537 GetNegatedExpression(N0, DAG, LegalOperations), 9538 GetNegatedExpression(N1, DAG, LegalOperations), 9539 Flags); 9540 } 9541 } 9542 9543 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 9544 return CombineRepeatedDivisors; 9545 9546 return SDValue(); 9547 } 9548 9549 SDValue DAGCombiner::visitFREM(SDNode *N) { 9550 SDValue N0 = N->getOperand(0); 9551 SDValue N1 = N->getOperand(1); 9552 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9553 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9554 EVT VT = N->getValueType(0); 9555 9556 // fold (frem c1, c2) -> fmod(c1,c2) 9557 if (N0CFP && N1CFP) 9558 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 9559 &cast<BinaryWithFlagsSDNode>(N)->Flags); 9560 9561 return SDValue(); 9562 } 9563 9564 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 9565 if (!DAG.getTarget().Options.UnsafeFPMath) 9566 return SDValue(); 9567 9568 SDValue N0 = N->getOperand(0); 9569 if (TLI.isFsqrtCheap(N0, DAG)) 9570 return SDValue(); 9571 9572 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 9573 // For now, create a Flags object for use with all unsafe math transforms. 9574 SDNodeFlags Flags; 9575 Flags.setUnsafeAlgebra(true); 9576 return buildSqrtEstimate(N0, &Flags); 9577 } 9578 9579 /// copysign(x, fp_extend(y)) -> copysign(x, y) 9580 /// copysign(x, fp_round(y)) -> copysign(x, y) 9581 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 9582 SDValue N1 = N->getOperand(1); 9583 if ((N1.getOpcode() == ISD::FP_EXTEND || 9584 N1.getOpcode() == ISD::FP_ROUND)) { 9585 // Do not optimize out type conversion of f128 type yet. 9586 // For some targets like x86_64, configuration is changed to keep one f128 9587 // value in one SSE register, but instruction selection cannot handle 9588 // FCOPYSIGN on SSE registers yet. 9589 EVT N1VT = N1->getValueType(0); 9590 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 9591 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 9592 } 9593 return false; 9594 } 9595 9596 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 9597 SDValue N0 = N->getOperand(0); 9598 SDValue N1 = N->getOperand(1); 9599 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9600 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9601 EVT VT = N->getValueType(0); 9602 9603 if (N0CFP && N1CFP) // Constant fold 9604 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 9605 9606 if (N1CFP) { 9607 const APFloat &V = N1CFP->getValueAPF(); 9608 // copysign(x, c1) -> fabs(x) iff ispos(c1) 9609 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 9610 if (!V.isNegative()) { 9611 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 9612 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9613 } else { 9614 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9615 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9616 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 9617 } 9618 } 9619 9620 // copysign(fabs(x), y) -> copysign(x, y) 9621 // copysign(fneg(x), y) -> copysign(x, y) 9622 // copysign(copysign(x,z), y) -> copysign(x, y) 9623 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 9624 N0.getOpcode() == ISD::FCOPYSIGN) 9625 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 9626 9627 // copysign(x, abs(y)) -> abs(x) 9628 if (N1.getOpcode() == ISD::FABS) 9629 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9630 9631 // copysign(x, copysign(y,z)) -> copysign(x, z) 9632 if (N1.getOpcode() == ISD::FCOPYSIGN) 9633 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 9634 9635 // copysign(x, fp_extend(y)) -> copysign(x, y) 9636 // copysign(x, fp_round(y)) -> copysign(x, y) 9637 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 9638 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 9639 9640 return SDValue(); 9641 } 9642 9643 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 9644 SDValue N0 = N->getOperand(0); 9645 EVT VT = N->getValueType(0); 9646 EVT OpVT = N0.getValueType(); 9647 9648 // fold (sint_to_fp c1) -> c1fp 9649 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9650 // ...but only if the target supports immediate floating-point values 9651 (!LegalOperations || 9652 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9653 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9654 9655 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 9656 // but UINT_TO_FP is legal on this target, try to convert. 9657 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 9658 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 9659 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 9660 if (DAG.SignBitIsZero(N0)) 9661 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9662 } 9663 9664 // The next optimizations are desirable only if SELECT_CC can be lowered. 9665 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9666 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9667 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 9668 !VT.isVector() && 9669 (!LegalOperations || 9670 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9671 SDLoc DL(N); 9672 SDValue Ops[] = 9673 { N0.getOperand(0), N0.getOperand(1), 9674 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9675 N0.getOperand(2) }; 9676 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9677 } 9678 9679 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9680 // (select_cc x, y, 1.0, 0.0,, cc) 9681 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9682 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9683 (!LegalOperations || 9684 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9685 SDLoc DL(N); 9686 SDValue Ops[] = 9687 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9688 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9689 N0.getOperand(0).getOperand(2) }; 9690 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9691 } 9692 } 9693 9694 return SDValue(); 9695 } 9696 9697 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9698 SDValue N0 = N->getOperand(0); 9699 EVT VT = N->getValueType(0); 9700 EVT OpVT = N0.getValueType(); 9701 9702 // fold (uint_to_fp c1) -> c1fp 9703 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9704 // ...but only if the target supports immediate floating-point values 9705 (!LegalOperations || 9706 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9707 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9708 9709 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9710 // but SINT_TO_FP is legal on this target, try to convert. 9711 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9712 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9713 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9714 if (DAG.SignBitIsZero(N0)) 9715 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9716 } 9717 9718 // The next optimizations are desirable only if SELECT_CC can be lowered. 9719 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9720 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9721 9722 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9723 (!LegalOperations || 9724 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9725 SDLoc DL(N); 9726 SDValue Ops[] = 9727 { N0.getOperand(0), N0.getOperand(1), 9728 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9729 N0.getOperand(2) }; 9730 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9731 } 9732 } 9733 9734 return SDValue(); 9735 } 9736 9737 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9738 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9739 SDValue N0 = N->getOperand(0); 9740 EVT VT = N->getValueType(0); 9741 9742 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9743 return SDValue(); 9744 9745 SDValue Src = N0.getOperand(0); 9746 EVT SrcVT = Src.getValueType(); 9747 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9748 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9749 9750 // We can safely assume the conversion won't overflow the output range, 9751 // because (for example) (uint8_t)18293.f is undefined behavior. 9752 9753 // Since we can assume the conversion won't overflow, our decision as to 9754 // whether the input will fit in the float should depend on the minimum 9755 // of the input range and output range. 9756 9757 // This means this is also safe for a signed input and unsigned output, since 9758 // a negative input would lead to undefined behavior. 9759 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9760 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9761 unsigned ActualSize = std::min(InputSize, OutputSize); 9762 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9763 9764 // We can only fold away the float conversion if the input range can be 9765 // represented exactly in the float range. 9766 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9767 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9768 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9769 : ISD::ZERO_EXTEND; 9770 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9771 } 9772 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9773 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9774 return DAG.getBitcast(VT, Src); 9775 } 9776 return SDValue(); 9777 } 9778 9779 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9780 SDValue N0 = N->getOperand(0); 9781 EVT VT = N->getValueType(0); 9782 9783 // fold (fp_to_sint c1fp) -> c1 9784 if (isConstantFPBuildVectorOrConstantFP(N0)) 9785 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9786 9787 return FoldIntToFPToInt(N, DAG); 9788 } 9789 9790 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9791 SDValue N0 = N->getOperand(0); 9792 EVT VT = N->getValueType(0); 9793 9794 // fold (fp_to_uint c1fp) -> c1 9795 if (isConstantFPBuildVectorOrConstantFP(N0)) 9796 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9797 9798 return FoldIntToFPToInt(N, DAG); 9799 } 9800 9801 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9802 SDValue N0 = N->getOperand(0); 9803 SDValue N1 = N->getOperand(1); 9804 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9805 EVT VT = N->getValueType(0); 9806 9807 // fold (fp_round c1fp) -> c1fp 9808 if (N0CFP) 9809 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9810 9811 // fold (fp_round (fp_extend x)) -> x 9812 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9813 return N0.getOperand(0); 9814 9815 // fold (fp_round (fp_round x)) -> (fp_round x) 9816 if (N0.getOpcode() == ISD::FP_ROUND) { 9817 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9818 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 9819 9820 // Skip this folding if it results in an fp_round from f80 to f16. 9821 // 9822 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9823 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9824 // instructions from f32 or f64. Moreover, the first (value-preserving) 9825 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9826 // x86. 9827 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9828 return SDValue(); 9829 9830 // If the first fp_round isn't a value preserving truncation, it might 9831 // introduce a tie in the second fp_round, that wouldn't occur in the 9832 // single-step fp_round we want to fold to. 9833 // In other words, double rounding isn't the same as rounding. 9834 // Also, this is a value preserving truncation iff both fp_round's are. 9835 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9836 SDLoc DL(N); 9837 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9838 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9839 } 9840 } 9841 9842 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9843 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9844 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9845 N0.getOperand(0), N1); 9846 AddToWorklist(Tmp.getNode()); 9847 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9848 Tmp, N0.getOperand(1)); 9849 } 9850 9851 return SDValue(); 9852 } 9853 9854 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9855 SDValue N0 = N->getOperand(0); 9856 EVT VT = N->getValueType(0); 9857 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9858 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9859 9860 // fold (fp_round_inreg c1fp) -> c1fp 9861 if (N0CFP && isTypeLegal(EVT)) { 9862 SDLoc DL(N); 9863 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9864 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9865 } 9866 9867 return SDValue(); 9868 } 9869 9870 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9871 SDValue N0 = N->getOperand(0); 9872 EVT VT = N->getValueType(0); 9873 9874 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9875 if (N->hasOneUse() && 9876 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9877 return SDValue(); 9878 9879 // fold (fp_extend c1fp) -> c1fp 9880 if (isConstantFPBuildVectorOrConstantFP(N0)) 9881 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9882 9883 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9884 if (N0.getOpcode() == ISD::FP16_TO_FP && 9885 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9886 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9887 9888 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9889 // value of X. 9890 if (N0.getOpcode() == ISD::FP_ROUND 9891 && N0.getConstantOperandVal(1) == 1) { 9892 SDValue In = N0.getOperand(0); 9893 if (In.getValueType() == VT) return In; 9894 if (VT.bitsLT(In.getValueType())) 9895 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9896 In, N0.getOperand(1)); 9897 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9898 } 9899 9900 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9901 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9902 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9903 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9904 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9905 LN0->getChain(), 9906 LN0->getBasePtr(), N0.getValueType(), 9907 LN0->getMemOperand()); 9908 CombineTo(N, ExtLoad); 9909 CombineTo(N0.getNode(), 9910 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9911 N0.getValueType(), ExtLoad, 9912 DAG.getIntPtrConstant(1, SDLoc(N0))), 9913 ExtLoad.getValue(1)); 9914 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9915 } 9916 9917 return SDValue(); 9918 } 9919 9920 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9921 SDValue N0 = N->getOperand(0); 9922 EVT VT = N->getValueType(0); 9923 9924 // fold (fceil c1) -> fceil(c1) 9925 if (isConstantFPBuildVectorOrConstantFP(N0)) 9926 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9927 9928 return SDValue(); 9929 } 9930 9931 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9932 SDValue N0 = N->getOperand(0); 9933 EVT VT = N->getValueType(0); 9934 9935 // fold (ftrunc c1) -> ftrunc(c1) 9936 if (isConstantFPBuildVectorOrConstantFP(N0)) 9937 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9938 9939 return SDValue(); 9940 } 9941 9942 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9943 SDValue N0 = N->getOperand(0); 9944 EVT VT = N->getValueType(0); 9945 9946 // fold (ffloor c1) -> ffloor(c1) 9947 if (isConstantFPBuildVectorOrConstantFP(N0)) 9948 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9949 9950 return SDValue(); 9951 } 9952 9953 // FIXME: FNEG and FABS have a lot in common; refactor. 9954 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9955 SDValue N0 = N->getOperand(0); 9956 EVT VT = N->getValueType(0); 9957 9958 // Constant fold FNEG. 9959 if (isConstantFPBuildVectorOrConstantFP(N0)) 9960 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9961 9962 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9963 &DAG.getTarget().Options)) 9964 return GetNegatedExpression(N0, DAG, LegalOperations); 9965 9966 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9967 // constant pool values. 9968 if (!TLI.isFNegFree(VT) && 9969 N0.getOpcode() == ISD::BITCAST && 9970 N0.getNode()->hasOneUse()) { 9971 SDValue Int = N0.getOperand(0); 9972 EVT IntVT = Int.getValueType(); 9973 if (IntVT.isInteger() && !IntVT.isVector()) { 9974 APInt SignMask; 9975 if (N0.getValueType().isVector()) { 9976 // For a vector, get a mask such as 0x80... per scalar element 9977 // and splat it. 9978 SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits()); 9979 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9980 } else { 9981 // For a scalar, just generate 0x80... 9982 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9983 } 9984 SDLoc DL0(N0); 9985 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9986 DAG.getConstant(SignMask, DL0, IntVT)); 9987 AddToWorklist(Int.getNode()); 9988 return DAG.getBitcast(VT, Int); 9989 } 9990 } 9991 9992 // (fneg (fmul c, x)) -> (fmul -c, x) 9993 if (N0.getOpcode() == ISD::FMUL && 9994 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9995 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9996 if (CFP1) { 9997 APFloat CVal = CFP1->getValueAPF(); 9998 CVal.changeSign(); 9999 if (Level >= AfterLegalizeDAG && 10000 (TLI.isFPImmLegal(CVal, VT) || 10001 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10002 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10003 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10004 N0.getOperand(1)), 10005 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 10006 } 10007 } 10008 10009 return SDValue(); 10010 } 10011 10012 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10013 SDValue N0 = N->getOperand(0); 10014 SDValue N1 = N->getOperand(1); 10015 EVT VT = N->getValueType(0); 10016 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10017 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10018 10019 if (N0CFP && N1CFP) { 10020 const APFloat &C0 = N0CFP->getValueAPF(); 10021 const APFloat &C1 = N1CFP->getValueAPF(); 10022 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10023 } 10024 10025 // Canonicalize to constant on RHS. 10026 if (isConstantFPBuildVectorOrConstantFP(N0) && 10027 !isConstantFPBuildVectorOrConstantFP(N1)) 10028 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10029 10030 return SDValue(); 10031 } 10032 10033 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10034 SDValue N0 = N->getOperand(0); 10035 SDValue N1 = N->getOperand(1); 10036 EVT VT = N->getValueType(0); 10037 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10038 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10039 10040 if (N0CFP && N1CFP) { 10041 const APFloat &C0 = N0CFP->getValueAPF(); 10042 const APFloat &C1 = N1CFP->getValueAPF(); 10043 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10044 } 10045 10046 // Canonicalize to constant on RHS. 10047 if (isConstantFPBuildVectorOrConstantFP(N0) && 10048 !isConstantFPBuildVectorOrConstantFP(N1)) 10049 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10050 10051 return SDValue(); 10052 } 10053 10054 SDValue DAGCombiner::visitFABS(SDNode *N) { 10055 SDValue N0 = N->getOperand(0); 10056 EVT VT = N->getValueType(0); 10057 10058 // fold (fabs c1) -> fabs(c1) 10059 if (isConstantFPBuildVectorOrConstantFP(N0)) 10060 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10061 10062 // fold (fabs (fabs x)) -> (fabs x) 10063 if (N0.getOpcode() == ISD::FABS) 10064 return N->getOperand(0); 10065 10066 // fold (fabs (fneg x)) -> (fabs x) 10067 // fold (fabs (fcopysign x, y)) -> (fabs x) 10068 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10069 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10070 10071 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10072 // constant pool values. 10073 if (!TLI.isFAbsFree(VT) && 10074 N0.getOpcode() == ISD::BITCAST && 10075 N0.getNode()->hasOneUse()) { 10076 SDValue Int = N0.getOperand(0); 10077 EVT IntVT = Int.getValueType(); 10078 if (IntVT.isInteger() && !IntVT.isVector()) { 10079 APInt SignMask; 10080 if (N0.getValueType().isVector()) { 10081 // For a vector, get a mask such as 0x7f... per scalar element 10082 // and splat it. 10083 SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits()); 10084 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10085 } else { 10086 // For a scalar, just generate 0x7f... 10087 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 10088 } 10089 SDLoc DL(N0); 10090 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10091 DAG.getConstant(SignMask, DL, IntVT)); 10092 AddToWorklist(Int.getNode()); 10093 return DAG.getBitcast(N->getValueType(0), Int); 10094 } 10095 } 10096 10097 return SDValue(); 10098 } 10099 10100 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10101 SDValue Chain = N->getOperand(0); 10102 SDValue N1 = N->getOperand(1); 10103 SDValue N2 = N->getOperand(2); 10104 10105 // If N is a constant we could fold this into a fallthrough or unconditional 10106 // branch. However that doesn't happen very often in normal code, because 10107 // Instcombine/SimplifyCFG should have handled the available opportunities. 10108 // If we did this folding here, it would be necessary to update the 10109 // MachineBasicBlock CFG, which is awkward. 10110 10111 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10112 // on the target. 10113 if (N1.getOpcode() == ISD::SETCC && 10114 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10115 N1.getOperand(0).getValueType())) { 10116 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10117 Chain, N1.getOperand(2), 10118 N1.getOperand(0), N1.getOperand(1), N2); 10119 } 10120 10121 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10122 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10123 (N1.getOperand(0).hasOneUse() && 10124 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10125 SDNode *Trunc = nullptr; 10126 if (N1.getOpcode() == ISD::TRUNCATE) { 10127 // Look pass the truncate. 10128 Trunc = N1.getNode(); 10129 N1 = N1.getOperand(0); 10130 } 10131 10132 // Match this pattern so that we can generate simpler code: 10133 // 10134 // %a = ... 10135 // %b = and i32 %a, 2 10136 // %c = srl i32 %b, 1 10137 // brcond i32 %c ... 10138 // 10139 // into 10140 // 10141 // %a = ... 10142 // %b = and i32 %a, 2 10143 // %c = setcc eq %b, 0 10144 // brcond %c ... 10145 // 10146 // This applies only when the AND constant value has one bit set and the 10147 // SRL constant is equal to the log2 of the AND constant. The back-end is 10148 // smart enough to convert the result into a TEST/JMP sequence. 10149 SDValue Op0 = N1.getOperand(0); 10150 SDValue Op1 = N1.getOperand(1); 10151 10152 if (Op0.getOpcode() == ISD::AND && 10153 Op1.getOpcode() == ISD::Constant) { 10154 SDValue AndOp1 = Op0.getOperand(1); 10155 10156 if (AndOp1.getOpcode() == ISD::Constant) { 10157 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10158 10159 if (AndConst.isPowerOf2() && 10160 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10161 SDLoc DL(N); 10162 SDValue SetCC = 10163 DAG.getSetCC(DL, 10164 getSetCCResultType(Op0.getValueType()), 10165 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10166 ISD::SETNE); 10167 10168 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10169 MVT::Other, Chain, SetCC, N2); 10170 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10171 // will convert it back to (X & C1) >> C2. 10172 CombineTo(N, NewBRCond, false); 10173 // Truncate is dead. 10174 if (Trunc) 10175 deleteAndRecombine(Trunc); 10176 // Replace the uses of SRL with SETCC 10177 WorklistRemover DeadNodes(*this); 10178 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10179 deleteAndRecombine(N1.getNode()); 10180 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10181 } 10182 } 10183 } 10184 10185 if (Trunc) 10186 // Restore N1 if the above transformation doesn't match. 10187 N1 = N->getOperand(1); 10188 } 10189 10190 // Transform br(xor(x, y)) -> br(x != y) 10191 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 10192 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 10193 SDNode *TheXor = N1.getNode(); 10194 SDValue Op0 = TheXor->getOperand(0); 10195 SDValue Op1 = TheXor->getOperand(1); 10196 if (Op0.getOpcode() == Op1.getOpcode()) { 10197 // Avoid missing important xor optimizations. 10198 if (SDValue Tmp = visitXOR(TheXor)) { 10199 if (Tmp.getNode() != TheXor) { 10200 DEBUG(dbgs() << "\nReplacing.8 "; 10201 TheXor->dump(&DAG); 10202 dbgs() << "\nWith: "; 10203 Tmp.getNode()->dump(&DAG); 10204 dbgs() << '\n'); 10205 WorklistRemover DeadNodes(*this); 10206 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 10207 deleteAndRecombine(TheXor); 10208 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10209 MVT::Other, Chain, Tmp, N2); 10210 } 10211 10212 // visitXOR has changed XOR's operands or replaced the XOR completely, 10213 // bail out. 10214 return SDValue(N, 0); 10215 } 10216 } 10217 10218 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 10219 bool Equal = false; 10220 if (isOneConstant(Op0) && Op0.hasOneUse() && 10221 Op0.getOpcode() == ISD::XOR) { 10222 TheXor = Op0.getNode(); 10223 Equal = true; 10224 } 10225 10226 EVT SetCCVT = N1.getValueType(); 10227 if (LegalTypes) 10228 SetCCVT = getSetCCResultType(SetCCVT); 10229 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 10230 SetCCVT, 10231 Op0, Op1, 10232 Equal ? ISD::SETEQ : ISD::SETNE); 10233 // Replace the uses of XOR with SETCC 10234 WorklistRemover DeadNodes(*this); 10235 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10236 deleteAndRecombine(N1.getNode()); 10237 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10238 MVT::Other, Chain, SetCC, N2); 10239 } 10240 } 10241 10242 return SDValue(); 10243 } 10244 10245 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 10246 // 10247 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 10248 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 10249 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 10250 10251 // If N is a constant we could fold this into a fallthrough or unconditional 10252 // branch. However that doesn't happen very often in normal code, because 10253 // Instcombine/SimplifyCFG should have handled the available opportunities. 10254 // If we did this folding here, it would be necessary to update the 10255 // MachineBasicBlock CFG, which is awkward. 10256 10257 // Use SimplifySetCC to simplify SETCC's. 10258 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 10259 CondLHS, CondRHS, CC->get(), SDLoc(N), 10260 false); 10261 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 10262 10263 // fold to a simpler setcc 10264 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 10265 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10266 N->getOperand(0), Simp.getOperand(2), 10267 Simp.getOperand(0), Simp.getOperand(1), 10268 N->getOperand(4)); 10269 10270 return SDValue(); 10271 } 10272 10273 /// Return true if 'Use' is a load or a store that uses N as its base pointer 10274 /// and that N may be folded in the load / store addressing mode. 10275 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 10276 SelectionDAG &DAG, 10277 const TargetLowering &TLI) { 10278 EVT VT; 10279 unsigned AS; 10280 10281 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 10282 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 10283 return false; 10284 VT = LD->getMemoryVT(); 10285 AS = LD->getAddressSpace(); 10286 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 10287 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 10288 return false; 10289 VT = ST->getMemoryVT(); 10290 AS = ST->getAddressSpace(); 10291 } else 10292 return false; 10293 10294 TargetLowering::AddrMode AM; 10295 if (N->getOpcode() == ISD::ADD) { 10296 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10297 if (Offset) 10298 // [reg +/- imm] 10299 AM.BaseOffs = Offset->getSExtValue(); 10300 else 10301 // [reg +/- reg] 10302 AM.Scale = 1; 10303 } else if (N->getOpcode() == ISD::SUB) { 10304 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10305 if (Offset) 10306 // [reg +/- imm] 10307 AM.BaseOffs = -Offset->getSExtValue(); 10308 else 10309 // [reg +/- reg] 10310 AM.Scale = 1; 10311 } else 10312 return false; 10313 10314 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 10315 VT.getTypeForEVT(*DAG.getContext()), AS); 10316 } 10317 10318 /// Try turning a load/store into a pre-indexed load/store when the base 10319 /// pointer is an add or subtract and it has other uses besides the load/store. 10320 /// After the transformation, the new indexed load/store has effectively folded 10321 /// the add/subtract in and all of its other uses are redirected to the 10322 /// new load/store. 10323 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 10324 if (Level < AfterLegalizeDAG) 10325 return false; 10326 10327 bool isLoad = true; 10328 SDValue Ptr; 10329 EVT VT; 10330 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10331 if (LD->isIndexed()) 10332 return false; 10333 VT = LD->getMemoryVT(); 10334 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 10335 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 10336 return false; 10337 Ptr = LD->getBasePtr(); 10338 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10339 if (ST->isIndexed()) 10340 return false; 10341 VT = ST->getMemoryVT(); 10342 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 10343 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 10344 return false; 10345 Ptr = ST->getBasePtr(); 10346 isLoad = false; 10347 } else { 10348 return false; 10349 } 10350 10351 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 10352 // out. There is no reason to make this a preinc/predec. 10353 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 10354 Ptr.getNode()->hasOneUse()) 10355 return false; 10356 10357 // Ask the target to do addressing mode selection. 10358 SDValue BasePtr; 10359 SDValue Offset; 10360 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10361 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 10362 return false; 10363 10364 // Backends without true r+i pre-indexed forms may need to pass a 10365 // constant base with a variable offset so that constant coercion 10366 // will work with the patterns in canonical form. 10367 bool Swapped = false; 10368 if (isa<ConstantSDNode>(BasePtr)) { 10369 std::swap(BasePtr, Offset); 10370 Swapped = true; 10371 } 10372 10373 // Don't create a indexed load / store with zero offset. 10374 if (isNullConstant(Offset)) 10375 return false; 10376 10377 // Try turning it into a pre-indexed load / store except when: 10378 // 1) The new base ptr is a frame index. 10379 // 2) If N is a store and the new base ptr is either the same as or is a 10380 // predecessor of the value being stored. 10381 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 10382 // that would create a cycle. 10383 // 4) All uses are load / store ops that use it as old base ptr. 10384 10385 // Check #1. Preinc'ing a frame index would require copying the stack pointer 10386 // (plus the implicit offset) to a register to preinc anyway. 10387 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10388 return false; 10389 10390 // Check #2. 10391 if (!isLoad) { 10392 SDValue Val = cast<StoreSDNode>(N)->getValue(); 10393 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 10394 return false; 10395 } 10396 10397 // Caches for hasPredecessorHelper. 10398 SmallPtrSet<const SDNode *, 32> Visited; 10399 SmallVector<const SDNode *, 16> Worklist; 10400 Worklist.push_back(N); 10401 10402 // If the offset is a constant, there may be other adds of constants that 10403 // can be folded with this one. We should do this to avoid having to keep 10404 // a copy of the original base pointer. 10405 SmallVector<SDNode *, 16> OtherUses; 10406 if (isa<ConstantSDNode>(Offset)) 10407 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 10408 UE = BasePtr.getNode()->use_end(); 10409 UI != UE; ++UI) { 10410 SDUse &Use = UI.getUse(); 10411 // Skip the use that is Ptr and uses of other results from BasePtr's 10412 // node (important for nodes that return multiple results). 10413 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 10414 continue; 10415 10416 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 10417 continue; 10418 10419 if (Use.getUser()->getOpcode() != ISD::ADD && 10420 Use.getUser()->getOpcode() != ISD::SUB) { 10421 OtherUses.clear(); 10422 break; 10423 } 10424 10425 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 10426 if (!isa<ConstantSDNode>(Op1)) { 10427 OtherUses.clear(); 10428 break; 10429 } 10430 10431 // FIXME: In some cases, we can be smarter about this. 10432 if (Op1.getValueType() != Offset.getValueType()) { 10433 OtherUses.clear(); 10434 break; 10435 } 10436 10437 OtherUses.push_back(Use.getUser()); 10438 } 10439 10440 if (Swapped) 10441 std::swap(BasePtr, Offset); 10442 10443 // Now check for #3 and #4. 10444 bool RealUse = false; 10445 10446 for (SDNode *Use : Ptr.getNode()->uses()) { 10447 if (Use == N) 10448 continue; 10449 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 10450 return false; 10451 10452 // If Ptr may be folded in addressing mode of other use, then it's 10453 // not profitable to do this transformation. 10454 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 10455 RealUse = true; 10456 } 10457 10458 if (!RealUse) 10459 return false; 10460 10461 SDValue Result; 10462 if (isLoad) 10463 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10464 BasePtr, Offset, AM); 10465 else 10466 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10467 BasePtr, Offset, AM); 10468 ++PreIndexedNodes; 10469 ++NodesCombined; 10470 DEBUG(dbgs() << "\nReplacing.4 "; 10471 N->dump(&DAG); 10472 dbgs() << "\nWith: "; 10473 Result.getNode()->dump(&DAG); 10474 dbgs() << '\n'); 10475 WorklistRemover DeadNodes(*this); 10476 if (isLoad) { 10477 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10478 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10479 } else { 10480 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10481 } 10482 10483 // Finally, since the node is now dead, remove it from the graph. 10484 deleteAndRecombine(N); 10485 10486 if (Swapped) 10487 std::swap(BasePtr, Offset); 10488 10489 // Replace other uses of BasePtr that can be updated to use Ptr 10490 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 10491 unsigned OffsetIdx = 1; 10492 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 10493 OffsetIdx = 0; 10494 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 10495 BasePtr.getNode() && "Expected BasePtr operand"); 10496 10497 // We need to replace ptr0 in the following expression: 10498 // x0 * offset0 + y0 * ptr0 = t0 10499 // knowing that 10500 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 10501 // 10502 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 10503 // indexed load/store and the expresion that needs to be re-written. 10504 // 10505 // Therefore, we have: 10506 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 10507 10508 ConstantSDNode *CN = 10509 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 10510 int X0, X1, Y0, Y1; 10511 const APInt &Offset0 = CN->getAPIntValue(); 10512 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 10513 10514 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 10515 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 10516 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 10517 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 10518 10519 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 10520 10521 APInt CNV = Offset0; 10522 if (X0 < 0) CNV = -CNV; 10523 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 10524 else CNV = CNV - Offset1; 10525 10526 SDLoc DL(OtherUses[i]); 10527 10528 // We can now generate the new expression. 10529 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 10530 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 10531 10532 SDValue NewUse = DAG.getNode(Opcode, 10533 DL, 10534 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 10535 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 10536 deleteAndRecombine(OtherUses[i]); 10537 } 10538 10539 // Replace the uses of Ptr with uses of the updated base value. 10540 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 10541 deleteAndRecombine(Ptr.getNode()); 10542 10543 return true; 10544 } 10545 10546 /// Try to combine a load/store with a add/sub of the base pointer node into a 10547 /// post-indexed load/store. The transformation folded the add/subtract into the 10548 /// new indexed load/store effectively and all of its uses are redirected to the 10549 /// new load/store. 10550 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 10551 if (Level < AfterLegalizeDAG) 10552 return false; 10553 10554 bool isLoad = true; 10555 SDValue Ptr; 10556 EVT VT; 10557 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10558 if (LD->isIndexed()) 10559 return false; 10560 VT = LD->getMemoryVT(); 10561 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 10562 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 10563 return false; 10564 Ptr = LD->getBasePtr(); 10565 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10566 if (ST->isIndexed()) 10567 return false; 10568 VT = ST->getMemoryVT(); 10569 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 10570 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 10571 return false; 10572 Ptr = ST->getBasePtr(); 10573 isLoad = false; 10574 } else { 10575 return false; 10576 } 10577 10578 if (Ptr.getNode()->hasOneUse()) 10579 return false; 10580 10581 for (SDNode *Op : Ptr.getNode()->uses()) { 10582 if (Op == N || 10583 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 10584 continue; 10585 10586 SDValue BasePtr; 10587 SDValue Offset; 10588 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10589 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 10590 // Don't create a indexed load / store with zero offset. 10591 if (isNullConstant(Offset)) 10592 continue; 10593 10594 // Try turning it into a post-indexed load / store except when 10595 // 1) All uses are load / store ops that use it as base ptr (and 10596 // it may be folded as addressing mmode). 10597 // 2) Op must be independent of N, i.e. Op is neither a predecessor 10598 // nor a successor of N. Otherwise, if Op is folded that would 10599 // create a cycle. 10600 10601 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10602 continue; 10603 10604 // Check for #1. 10605 bool TryNext = false; 10606 for (SDNode *Use : BasePtr.getNode()->uses()) { 10607 if (Use == Ptr.getNode()) 10608 continue; 10609 10610 // If all the uses are load / store addresses, then don't do the 10611 // transformation. 10612 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 10613 bool RealUse = false; 10614 for (SDNode *UseUse : Use->uses()) { 10615 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 10616 RealUse = true; 10617 } 10618 10619 if (!RealUse) { 10620 TryNext = true; 10621 break; 10622 } 10623 } 10624 } 10625 10626 if (TryNext) 10627 continue; 10628 10629 // Check for #2 10630 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 10631 SDValue Result = isLoad 10632 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10633 BasePtr, Offset, AM) 10634 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10635 BasePtr, Offset, AM); 10636 ++PostIndexedNodes; 10637 ++NodesCombined; 10638 DEBUG(dbgs() << "\nReplacing.5 "; 10639 N->dump(&DAG); 10640 dbgs() << "\nWith: "; 10641 Result.getNode()->dump(&DAG); 10642 dbgs() << '\n'); 10643 WorklistRemover DeadNodes(*this); 10644 if (isLoad) { 10645 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10646 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10647 } else { 10648 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10649 } 10650 10651 // Finally, since the node is now dead, remove it from the graph. 10652 deleteAndRecombine(N); 10653 10654 // Replace the uses of Use with uses of the updated base value. 10655 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 10656 Result.getValue(isLoad ? 1 : 0)); 10657 deleteAndRecombine(Op); 10658 return true; 10659 } 10660 } 10661 } 10662 10663 return false; 10664 } 10665 10666 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 10667 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 10668 ISD::MemIndexedMode AM = LD->getAddressingMode(); 10669 assert(AM != ISD::UNINDEXED); 10670 SDValue BP = LD->getOperand(1); 10671 SDValue Inc = LD->getOperand(2); 10672 10673 // Some backends use TargetConstants for load offsets, but don't expect 10674 // TargetConstants in general ADD nodes. We can convert these constants into 10675 // regular Constants (if the constant is not opaque). 10676 assert((Inc.getOpcode() != ISD::TargetConstant || 10677 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10678 "Cannot split out indexing using opaque target constants"); 10679 if (Inc.getOpcode() == ISD::TargetConstant) { 10680 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10681 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10682 ConstInc->getValueType(0)); 10683 } 10684 10685 unsigned Opc = 10686 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10687 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10688 } 10689 10690 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10691 LoadSDNode *LD = cast<LoadSDNode>(N); 10692 SDValue Chain = LD->getChain(); 10693 SDValue Ptr = LD->getBasePtr(); 10694 10695 // If load is not volatile and there are no uses of the loaded value (and 10696 // the updated indexed value in case of indexed loads), change uses of the 10697 // chain value into uses of the chain input (i.e. delete the dead load). 10698 if (!LD->isVolatile()) { 10699 if (N->getValueType(1) == MVT::Other) { 10700 // Unindexed loads. 10701 if (!N->hasAnyUseOfValue(0)) { 10702 // It's not safe to use the two value CombineTo variant here. e.g. 10703 // v1, chain2 = load chain1, loc 10704 // v2, chain3 = load chain2, loc 10705 // v3 = add v2, c 10706 // Now we replace use of chain2 with chain1. This makes the second load 10707 // isomorphic to the one we are deleting, and thus makes this load live. 10708 DEBUG(dbgs() << "\nReplacing.6 "; 10709 N->dump(&DAG); 10710 dbgs() << "\nWith chain: "; 10711 Chain.getNode()->dump(&DAG); 10712 dbgs() << "\n"); 10713 WorklistRemover DeadNodes(*this); 10714 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10715 10716 if (N->use_empty()) 10717 deleteAndRecombine(N); 10718 10719 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10720 } 10721 } else { 10722 // Indexed loads. 10723 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10724 10725 // If this load has an opaque TargetConstant offset, then we cannot split 10726 // the indexing into an add/sub directly (that TargetConstant may not be 10727 // valid for a different type of node, and we cannot convert an opaque 10728 // target constant into a regular constant). 10729 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10730 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10731 10732 if (!N->hasAnyUseOfValue(0) && 10733 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10734 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10735 SDValue Index; 10736 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10737 Index = SplitIndexingFromLoad(LD); 10738 // Try to fold the base pointer arithmetic into subsequent loads and 10739 // stores. 10740 AddUsersToWorklist(N); 10741 } else 10742 Index = DAG.getUNDEF(N->getValueType(1)); 10743 DEBUG(dbgs() << "\nReplacing.7 "; 10744 N->dump(&DAG); 10745 dbgs() << "\nWith: "; 10746 Undef.getNode()->dump(&DAG); 10747 dbgs() << " and 2 other values\n"); 10748 WorklistRemover DeadNodes(*this); 10749 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10750 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10751 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10752 deleteAndRecombine(N); 10753 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10754 } 10755 } 10756 } 10757 10758 // If this load is directly stored, replace the load value with the stored 10759 // value. 10760 // TODO: Handle store large -> read small portion. 10761 // TODO: Handle TRUNCSTORE/LOADEXT 10762 if (OptLevel != CodeGenOpt::None && 10763 ISD::isNormalLoad(N) && !LD->isVolatile()) { 10764 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10765 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10766 if (PrevST->getBasePtr() == Ptr && 10767 PrevST->getValue().getValueType() == N->getValueType(0)) 10768 return CombineTo(N, Chain.getOperand(1), Chain); 10769 } 10770 } 10771 10772 // Try to infer better alignment information than the load already has. 10773 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10774 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10775 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10776 SDValue NewLoad = DAG.getExtLoad( 10777 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10778 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10779 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10780 if (NewLoad.getNode() != N) 10781 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10782 } 10783 } 10784 } 10785 10786 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10787 : DAG.getSubtarget().useAA(); 10788 #ifndef NDEBUG 10789 if (CombinerAAOnlyFunc.getNumOccurrences() && 10790 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10791 UseAA = false; 10792 #endif 10793 if (UseAA && LD->isUnindexed()) { 10794 // Walk up chain skipping non-aliasing memory nodes. 10795 SDValue BetterChain = FindBetterChain(N, Chain); 10796 10797 // If there is a better chain. 10798 if (Chain != BetterChain) { 10799 SDValue ReplLoad; 10800 10801 // Replace the chain to void dependency. 10802 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10803 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10804 BetterChain, Ptr, LD->getMemOperand()); 10805 } else { 10806 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10807 LD->getValueType(0), 10808 BetterChain, Ptr, LD->getMemoryVT(), 10809 LD->getMemOperand()); 10810 } 10811 10812 // Create token factor to keep old chain connected. 10813 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10814 MVT::Other, Chain, ReplLoad.getValue(1)); 10815 10816 // Make sure the new and old chains are cleaned up. 10817 AddToWorklist(Token.getNode()); 10818 10819 // Replace uses with load result and token factor. Don't add users 10820 // to work list. 10821 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10822 } 10823 } 10824 10825 // Try transforming N to an indexed load. 10826 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10827 return SDValue(N, 0); 10828 10829 // Try to slice up N to more direct loads if the slices are mapped to 10830 // different register banks or pairing can take place. 10831 if (SliceUpLoad(N)) 10832 return SDValue(N, 0); 10833 10834 return SDValue(); 10835 } 10836 10837 namespace { 10838 /// \brief Helper structure used to slice a load in smaller loads. 10839 /// Basically a slice is obtained from the following sequence: 10840 /// Origin = load Ty1, Base 10841 /// Shift = srl Ty1 Origin, CstTy Amount 10842 /// Inst = trunc Shift to Ty2 10843 /// 10844 /// Then, it will be rewriten into: 10845 /// Slice = load SliceTy, Base + SliceOffset 10846 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10847 /// 10848 /// SliceTy is deduced from the number of bits that are actually used to 10849 /// build Inst. 10850 struct LoadedSlice { 10851 /// \brief Helper structure used to compute the cost of a slice. 10852 struct Cost { 10853 /// Are we optimizing for code size. 10854 bool ForCodeSize; 10855 /// Various cost. 10856 unsigned Loads; 10857 unsigned Truncates; 10858 unsigned CrossRegisterBanksCopies; 10859 unsigned ZExts; 10860 unsigned Shift; 10861 10862 Cost(bool ForCodeSize = false) 10863 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10864 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10865 10866 /// \brief Get the cost of one isolated slice. 10867 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10868 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10869 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10870 EVT TruncType = LS.Inst->getValueType(0); 10871 EVT LoadedType = LS.getLoadedType(); 10872 if (TruncType != LoadedType && 10873 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10874 ZExts = 1; 10875 } 10876 10877 /// \brief Account for slicing gain in the current cost. 10878 /// Slicing provide a few gains like removing a shift or a 10879 /// truncate. This method allows to grow the cost of the original 10880 /// load with the gain from this slice. 10881 void addSliceGain(const LoadedSlice &LS) { 10882 // Each slice saves a truncate. 10883 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10884 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10885 LS.Inst->getValueType(0))) 10886 ++Truncates; 10887 // If there is a shift amount, this slice gets rid of it. 10888 if (LS.Shift) 10889 ++Shift; 10890 // If this slice can merge a cross register bank copy, account for it. 10891 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10892 ++CrossRegisterBanksCopies; 10893 } 10894 10895 Cost &operator+=(const Cost &RHS) { 10896 Loads += RHS.Loads; 10897 Truncates += RHS.Truncates; 10898 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10899 ZExts += RHS.ZExts; 10900 Shift += RHS.Shift; 10901 return *this; 10902 } 10903 10904 bool operator==(const Cost &RHS) const { 10905 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10906 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10907 ZExts == RHS.ZExts && Shift == RHS.Shift; 10908 } 10909 10910 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10911 10912 bool operator<(const Cost &RHS) const { 10913 // Assume cross register banks copies are as expensive as loads. 10914 // FIXME: Do we want some more target hooks? 10915 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10916 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10917 // Unless we are optimizing for code size, consider the 10918 // expensive operation first. 10919 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10920 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10921 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10922 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10923 } 10924 10925 bool operator>(const Cost &RHS) const { return RHS < *this; } 10926 10927 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10928 10929 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10930 }; 10931 // The last instruction that represent the slice. This should be a 10932 // truncate instruction. 10933 SDNode *Inst; 10934 // The original load instruction. 10935 LoadSDNode *Origin; 10936 // The right shift amount in bits from the original load. 10937 unsigned Shift; 10938 // The DAG from which Origin came from. 10939 // This is used to get some contextual information about legal types, etc. 10940 SelectionDAG *DAG; 10941 10942 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10943 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10944 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10945 10946 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10947 /// \return Result is \p BitWidth and has used bits set to 1 and 10948 /// not used bits set to 0. 10949 APInt getUsedBits() const { 10950 // Reproduce the trunc(lshr) sequence: 10951 // - Start from the truncated value. 10952 // - Zero extend to the desired bit width. 10953 // - Shift left. 10954 assert(Origin && "No original load to compare against."); 10955 unsigned BitWidth = Origin->getValueSizeInBits(0); 10956 assert(Inst && "This slice is not bound to an instruction"); 10957 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10958 "Extracted slice is bigger than the whole type!"); 10959 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10960 UsedBits.setAllBits(); 10961 UsedBits = UsedBits.zext(BitWidth); 10962 UsedBits <<= Shift; 10963 return UsedBits; 10964 } 10965 10966 /// \brief Get the size of the slice to be loaded in bytes. 10967 unsigned getLoadedSize() const { 10968 unsigned SliceSize = getUsedBits().countPopulation(); 10969 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10970 return SliceSize / 8; 10971 } 10972 10973 /// \brief Get the type that will be loaded for this slice. 10974 /// Note: This may not be the final type for the slice. 10975 EVT getLoadedType() const { 10976 assert(DAG && "Missing context"); 10977 LLVMContext &Ctxt = *DAG->getContext(); 10978 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10979 } 10980 10981 /// \brief Get the alignment of the load used for this slice. 10982 unsigned getAlignment() const { 10983 unsigned Alignment = Origin->getAlignment(); 10984 unsigned Offset = getOffsetFromBase(); 10985 if (Offset != 0) 10986 Alignment = MinAlign(Alignment, Alignment + Offset); 10987 return Alignment; 10988 } 10989 10990 /// \brief Check if this slice can be rewritten with legal operations. 10991 bool isLegal() const { 10992 // An invalid slice is not legal. 10993 if (!Origin || !Inst || !DAG) 10994 return false; 10995 10996 // Offsets are for indexed load only, we do not handle that. 10997 if (!Origin->getOffset().isUndef()) 10998 return false; 10999 11000 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11001 11002 // Check that the type is legal. 11003 EVT SliceType = getLoadedType(); 11004 if (!TLI.isTypeLegal(SliceType)) 11005 return false; 11006 11007 // Check that the load is legal for this type. 11008 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11009 return false; 11010 11011 // Check that the offset can be computed. 11012 // 1. Check its type. 11013 EVT PtrType = Origin->getBasePtr().getValueType(); 11014 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11015 return false; 11016 11017 // 2. Check that it fits in the immediate. 11018 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11019 return false; 11020 11021 // 3. Check that the computation is legal. 11022 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11023 return false; 11024 11025 // Check that the zext is legal if it needs one. 11026 EVT TruncateType = Inst->getValueType(0); 11027 if (TruncateType != SliceType && 11028 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11029 return false; 11030 11031 return true; 11032 } 11033 11034 /// \brief Get the offset in bytes of this slice in the original chunk of 11035 /// bits. 11036 /// \pre DAG != nullptr. 11037 uint64_t getOffsetFromBase() const { 11038 assert(DAG && "Missing context."); 11039 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11040 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11041 uint64_t Offset = Shift / 8; 11042 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11043 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11044 "The size of the original loaded type is not a multiple of a" 11045 " byte."); 11046 // If Offset is bigger than TySizeInBytes, it means we are loading all 11047 // zeros. This should have been optimized before in the process. 11048 assert(TySizeInBytes > Offset && 11049 "Invalid shift amount for given loaded size"); 11050 if (IsBigEndian) 11051 Offset = TySizeInBytes - Offset - getLoadedSize(); 11052 return Offset; 11053 } 11054 11055 /// \brief Generate the sequence of instructions to load the slice 11056 /// represented by this object and redirect the uses of this slice to 11057 /// this new sequence of instructions. 11058 /// \pre this->Inst && this->Origin are valid Instructions and this 11059 /// object passed the legal check: LoadedSlice::isLegal returned true. 11060 /// \return The last instruction of the sequence used to load the slice. 11061 SDValue loadSlice() const { 11062 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11063 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11064 SDValue BaseAddr = OldBaseAddr; 11065 // Get the offset in that chunk of bytes w.r.t. the endianness. 11066 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11067 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11068 if (Offset) { 11069 // BaseAddr = BaseAddr + Offset. 11070 EVT ArithType = BaseAddr.getValueType(); 11071 SDLoc DL(Origin); 11072 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11073 DAG->getConstant(Offset, DL, ArithType)); 11074 } 11075 11076 // Create the type of the loaded slice according to its size. 11077 EVT SliceType = getLoadedType(); 11078 11079 // Create the load for the slice. 11080 SDValue LastInst = 11081 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11082 Origin->getPointerInfo().getWithOffset(Offset), 11083 getAlignment(), Origin->getMemOperand()->getFlags()); 11084 // If the final type is not the same as the loaded type, this means that 11085 // we have to pad with zero. Create a zero extend for that. 11086 EVT FinalType = Inst->getValueType(0); 11087 if (SliceType != FinalType) 11088 LastInst = 11089 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11090 return LastInst; 11091 } 11092 11093 /// \brief Check if this slice can be merged with an expensive cross register 11094 /// bank copy. E.g., 11095 /// i = load i32 11096 /// f = bitcast i32 i to float 11097 bool canMergeExpensiveCrossRegisterBankCopy() const { 11098 if (!Inst || !Inst->hasOneUse()) 11099 return false; 11100 SDNode *Use = *Inst->use_begin(); 11101 if (Use->getOpcode() != ISD::BITCAST) 11102 return false; 11103 assert(DAG && "Missing context"); 11104 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11105 EVT ResVT = Use->getValueType(0); 11106 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11107 const TargetRegisterClass *ArgRC = 11108 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11109 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11110 return false; 11111 11112 // At this point, we know that we perform a cross-register-bank copy. 11113 // Check if it is expensive. 11114 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11115 // Assume bitcasts are cheap, unless both register classes do not 11116 // explicitly share a common sub class. 11117 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11118 return false; 11119 11120 // Check if it will be merged with the load. 11121 // 1. Check the alignment constraint. 11122 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11123 ResVT.getTypeForEVT(*DAG->getContext())); 11124 11125 if (RequiredAlignment > getAlignment()) 11126 return false; 11127 11128 // 2. Check that the load is a legal operation for that type. 11129 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11130 return false; 11131 11132 // 3. Check that we do not have a zext in the way. 11133 if (Inst->getValueType(0) != getLoadedType()) 11134 return false; 11135 11136 return true; 11137 } 11138 }; 11139 } 11140 11141 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11142 /// \p UsedBits looks like 0..0 1..1 0..0. 11143 static bool areUsedBitsDense(const APInt &UsedBits) { 11144 // If all the bits are one, this is dense! 11145 if (UsedBits.isAllOnesValue()) 11146 return true; 11147 11148 // Get rid of the unused bits on the right. 11149 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11150 // Get rid of the unused bits on the left. 11151 if (NarrowedUsedBits.countLeadingZeros()) 11152 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11153 // Check that the chunk of bits is completely used. 11154 return NarrowedUsedBits.isAllOnesValue(); 11155 } 11156 11157 /// \brief Check whether or not \p First and \p Second are next to each other 11158 /// in memory. This means that there is no hole between the bits loaded 11159 /// by \p First and the bits loaded by \p Second. 11160 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11161 const LoadedSlice &Second) { 11162 assert(First.Origin == Second.Origin && First.Origin && 11163 "Unable to match different memory origins."); 11164 APInt UsedBits = First.getUsedBits(); 11165 assert((UsedBits & Second.getUsedBits()) == 0 && 11166 "Slices are not supposed to overlap."); 11167 UsedBits |= Second.getUsedBits(); 11168 return areUsedBitsDense(UsedBits); 11169 } 11170 11171 /// \brief Adjust the \p GlobalLSCost according to the target 11172 /// paring capabilities and the layout of the slices. 11173 /// \pre \p GlobalLSCost should account for at least as many loads as 11174 /// there is in the slices in \p LoadedSlices. 11175 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11176 LoadedSlice::Cost &GlobalLSCost) { 11177 unsigned NumberOfSlices = LoadedSlices.size(); 11178 // If there is less than 2 elements, no pairing is possible. 11179 if (NumberOfSlices < 2) 11180 return; 11181 11182 // Sort the slices so that elements that are likely to be next to each 11183 // other in memory are next to each other in the list. 11184 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11185 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11186 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11187 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11188 }); 11189 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11190 // First (resp. Second) is the first (resp. Second) potentially candidate 11191 // to be placed in a paired load. 11192 const LoadedSlice *First = nullptr; 11193 const LoadedSlice *Second = nullptr; 11194 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 11195 // Set the beginning of the pair. 11196 First = Second) { 11197 11198 Second = &LoadedSlices[CurrSlice]; 11199 11200 // If First is NULL, it means we start a new pair. 11201 // Get to the next slice. 11202 if (!First) 11203 continue; 11204 11205 EVT LoadedType = First->getLoadedType(); 11206 11207 // If the types of the slices are different, we cannot pair them. 11208 if (LoadedType != Second->getLoadedType()) 11209 continue; 11210 11211 // Check if the target supplies paired loads for this type. 11212 unsigned RequiredAlignment = 0; 11213 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 11214 // move to the next pair, this type is hopeless. 11215 Second = nullptr; 11216 continue; 11217 } 11218 // Check if we meet the alignment requirement. 11219 if (RequiredAlignment > First->getAlignment()) 11220 continue; 11221 11222 // Check that both loads are next to each other in memory. 11223 if (!areSlicesNextToEachOther(*First, *Second)) 11224 continue; 11225 11226 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 11227 --GlobalLSCost.Loads; 11228 // Move to the next pair. 11229 Second = nullptr; 11230 } 11231 } 11232 11233 /// \brief Check the profitability of all involved LoadedSlice. 11234 /// Currently, it is considered profitable if there is exactly two 11235 /// involved slices (1) which are (2) next to each other in memory, and 11236 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 11237 /// 11238 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 11239 /// the elements themselves. 11240 /// 11241 /// FIXME: When the cost model will be mature enough, we can relax 11242 /// constraints (1) and (2). 11243 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11244 const APInt &UsedBits, bool ForCodeSize) { 11245 unsigned NumberOfSlices = LoadedSlices.size(); 11246 if (StressLoadSlicing) 11247 return NumberOfSlices > 1; 11248 11249 // Check (1). 11250 if (NumberOfSlices != 2) 11251 return false; 11252 11253 // Check (2). 11254 if (!areUsedBitsDense(UsedBits)) 11255 return false; 11256 11257 // Check (3). 11258 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 11259 // The original code has one big load. 11260 OrigCost.Loads = 1; 11261 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 11262 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 11263 // Accumulate the cost of all the slices. 11264 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 11265 GlobalSlicingCost += SliceCost; 11266 11267 // Account as cost in the original configuration the gain obtained 11268 // with the current slices. 11269 OrigCost.addSliceGain(LS); 11270 } 11271 11272 // If the target supports paired load, adjust the cost accordingly. 11273 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 11274 return OrigCost > GlobalSlicingCost; 11275 } 11276 11277 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 11278 /// operations, split it in the various pieces being extracted. 11279 /// 11280 /// This sort of thing is introduced by SROA. 11281 /// This slicing takes care not to insert overlapping loads. 11282 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 11283 bool DAGCombiner::SliceUpLoad(SDNode *N) { 11284 if (Level < AfterLegalizeDAG) 11285 return false; 11286 11287 LoadSDNode *LD = cast<LoadSDNode>(N); 11288 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 11289 !LD->getValueType(0).isInteger()) 11290 return false; 11291 11292 // Keep track of already used bits to detect overlapping values. 11293 // In that case, we will just abort the transformation. 11294 APInt UsedBits(LD->getValueSizeInBits(0), 0); 11295 11296 SmallVector<LoadedSlice, 4> LoadedSlices; 11297 11298 // Check if this load is used as several smaller chunks of bits. 11299 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 11300 // of computation for each trunc. 11301 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 11302 UI != UIEnd; ++UI) { 11303 // Skip the uses of the chain. 11304 if (UI.getUse().getResNo() != 0) 11305 continue; 11306 11307 SDNode *User = *UI; 11308 unsigned Shift = 0; 11309 11310 // Check if this is a trunc(lshr). 11311 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 11312 isa<ConstantSDNode>(User->getOperand(1))) { 11313 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 11314 User = *User->use_begin(); 11315 } 11316 11317 // At this point, User is a Truncate, iff we encountered, trunc or 11318 // trunc(lshr). 11319 if (User->getOpcode() != ISD::TRUNCATE) 11320 return false; 11321 11322 // The width of the type must be a power of 2 and greater than 8-bits. 11323 // Otherwise the load cannot be represented in LLVM IR. 11324 // Moreover, if we shifted with a non-8-bits multiple, the slice 11325 // will be across several bytes. We do not support that. 11326 unsigned Width = User->getValueSizeInBits(0); 11327 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 11328 return 0; 11329 11330 // Build the slice for this chain of computations. 11331 LoadedSlice LS(User, LD, Shift, &DAG); 11332 APInt CurrentUsedBits = LS.getUsedBits(); 11333 11334 // Check if this slice overlaps with another. 11335 if ((CurrentUsedBits & UsedBits) != 0) 11336 return false; 11337 // Update the bits used globally. 11338 UsedBits |= CurrentUsedBits; 11339 11340 // Check if the new slice would be legal. 11341 if (!LS.isLegal()) 11342 return false; 11343 11344 // Record the slice. 11345 LoadedSlices.push_back(LS); 11346 } 11347 11348 // Abort slicing if it does not seem to be profitable. 11349 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 11350 return false; 11351 11352 ++SlicedLoads; 11353 11354 // Rewrite each chain to use an independent load. 11355 // By construction, each chain can be represented by a unique load. 11356 11357 // Prepare the argument for the new token factor for all the slices. 11358 SmallVector<SDValue, 8> ArgChains; 11359 for (SmallVectorImpl<LoadedSlice>::const_iterator 11360 LSIt = LoadedSlices.begin(), 11361 LSItEnd = LoadedSlices.end(); 11362 LSIt != LSItEnd; ++LSIt) { 11363 SDValue SliceInst = LSIt->loadSlice(); 11364 CombineTo(LSIt->Inst, SliceInst, true); 11365 if (SliceInst.getOpcode() != ISD::LOAD) 11366 SliceInst = SliceInst.getOperand(0); 11367 assert(SliceInst->getOpcode() == ISD::LOAD && 11368 "It takes more than a zext to get to the loaded slice!!"); 11369 ArgChains.push_back(SliceInst.getValue(1)); 11370 } 11371 11372 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 11373 ArgChains); 11374 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11375 return true; 11376 } 11377 11378 /// Check to see if V is (and load (ptr), imm), where the load is having 11379 /// specific bytes cleared out. If so, return the byte size being masked out 11380 /// and the shift amount. 11381 static std::pair<unsigned, unsigned> 11382 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 11383 std::pair<unsigned, unsigned> Result(0, 0); 11384 11385 // Check for the structure we're looking for. 11386 if (V->getOpcode() != ISD::AND || 11387 !isa<ConstantSDNode>(V->getOperand(1)) || 11388 !ISD::isNormalLoad(V->getOperand(0).getNode())) 11389 return Result; 11390 11391 // Check the chain and pointer. 11392 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 11393 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 11394 11395 // The store should be chained directly to the load or be an operand of a 11396 // tokenfactor. 11397 if (LD == Chain.getNode()) 11398 ; // ok. 11399 else if (Chain->getOpcode() != ISD::TokenFactor) 11400 return Result; // Fail. 11401 else { 11402 bool isOk = false; 11403 for (const SDValue &ChainOp : Chain->op_values()) 11404 if (ChainOp.getNode() == LD) { 11405 isOk = true; 11406 break; 11407 } 11408 if (!isOk) return Result; 11409 } 11410 11411 // This only handles simple types. 11412 if (V.getValueType() != MVT::i16 && 11413 V.getValueType() != MVT::i32 && 11414 V.getValueType() != MVT::i64) 11415 return Result; 11416 11417 // Check the constant mask. Invert it so that the bits being masked out are 11418 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 11419 // follow the sign bit for uniformity. 11420 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 11421 unsigned NotMaskLZ = countLeadingZeros(NotMask); 11422 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 11423 unsigned NotMaskTZ = countTrailingZeros(NotMask); 11424 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 11425 if (NotMaskLZ == 64) return Result; // All zero mask. 11426 11427 // See if we have a continuous run of bits. If so, we have 0*1+0* 11428 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 11429 return Result; 11430 11431 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 11432 if (V.getValueType() != MVT::i64 && NotMaskLZ) 11433 NotMaskLZ -= 64-V.getValueSizeInBits(); 11434 11435 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 11436 switch (MaskedBytes) { 11437 case 1: 11438 case 2: 11439 case 4: break; 11440 default: return Result; // All one mask, or 5-byte mask. 11441 } 11442 11443 // Verify that the first bit starts at a multiple of mask so that the access 11444 // is aligned the same as the access width. 11445 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 11446 11447 Result.first = MaskedBytes; 11448 Result.second = NotMaskTZ/8; 11449 return Result; 11450 } 11451 11452 11453 /// Check to see if IVal is something that provides a value as specified by 11454 /// MaskInfo. If so, replace the specified store with a narrower store of 11455 /// truncated IVal. 11456 static SDNode * 11457 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 11458 SDValue IVal, StoreSDNode *St, 11459 DAGCombiner *DC) { 11460 unsigned NumBytes = MaskInfo.first; 11461 unsigned ByteShift = MaskInfo.second; 11462 SelectionDAG &DAG = DC->getDAG(); 11463 11464 // Check to see if IVal is all zeros in the part being masked in by the 'or' 11465 // that uses this. If not, this is not a replacement. 11466 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 11467 ByteShift*8, (ByteShift+NumBytes)*8); 11468 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 11469 11470 // Check that it is legal on the target to do this. It is legal if the new 11471 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 11472 // legalization. 11473 MVT VT = MVT::getIntegerVT(NumBytes*8); 11474 if (!DC->isTypeLegal(VT)) 11475 return nullptr; 11476 11477 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 11478 // shifted by ByteShift and truncated down to NumBytes. 11479 if (ByteShift) { 11480 SDLoc DL(IVal); 11481 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 11482 DAG.getConstant(ByteShift*8, DL, 11483 DC->getShiftAmountTy(IVal.getValueType()))); 11484 } 11485 11486 // Figure out the offset for the store and the alignment of the access. 11487 unsigned StOffset; 11488 unsigned NewAlign = St->getAlignment(); 11489 11490 if (DAG.getDataLayout().isLittleEndian()) 11491 StOffset = ByteShift; 11492 else 11493 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 11494 11495 SDValue Ptr = St->getBasePtr(); 11496 if (StOffset) { 11497 SDLoc DL(IVal); 11498 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 11499 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 11500 NewAlign = MinAlign(NewAlign, StOffset); 11501 } 11502 11503 // Truncate down to the new size. 11504 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 11505 11506 ++OpsNarrowed; 11507 return DAG 11508 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 11509 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 11510 .getNode(); 11511 } 11512 11513 11514 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 11515 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 11516 /// narrowing the load and store if it would end up being a win for performance 11517 /// or code size. 11518 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 11519 StoreSDNode *ST = cast<StoreSDNode>(N); 11520 if (ST->isVolatile()) 11521 return SDValue(); 11522 11523 SDValue Chain = ST->getChain(); 11524 SDValue Value = ST->getValue(); 11525 SDValue Ptr = ST->getBasePtr(); 11526 EVT VT = Value.getValueType(); 11527 11528 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 11529 return SDValue(); 11530 11531 unsigned Opc = Value.getOpcode(); 11532 11533 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 11534 // is a byte mask indicating a consecutive number of bytes, check to see if 11535 // Y is known to provide just those bytes. If so, we try to replace the 11536 // load + replace + store sequence with a single (narrower) store, which makes 11537 // the load dead. 11538 if (Opc == ISD::OR) { 11539 std::pair<unsigned, unsigned> MaskedLoad; 11540 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 11541 if (MaskedLoad.first) 11542 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11543 Value.getOperand(1), ST,this)) 11544 return SDValue(NewST, 0); 11545 11546 // Or is commutative, so try swapping X and Y. 11547 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 11548 if (MaskedLoad.first) 11549 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11550 Value.getOperand(0), ST,this)) 11551 return SDValue(NewST, 0); 11552 } 11553 11554 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 11555 Value.getOperand(1).getOpcode() != ISD::Constant) 11556 return SDValue(); 11557 11558 SDValue N0 = Value.getOperand(0); 11559 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 11560 Chain == SDValue(N0.getNode(), 1)) { 11561 LoadSDNode *LD = cast<LoadSDNode>(N0); 11562 if (LD->getBasePtr() != Ptr || 11563 LD->getPointerInfo().getAddrSpace() != 11564 ST->getPointerInfo().getAddrSpace()) 11565 return SDValue(); 11566 11567 // Find the type to narrow it the load / op / store to. 11568 SDValue N1 = Value.getOperand(1); 11569 unsigned BitWidth = N1.getValueSizeInBits(); 11570 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 11571 if (Opc == ISD::AND) 11572 Imm ^= APInt::getAllOnesValue(BitWidth); 11573 if (Imm == 0 || Imm.isAllOnesValue()) 11574 return SDValue(); 11575 unsigned ShAmt = Imm.countTrailingZeros(); 11576 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 11577 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 11578 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11579 // The narrowing should be profitable, the load/store operation should be 11580 // legal (or custom) and the store size should be equal to the NewVT width. 11581 while (NewBW < BitWidth && 11582 (NewVT.getStoreSizeInBits() != NewBW || 11583 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 11584 !TLI.isNarrowingProfitable(VT, NewVT))) { 11585 NewBW = NextPowerOf2(NewBW); 11586 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11587 } 11588 if (NewBW >= BitWidth) 11589 return SDValue(); 11590 11591 // If the lsb changed does not start at the type bitwidth boundary, 11592 // start at the previous one. 11593 if (ShAmt % NewBW) 11594 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 11595 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 11596 std::min(BitWidth, ShAmt + NewBW)); 11597 if ((Imm & Mask) == Imm) { 11598 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 11599 if (Opc == ISD::AND) 11600 NewImm ^= APInt::getAllOnesValue(NewBW); 11601 uint64_t PtrOff = ShAmt / 8; 11602 // For big endian targets, we need to adjust the offset to the pointer to 11603 // load the correct bytes. 11604 if (DAG.getDataLayout().isBigEndian()) 11605 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 11606 11607 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 11608 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 11609 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 11610 return SDValue(); 11611 11612 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 11613 Ptr.getValueType(), Ptr, 11614 DAG.getConstant(PtrOff, SDLoc(LD), 11615 Ptr.getValueType())); 11616 SDValue NewLD = 11617 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 11618 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 11619 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11620 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 11621 DAG.getConstant(NewImm, SDLoc(Value), 11622 NewVT)); 11623 SDValue NewST = 11624 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 11625 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 11626 11627 AddToWorklist(NewPtr.getNode()); 11628 AddToWorklist(NewLD.getNode()); 11629 AddToWorklist(NewVal.getNode()); 11630 WorklistRemover DeadNodes(*this); 11631 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 11632 ++OpsNarrowed; 11633 return NewST; 11634 } 11635 } 11636 11637 return SDValue(); 11638 } 11639 11640 /// For a given floating point load / store pair, if the load value isn't used 11641 /// by any other operations, then consider transforming the pair to integer 11642 /// load / store operations if the target deems the transformation profitable. 11643 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 11644 StoreSDNode *ST = cast<StoreSDNode>(N); 11645 SDValue Chain = ST->getChain(); 11646 SDValue Value = ST->getValue(); 11647 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 11648 Value.hasOneUse() && 11649 Chain == SDValue(Value.getNode(), 1)) { 11650 LoadSDNode *LD = cast<LoadSDNode>(Value); 11651 EVT VT = LD->getMemoryVT(); 11652 if (!VT.isFloatingPoint() || 11653 VT != ST->getMemoryVT() || 11654 LD->isNonTemporal() || 11655 ST->isNonTemporal() || 11656 LD->getPointerInfo().getAddrSpace() != 0 || 11657 ST->getPointerInfo().getAddrSpace() != 0) 11658 return SDValue(); 11659 11660 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 11661 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 11662 !TLI.isOperationLegal(ISD::STORE, IntVT) || 11663 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 11664 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 11665 return SDValue(); 11666 11667 unsigned LDAlign = LD->getAlignment(); 11668 unsigned STAlign = ST->getAlignment(); 11669 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11670 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11671 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11672 return SDValue(); 11673 11674 SDValue NewLD = 11675 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11676 LD->getPointerInfo(), LDAlign); 11677 11678 SDValue NewST = 11679 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11680 ST->getPointerInfo(), STAlign); 11681 11682 AddToWorklist(NewLD.getNode()); 11683 AddToWorklist(NewST.getNode()); 11684 WorklistRemover DeadNodes(*this); 11685 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11686 ++LdStFP2Int; 11687 return NewST; 11688 } 11689 11690 return SDValue(); 11691 } 11692 11693 // This is a helper function for visitMUL to check the profitability 11694 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11695 // MulNode is the original multiply, AddNode is (add x, c1), 11696 // and ConstNode is c2. 11697 // 11698 // If the (add x, c1) has multiple uses, we could increase 11699 // the number of adds if we make this transformation. 11700 // It would only be worth doing this if we can remove a 11701 // multiply in the process. Check for that here. 11702 // To illustrate: 11703 // (A + c1) * c3 11704 // (A + c2) * c3 11705 // We're checking for cases where we have common "c3 * A" expressions. 11706 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11707 SDValue &AddNode, 11708 SDValue &ConstNode) { 11709 APInt Val; 11710 11711 // If the add only has one use, this would be OK to do. 11712 if (AddNode.getNode()->hasOneUse()) 11713 return true; 11714 11715 // Walk all the users of the constant with which we're multiplying. 11716 for (SDNode *Use : ConstNode->uses()) { 11717 11718 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11719 continue; 11720 11721 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11722 SDNode *OtherOp; 11723 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11724 11725 // OtherOp is what we're multiplying against the constant. 11726 if (Use->getOperand(0) == ConstNode) 11727 OtherOp = Use->getOperand(1).getNode(); 11728 else 11729 OtherOp = Use->getOperand(0).getNode(); 11730 11731 // Check to see if multiply is with the same operand of our "add". 11732 // 11733 // ConstNode = CONST 11734 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11735 // ... 11736 // AddNode = (A + c1) <-- MulVar is A. 11737 // = AddNode * ConstNode <-- current visiting instruction. 11738 // 11739 // If we make this transformation, we will have a common 11740 // multiply (ConstNode * A) that we can save. 11741 if (OtherOp == MulVar) 11742 return true; 11743 11744 // Now check to see if a future expansion will give us a common 11745 // multiply. 11746 // 11747 // ConstNode = CONST 11748 // AddNode = (A + c1) 11749 // ... = AddNode * ConstNode <-- current visiting instruction. 11750 // ... 11751 // OtherOp = (A + c2) 11752 // Use = OtherOp * ConstNode <-- visiting Use. 11753 // 11754 // If we make this transformation, we will have a common 11755 // multiply (CONST * A) after we also do the same transformation 11756 // to the "t2" instruction. 11757 if (OtherOp->getOpcode() == ISD::ADD && 11758 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11759 OtherOp->getOperand(0).getNode() == MulVar) 11760 return true; 11761 } 11762 } 11763 11764 // Didn't find a case where this would be profitable. 11765 return false; 11766 } 11767 11768 SDValue DAGCombiner::getMergedConstantVectorStore( 11769 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores, 11770 SmallVectorImpl<SDValue> &Chains, EVT Ty) const { 11771 SmallVector<SDValue, 8> BuildVector; 11772 11773 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11774 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11775 Chains.push_back(St->getChain()); 11776 BuildVector.push_back(St->getValue()); 11777 } 11778 11779 return DAG.getBuildVector(Ty, SL, BuildVector); 11780 } 11781 11782 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11783 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11784 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11785 // Make sure we have something to merge. 11786 if (NumStores < 2) 11787 return false; 11788 11789 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11790 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11791 unsigned LatestNodeUsed = 0; 11792 11793 for (unsigned i=0; i < NumStores; ++i) { 11794 // Find a chain for the new wide-store operand. Notice that some 11795 // of the store nodes that we found may not be selected for inclusion 11796 // in the wide store. The chain we use needs to be the chain of the 11797 // latest store node which is *used* and replaced by the wide store. 11798 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11799 LatestNodeUsed = i; 11800 } 11801 11802 SmallVector<SDValue, 8> Chains; 11803 11804 // The latest Node in the DAG. 11805 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11806 SDLoc DL(StoreNodes[0].MemNode); 11807 11808 SDValue StoredVal; 11809 if (UseVector) { 11810 bool IsVec = MemVT.isVector(); 11811 unsigned Elts = NumStores; 11812 if (IsVec) { 11813 // When merging vector stores, get the total number of elements. 11814 Elts *= MemVT.getVectorNumElements(); 11815 } 11816 // Get the type for the merged vector store. 11817 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11818 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11819 11820 if (IsConstantSrc) { 11821 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11822 } else { 11823 SmallVector<SDValue, 8> Ops; 11824 for (unsigned i = 0; i < NumStores; ++i) { 11825 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11826 SDValue Val = St->getValue(); 11827 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11828 if (Val.getValueType() != MemVT) 11829 return false; 11830 Ops.push_back(Val); 11831 Chains.push_back(St->getChain()); 11832 } 11833 11834 // Build the extracted vector elements back into a vector. 11835 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11836 DL, Ty, Ops); } 11837 } else { 11838 // We should always use a vector store when merging extracted vector 11839 // elements, so this path implies a store of constants. 11840 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11841 11842 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11843 APInt StoreInt(SizeInBits, 0); 11844 11845 // Construct a single integer constant which is made of the smaller 11846 // constant inputs. 11847 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11848 for (unsigned i = 0; i < NumStores; ++i) { 11849 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11850 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11851 Chains.push_back(St->getChain()); 11852 11853 SDValue Val = St->getValue(); 11854 StoreInt <<= ElementSizeBytes * 8; 11855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11856 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11857 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11858 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11859 } else { 11860 llvm_unreachable("Invalid constant element type"); 11861 } 11862 } 11863 11864 // Create the new Load and Store operations. 11865 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11866 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11867 } 11868 11869 assert(!Chains.empty()); 11870 11871 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11872 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11873 FirstInChain->getBasePtr(), 11874 FirstInChain->getPointerInfo(), 11875 FirstInChain->getAlignment()); 11876 11877 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11878 : DAG.getSubtarget().useAA(); 11879 if (UseAA) { 11880 // Replace all merged stores with the new store. 11881 for (unsigned i = 0; i < NumStores; ++i) 11882 CombineTo(StoreNodes[i].MemNode, NewStore); 11883 } else { 11884 // Replace the last store with the new store. 11885 CombineTo(LatestOp, NewStore); 11886 // Erase all other stores. 11887 for (unsigned i = 0; i < NumStores; ++i) { 11888 if (StoreNodes[i].MemNode == LatestOp) 11889 continue; 11890 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11891 // ReplaceAllUsesWith will replace all uses that existed when it was 11892 // called, but graph optimizations may cause new ones to appear. For 11893 // example, the case in pr14333 looks like 11894 // 11895 // St's chain -> St -> another store -> X 11896 // 11897 // And the only difference from St to the other store is the chain. 11898 // When we change it's chain to be St's chain they become identical, 11899 // get CSEed and the net result is that X is now a use of St. 11900 // Since we know that St is redundant, just iterate. 11901 while (!St->use_empty()) 11902 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11903 deleteAndRecombine(St); 11904 } 11905 } 11906 11907 StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end()); 11908 return true; 11909 } 11910 11911 void DAGCombiner::getStoreMergeAndAliasCandidates( 11912 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11913 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11914 // This holds the base pointer, index, and the offset in bytes from the base 11915 // pointer. 11916 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11917 11918 // We must have a base and an offset. 11919 if (!BasePtr.Base.getNode()) 11920 return; 11921 11922 // Do not handle stores to undef base pointers. 11923 if (BasePtr.Base.isUndef()) 11924 return; 11925 11926 // Walk up the chain and look for nodes with offsets from the same 11927 // base pointer. Stop when reaching an instruction with a different kind 11928 // or instruction which has a different base pointer. 11929 EVT MemVT = St->getMemoryVT(); 11930 unsigned Seq = 0; 11931 StoreSDNode *Index = St; 11932 11933 11934 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11935 : DAG.getSubtarget().useAA(); 11936 11937 if (UseAA) { 11938 // Look at other users of the same chain. Stores on the same chain do not 11939 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11940 // to be on the same chain, so don't bother looking at adjacent chains. 11941 11942 SDValue Chain = St->getChain(); 11943 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11944 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11945 if (I.getOperandNo() != 0) 11946 continue; 11947 11948 if (OtherST->isVolatile() || OtherST->isIndexed()) 11949 continue; 11950 11951 if (OtherST->getMemoryVT() != MemVT) 11952 continue; 11953 11954 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11955 11956 if (Ptr.equalBaseIndex(BasePtr)) 11957 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11958 } 11959 } 11960 11961 return; 11962 } 11963 11964 while (Index) { 11965 // If the chain has more than one use, then we can't reorder the mem ops. 11966 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11967 break; 11968 11969 // Find the base pointer and offset for this memory node. 11970 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11971 11972 // Check that the base pointer is the same as the original one. 11973 if (!Ptr.equalBaseIndex(BasePtr)) 11974 break; 11975 11976 // The memory operands must not be volatile. 11977 if (Index->isVolatile() || Index->isIndexed()) 11978 break; 11979 11980 // No truncation. 11981 if (Index->isTruncatingStore()) 11982 break; 11983 11984 // The stored memory type must be the same. 11985 if (Index->getMemoryVT() != MemVT) 11986 break; 11987 11988 // We do not allow under-aligned stores in order to prevent 11989 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11990 // be irrelevant here; what MATTERS is that we not move memory 11991 // operations that potentially overlap past each-other. 11992 if (Index->getAlignment() < MemVT.getStoreSize()) 11993 break; 11994 11995 // We found a potential memory operand to merge. 11996 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11997 11998 // Find the next memory operand in the chain. If the next operand in the 11999 // chain is a store then move up and continue the scan with the next 12000 // memory operand. If the next operand is a load save it and use alias 12001 // information to check if it interferes with anything. 12002 SDNode *NextInChain = Index->getChain().getNode(); 12003 while (1) { 12004 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 12005 // We found a store node. Use it for the next iteration. 12006 Index = STn; 12007 break; 12008 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 12009 if (Ldn->isVolatile()) { 12010 Index = nullptr; 12011 break; 12012 } 12013 12014 // Save the load node for later. Continue the scan. 12015 AliasLoadNodes.push_back(Ldn); 12016 NextInChain = Ldn->getChain().getNode(); 12017 continue; 12018 } else { 12019 Index = nullptr; 12020 break; 12021 } 12022 } 12023 } 12024 } 12025 12026 // We need to check that merging these stores does not cause a loop 12027 // in the DAG. Any store candidate may depend on another candidate 12028 // indirectly through its operand (we already consider dependencies 12029 // through the chain). Check in parallel by searching up from 12030 // non-chain operands of candidates. 12031 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12032 SmallVectorImpl<MemOpLink> &StoreNodes) { 12033 SmallPtrSet<const SDNode *, 16> Visited; 12034 SmallVector<const SDNode *, 8> Worklist; 12035 // search ops of store candidates 12036 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 12037 SDNode *n = StoreNodes[i].MemNode; 12038 // Potential loops may happen only through non-chain operands 12039 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12040 Worklist.push_back(n->getOperand(j).getNode()); 12041 } 12042 // search through DAG. We can stop early if we find a storenode 12043 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 12044 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 12045 return false; 12046 } 12047 return true; 12048 } 12049 12050 bool DAGCombiner::MergeConsecutiveStores( 12051 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12052 if (OptLevel == CodeGenOpt::None) 12053 return false; 12054 12055 EVT MemVT = St->getMemoryVT(); 12056 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12057 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12058 Attribute::NoImplicitFloat); 12059 12060 // This function cannot currently deal with non-byte-sized memory sizes. 12061 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12062 return false; 12063 12064 if (!MemVT.isSimple()) 12065 return false; 12066 12067 // Perform an early exit check. Do not bother looking at stored values that 12068 // are not constants, loads, or extracted vector elements. 12069 SDValue StoredVal = St->getValue(); 12070 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12071 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12072 isa<ConstantFPSDNode>(StoredVal); 12073 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12074 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12075 12076 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12077 return false; 12078 12079 // Don't merge vectors into wider vectors if the source data comes from loads. 12080 // TODO: This restriction can be lifted by using logic similar to the 12081 // ExtractVecSrc case. 12082 if (MemVT.isVector() && IsLoadSrc) 12083 return false; 12084 12085 // Only look at ends of store sequences. 12086 SDValue Chain = SDValue(St, 0); 12087 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 12088 return false; 12089 12090 // Save the LoadSDNodes that we find in the chain. 12091 // We need to make sure that these nodes do not interfere with 12092 // any of the store nodes. 12093 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 12094 12095 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 12096 12097 // Check if there is anything to merge. 12098 if (StoreNodes.size() < 2) 12099 return false; 12100 12101 // only do dependence check in AA case 12102 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12103 : DAG.getSubtarget().useAA(); 12104 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 12105 return false; 12106 12107 // Sort the memory operands according to their distance from the 12108 // base pointer. As a secondary criteria: make sure stores coming 12109 // later in the code come first in the list. This is important for 12110 // the non-UseAA case, because we're merging stores into the FINAL 12111 // store along a chain which potentially contains aliasing stores. 12112 // Thus, if there are multiple stores to the same address, the last 12113 // one can be considered for merging but not the others. 12114 std::sort(StoreNodes.begin(), StoreNodes.end(), 12115 [](MemOpLink LHS, MemOpLink RHS) { 12116 return LHS.OffsetFromBase < RHS.OffsetFromBase || 12117 (LHS.OffsetFromBase == RHS.OffsetFromBase && 12118 LHS.SequenceNum < RHS.SequenceNum); 12119 }); 12120 12121 // Scan the memory operations on the chain and find the first non-consecutive 12122 // store memory address. 12123 unsigned LastConsecutiveStore = 0; 12124 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12125 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 12126 12127 // Check that the addresses are consecutive starting from the second 12128 // element in the list of stores. 12129 if (i > 0) { 12130 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12131 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12132 break; 12133 } 12134 12135 // Check if this store interferes with any of the loads that we found. 12136 // If we find a load that alias with this store. Stop the sequence. 12137 if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) { 12138 return isAlias(Ldn, StoreNodes[i].MemNode); 12139 })) 12140 break; 12141 12142 // Mark this node as useful. 12143 LastConsecutiveStore = i; 12144 } 12145 12146 // The node with the lowest store address. 12147 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12148 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12149 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12150 LLVMContext &Context = *DAG.getContext(); 12151 const DataLayout &DL = DAG.getDataLayout(); 12152 12153 // Store the constants into memory as one consecutive store. 12154 if (IsConstantSrc) { 12155 unsigned LastLegalType = 0; 12156 unsigned LastLegalVectorType = 0; 12157 bool NonZero = false; 12158 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 12159 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12160 SDValue StoredVal = St->getValue(); 12161 12162 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 12163 NonZero |= !C->isNullValue(); 12164 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 12165 NonZero |= !C->getConstantFPValue()->isNullValue(); 12166 } else { 12167 // Non-constant. 12168 break; 12169 } 12170 12171 // Find a legal type for the constant store. 12172 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 12173 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12174 bool IsFast; 12175 if (TLI.isTypeLegal(StoreTy) && 12176 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12177 FirstStoreAlign, &IsFast) && IsFast) { 12178 LastLegalType = i+1; 12179 // Or check whether a truncstore is legal. 12180 } else if (TLI.getTypeAction(Context, StoreTy) == 12181 TargetLowering::TypePromoteInteger) { 12182 EVT LegalizedStoredValueTy = 12183 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 12184 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12185 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12186 FirstStoreAS, FirstStoreAlign, &IsFast) && 12187 IsFast) { 12188 LastLegalType = i + 1; 12189 } 12190 } 12191 12192 // We only use vectors if the constant is known to be zero or the target 12193 // allows it and the function is not marked with the noimplicitfloat 12194 // attribute. 12195 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 12196 FirstStoreAS)) && 12197 !NoVectors) { 12198 // Find a legal type for the vector store. 12199 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 12200 if (TLI.isTypeLegal(Ty) && 12201 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12202 FirstStoreAlign, &IsFast) && IsFast) 12203 LastLegalVectorType = i + 1; 12204 } 12205 } 12206 12207 // Check if we found a legal integer type to store. 12208 if (LastLegalType == 0 && LastLegalVectorType == 0) 12209 return false; 12210 12211 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 12212 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 12213 12214 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 12215 true, UseVector); 12216 } 12217 12218 // When extracting multiple vector elements, try to store them 12219 // in one vector store rather than a sequence of scalar stores. 12220 if (IsExtractVecSrc) { 12221 unsigned NumStoresToMerge = 0; 12222 bool IsVec = MemVT.isVector(); 12223 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 12224 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12225 unsigned StoreValOpcode = St->getValue().getOpcode(); 12226 // This restriction could be loosened. 12227 // Bail out if any stored values are not elements extracted from a vector. 12228 // It should be possible to handle mixed sources, but load sources need 12229 // more careful handling (see the block of code below that handles 12230 // consecutive loads). 12231 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 12232 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 12233 return false; 12234 12235 // Find a legal type for the vector store. 12236 unsigned Elts = i + 1; 12237 if (IsVec) { 12238 // When merging vector stores, get the total number of elements. 12239 Elts *= MemVT.getVectorNumElements(); 12240 } 12241 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12242 bool IsFast; 12243 if (TLI.isTypeLegal(Ty) && 12244 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12245 FirstStoreAlign, &IsFast) && IsFast) 12246 NumStoresToMerge = i + 1; 12247 } 12248 12249 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 12250 false, true); 12251 } 12252 12253 // Below we handle the case of multiple consecutive stores that 12254 // come from multiple consecutive loads. We merge them into a single 12255 // wide load and a single wide store. 12256 12257 // Look for load nodes which are used by the stored values. 12258 SmallVector<MemOpLink, 8> LoadNodes; 12259 12260 // Find acceptable loads. Loads need to have the same chain (token factor), 12261 // must not be zext, volatile, indexed, and they must be consecutive. 12262 BaseIndexOffset LdBasePtr; 12263 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 12264 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12265 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 12266 if (!Ld) break; 12267 12268 // Loads must only have one use. 12269 if (!Ld->hasNUsesOfValue(1, 0)) 12270 break; 12271 12272 // The memory operands must not be volatile. 12273 if (Ld->isVolatile() || Ld->isIndexed()) 12274 break; 12275 12276 // We do not accept ext loads. 12277 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 12278 break; 12279 12280 // The stored memory type must be the same. 12281 if (Ld->getMemoryVT() != MemVT) 12282 break; 12283 12284 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12285 // If this is not the first ptr that we check. 12286 if (LdBasePtr.Base.getNode()) { 12287 // The base ptr must be the same. 12288 if (!LdPtr.equalBaseIndex(LdBasePtr)) 12289 break; 12290 } else { 12291 // Check that all other base pointers are the same as this one. 12292 LdBasePtr = LdPtr; 12293 } 12294 12295 // We found a potential memory operand to merge. 12296 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 12297 } 12298 12299 if (LoadNodes.size() < 2) 12300 return false; 12301 12302 // If we have load/store pair instructions and we only have two values, 12303 // don't bother. 12304 unsigned RequiredAlignment; 12305 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 12306 St->getAlignment() >= RequiredAlignment) 12307 return false; 12308 12309 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 12310 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 12311 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 12312 12313 // Scan the memory operations on the chain and find the first non-consecutive 12314 // load memory address. These variables hold the index in the store node 12315 // array. 12316 unsigned LastConsecutiveLoad = 0; 12317 // This variable refers to the size and not index in the array. 12318 unsigned LastLegalVectorType = 0; 12319 unsigned LastLegalIntegerType = 0; 12320 StartAddress = LoadNodes[0].OffsetFromBase; 12321 SDValue FirstChain = FirstLoad->getChain(); 12322 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 12323 // All loads must share the same chain. 12324 if (LoadNodes[i].MemNode->getChain() != FirstChain) 12325 break; 12326 12327 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 12328 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12329 break; 12330 LastConsecutiveLoad = i; 12331 // Find a legal type for the vector store. 12332 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 12333 bool IsFastSt, IsFastLd; 12334 if (TLI.isTypeLegal(StoreTy) && 12335 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12336 FirstStoreAlign, &IsFastSt) && IsFastSt && 12337 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12338 FirstLoadAlign, &IsFastLd) && IsFastLd) { 12339 LastLegalVectorType = i + 1; 12340 } 12341 12342 // Find a legal type for the integer store. 12343 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 12344 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12345 if (TLI.isTypeLegal(StoreTy) && 12346 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12347 FirstStoreAlign, &IsFastSt) && IsFastSt && 12348 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12349 FirstLoadAlign, &IsFastLd) && IsFastLd) 12350 LastLegalIntegerType = i + 1; 12351 // Or check whether a truncstore and extload is legal. 12352 else if (TLI.getTypeAction(Context, StoreTy) == 12353 TargetLowering::TypePromoteInteger) { 12354 EVT LegalizedStoredValueTy = 12355 TLI.getTypeToTransformTo(Context, StoreTy); 12356 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12357 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12358 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12359 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 12360 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12361 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 12362 IsFastSt && 12363 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12364 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 12365 IsFastLd) 12366 LastLegalIntegerType = i+1; 12367 } 12368 } 12369 12370 // Only use vector types if the vector type is larger than the integer type. 12371 // If they are the same, use integers. 12372 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 12373 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 12374 12375 // We add +1 here because the LastXXX variables refer to location while 12376 // the NumElem refers to array/index size. 12377 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 12378 NumElem = std::min(LastLegalType, NumElem); 12379 12380 if (NumElem < 2) 12381 return false; 12382 12383 // Collect the chains from all merged stores. 12384 SmallVector<SDValue, 8> MergeStoreChains; 12385 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 12386 12387 // The latest Node in the DAG. 12388 unsigned LatestNodeUsed = 0; 12389 for (unsigned i=1; i<NumElem; ++i) { 12390 // Find a chain for the new wide-store operand. Notice that some 12391 // of the store nodes that we found may not be selected for inclusion 12392 // in the wide store. The chain we use needs to be the chain of the 12393 // latest store node which is *used* and replaced by the wide store. 12394 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 12395 LatestNodeUsed = i; 12396 12397 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 12398 } 12399 12400 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 12401 12402 // Find if it is better to use vectors or integers to load and store 12403 // to memory. 12404 EVT JointMemOpVT; 12405 if (UseVectorTy) { 12406 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 12407 } else { 12408 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 12409 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 12410 } 12411 12412 SDLoc LoadDL(LoadNodes[0].MemNode); 12413 SDLoc StoreDL(StoreNodes[0].MemNode); 12414 12415 // The merged loads are required to have the same incoming chain, so 12416 // using the first's chain is acceptable. 12417 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 12418 FirstLoad->getBasePtr(), 12419 FirstLoad->getPointerInfo(), FirstLoadAlign); 12420 12421 SDValue NewStoreChain = 12422 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 12423 12424 SDValue NewStore = 12425 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 12426 FirstInChain->getPointerInfo(), FirstStoreAlign); 12427 12428 // Transfer chain users from old loads to the new load. 12429 for (unsigned i = 0; i < NumElem; ++i) { 12430 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 12431 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 12432 SDValue(NewLoad.getNode(), 1)); 12433 } 12434 12435 if (UseAA) { 12436 // Replace the all stores with the new store. 12437 for (unsigned i = 0; i < NumElem; ++i) 12438 CombineTo(StoreNodes[i].MemNode, NewStore); 12439 } else { 12440 // Replace the last store with the new store. 12441 CombineTo(LatestOp, NewStore); 12442 // Erase all other stores. 12443 for (unsigned i = 0; i < NumElem; ++i) { 12444 // Remove all Store nodes. 12445 if (StoreNodes[i].MemNode == LatestOp) 12446 continue; 12447 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12448 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 12449 deleteAndRecombine(St); 12450 } 12451 } 12452 12453 StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end()); 12454 return true; 12455 } 12456 12457 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 12458 SDLoc SL(ST); 12459 SDValue ReplStore; 12460 12461 // Replace the chain to avoid dependency. 12462 if (ST->isTruncatingStore()) { 12463 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 12464 ST->getBasePtr(), ST->getMemoryVT(), 12465 ST->getMemOperand()); 12466 } else { 12467 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 12468 ST->getMemOperand()); 12469 } 12470 12471 // Create token to keep both nodes around. 12472 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 12473 MVT::Other, ST->getChain(), ReplStore); 12474 12475 // Make sure the new and old chains are cleaned up. 12476 AddToWorklist(Token.getNode()); 12477 12478 // Don't add users to work list. 12479 return CombineTo(ST, Token, false); 12480 } 12481 12482 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 12483 SDValue Value = ST->getValue(); 12484 if (Value.getOpcode() == ISD::TargetConstantFP) 12485 return SDValue(); 12486 12487 SDLoc DL(ST); 12488 12489 SDValue Chain = ST->getChain(); 12490 SDValue Ptr = ST->getBasePtr(); 12491 12492 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 12493 12494 // NOTE: If the original store is volatile, this transform must not increase 12495 // the number of stores. For example, on x86-32 an f64 can be stored in one 12496 // processor operation but an i64 (which is not legal) requires two. So the 12497 // transform should not be done in this case. 12498 12499 SDValue Tmp; 12500 switch (CFP->getSimpleValueType(0).SimpleTy) { 12501 default: 12502 llvm_unreachable("Unknown FP type"); 12503 case MVT::f16: // We don't do this for these yet. 12504 case MVT::f80: 12505 case MVT::f128: 12506 case MVT::ppcf128: 12507 return SDValue(); 12508 case MVT::f32: 12509 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 12510 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12511 ; 12512 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 12513 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 12514 MVT::i32); 12515 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 12516 } 12517 12518 return SDValue(); 12519 case MVT::f64: 12520 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 12521 !ST->isVolatile()) || 12522 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 12523 ; 12524 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 12525 getZExtValue(), SDLoc(CFP), MVT::i64); 12526 return DAG.getStore(Chain, DL, Tmp, 12527 Ptr, ST->getMemOperand()); 12528 } 12529 12530 if (!ST->isVolatile() && 12531 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12532 // Many FP stores are not made apparent until after legalize, e.g. for 12533 // argument passing. Since this is so common, custom legalize the 12534 // 64-bit integer store into two 32-bit stores. 12535 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 12536 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 12537 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 12538 if (DAG.getDataLayout().isBigEndian()) 12539 std::swap(Lo, Hi); 12540 12541 unsigned Alignment = ST->getAlignment(); 12542 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12543 AAMDNodes AAInfo = ST->getAAInfo(); 12544 12545 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12546 ST->getAlignment(), MMOFlags, AAInfo); 12547 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12548 DAG.getConstant(4, DL, Ptr.getValueType())); 12549 Alignment = MinAlign(Alignment, 4U); 12550 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 12551 ST->getPointerInfo().getWithOffset(4), 12552 Alignment, MMOFlags, AAInfo); 12553 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12554 St0, St1); 12555 } 12556 12557 return SDValue(); 12558 } 12559 } 12560 12561 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12562 StoreSDNode *ST = cast<StoreSDNode>(N); 12563 SDValue Chain = ST->getChain(); 12564 SDValue Value = ST->getValue(); 12565 SDValue Ptr = ST->getBasePtr(); 12566 12567 // If this is a store of a bit convert, store the input value if the 12568 // resultant store does not need a higher alignment than the original. 12569 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12570 ST->isUnindexed()) { 12571 EVT SVT = Value.getOperand(0).getValueType(); 12572 if (((!LegalOperations && !ST->isVolatile()) || 12573 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12574 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12575 unsigned OrigAlign = ST->getAlignment(); 12576 bool Fast = false; 12577 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12578 ST->getAddressSpace(), OrigAlign, &Fast) && 12579 Fast) { 12580 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12581 ST->getPointerInfo(), OrigAlign, 12582 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12583 } 12584 } 12585 } 12586 12587 // Turn 'store undef, Ptr' -> nothing. 12588 if (Value.isUndef() && ST->isUnindexed()) 12589 return Chain; 12590 12591 // Try to infer better alignment information than the store already has. 12592 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12593 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12594 if (Align > ST->getAlignment()) { 12595 SDValue NewStore = 12596 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12597 ST->getMemoryVT(), Align, 12598 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12599 if (NewStore.getNode() != N) 12600 return CombineTo(ST, NewStore, true); 12601 } 12602 } 12603 } 12604 12605 // Try transforming a pair floating point load / store ops to integer 12606 // load / store ops. 12607 if (SDValue NewST = TransformFPLoadStorePair(N)) 12608 return NewST; 12609 12610 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12611 : DAG.getSubtarget().useAA(); 12612 #ifndef NDEBUG 12613 if (CombinerAAOnlyFunc.getNumOccurrences() && 12614 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12615 UseAA = false; 12616 #endif 12617 if (UseAA && ST->isUnindexed()) { 12618 // FIXME: We should do this even without AA enabled. AA will just allow 12619 // FindBetterChain to work in more situations. The problem with this is that 12620 // any combine that expects memory operations to be on consecutive chains 12621 // first needs to be updated to look for users of the same chain. 12622 12623 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12624 // adjacent stores. 12625 if (findBetterNeighborChains(ST)) { 12626 // replaceStoreChain uses CombineTo, which handled all of the worklist 12627 // manipulation. Return the original node to not do anything else. 12628 return SDValue(ST, 0); 12629 } 12630 Chain = ST->getChain(); 12631 } 12632 12633 // Try transforming N to an indexed store. 12634 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12635 return SDValue(N, 0); 12636 12637 // FIXME: is there such a thing as a truncating indexed store? 12638 if (ST->isTruncatingStore() && ST->isUnindexed() && 12639 Value.getValueType().isInteger()) { 12640 // See if we can simplify the input to this truncstore with knowledge that 12641 // only the low bits are being used. For example: 12642 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12643 SDValue Shorter = GetDemandedBits( 12644 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12645 ST->getMemoryVT().getScalarSizeInBits())); 12646 AddToWorklist(Value.getNode()); 12647 if (Shorter.getNode()) 12648 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12649 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12650 12651 // Otherwise, see if we can simplify the operation with 12652 // SimplifyDemandedBits, which only works if the value has a single use. 12653 if (SimplifyDemandedBits( 12654 Value, 12655 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12656 ST->getMemoryVT().getScalarSizeInBits()))) 12657 return SDValue(N, 0); 12658 } 12659 12660 // If this is a load followed by a store to the same location, then the store 12661 // is dead/noop. 12662 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12663 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12664 ST->isUnindexed() && !ST->isVolatile() && 12665 // There can't be any side effects between the load and store, such as 12666 // a call or store. 12667 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12668 // The store is dead, remove it. 12669 return Chain; 12670 } 12671 } 12672 12673 // If this is a store followed by a store with the same value to the same 12674 // location, then the store is dead/noop. 12675 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12676 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12677 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12678 ST1->isUnindexed() && !ST1->isVolatile()) { 12679 // The store is dead, remove it. 12680 return Chain; 12681 } 12682 } 12683 12684 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12685 // truncating store. We can do this even if this is already a truncstore. 12686 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12687 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12688 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12689 ST->getMemoryVT())) { 12690 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12691 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12692 } 12693 12694 // Only perform this optimization before the types are legal, because we 12695 // don't want to perform this optimization on every DAGCombine invocation. 12696 if (!LegalTypes) { 12697 for (;;) { 12698 // There can be multiple store sequences on the same chain. 12699 // Keep trying to merge store sequences until we are unable to do so 12700 // or until we merge the last store on the chain. 12701 SmallVector<MemOpLink, 8> StoreNodes; 12702 bool Changed = MergeConsecutiveStores(ST, StoreNodes); 12703 if (!Changed) break; 12704 12705 if (any_of(StoreNodes, 12706 [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) { 12707 // ST has been merged and no longer exists. 12708 return SDValue(N, 0); 12709 } 12710 } 12711 } 12712 12713 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12714 // 12715 // Make sure to do this only after attempting to merge stores in order to 12716 // avoid changing the types of some subset of stores due to visit order, 12717 // preventing their merging. 12718 if (isa<ConstantFPSDNode>(Value)) { 12719 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12720 return NewSt; 12721 } 12722 12723 if (SDValue NewSt = splitMergedValStore(ST)) 12724 return NewSt; 12725 12726 return ReduceLoadOpStoreWidth(N); 12727 } 12728 12729 /// For the instruction sequence of store below, F and I values 12730 /// are bundled together as an i64 value before being stored into memory. 12731 /// Sometimes it is more efficent to generate separate stores for F and I, 12732 /// which can remove the bitwise instructions or sink them to colder places. 12733 /// 12734 /// (store (or (zext (bitcast F to i32) to i64), 12735 /// (shl (zext I to i64), 32)), addr) --> 12736 /// (store F, addr) and (store I, addr+4) 12737 /// 12738 /// Similarly, splitting for other merged store can also be beneficial, like: 12739 /// For pair of {i32, i32}, i64 store --> two i32 stores. 12740 /// For pair of {i32, i16}, i64 store --> two i32 stores. 12741 /// For pair of {i16, i16}, i32 store --> two i16 stores. 12742 /// For pair of {i16, i8}, i32 store --> two i16 stores. 12743 /// For pair of {i8, i8}, i16 store --> two i8 stores. 12744 /// 12745 /// We allow each target to determine specifically which kind of splitting is 12746 /// supported. 12747 /// 12748 /// The store patterns are commonly seen from the simple code snippet below 12749 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 12750 /// void goo(const std::pair<int, float> &); 12751 /// hoo() { 12752 /// ... 12753 /// goo(std::make_pair(tmp, ftmp)); 12754 /// ... 12755 /// } 12756 /// 12757 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 12758 if (OptLevel == CodeGenOpt::None) 12759 return SDValue(); 12760 12761 SDValue Val = ST->getValue(); 12762 SDLoc DL(ST); 12763 12764 // Match OR operand. 12765 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 12766 return SDValue(); 12767 12768 // Match SHL operand and get Lower and Higher parts of Val. 12769 SDValue Op1 = Val.getOperand(0); 12770 SDValue Op2 = Val.getOperand(1); 12771 SDValue Lo, Hi; 12772 if (Op1.getOpcode() != ISD::SHL) { 12773 std::swap(Op1, Op2); 12774 if (Op1.getOpcode() != ISD::SHL) 12775 return SDValue(); 12776 } 12777 Lo = Op2; 12778 Hi = Op1.getOperand(0); 12779 if (!Op1.hasOneUse()) 12780 return SDValue(); 12781 12782 // Match shift amount to HalfValBitSize. 12783 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 12784 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 12785 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 12786 return SDValue(); 12787 12788 // Lo and Hi are zero-extended from int with size less equal than 32 12789 // to i64. 12790 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 12791 !Lo.getOperand(0).getValueType().isScalarInteger() || 12792 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 12793 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 12794 !Hi.getOperand(0).getValueType().isScalarInteger() || 12795 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 12796 return SDValue(); 12797 12798 // Use the EVT of low and high parts before bitcast as the input 12799 // of target query. 12800 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 12801 ? Lo.getOperand(0).getValueType() 12802 : Lo.getValueType(); 12803 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 12804 ? Hi.getOperand(0).getValueType() 12805 : Hi.getValueType(); 12806 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 12807 return SDValue(); 12808 12809 // Start to split store. 12810 unsigned Alignment = ST->getAlignment(); 12811 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12812 AAMDNodes AAInfo = ST->getAAInfo(); 12813 12814 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 12815 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 12816 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 12817 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 12818 12819 SDValue Chain = ST->getChain(); 12820 SDValue Ptr = ST->getBasePtr(); 12821 // Lower value store. 12822 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12823 ST->getAlignment(), MMOFlags, AAInfo); 12824 Ptr = 12825 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12826 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 12827 // Higher value store. 12828 SDValue St1 = 12829 DAG.getStore(St0, DL, Hi, Ptr, 12830 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 12831 Alignment / 2, MMOFlags, AAInfo); 12832 return St1; 12833 } 12834 12835 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12836 SDValue InVec = N->getOperand(0); 12837 SDValue InVal = N->getOperand(1); 12838 SDValue EltNo = N->getOperand(2); 12839 SDLoc DL(N); 12840 12841 // If the inserted element is an UNDEF, just use the input vector. 12842 if (InVal.isUndef()) 12843 return InVec; 12844 12845 EVT VT = InVec.getValueType(); 12846 12847 // Check that we know which element is being inserted 12848 if (!isa<ConstantSDNode>(EltNo)) 12849 return SDValue(); 12850 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12851 12852 // Canonicalize insert_vector_elt dag nodes. 12853 // Example: 12854 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12855 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12856 // 12857 // Do this only if the child insert_vector node has one use; also 12858 // do this only if indices are both constants and Idx1 < Idx0. 12859 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12860 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12861 unsigned OtherElt = 12862 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12863 if (Elt < OtherElt) { 12864 // Swap nodes. 12865 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 12866 InVec.getOperand(0), InVal, EltNo); 12867 AddToWorklist(NewOp.getNode()); 12868 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12869 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12870 } 12871 } 12872 12873 // If we can't generate a legal BUILD_VECTOR, exit 12874 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12875 return SDValue(); 12876 12877 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12878 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12879 // vector elements. 12880 SmallVector<SDValue, 8> Ops; 12881 // Do not combine these two vectors if the output vector will not replace 12882 // the input vector. 12883 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12884 Ops.append(InVec.getNode()->op_begin(), 12885 InVec.getNode()->op_end()); 12886 } else if (InVec.isUndef()) { 12887 unsigned NElts = VT.getVectorNumElements(); 12888 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12889 } else { 12890 return SDValue(); 12891 } 12892 12893 // Insert the element 12894 if (Elt < Ops.size()) { 12895 // All the operands of BUILD_VECTOR must have the same type; 12896 // we enforce that here. 12897 EVT OpVT = Ops[0].getValueType(); 12898 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 12899 } 12900 12901 // Return the new vector 12902 return DAG.getBuildVector(VT, DL, Ops); 12903 } 12904 12905 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12906 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12907 assert(!OriginalLoad->isVolatile()); 12908 12909 EVT ResultVT = EVE->getValueType(0); 12910 EVT VecEltVT = InVecVT.getVectorElementType(); 12911 unsigned Align = OriginalLoad->getAlignment(); 12912 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12913 VecEltVT.getTypeForEVT(*DAG.getContext())); 12914 12915 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12916 return SDValue(); 12917 12918 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 12919 ISD::NON_EXTLOAD : ISD::EXTLOAD; 12920 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 12921 return SDValue(); 12922 12923 Align = NewAlign; 12924 12925 SDValue NewPtr = OriginalLoad->getBasePtr(); 12926 SDValue Offset; 12927 EVT PtrType = NewPtr.getValueType(); 12928 MachinePointerInfo MPI; 12929 SDLoc DL(EVE); 12930 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12931 int Elt = ConstEltNo->getZExtValue(); 12932 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12933 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12934 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12935 } else { 12936 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12937 Offset = DAG.getNode( 12938 ISD::MUL, DL, PtrType, Offset, 12939 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12940 MPI = OriginalLoad->getPointerInfo(); 12941 } 12942 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12943 12944 // The replacement we need to do here is a little tricky: we need to 12945 // replace an extractelement of a load with a load. 12946 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12947 // Note that this replacement assumes that the extractvalue is the only 12948 // use of the load; that's okay because we don't want to perform this 12949 // transformation in other cases anyway. 12950 SDValue Load; 12951 SDValue Chain; 12952 if (ResultVT.bitsGT(VecEltVT)) { 12953 // If the result type of vextract is wider than the load, then issue an 12954 // extending load instead. 12955 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12956 VecEltVT) 12957 ? ISD::ZEXTLOAD 12958 : ISD::EXTLOAD; 12959 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 12960 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 12961 Align, OriginalLoad->getMemOperand()->getFlags(), 12962 OriginalLoad->getAAInfo()); 12963 Chain = Load.getValue(1); 12964 } else { 12965 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 12966 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 12967 OriginalLoad->getAAInfo()); 12968 Chain = Load.getValue(1); 12969 if (ResultVT.bitsLT(VecEltVT)) 12970 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12971 else 12972 Load = DAG.getBitcast(ResultVT, Load); 12973 } 12974 WorklistRemover DeadNodes(*this); 12975 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12976 SDValue To[] = { Load, Chain }; 12977 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12978 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12979 // worklist explicitly as well. 12980 AddToWorklist(Load.getNode()); 12981 AddUsersToWorklist(Load.getNode()); // Add users too 12982 // Make sure to revisit this node to clean it up; it will usually be dead. 12983 AddToWorklist(EVE); 12984 ++OpsNarrowed; 12985 return SDValue(EVE, 0); 12986 } 12987 12988 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12989 // (vextract (scalar_to_vector val, 0) -> val 12990 SDValue InVec = N->getOperand(0); 12991 EVT VT = InVec.getValueType(); 12992 EVT NVT = N->getValueType(0); 12993 12994 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12995 // Check if the result type doesn't match the inserted element type. A 12996 // SCALAR_TO_VECTOR may truncate the inserted element and the 12997 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12998 SDValue InOp = InVec.getOperand(0); 12999 if (InOp.getValueType() != NVT) { 13000 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13001 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 13002 } 13003 return InOp; 13004 } 13005 13006 SDValue EltNo = N->getOperand(1); 13007 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 13008 13009 // extract_vector_elt (build_vector x, y), 1 -> y 13010 if (ConstEltNo && 13011 InVec.getOpcode() == ISD::BUILD_VECTOR && 13012 TLI.isTypeLegal(VT) && 13013 (InVec.hasOneUse() || 13014 TLI.aggressivelyPreferBuildVectorSources(VT))) { 13015 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 13016 EVT InEltVT = Elt.getValueType(); 13017 13018 // Sometimes build_vector's scalar input types do not match result type. 13019 if (NVT == InEltVT) 13020 return Elt; 13021 13022 // TODO: It may be useful to truncate if free if the build_vector implicitly 13023 // converts. 13024 } 13025 13026 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 13027 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 13028 ConstEltNo->isNullValue() && VT.isInteger()) { 13029 SDValue BCSrc = InVec.getOperand(0); 13030 if (BCSrc.getValueType().isScalarInteger()) 13031 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 13032 } 13033 13034 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 13035 // 13036 // This only really matters if the index is non-constant since other combines 13037 // on the constant elements already work. 13038 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 13039 EltNo == InVec.getOperand(2)) { 13040 SDValue Elt = InVec.getOperand(1); 13041 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 13042 } 13043 13044 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 13045 // We only perform this optimization before the op legalization phase because 13046 // we may introduce new vector instructions which are not backed by TD 13047 // patterns. For example on AVX, extracting elements from a wide vector 13048 // without using extract_subvector. However, if we can find an underlying 13049 // scalar value, then we can always use that. 13050 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 13051 int NumElem = VT.getVectorNumElements(); 13052 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 13053 // Find the new index to extract from. 13054 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 13055 13056 // Extracting an undef index is undef. 13057 if (OrigElt == -1) 13058 return DAG.getUNDEF(NVT); 13059 13060 // Select the right vector half to extract from. 13061 SDValue SVInVec; 13062 if (OrigElt < NumElem) { 13063 SVInVec = InVec->getOperand(0); 13064 } else { 13065 SVInVec = InVec->getOperand(1); 13066 OrigElt -= NumElem; 13067 } 13068 13069 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 13070 SDValue InOp = SVInVec.getOperand(OrigElt); 13071 if (InOp.getValueType() != NVT) { 13072 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13073 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 13074 } 13075 13076 return InOp; 13077 } 13078 13079 // FIXME: We should handle recursing on other vector shuffles and 13080 // scalar_to_vector here as well. 13081 13082 if (!LegalOperations) { 13083 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13084 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 13085 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 13086 } 13087 } 13088 13089 bool BCNumEltsChanged = false; 13090 EVT ExtVT = VT.getVectorElementType(); 13091 EVT LVT = ExtVT; 13092 13093 // If the result of load has to be truncated, then it's not necessarily 13094 // profitable. 13095 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 13096 return SDValue(); 13097 13098 if (InVec.getOpcode() == ISD::BITCAST) { 13099 // Don't duplicate a load with other uses. 13100 if (!InVec.hasOneUse()) 13101 return SDValue(); 13102 13103 EVT BCVT = InVec.getOperand(0).getValueType(); 13104 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 13105 return SDValue(); 13106 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 13107 BCNumEltsChanged = true; 13108 InVec = InVec.getOperand(0); 13109 ExtVT = BCVT.getVectorElementType(); 13110 } 13111 13112 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 13113 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 13114 ISD::isNormalLoad(InVec.getNode()) && 13115 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 13116 SDValue Index = N->getOperand(1); 13117 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 13118 if (!OrigLoad->isVolatile()) { 13119 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 13120 OrigLoad); 13121 } 13122 } 13123 } 13124 13125 // Perform only after legalization to ensure build_vector / vector_shuffle 13126 // optimizations have already been done. 13127 if (!LegalOperations) return SDValue(); 13128 13129 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 13130 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 13131 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 13132 13133 if (ConstEltNo) { 13134 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13135 13136 LoadSDNode *LN0 = nullptr; 13137 const ShuffleVectorSDNode *SVN = nullptr; 13138 if (ISD::isNormalLoad(InVec.getNode())) { 13139 LN0 = cast<LoadSDNode>(InVec); 13140 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 13141 InVec.getOperand(0).getValueType() == ExtVT && 13142 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 13143 // Don't duplicate a load with other uses. 13144 if (!InVec.hasOneUse()) 13145 return SDValue(); 13146 13147 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 13148 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 13149 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 13150 // => 13151 // (load $addr+1*size) 13152 13153 // Don't duplicate a load with other uses. 13154 if (!InVec.hasOneUse()) 13155 return SDValue(); 13156 13157 // If the bit convert changed the number of elements, it is unsafe 13158 // to examine the mask. 13159 if (BCNumEltsChanged) 13160 return SDValue(); 13161 13162 // Select the input vector, guarding against out of range extract vector. 13163 unsigned NumElems = VT.getVectorNumElements(); 13164 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 13165 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 13166 13167 if (InVec.getOpcode() == ISD::BITCAST) { 13168 // Don't duplicate a load with other uses. 13169 if (!InVec.hasOneUse()) 13170 return SDValue(); 13171 13172 InVec = InVec.getOperand(0); 13173 } 13174 if (ISD::isNormalLoad(InVec.getNode())) { 13175 LN0 = cast<LoadSDNode>(InVec); 13176 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 13177 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 13178 } 13179 } 13180 13181 // Make sure we found a non-volatile load and the extractelement is 13182 // the only use. 13183 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 13184 return SDValue(); 13185 13186 // If Idx was -1 above, Elt is going to be -1, so just return undef. 13187 if (Elt == -1) 13188 return DAG.getUNDEF(LVT); 13189 13190 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 13191 } 13192 13193 return SDValue(); 13194 } 13195 13196 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 13197 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 13198 // We perform this optimization post type-legalization because 13199 // the type-legalizer often scalarizes integer-promoted vectors. 13200 // Performing this optimization before may create bit-casts which 13201 // will be type-legalized to complex code sequences. 13202 // We perform this optimization only before the operation legalizer because we 13203 // may introduce illegal operations. 13204 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 13205 return SDValue(); 13206 13207 unsigned NumInScalars = N->getNumOperands(); 13208 SDLoc DL(N); 13209 EVT VT = N->getValueType(0); 13210 13211 // Check to see if this is a BUILD_VECTOR of a bunch of values 13212 // which come from any_extend or zero_extend nodes. If so, we can create 13213 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 13214 // optimizations. We do not handle sign-extend because we can't fill the sign 13215 // using shuffles. 13216 EVT SourceType = MVT::Other; 13217 bool AllAnyExt = true; 13218 13219 for (unsigned i = 0; i != NumInScalars; ++i) { 13220 SDValue In = N->getOperand(i); 13221 // Ignore undef inputs. 13222 if (In.isUndef()) continue; 13223 13224 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 13225 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 13226 13227 // Abort if the element is not an extension. 13228 if (!ZeroExt && !AnyExt) { 13229 SourceType = MVT::Other; 13230 break; 13231 } 13232 13233 // The input is a ZeroExt or AnyExt. Check the original type. 13234 EVT InTy = In.getOperand(0).getValueType(); 13235 13236 // Check that all of the widened source types are the same. 13237 if (SourceType == MVT::Other) 13238 // First time. 13239 SourceType = InTy; 13240 else if (InTy != SourceType) { 13241 // Multiple income types. Abort. 13242 SourceType = MVT::Other; 13243 break; 13244 } 13245 13246 // Check if all of the extends are ANY_EXTENDs. 13247 AllAnyExt &= AnyExt; 13248 } 13249 13250 // In order to have valid types, all of the inputs must be extended from the 13251 // same source type and all of the inputs must be any or zero extend. 13252 // Scalar sizes must be a power of two. 13253 EVT OutScalarTy = VT.getScalarType(); 13254 bool ValidTypes = SourceType != MVT::Other && 13255 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 13256 isPowerOf2_32(SourceType.getSizeInBits()); 13257 13258 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 13259 // turn into a single shuffle instruction. 13260 if (!ValidTypes) 13261 return SDValue(); 13262 13263 bool isLE = DAG.getDataLayout().isLittleEndian(); 13264 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 13265 assert(ElemRatio > 1 && "Invalid element size ratio"); 13266 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 13267 DAG.getConstant(0, DL, SourceType); 13268 13269 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 13270 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 13271 13272 // Populate the new build_vector 13273 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13274 SDValue Cast = N->getOperand(i); 13275 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 13276 Cast.getOpcode() == ISD::ZERO_EXTEND || 13277 Cast.isUndef()) && "Invalid cast opcode"); 13278 SDValue In; 13279 if (Cast.isUndef()) 13280 In = DAG.getUNDEF(SourceType); 13281 else 13282 In = Cast->getOperand(0); 13283 unsigned Index = isLE ? (i * ElemRatio) : 13284 (i * ElemRatio + (ElemRatio - 1)); 13285 13286 assert(Index < Ops.size() && "Invalid index"); 13287 Ops[Index] = In; 13288 } 13289 13290 // The type of the new BUILD_VECTOR node. 13291 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 13292 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 13293 "Invalid vector size"); 13294 // Check if the new vector type is legal. 13295 if (!isTypeLegal(VecVT)) return SDValue(); 13296 13297 // Make the new BUILD_VECTOR. 13298 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 13299 13300 // The new BUILD_VECTOR node has the potential to be further optimized. 13301 AddToWorklist(BV.getNode()); 13302 // Bitcast to the desired type. 13303 return DAG.getBitcast(VT, BV); 13304 } 13305 13306 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 13307 EVT VT = N->getValueType(0); 13308 13309 unsigned NumInScalars = N->getNumOperands(); 13310 SDLoc DL(N); 13311 13312 EVT SrcVT = MVT::Other; 13313 unsigned Opcode = ISD::DELETED_NODE; 13314 unsigned NumDefs = 0; 13315 13316 for (unsigned i = 0; i != NumInScalars; ++i) { 13317 SDValue In = N->getOperand(i); 13318 unsigned Opc = In.getOpcode(); 13319 13320 if (Opc == ISD::UNDEF) 13321 continue; 13322 13323 // If all scalar values are floats and converted from integers. 13324 if (Opcode == ISD::DELETED_NODE && 13325 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 13326 Opcode = Opc; 13327 } 13328 13329 if (Opc != Opcode) 13330 return SDValue(); 13331 13332 EVT InVT = In.getOperand(0).getValueType(); 13333 13334 // If all scalar values are typed differently, bail out. It's chosen to 13335 // simplify BUILD_VECTOR of integer types. 13336 if (SrcVT == MVT::Other) 13337 SrcVT = InVT; 13338 if (SrcVT != InVT) 13339 return SDValue(); 13340 NumDefs++; 13341 } 13342 13343 // If the vector has just one element defined, it's not worth to fold it into 13344 // a vectorized one. 13345 if (NumDefs < 2) 13346 return SDValue(); 13347 13348 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 13349 && "Should only handle conversion from integer to float."); 13350 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 13351 13352 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 13353 13354 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 13355 return SDValue(); 13356 13357 // Just because the floating-point vector type is legal does not necessarily 13358 // mean that the corresponding integer vector type is. 13359 if (!isTypeLegal(NVT)) 13360 return SDValue(); 13361 13362 SmallVector<SDValue, 8> Opnds; 13363 for (unsigned i = 0; i != NumInScalars; ++i) { 13364 SDValue In = N->getOperand(i); 13365 13366 if (In.isUndef()) 13367 Opnds.push_back(DAG.getUNDEF(SrcVT)); 13368 else 13369 Opnds.push_back(In.getOperand(0)); 13370 } 13371 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 13372 AddToWorklist(BV.getNode()); 13373 13374 return DAG.getNode(Opcode, DL, VT, BV); 13375 } 13376 13377 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 13378 ArrayRef<int> VectorMask, 13379 SDValue VecIn1, SDValue VecIn2, 13380 unsigned LeftIdx) { 13381 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13382 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 13383 13384 EVT VT = N->getValueType(0); 13385 EVT InVT1 = VecIn1.getValueType(); 13386 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 13387 13388 unsigned Vec2Offset = InVT1.getVectorNumElements(); 13389 unsigned NumElems = VT.getVectorNumElements(); 13390 unsigned ShuffleNumElems = NumElems; 13391 13392 // We can't generate a shuffle node with mismatched input and output types. 13393 // Try to make the types match the type of the output. 13394 if (InVT1 != VT || InVT2 != VT) { 13395 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 13396 // If the output vector length is a multiple of both input lengths, 13397 // we can concatenate them and pad the rest with undefs. 13398 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 13399 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 13400 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 13401 ConcatOps[0] = VecIn1; 13402 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 13403 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 13404 VecIn2 = SDValue(); 13405 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 13406 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 13407 return SDValue(); 13408 13409 if (!VecIn2.getNode()) { 13410 // If we only have one input vector, and it's twice the size of the 13411 // output, split it in two. 13412 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 13413 DAG.getConstant(NumElems, DL, IdxTy)); 13414 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 13415 // Since we now have shorter input vectors, adjust the offset of the 13416 // second vector's start. 13417 Vec2Offset = NumElems; 13418 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 13419 // VecIn1 is wider than the output, and we have another, possibly 13420 // smaller input. Pad the smaller input with undefs, shuffle at the 13421 // input vector width, and extract the output. 13422 // The shuffle type is different than VT, so check legality again. 13423 if (LegalOperations && 13424 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 13425 return SDValue(); 13426 13427 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 13428 // lower it back into a BUILD_VECTOR. So if the inserted type is 13429 // illegal, don't even try. 13430 if (InVT1 != InVT2) { 13431 if (!TLI.isTypeLegal(InVT2)) 13432 return SDValue(); 13433 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 13434 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 13435 } 13436 ShuffleNumElems = NumElems * 2; 13437 } else { 13438 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 13439 // than VecIn1. We can't handle this for now - this case will disappear 13440 // when we start sorting the vectors by type. 13441 return SDValue(); 13442 } 13443 } else { 13444 // TODO: Support cases where the length mismatch isn't exactly by a 13445 // factor of 2. 13446 // TODO: Move this check upwards, so that if we have bad type 13447 // mismatches, we don't create any DAG nodes. 13448 return SDValue(); 13449 } 13450 } 13451 13452 // Initialize mask to undef. 13453 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 13454 13455 // Only need to run up to the number of elements actually used, not the 13456 // total number of elements in the shuffle - if we are shuffling a wider 13457 // vector, the high lanes should be set to undef. 13458 for (unsigned i = 0; i != NumElems; ++i) { 13459 if (VectorMask[i] <= 0) 13460 continue; 13461 13462 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 13463 if (VectorMask[i] == (int)LeftIdx) { 13464 Mask[i] = ExtIndex; 13465 } else if (VectorMask[i] == (int)LeftIdx + 1) { 13466 Mask[i] = Vec2Offset + ExtIndex; 13467 } 13468 } 13469 13470 // The type the input vectors may have changed above. 13471 InVT1 = VecIn1.getValueType(); 13472 13473 // If we already have a VecIn2, it should have the same type as VecIn1. 13474 // If we don't, get an undef/zero vector of the appropriate type. 13475 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 13476 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 13477 13478 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 13479 if (ShuffleNumElems > NumElems) 13480 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 13481 13482 return Shuffle; 13483 } 13484 13485 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 13486 // operations. If the types of the vectors we're extracting from allow it, 13487 // turn this into a vector_shuffle node. 13488 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 13489 SDLoc DL(N); 13490 EVT VT = N->getValueType(0); 13491 13492 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 13493 if (!isTypeLegal(VT)) 13494 return SDValue(); 13495 13496 // May only combine to shuffle after legalize if shuffle is legal. 13497 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 13498 return SDValue(); 13499 13500 bool UsesZeroVector = false; 13501 unsigned NumElems = N->getNumOperands(); 13502 13503 // Record, for each element of the newly built vector, which input vector 13504 // that element comes from. -1 stands for undef, 0 for the zero vector, 13505 // and positive values for the input vectors. 13506 // VectorMask maps each element to its vector number, and VecIn maps vector 13507 // numbers to their initial SDValues. 13508 13509 SmallVector<int, 8> VectorMask(NumElems, -1); 13510 SmallVector<SDValue, 8> VecIn; 13511 VecIn.push_back(SDValue()); 13512 13513 for (unsigned i = 0; i != NumElems; ++i) { 13514 SDValue Op = N->getOperand(i); 13515 13516 if (Op.isUndef()) 13517 continue; 13518 13519 // See if we can use a blend with a zero vector. 13520 // TODO: Should we generalize this to a blend with an arbitrary constant 13521 // vector? 13522 if (isNullConstant(Op) || isNullFPConstant(Op)) { 13523 UsesZeroVector = true; 13524 VectorMask[i] = 0; 13525 continue; 13526 } 13527 13528 // Not an undef or zero. If the input is something other than an 13529 // EXTRACT_VECTOR_ELT with a constant index, bail out. 13530 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13531 !isa<ConstantSDNode>(Op.getOperand(1))) 13532 return SDValue(); 13533 13534 SDValue ExtractedFromVec = Op.getOperand(0); 13535 13536 // All inputs must have the same element type as the output. 13537 if (VT.getVectorElementType() != 13538 ExtractedFromVec.getValueType().getVectorElementType()) 13539 return SDValue(); 13540 13541 // Have we seen this input vector before? 13542 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 13543 // a map back from SDValues to numbers isn't worth it. 13544 unsigned Idx = std::distance( 13545 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 13546 if (Idx == VecIn.size()) 13547 VecIn.push_back(ExtractedFromVec); 13548 13549 VectorMask[i] = Idx; 13550 } 13551 13552 // If we didn't find at least one input vector, bail out. 13553 if (VecIn.size() < 2) 13554 return SDValue(); 13555 13556 // TODO: We want to sort the vectors by descending length, so that adjacent 13557 // pairs have similar length, and the longer vector is always first in the 13558 // pair. 13559 13560 // TODO: Should this fire if some of the input vectors has illegal type (like 13561 // it does now), or should we let legalization run its course first? 13562 13563 // Shuffle phase: 13564 // Take pairs of vectors, and shuffle them so that the result has elements 13565 // from these vectors in the correct places. 13566 // For example, given: 13567 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 13568 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 13569 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 13570 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 13571 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 13572 // We will generate: 13573 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 13574 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 13575 SmallVector<SDValue, 4> Shuffles; 13576 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 13577 unsigned LeftIdx = 2 * In + 1; 13578 SDValue VecLeft = VecIn[LeftIdx]; 13579 SDValue VecRight = 13580 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 13581 13582 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 13583 VecRight, LeftIdx)) 13584 Shuffles.push_back(Shuffle); 13585 else 13586 return SDValue(); 13587 } 13588 13589 // If we need the zero vector as an "ingredient" in the blend tree, add it 13590 // to the list of shuffles. 13591 if (UsesZeroVector) 13592 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 13593 : DAG.getConstantFP(0.0, DL, VT)); 13594 13595 // If we only have one shuffle, we're done. 13596 if (Shuffles.size() == 1) 13597 return Shuffles[0]; 13598 13599 // Update the vector mask to point to the post-shuffle vectors. 13600 for (int &Vec : VectorMask) 13601 if (Vec == 0) 13602 Vec = Shuffles.size() - 1; 13603 else 13604 Vec = (Vec - 1) / 2; 13605 13606 // More than one shuffle. Generate a binary tree of blends, e.g. if from 13607 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 13608 // generate: 13609 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 13610 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 13611 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 13612 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 13613 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 13614 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 13615 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 13616 13617 // Make sure the initial size of the shuffle list is even. 13618 if (Shuffles.size() % 2) 13619 Shuffles.push_back(DAG.getUNDEF(VT)); 13620 13621 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 13622 if (CurSize % 2) { 13623 Shuffles[CurSize] = DAG.getUNDEF(VT); 13624 CurSize++; 13625 } 13626 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 13627 int Left = 2 * In; 13628 int Right = 2 * In + 1; 13629 SmallVector<int, 8> Mask(NumElems, -1); 13630 for (unsigned i = 0; i != NumElems; ++i) { 13631 if (VectorMask[i] == Left) { 13632 Mask[i] = i; 13633 VectorMask[i] = In; 13634 } else if (VectorMask[i] == Right) { 13635 Mask[i] = i + NumElems; 13636 VectorMask[i] = In; 13637 } 13638 } 13639 13640 Shuffles[In] = 13641 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 13642 } 13643 } 13644 13645 return Shuffles[0]; 13646 } 13647 13648 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 13649 EVT VT = N->getValueType(0); 13650 13651 // A vector built entirely of undefs is undef. 13652 if (ISD::allOperandsUndef(N)) 13653 return DAG.getUNDEF(VT); 13654 13655 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 13656 return V; 13657 13658 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 13659 return V; 13660 13661 if (SDValue V = reduceBuildVecToShuffle(N)) 13662 return V; 13663 13664 return SDValue(); 13665 } 13666 13667 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 13668 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13669 EVT OpVT = N->getOperand(0).getValueType(); 13670 13671 // If the operands are legal vectors, leave them alone. 13672 if (TLI.isTypeLegal(OpVT)) 13673 return SDValue(); 13674 13675 SDLoc DL(N); 13676 EVT VT = N->getValueType(0); 13677 SmallVector<SDValue, 8> Ops; 13678 13679 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 13680 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13681 13682 // Keep track of what we encounter. 13683 bool AnyInteger = false; 13684 bool AnyFP = false; 13685 for (const SDValue &Op : N->ops()) { 13686 if (ISD::BITCAST == Op.getOpcode() && 13687 !Op.getOperand(0).getValueType().isVector()) 13688 Ops.push_back(Op.getOperand(0)); 13689 else if (ISD::UNDEF == Op.getOpcode()) 13690 Ops.push_back(ScalarUndef); 13691 else 13692 return SDValue(); 13693 13694 // Note whether we encounter an integer or floating point scalar. 13695 // If it's neither, bail out, it could be something weird like x86mmx. 13696 EVT LastOpVT = Ops.back().getValueType(); 13697 if (LastOpVT.isFloatingPoint()) 13698 AnyFP = true; 13699 else if (LastOpVT.isInteger()) 13700 AnyInteger = true; 13701 else 13702 return SDValue(); 13703 } 13704 13705 // If any of the operands is a floating point scalar bitcast to a vector, 13706 // use floating point types throughout, and bitcast everything. 13707 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 13708 if (AnyFP) { 13709 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 13710 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13711 if (AnyInteger) { 13712 for (SDValue &Op : Ops) { 13713 if (Op.getValueType() == SVT) 13714 continue; 13715 if (Op.isUndef()) 13716 Op = ScalarUndef; 13717 else 13718 Op = DAG.getBitcast(SVT, Op); 13719 } 13720 } 13721 } 13722 13723 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 13724 VT.getSizeInBits() / SVT.getSizeInBits()); 13725 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 13726 } 13727 13728 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 13729 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 13730 // most two distinct vectors the same size as the result, attempt to turn this 13731 // into a legal shuffle. 13732 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 13733 EVT VT = N->getValueType(0); 13734 EVT OpVT = N->getOperand(0).getValueType(); 13735 int NumElts = VT.getVectorNumElements(); 13736 int NumOpElts = OpVT.getVectorNumElements(); 13737 13738 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 13739 SmallVector<int, 8> Mask; 13740 13741 for (SDValue Op : N->ops()) { 13742 // Peek through any bitcast. 13743 while (Op.getOpcode() == ISD::BITCAST) 13744 Op = Op.getOperand(0); 13745 13746 // UNDEF nodes convert to UNDEF shuffle mask values. 13747 if (Op.isUndef()) { 13748 Mask.append((unsigned)NumOpElts, -1); 13749 continue; 13750 } 13751 13752 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13753 return SDValue(); 13754 13755 // What vector are we extracting the subvector from and at what index? 13756 SDValue ExtVec = Op.getOperand(0); 13757 13758 // We want the EVT of the original extraction to correctly scale the 13759 // extraction index. 13760 EVT ExtVT = ExtVec.getValueType(); 13761 13762 // Peek through any bitcast. 13763 while (ExtVec.getOpcode() == ISD::BITCAST) 13764 ExtVec = ExtVec.getOperand(0); 13765 13766 // UNDEF nodes convert to UNDEF shuffle mask values. 13767 if (ExtVec.isUndef()) { 13768 Mask.append((unsigned)NumOpElts, -1); 13769 continue; 13770 } 13771 13772 if (!isa<ConstantSDNode>(Op.getOperand(1))) 13773 return SDValue(); 13774 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 13775 13776 // Ensure that we are extracting a subvector from a vector the same 13777 // size as the result. 13778 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 13779 return SDValue(); 13780 13781 // Scale the subvector index to account for any bitcast. 13782 int NumExtElts = ExtVT.getVectorNumElements(); 13783 if (0 == (NumExtElts % NumElts)) 13784 ExtIdx /= (NumExtElts / NumElts); 13785 else if (0 == (NumElts % NumExtElts)) 13786 ExtIdx *= (NumElts / NumExtElts); 13787 else 13788 return SDValue(); 13789 13790 // At most we can reference 2 inputs in the final shuffle. 13791 if (SV0.isUndef() || SV0 == ExtVec) { 13792 SV0 = ExtVec; 13793 for (int i = 0; i != NumOpElts; ++i) 13794 Mask.push_back(i + ExtIdx); 13795 } else if (SV1.isUndef() || SV1 == ExtVec) { 13796 SV1 = ExtVec; 13797 for (int i = 0; i != NumOpElts; ++i) 13798 Mask.push_back(i + ExtIdx + NumElts); 13799 } else { 13800 return SDValue(); 13801 } 13802 } 13803 13804 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13805 return SDValue(); 13806 13807 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13808 DAG.getBitcast(VT, SV1), Mask); 13809 } 13810 13811 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13812 // If we only have one input vector, we don't need to do any concatenation. 13813 if (N->getNumOperands() == 1) 13814 return N->getOperand(0); 13815 13816 // Check if all of the operands are undefs. 13817 EVT VT = N->getValueType(0); 13818 if (ISD::allOperandsUndef(N)) 13819 return DAG.getUNDEF(VT); 13820 13821 // Optimize concat_vectors where all but the first of the vectors are undef. 13822 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13823 return Op.isUndef(); 13824 })) { 13825 SDValue In = N->getOperand(0); 13826 assert(In.getValueType().isVector() && "Must concat vectors"); 13827 13828 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13829 if (In->getOpcode() == ISD::BITCAST && 13830 !In->getOperand(0)->getValueType(0).isVector()) { 13831 SDValue Scalar = In->getOperand(0); 13832 13833 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13834 // look through the trunc so we can still do the transform: 13835 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13836 if (Scalar->getOpcode() == ISD::TRUNCATE && 13837 !TLI.isTypeLegal(Scalar.getValueType()) && 13838 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13839 Scalar = Scalar->getOperand(0); 13840 13841 EVT SclTy = Scalar->getValueType(0); 13842 13843 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13844 return SDValue(); 13845 13846 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13847 VT.getSizeInBits() / SclTy.getSizeInBits()); 13848 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13849 return SDValue(); 13850 13851 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 13852 return DAG.getBitcast(VT, Res); 13853 } 13854 } 13855 13856 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13857 // We have already tested above for an UNDEF only concatenation. 13858 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13859 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13860 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13861 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13862 }; 13863 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13864 SmallVector<SDValue, 8> Opnds; 13865 EVT SVT = VT.getScalarType(); 13866 13867 EVT MinVT = SVT; 13868 if (!SVT.isFloatingPoint()) { 13869 // If BUILD_VECTOR are from built from integer, they may have different 13870 // operand types. Get the smallest type and truncate all operands to it. 13871 bool FoundMinVT = false; 13872 for (const SDValue &Op : N->ops()) 13873 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13874 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13875 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13876 FoundMinVT = true; 13877 } 13878 assert(FoundMinVT && "Concat vector type mismatch"); 13879 } 13880 13881 for (const SDValue &Op : N->ops()) { 13882 EVT OpVT = Op.getValueType(); 13883 unsigned NumElts = OpVT.getVectorNumElements(); 13884 13885 if (ISD::UNDEF == Op.getOpcode()) 13886 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13887 13888 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13889 if (SVT.isFloatingPoint()) { 13890 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13891 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13892 } else { 13893 for (unsigned i = 0; i != NumElts; ++i) 13894 Opnds.push_back( 13895 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13896 } 13897 } 13898 } 13899 13900 assert(VT.getVectorNumElements() == Opnds.size() && 13901 "Concat vector type mismatch"); 13902 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13903 } 13904 13905 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13906 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13907 return V; 13908 13909 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13910 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13911 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13912 return V; 13913 13914 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13915 // nodes often generate nop CONCAT_VECTOR nodes. 13916 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13917 // place the incoming vectors at the exact same location. 13918 SDValue SingleSource = SDValue(); 13919 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13920 13921 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13922 SDValue Op = N->getOperand(i); 13923 13924 if (Op.isUndef()) 13925 continue; 13926 13927 // Check if this is the identity extract: 13928 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13929 return SDValue(); 13930 13931 // Find the single incoming vector for the extract_subvector. 13932 if (SingleSource.getNode()) { 13933 if (Op.getOperand(0) != SingleSource) 13934 return SDValue(); 13935 } else { 13936 SingleSource = Op.getOperand(0); 13937 13938 // Check the source type is the same as the type of the result. 13939 // If not, this concat may extend the vector, so we can not 13940 // optimize it away. 13941 if (SingleSource.getValueType() != N->getValueType(0)) 13942 return SDValue(); 13943 } 13944 13945 unsigned IdentityIndex = i * PartNumElem; 13946 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13947 // The extract index must be constant. 13948 if (!CS) 13949 return SDValue(); 13950 13951 // Check that we are reading from the identity index. 13952 if (CS->getZExtValue() != IdentityIndex) 13953 return SDValue(); 13954 } 13955 13956 if (SingleSource.getNode()) 13957 return SingleSource; 13958 13959 return SDValue(); 13960 } 13961 13962 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13963 EVT NVT = N->getValueType(0); 13964 SDValue V = N->getOperand(0); 13965 13966 // Extract from UNDEF is UNDEF. 13967 if (V.isUndef()) 13968 return DAG.getUNDEF(NVT); 13969 13970 // Combine: 13971 // (extract_subvec (concat V1, V2, ...), i) 13972 // Into: 13973 // Vi if possible 13974 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13975 // type. 13976 if (V->getOpcode() == ISD::CONCAT_VECTORS && 13977 isa<ConstantSDNode>(N->getOperand(1)) && 13978 V->getOperand(0).getValueType() == NVT) { 13979 unsigned Idx = N->getConstantOperandVal(1); 13980 unsigned NumElems = NVT.getVectorNumElements(); 13981 assert((Idx % NumElems) == 0 && 13982 "IDX in concat is not a multiple of the result vector length."); 13983 return V->getOperand(Idx / NumElems); 13984 } 13985 13986 // Skip bitcasting 13987 if (V->getOpcode() == ISD::BITCAST) 13988 V = V.getOperand(0); 13989 13990 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13991 // Handle only simple case where vector being inserted and vector 13992 // being extracted are of same size. 13993 EVT SmallVT = V->getOperand(1).getValueType(); 13994 if (!NVT.bitsEq(SmallVT)) 13995 return SDValue(); 13996 13997 // Only handle cases where both indexes are constants. 13998 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13999 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14000 14001 if (InsIdx && ExtIdx) { 14002 // Combine: 14003 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 14004 // Into: 14005 // indices are equal or bit offsets are equal => V1 14006 // otherwise => (extract_subvec V1, ExtIdx) 14007 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 14008 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 14009 return DAG.getBitcast(NVT, V->getOperand(1)); 14010 return DAG.getNode( 14011 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 14012 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 14013 N->getOperand(1)); 14014 } 14015 } 14016 14017 return SDValue(); 14018 } 14019 14020 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 14021 SDValue V, SelectionDAG &DAG) { 14022 SDLoc DL(V); 14023 EVT VT = V.getValueType(); 14024 14025 switch (V.getOpcode()) { 14026 default: 14027 return V; 14028 14029 case ISD::CONCAT_VECTORS: { 14030 EVT OpVT = V->getOperand(0).getValueType(); 14031 int OpSize = OpVT.getVectorNumElements(); 14032 SmallBitVector OpUsedElements(OpSize, false); 14033 bool FoundSimplification = false; 14034 SmallVector<SDValue, 4> NewOps; 14035 NewOps.reserve(V->getNumOperands()); 14036 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 14037 SDValue Op = V->getOperand(i); 14038 bool OpUsed = false; 14039 for (int j = 0; j < OpSize; ++j) 14040 if (UsedElements[i * OpSize + j]) { 14041 OpUsedElements[j] = true; 14042 OpUsed = true; 14043 } 14044 NewOps.push_back( 14045 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 14046 : DAG.getUNDEF(OpVT)); 14047 FoundSimplification |= Op == NewOps.back(); 14048 OpUsedElements.reset(); 14049 } 14050 if (FoundSimplification) 14051 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 14052 return V; 14053 } 14054 14055 case ISD::INSERT_SUBVECTOR: { 14056 SDValue BaseV = V->getOperand(0); 14057 SDValue SubV = V->getOperand(1); 14058 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14059 if (!IdxN) 14060 return V; 14061 14062 int SubSize = SubV.getValueType().getVectorNumElements(); 14063 int Idx = IdxN->getZExtValue(); 14064 bool SubVectorUsed = false; 14065 SmallBitVector SubUsedElements(SubSize, false); 14066 for (int i = 0; i < SubSize; ++i) 14067 if (UsedElements[i + Idx]) { 14068 SubVectorUsed = true; 14069 SubUsedElements[i] = true; 14070 UsedElements[i + Idx] = false; 14071 } 14072 14073 // Now recurse on both the base and sub vectors. 14074 SDValue SimplifiedSubV = 14075 SubVectorUsed 14076 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 14077 : DAG.getUNDEF(SubV.getValueType()); 14078 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 14079 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 14080 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 14081 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 14082 return V; 14083 } 14084 } 14085 } 14086 14087 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 14088 SDValue N1, SelectionDAG &DAG) { 14089 EVT VT = SVN->getValueType(0); 14090 int NumElts = VT.getVectorNumElements(); 14091 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 14092 for (int M : SVN->getMask()) 14093 if (M >= 0 && M < NumElts) 14094 N0UsedElements[M] = true; 14095 else if (M >= NumElts) 14096 N1UsedElements[M - NumElts] = true; 14097 14098 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 14099 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 14100 if (S0 == N0 && S1 == N1) 14101 return SDValue(); 14102 14103 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 14104 } 14105 14106 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 14107 // or turn a shuffle of a single concat into simpler shuffle then concat. 14108 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 14109 EVT VT = N->getValueType(0); 14110 unsigned NumElts = VT.getVectorNumElements(); 14111 14112 SDValue N0 = N->getOperand(0); 14113 SDValue N1 = N->getOperand(1); 14114 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14115 14116 SmallVector<SDValue, 4> Ops; 14117 EVT ConcatVT = N0.getOperand(0).getValueType(); 14118 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 14119 unsigned NumConcats = NumElts / NumElemsPerConcat; 14120 14121 // Special case: shuffle(concat(A,B)) can be more efficiently represented 14122 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 14123 // half vector elements. 14124 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 14125 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 14126 SVN->getMask().end(), [](int i) { return i == -1; })) { 14127 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 14128 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 14129 N1 = DAG.getUNDEF(ConcatVT); 14130 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 14131 } 14132 14133 // Look at every vector that's inserted. We're looking for exact 14134 // subvector-sized copies from a concatenated vector 14135 for (unsigned I = 0; I != NumConcats; ++I) { 14136 // Make sure we're dealing with a copy. 14137 unsigned Begin = I * NumElemsPerConcat; 14138 bool AllUndef = true, NoUndef = true; 14139 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 14140 if (SVN->getMaskElt(J) >= 0) 14141 AllUndef = false; 14142 else 14143 NoUndef = false; 14144 } 14145 14146 if (NoUndef) { 14147 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 14148 return SDValue(); 14149 14150 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 14151 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 14152 return SDValue(); 14153 14154 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 14155 if (FirstElt < N0.getNumOperands()) 14156 Ops.push_back(N0.getOperand(FirstElt)); 14157 else 14158 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 14159 14160 } else if (AllUndef) { 14161 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 14162 } else { // Mixed with general masks and undefs, can't do optimization. 14163 return SDValue(); 14164 } 14165 } 14166 14167 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14168 } 14169 14170 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14171 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14172 // 14173 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 14174 // a simplification in some sense, but it isn't appropriate in general: some 14175 // BUILD_VECTORs are substantially cheaper than others. The general case 14176 // of a BUILD_VECTOR requires inserting each element individually (or 14177 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 14178 // all constants is a single constant pool load. A BUILD_VECTOR where each 14179 // element is identical is a splat. A BUILD_VECTOR where most of the operands 14180 // are undef lowers to a small number of element insertions. 14181 // 14182 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 14183 // We don't fold shuffles where one side is a non-zero constant, and we don't 14184 // fold shuffles if the resulting BUILD_VECTOR would have duplicate 14185 // non-constant operands. This seems to work out reasonably well in practice. 14186 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 14187 SelectionDAG &DAG, 14188 const TargetLowering &TLI) { 14189 EVT VT = SVN->getValueType(0); 14190 unsigned NumElts = VT.getVectorNumElements(); 14191 SDValue N0 = SVN->getOperand(0); 14192 SDValue N1 = SVN->getOperand(1); 14193 14194 if (!N0->hasOneUse() || !N1->hasOneUse()) 14195 return SDValue(); 14196 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 14197 // discussed above. 14198 if (!N1.isUndef()) { 14199 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 14200 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 14201 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 14202 return SDValue(); 14203 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 14204 return SDValue(); 14205 } 14206 14207 SmallVector<SDValue, 8> Ops; 14208 SmallSet<SDValue, 16> DuplicateOps; 14209 for (int M : SVN->getMask()) { 14210 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 14211 if (M >= 0) { 14212 int Idx = M < (int)NumElts ? M : M - NumElts; 14213 SDValue &S = (M < (int)NumElts ? N0 : N1); 14214 if (S.getOpcode() == ISD::BUILD_VECTOR) { 14215 Op = S.getOperand(Idx); 14216 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14217 if (Idx == 0) 14218 Op = S.getOperand(0); 14219 } else { 14220 // Operand can't be combined - bail out. 14221 return SDValue(); 14222 } 14223 } 14224 14225 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is 14226 // fine, but it's likely to generate low-quality code if the target can't 14227 // reconstruct an appropriate shuffle. 14228 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 14229 if (!DuplicateOps.insert(Op).second) 14230 return SDValue(); 14231 14232 Ops.push_back(Op); 14233 } 14234 // BUILD_VECTOR requires all inputs to be of the same type, find the 14235 // maximum type and extend them all. 14236 EVT SVT = VT.getScalarType(); 14237 if (SVT.isInteger()) 14238 for (SDValue &Op : Ops) 14239 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 14240 if (SVT != VT.getScalarType()) 14241 for (SDValue &Op : Ops) 14242 Op = TLI.isZExtFree(Op.getValueType(), SVT) 14243 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 14244 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 14245 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 14246 } 14247 14248 // Match shuffles that can be converted to any_vector_extend_in_reg. 14249 // This is often generated during legalization. 14250 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 14251 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 14252 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 14253 SelectionDAG &DAG, 14254 const TargetLowering &TLI, 14255 bool LegalOperations) { 14256 EVT VT = SVN->getValueType(0); 14257 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14258 14259 // TODO Add support for big-endian when we have a test case. 14260 if (!VT.isInteger() || IsBigEndian) 14261 return SDValue(); 14262 14263 unsigned NumElts = VT.getVectorNumElements(); 14264 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14265 ArrayRef<int> Mask = SVN->getMask(); 14266 SDValue N0 = SVN->getOperand(0); 14267 14268 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 14269 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 14270 for (unsigned i = 0; i != NumElts; ++i) { 14271 if (Mask[i] < 0) 14272 continue; 14273 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 14274 continue; 14275 return false; 14276 } 14277 return true; 14278 }; 14279 14280 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 14281 // power-of-2 extensions as they are the most likely. 14282 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 14283 if (!isAnyExtend(Scale)) 14284 continue; 14285 14286 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 14287 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 14288 if (!LegalOperations || 14289 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 14290 return DAG.getBitcast(VT, 14291 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 14292 } 14293 14294 return SDValue(); 14295 } 14296 14297 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 14298 // each source element of a large type into the lowest elements of a smaller 14299 // destination type. This is often generated during legalization. 14300 // If the source node itself was a '*_extend_vector_inreg' node then we should 14301 // then be able to remove it. 14302 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) { 14303 EVT VT = SVN->getValueType(0); 14304 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14305 14306 // TODO Add support for big-endian when we have a test case. 14307 if (!VT.isInteger() || IsBigEndian) 14308 return SDValue(); 14309 14310 SDValue N0 = SVN->getOperand(0); 14311 while (N0.getOpcode() == ISD::BITCAST) 14312 N0 = N0.getOperand(0); 14313 14314 unsigned Opcode = N0.getOpcode(); 14315 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 14316 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 14317 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 14318 return SDValue(); 14319 14320 SDValue N00 = N0.getOperand(0); 14321 ArrayRef<int> Mask = SVN->getMask(); 14322 unsigned NumElts = VT.getVectorNumElements(); 14323 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14324 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 14325 14326 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 14327 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 14328 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 14329 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 14330 for (unsigned i = 0; i != NumElts; ++i) { 14331 if (Mask[i] < 0) 14332 continue; 14333 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 14334 continue; 14335 return false; 14336 } 14337 return true; 14338 }; 14339 14340 // At the moment we just handle the case where we've truncated back to the 14341 // same size as before the extension. 14342 // TODO: handle more extension/truncation cases as cases arise. 14343 if (EltSizeInBits != ExtSrcSizeInBits) 14344 return SDValue(); 14345 14346 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for 14347 // power-of-2 truncations as they are the most likely. 14348 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) 14349 if (isTruncate(Scale)) 14350 return DAG.getBitcast(VT, N00); 14351 14352 return SDValue(); 14353 } 14354 14355 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 14356 EVT VT = N->getValueType(0); 14357 unsigned NumElts = VT.getVectorNumElements(); 14358 14359 SDValue N0 = N->getOperand(0); 14360 SDValue N1 = N->getOperand(1); 14361 14362 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 14363 14364 // Canonicalize shuffle undef, undef -> undef 14365 if (N0.isUndef() && N1.isUndef()) 14366 return DAG.getUNDEF(VT); 14367 14368 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14369 14370 // Canonicalize shuffle v, v -> v, undef 14371 if (N0 == N1) { 14372 SmallVector<int, 8> NewMask; 14373 for (unsigned i = 0; i != NumElts; ++i) { 14374 int Idx = SVN->getMaskElt(i); 14375 if (Idx >= (int)NumElts) Idx -= NumElts; 14376 NewMask.push_back(Idx); 14377 } 14378 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 14379 } 14380 14381 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 14382 if (N0.isUndef()) 14383 return DAG.getCommutedVectorShuffle(*SVN); 14384 14385 // Remove references to rhs if it is undef 14386 if (N1.isUndef()) { 14387 bool Changed = false; 14388 SmallVector<int, 8> NewMask; 14389 for (unsigned i = 0; i != NumElts; ++i) { 14390 int Idx = SVN->getMaskElt(i); 14391 if (Idx >= (int)NumElts) { 14392 Idx = -1; 14393 Changed = true; 14394 } 14395 NewMask.push_back(Idx); 14396 } 14397 if (Changed) 14398 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 14399 } 14400 14401 // If it is a splat, check if the argument vector is another splat or a 14402 // build_vector. 14403 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 14404 SDNode *V = N0.getNode(); 14405 14406 // If this is a bit convert that changes the element type of the vector but 14407 // not the number of vector elements, look through it. Be careful not to 14408 // look though conversions that change things like v4f32 to v2f64. 14409 if (V->getOpcode() == ISD::BITCAST) { 14410 SDValue ConvInput = V->getOperand(0); 14411 if (ConvInput.getValueType().isVector() && 14412 ConvInput.getValueType().getVectorNumElements() == NumElts) 14413 V = ConvInput.getNode(); 14414 } 14415 14416 if (V->getOpcode() == ISD::BUILD_VECTOR) { 14417 assert(V->getNumOperands() == NumElts && 14418 "BUILD_VECTOR has wrong number of operands"); 14419 SDValue Base; 14420 bool AllSame = true; 14421 for (unsigned i = 0; i != NumElts; ++i) { 14422 if (!V->getOperand(i).isUndef()) { 14423 Base = V->getOperand(i); 14424 break; 14425 } 14426 } 14427 // Splat of <u, u, u, u>, return <u, u, u, u> 14428 if (!Base.getNode()) 14429 return N0; 14430 for (unsigned i = 0; i != NumElts; ++i) { 14431 if (V->getOperand(i) != Base) { 14432 AllSame = false; 14433 break; 14434 } 14435 } 14436 // Splat of <x, x, x, x>, return <x, x, x, x> 14437 if (AllSame) 14438 return N0; 14439 14440 // Canonicalize any other splat as a build_vector. 14441 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 14442 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 14443 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 14444 14445 // We may have jumped through bitcasts, so the type of the 14446 // BUILD_VECTOR may not match the type of the shuffle. 14447 if (V->getValueType(0) != VT) 14448 NewBV = DAG.getBitcast(VT, NewBV); 14449 return NewBV; 14450 } 14451 } 14452 14453 // There are various patterns used to build up a vector from smaller vectors, 14454 // subvectors, or elements. Scan chains of these and replace unused insertions 14455 // or components with undef. 14456 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 14457 return S; 14458 14459 // Match shuffles that can be converted to any_vector_extend_in_reg. 14460 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 14461 return V; 14462 14463 // Combine "truncate_vector_in_reg" style shuffles. 14464 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 14465 return V; 14466 14467 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 14468 Level < AfterLegalizeVectorOps && 14469 (N1.isUndef() || 14470 (N1.getOpcode() == ISD::CONCAT_VECTORS && 14471 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 14472 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 14473 return V; 14474 } 14475 14476 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14477 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14478 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14479 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 14480 return Res; 14481 14482 // If this shuffle only has a single input that is a bitcasted shuffle, 14483 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 14484 // back to their original types. 14485 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 14486 N1.isUndef() && Level < AfterLegalizeVectorOps && 14487 TLI.isTypeLegal(VT)) { 14488 14489 // Peek through the bitcast only if there is one user. 14490 SDValue BC0 = N0; 14491 while (BC0.getOpcode() == ISD::BITCAST) { 14492 if (!BC0.hasOneUse()) 14493 break; 14494 BC0 = BC0.getOperand(0); 14495 } 14496 14497 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 14498 if (Scale == 1) 14499 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 14500 14501 SmallVector<int, 8> NewMask; 14502 for (int M : Mask) 14503 for (int s = 0; s != Scale; ++s) 14504 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 14505 return NewMask; 14506 }; 14507 14508 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 14509 EVT SVT = VT.getScalarType(); 14510 EVT InnerVT = BC0->getValueType(0); 14511 EVT InnerSVT = InnerVT.getScalarType(); 14512 14513 // Determine which shuffle works with the smaller scalar type. 14514 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 14515 EVT ScaleSVT = ScaleVT.getScalarType(); 14516 14517 if (TLI.isTypeLegal(ScaleVT) && 14518 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 14519 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 14520 14521 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14522 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14523 14524 // Scale the shuffle masks to the smaller scalar type. 14525 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 14526 SmallVector<int, 8> InnerMask = 14527 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 14528 SmallVector<int, 8> OuterMask = 14529 ScaleShuffleMask(SVN->getMask(), OuterScale); 14530 14531 // Merge the shuffle masks. 14532 SmallVector<int, 8> NewMask; 14533 for (int M : OuterMask) 14534 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 14535 14536 // Test for shuffle mask legality over both commutations. 14537 SDValue SV0 = BC0->getOperand(0); 14538 SDValue SV1 = BC0->getOperand(1); 14539 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14540 if (!LegalMask) { 14541 std::swap(SV0, SV1); 14542 ShuffleVectorSDNode::commuteMask(NewMask); 14543 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14544 } 14545 14546 if (LegalMask) { 14547 SV0 = DAG.getBitcast(ScaleVT, SV0); 14548 SV1 = DAG.getBitcast(ScaleVT, SV1); 14549 return DAG.getBitcast( 14550 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 14551 } 14552 } 14553 } 14554 } 14555 14556 // Canonicalize shuffles according to rules: 14557 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 14558 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 14559 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 14560 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 14561 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 14562 TLI.isTypeLegal(VT)) { 14563 // The incoming shuffle must be of the same type as the result of the 14564 // current shuffle. 14565 assert(N1->getOperand(0).getValueType() == VT && 14566 "Shuffle types don't match"); 14567 14568 SDValue SV0 = N1->getOperand(0); 14569 SDValue SV1 = N1->getOperand(1); 14570 bool HasSameOp0 = N0 == SV0; 14571 bool IsSV1Undef = SV1.isUndef(); 14572 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 14573 // Commute the operands of this shuffle so that next rule 14574 // will trigger. 14575 return DAG.getCommutedVectorShuffle(*SVN); 14576 } 14577 14578 // Try to fold according to rules: 14579 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14580 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14581 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14582 // Don't try to fold shuffles with illegal type. 14583 // Only fold if this shuffle is the only user of the other shuffle. 14584 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 14585 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 14586 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 14587 14588 // Don't try to fold splats; they're likely to simplify somehow, or they 14589 // might be free. 14590 if (OtherSV->isSplat()) 14591 return SDValue(); 14592 14593 // The incoming shuffle must be of the same type as the result of the 14594 // current shuffle. 14595 assert(OtherSV->getOperand(0).getValueType() == VT && 14596 "Shuffle types don't match"); 14597 14598 SDValue SV0, SV1; 14599 SmallVector<int, 4> Mask; 14600 // Compute the combined shuffle mask for a shuffle with SV0 as the first 14601 // operand, and SV1 as the second operand. 14602 for (unsigned i = 0; i != NumElts; ++i) { 14603 int Idx = SVN->getMaskElt(i); 14604 if (Idx < 0) { 14605 // Propagate Undef. 14606 Mask.push_back(Idx); 14607 continue; 14608 } 14609 14610 SDValue CurrentVec; 14611 if (Idx < (int)NumElts) { 14612 // This shuffle index refers to the inner shuffle N0. Lookup the inner 14613 // shuffle mask to identify which vector is actually referenced. 14614 Idx = OtherSV->getMaskElt(Idx); 14615 if (Idx < 0) { 14616 // Propagate Undef. 14617 Mask.push_back(Idx); 14618 continue; 14619 } 14620 14621 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 14622 : OtherSV->getOperand(1); 14623 } else { 14624 // This shuffle index references an element within N1. 14625 CurrentVec = N1; 14626 } 14627 14628 // Simple case where 'CurrentVec' is UNDEF. 14629 if (CurrentVec.isUndef()) { 14630 Mask.push_back(-1); 14631 continue; 14632 } 14633 14634 // Canonicalize the shuffle index. We don't know yet if CurrentVec 14635 // will be the first or second operand of the combined shuffle. 14636 Idx = Idx % NumElts; 14637 if (!SV0.getNode() || SV0 == CurrentVec) { 14638 // Ok. CurrentVec is the left hand side. 14639 // Update the mask accordingly. 14640 SV0 = CurrentVec; 14641 Mask.push_back(Idx); 14642 continue; 14643 } 14644 14645 // Bail out if we cannot convert the shuffle pair into a single shuffle. 14646 if (SV1.getNode() && SV1 != CurrentVec) 14647 return SDValue(); 14648 14649 // Ok. CurrentVec is the right hand side. 14650 // Update the mask accordingly. 14651 SV1 = CurrentVec; 14652 Mask.push_back(Idx + NumElts); 14653 } 14654 14655 // Check if all indices in Mask are Undef. In case, propagate Undef. 14656 bool isUndefMask = true; 14657 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 14658 isUndefMask &= Mask[i] < 0; 14659 14660 if (isUndefMask) 14661 return DAG.getUNDEF(VT); 14662 14663 if (!SV0.getNode()) 14664 SV0 = DAG.getUNDEF(VT); 14665 if (!SV1.getNode()) 14666 SV1 = DAG.getUNDEF(VT); 14667 14668 // Avoid introducing shuffles with illegal mask. 14669 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 14670 ShuffleVectorSDNode::commuteMask(Mask); 14671 14672 if (!TLI.isShuffleMaskLegal(Mask, VT)) 14673 return SDValue(); 14674 14675 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 14676 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 14677 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 14678 std::swap(SV0, SV1); 14679 } 14680 14681 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14682 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14683 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14684 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 14685 } 14686 14687 return SDValue(); 14688 } 14689 14690 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 14691 SDValue InVal = N->getOperand(0); 14692 EVT VT = N->getValueType(0); 14693 14694 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 14695 // with a VECTOR_SHUFFLE. 14696 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14697 SDValue InVec = InVal->getOperand(0); 14698 SDValue EltNo = InVal->getOperand(1); 14699 14700 // FIXME: We could support implicit truncation if the shuffle can be 14701 // scaled to a smaller vector scalar type. 14702 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 14703 if (C0 && VT == InVec.getValueType() && 14704 VT.getScalarType() == InVal.getValueType()) { 14705 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 14706 int Elt = C0->getZExtValue(); 14707 NewMask[0] = Elt; 14708 14709 if (TLI.isShuffleMaskLegal(NewMask, VT)) 14710 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 14711 NewMask); 14712 } 14713 } 14714 14715 return SDValue(); 14716 } 14717 14718 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 14719 EVT VT = N->getValueType(0); 14720 SDValue N0 = N->getOperand(0); 14721 SDValue N1 = N->getOperand(1); 14722 SDValue N2 = N->getOperand(2); 14723 14724 // If inserting an UNDEF, just return the original vector. 14725 if (N1.isUndef()) 14726 return N0; 14727 14728 // If this is an insert of an extracted vector into an undef vector, we can 14729 // just use the input to the extract. 14730 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 14731 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 14732 return N1.getOperand(0); 14733 14734 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 14735 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 14736 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 14737 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 14738 N0.getOperand(1).getValueType() == N1.getValueType() && 14739 N0.getOperand(2) == N2) 14740 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 14741 N1, N2); 14742 14743 if (!isa<ConstantSDNode>(N2)) 14744 return SDValue(); 14745 14746 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 14747 14748 // Canonicalize insert_subvector dag nodes. 14749 // Example: 14750 // (insert_subvector (insert_subvector A, Idx0), Idx1) 14751 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 14752 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 14753 N1.getValueType() == N0.getOperand(1).getValueType() && 14754 isa<ConstantSDNode>(N0.getOperand(2))) { 14755 unsigned OtherIdx = cast<ConstantSDNode>(N0.getOperand(2))->getZExtValue(); 14756 if (InsIdx < OtherIdx) { 14757 // Swap nodes. 14758 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 14759 N0.getOperand(0), N1, N2); 14760 AddToWorklist(NewOp.getNode()); 14761 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 14762 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 14763 } 14764 } 14765 14766 // If the input vector is a concatenation, and the insert replaces 14767 // one of the pieces, we can optimize into a single concat_vectors. 14768 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 14769 N0.getOperand(0).getValueType() == N1.getValueType()) { 14770 unsigned Factor = N1.getValueType().getVectorNumElements(); 14771 14772 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 14773 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 14774 14775 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14776 } 14777 14778 return SDValue(); 14779 } 14780 14781 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 14782 SDValue N0 = N->getOperand(0); 14783 14784 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 14785 if (N0->getOpcode() == ISD::FP16_TO_FP) 14786 return N0->getOperand(0); 14787 14788 return SDValue(); 14789 } 14790 14791 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 14792 SDValue N0 = N->getOperand(0); 14793 14794 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 14795 if (N0->getOpcode() == ISD::AND) { 14796 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 14797 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 14798 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 14799 N0.getOperand(0)); 14800 } 14801 } 14802 14803 return SDValue(); 14804 } 14805 14806 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 14807 /// with the destination vector and a zero vector. 14808 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 14809 /// vector_shuffle V, Zero, <0, 4, 2, 4> 14810 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 14811 EVT VT = N->getValueType(0); 14812 SDValue LHS = N->getOperand(0); 14813 SDValue RHS = N->getOperand(1); 14814 SDLoc DL(N); 14815 14816 // Make sure we're not running after operation legalization where it 14817 // may have custom lowered the vector shuffles. 14818 if (LegalOperations) 14819 return SDValue(); 14820 14821 if (N->getOpcode() != ISD::AND) 14822 return SDValue(); 14823 14824 if (RHS.getOpcode() == ISD::BITCAST) 14825 RHS = RHS.getOperand(0); 14826 14827 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 14828 return SDValue(); 14829 14830 EVT RVT = RHS.getValueType(); 14831 unsigned NumElts = RHS.getNumOperands(); 14832 14833 // Attempt to create a valid clear mask, splitting the mask into 14834 // sub elements and checking to see if each is 14835 // all zeros or all ones - suitable for shuffle masking. 14836 auto BuildClearMask = [&](int Split) { 14837 int NumSubElts = NumElts * Split; 14838 int NumSubBits = RVT.getScalarSizeInBits() / Split; 14839 14840 SmallVector<int, 8> Indices; 14841 for (int i = 0; i != NumSubElts; ++i) { 14842 int EltIdx = i / Split; 14843 int SubIdx = i % Split; 14844 SDValue Elt = RHS.getOperand(EltIdx); 14845 if (Elt.isUndef()) { 14846 Indices.push_back(-1); 14847 continue; 14848 } 14849 14850 APInt Bits; 14851 if (isa<ConstantSDNode>(Elt)) 14852 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 14853 else if (isa<ConstantFPSDNode>(Elt)) 14854 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 14855 else 14856 return SDValue(); 14857 14858 // Extract the sub element from the constant bit mask. 14859 if (DAG.getDataLayout().isBigEndian()) { 14860 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 14861 } else { 14862 Bits = Bits.lshr(SubIdx * NumSubBits); 14863 } 14864 14865 if (Split > 1) 14866 Bits = Bits.trunc(NumSubBits); 14867 14868 if (Bits.isAllOnesValue()) 14869 Indices.push_back(i); 14870 else if (Bits == 0) 14871 Indices.push_back(i + NumSubElts); 14872 else 14873 return SDValue(); 14874 } 14875 14876 // Let's see if the target supports this vector_shuffle. 14877 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 14878 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 14879 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 14880 return SDValue(); 14881 14882 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 14883 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 14884 DAG.getBitcast(ClearVT, LHS), 14885 Zero, Indices)); 14886 }; 14887 14888 // Determine maximum split level (byte level masking). 14889 int MaxSplit = 1; 14890 if (RVT.getScalarSizeInBits() % 8 == 0) 14891 MaxSplit = RVT.getScalarSizeInBits() / 8; 14892 14893 for (int Split = 1; Split <= MaxSplit; ++Split) 14894 if (RVT.getScalarSizeInBits() % Split == 0) 14895 if (SDValue S = BuildClearMask(Split)) 14896 return S; 14897 14898 return SDValue(); 14899 } 14900 14901 /// Visit a binary vector operation, like ADD. 14902 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 14903 assert(N->getValueType(0).isVector() && 14904 "SimplifyVBinOp only works on vectors!"); 14905 14906 SDValue LHS = N->getOperand(0); 14907 SDValue RHS = N->getOperand(1); 14908 SDValue Ops[] = {LHS, RHS}; 14909 14910 // See if we can constant fold the vector operation. 14911 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 14912 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 14913 return Fold; 14914 14915 // Try to convert a constant mask AND into a shuffle clear mask. 14916 if (SDValue Shuffle = XformToShuffleWithZero(N)) 14917 return Shuffle; 14918 14919 // Type legalization might introduce new shuffles in the DAG. 14920 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 14921 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 14922 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 14923 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 14924 LHS.getOperand(1).isUndef() && 14925 RHS.getOperand(1).isUndef()) { 14926 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 14927 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 14928 14929 if (SVN0->getMask().equals(SVN1->getMask())) { 14930 EVT VT = N->getValueType(0); 14931 SDValue UndefVector = LHS.getOperand(1); 14932 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 14933 LHS.getOperand(0), RHS.getOperand(0), 14934 N->getFlags()); 14935 AddUsersToWorklist(N); 14936 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 14937 SVN0->getMask()); 14938 } 14939 } 14940 14941 return SDValue(); 14942 } 14943 14944 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 14945 SDValue N2) { 14946 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 14947 14948 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 14949 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 14950 14951 // If we got a simplified select_cc node back from SimplifySelectCC, then 14952 // break it down into a new SETCC node, and a new SELECT node, and then return 14953 // the SELECT node, since we were called with a SELECT node. 14954 if (SCC.getNode()) { 14955 // Check to see if we got a select_cc back (to turn into setcc/select). 14956 // Otherwise, just return whatever node we got back, like fabs. 14957 if (SCC.getOpcode() == ISD::SELECT_CC) { 14958 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 14959 N0.getValueType(), 14960 SCC.getOperand(0), SCC.getOperand(1), 14961 SCC.getOperand(4)); 14962 AddToWorklist(SETCC.getNode()); 14963 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 14964 SCC.getOperand(2), SCC.getOperand(3)); 14965 } 14966 14967 return SCC; 14968 } 14969 return SDValue(); 14970 } 14971 14972 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 14973 /// being selected between, see if we can simplify the select. Callers of this 14974 /// should assume that TheSelect is deleted if this returns true. As such, they 14975 /// should return the appropriate thing (e.g. the node) back to the top-level of 14976 /// the DAG combiner loop to avoid it being looked at. 14977 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 14978 SDValue RHS) { 14979 14980 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14981 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 14982 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 14983 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 14984 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 14985 SDValue Sqrt = RHS; 14986 ISD::CondCode CC; 14987 SDValue CmpLHS; 14988 const ConstantFPSDNode *Zero = nullptr; 14989 14990 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 14991 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 14992 CmpLHS = TheSelect->getOperand(0); 14993 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 14994 } else { 14995 // SELECT or VSELECT 14996 SDValue Cmp = TheSelect->getOperand(0); 14997 if (Cmp.getOpcode() == ISD::SETCC) { 14998 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 14999 CmpLHS = Cmp.getOperand(0); 15000 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 15001 } 15002 } 15003 if (Zero && Zero->isZero() && 15004 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 15005 CC == ISD::SETULT || CC == ISD::SETLT)) { 15006 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15007 CombineTo(TheSelect, Sqrt); 15008 return true; 15009 } 15010 } 15011 } 15012 // Cannot simplify select with vector condition 15013 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 15014 15015 // If this is a select from two identical things, try to pull the operation 15016 // through the select. 15017 if (LHS.getOpcode() != RHS.getOpcode() || 15018 !LHS.hasOneUse() || !RHS.hasOneUse()) 15019 return false; 15020 15021 // If this is a load and the token chain is identical, replace the select 15022 // of two loads with a load through a select of the address to load from. 15023 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 15024 // constants have been dropped into the constant pool. 15025 if (LHS.getOpcode() == ISD::LOAD) { 15026 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 15027 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 15028 15029 // Token chains must be identical. 15030 if (LHS.getOperand(0) != RHS.getOperand(0) || 15031 // Do not let this transformation reduce the number of volatile loads. 15032 LLD->isVolatile() || RLD->isVolatile() || 15033 // FIXME: If either is a pre/post inc/dec load, 15034 // we'd need to split out the address adjustment. 15035 LLD->isIndexed() || RLD->isIndexed() || 15036 // If this is an EXTLOAD, the VT's must match. 15037 LLD->getMemoryVT() != RLD->getMemoryVT() || 15038 // If this is an EXTLOAD, the kind of extension must match. 15039 (LLD->getExtensionType() != RLD->getExtensionType() && 15040 // The only exception is if one of the extensions is anyext. 15041 LLD->getExtensionType() != ISD::EXTLOAD && 15042 RLD->getExtensionType() != ISD::EXTLOAD) || 15043 // FIXME: this discards src value information. This is 15044 // over-conservative. It would be beneficial to be able to remember 15045 // both potential memory locations. Since we are discarding 15046 // src value info, don't do the transformation if the memory 15047 // locations are not in the default address space. 15048 LLD->getPointerInfo().getAddrSpace() != 0 || 15049 RLD->getPointerInfo().getAddrSpace() != 0 || 15050 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 15051 LLD->getBasePtr().getValueType())) 15052 return false; 15053 15054 // Check that the select condition doesn't reach either load. If so, 15055 // folding this will induce a cycle into the DAG. If not, this is safe to 15056 // xform, so create a select of the addresses. 15057 SDValue Addr; 15058 if (TheSelect->getOpcode() == ISD::SELECT) { 15059 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 15060 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 15061 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 15062 return false; 15063 // The loads must not depend on one another. 15064 if (LLD->isPredecessorOf(RLD) || 15065 RLD->isPredecessorOf(LLD)) 15066 return false; 15067 Addr = DAG.getSelect(SDLoc(TheSelect), 15068 LLD->getBasePtr().getValueType(), 15069 TheSelect->getOperand(0), LLD->getBasePtr(), 15070 RLD->getBasePtr()); 15071 } else { // Otherwise SELECT_CC 15072 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 15073 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 15074 15075 if ((LLD->hasAnyUseOfValue(1) && 15076 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 15077 (RLD->hasAnyUseOfValue(1) && 15078 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 15079 return false; 15080 15081 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 15082 LLD->getBasePtr().getValueType(), 15083 TheSelect->getOperand(0), 15084 TheSelect->getOperand(1), 15085 LLD->getBasePtr(), RLD->getBasePtr(), 15086 TheSelect->getOperand(4)); 15087 } 15088 15089 SDValue Load; 15090 // It is safe to replace the two loads if they have different alignments, 15091 // but the new load must be the minimum (most restrictive) alignment of the 15092 // inputs. 15093 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 15094 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 15095 if (!RLD->isInvariant()) 15096 MMOFlags &= ~MachineMemOperand::MOInvariant; 15097 if (!RLD->isDereferenceable()) 15098 MMOFlags &= ~MachineMemOperand::MODereferenceable; 15099 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 15100 // FIXME: Discards pointer and AA info. 15101 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 15102 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 15103 MMOFlags); 15104 } else { 15105 // FIXME: Discards pointer and AA info. 15106 Load = DAG.getExtLoad( 15107 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 15108 : LLD->getExtensionType(), 15109 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 15110 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 15111 } 15112 15113 // Users of the select now use the result of the load. 15114 CombineTo(TheSelect, Load); 15115 15116 // Users of the old loads now use the new load's chain. We know the 15117 // old-load value is dead now. 15118 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 15119 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 15120 return true; 15121 } 15122 15123 return false; 15124 } 15125 15126 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 15127 /// bitwise 'and'. 15128 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 15129 SDValue N1, SDValue N2, SDValue N3, 15130 ISD::CondCode CC) { 15131 // If this is a select where the false operand is zero and the compare is a 15132 // check of the sign bit, see if we can perform the "gzip trick": 15133 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 15134 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 15135 EVT XType = N0.getValueType(); 15136 EVT AType = N2.getValueType(); 15137 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 15138 return SDValue(); 15139 15140 // If the comparison is testing for a positive value, we have to invert 15141 // the sign bit mask, so only do that transform if the target has a bitwise 15142 // 'and not' instruction (the invert is free). 15143 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 15144 // (X > -1) ? A : 0 15145 // (X > 0) ? X : 0 <-- This is canonical signed max. 15146 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 15147 return SDValue(); 15148 } else if (CC == ISD::SETLT) { 15149 // (X < 0) ? A : 0 15150 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 15151 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 15152 return SDValue(); 15153 } else { 15154 return SDValue(); 15155 } 15156 15157 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 15158 // constant. 15159 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 15160 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15161 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 15162 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 15163 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 15164 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 15165 AddToWorklist(Shift.getNode()); 15166 15167 if (XType.bitsGT(AType)) { 15168 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15169 AddToWorklist(Shift.getNode()); 15170 } 15171 15172 if (CC == ISD::SETGT) 15173 Shift = DAG.getNOT(DL, Shift, AType); 15174 15175 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15176 } 15177 15178 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 15179 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 15180 AddToWorklist(Shift.getNode()); 15181 15182 if (XType.bitsGT(AType)) { 15183 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15184 AddToWorklist(Shift.getNode()); 15185 } 15186 15187 if (CC == ISD::SETGT) 15188 Shift = DAG.getNOT(DL, Shift, AType); 15189 15190 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15191 } 15192 15193 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 15194 /// where 'cond' is the comparison specified by CC. 15195 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 15196 SDValue N2, SDValue N3, ISD::CondCode CC, 15197 bool NotExtCompare) { 15198 // (x ? y : y) -> y. 15199 if (N2 == N3) return N2; 15200 15201 EVT VT = N2.getValueType(); 15202 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 15203 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15204 15205 // Determine if the condition we're dealing with is constant 15206 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 15207 N0, N1, CC, DL, false); 15208 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 15209 15210 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 15211 // fold select_cc true, x, y -> x 15212 // fold select_cc false, x, y -> y 15213 return !SCCC->isNullValue() ? N2 : N3; 15214 } 15215 15216 // Check to see if we can simplify the select into an fabs node 15217 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 15218 // Allow either -0.0 or 0.0 15219 if (CFP->isZero()) { 15220 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 15221 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 15222 N0 == N2 && N3.getOpcode() == ISD::FNEG && 15223 N2 == N3.getOperand(0)) 15224 return DAG.getNode(ISD::FABS, DL, VT, N0); 15225 15226 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 15227 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 15228 N0 == N3 && N2.getOpcode() == ISD::FNEG && 15229 N2.getOperand(0) == N3) 15230 return DAG.getNode(ISD::FABS, DL, VT, N3); 15231 } 15232 } 15233 15234 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 15235 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 15236 // in it. This is a win when the constant is not otherwise available because 15237 // it replaces two constant pool loads with one. We only do this if the FP 15238 // type is known to be legal, because if it isn't, then we are before legalize 15239 // types an we want the other legalization to happen first (e.g. to avoid 15240 // messing with soft float) and if the ConstantFP is not legal, because if 15241 // it is legal, we may not need to store the FP constant in a constant pool. 15242 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 15243 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 15244 if (TLI.isTypeLegal(N2.getValueType()) && 15245 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 15246 TargetLowering::Legal && 15247 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 15248 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 15249 // If both constants have multiple uses, then we won't need to do an 15250 // extra load, they are likely around in registers for other users. 15251 (TV->hasOneUse() || FV->hasOneUse())) { 15252 Constant *Elts[] = { 15253 const_cast<ConstantFP*>(FV->getConstantFPValue()), 15254 const_cast<ConstantFP*>(TV->getConstantFPValue()) 15255 }; 15256 Type *FPTy = Elts[0]->getType(); 15257 const DataLayout &TD = DAG.getDataLayout(); 15258 15259 // Create a ConstantArray of the two constants. 15260 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 15261 SDValue CPIdx = 15262 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 15263 TD.getPrefTypeAlignment(FPTy)); 15264 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 15265 15266 // Get the offsets to the 0 and 1 element of the array so that we can 15267 // select between them. 15268 SDValue Zero = DAG.getIntPtrConstant(0, DL); 15269 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 15270 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 15271 15272 SDValue Cond = DAG.getSetCC(DL, 15273 getSetCCResultType(N0.getValueType()), 15274 N0, N1, CC); 15275 AddToWorklist(Cond.getNode()); 15276 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 15277 Cond, One, Zero); 15278 AddToWorklist(CstOffset.getNode()); 15279 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 15280 CstOffset); 15281 AddToWorklist(CPIdx.getNode()); 15282 return DAG.getLoad( 15283 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 15284 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 15285 Alignment); 15286 } 15287 } 15288 15289 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 15290 return V; 15291 15292 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 15293 // where y is has a single bit set. 15294 // A plaintext description would be, we can turn the SELECT_CC into an AND 15295 // when the condition can be materialized as an all-ones register. Any 15296 // single bit-test can be materialized as an all-ones register with 15297 // shift-left and shift-right-arith. 15298 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 15299 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 15300 SDValue AndLHS = N0->getOperand(0); 15301 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15302 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 15303 // Shift the tested bit over the sign bit. 15304 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 15305 SDValue ShlAmt = 15306 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 15307 getShiftAmountTy(AndLHS.getValueType())); 15308 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 15309 15310 // Now arithmetic right shift it all the way over, so the result is either 15311 // all-ones, or zero. 15312 SDValue ShrAmt = 15313 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 15314 getShiftAmountTy(Shl.getValueType())); 15315 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 15316 15317 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 15318 } 15319 } 15320 15321 // fold select C, 16, 0 -> shl C, 4 15322 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 15323 TLI.getBooleanContents(N0.getValueType()) == 15324 TargetLowering::ZeroOrOneBooleanContent) { 15325 15326 // If the caller doesn't want us to simplify this into a zext of a compare, 15327 // don't do it. 15328 if (NotExtCompare && N2C->isOne()) 15329 return SDValue(); 15330 15331 // Get a SetCC of the condition 15332 // NOTE: Don't create a SETCC if it's not legal on this target. 15333 if (!LegalOperations || 15334 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 15335 SDValue Temp, SCC; 15336 // cast from setcc result type to select result type 15337 if (LegalTypes) { 15338 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 15339 N0, N1, CC); 15340 if (N2.getValueType().bitsLT(SCC.getValueType())) 15341 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 15342 N2.getValueType()); 15343 else 15344 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15345 N2.getValueType(), SCC); 15346 } else { 15347 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 15348 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15349 N2.getValueType(), SCC); 15350 } 15351 15352 AddToWorklist(SCC.getNode()); 15353 AddToWorklist(Temp.getNode()); 15354 15355 if (N2C->isOne()) 15356 return Temp; 15357 15358 // shl setcc result by log2 n2c 15359 return DAG.getNode( 15360 ISD::SHL, DL, N2.getValueType(), Temp, 15361 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 15362 getShiftAmountTy(Temp.getValueType()))); 15363 } 15364 } 15365 15366 // Check to see if this is an integer abs. 15367 // select_cc setg[te] X, 0, X, -X -> 15368 // select_cc setgt X, -1, X, -X -> 15369 // select_cc setl[te] X, 0, -X, X -> 15370 // select_cc setlt X, 1, -X, X -> 15371 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 15372 if (N1C) { 15373 ConstantSDNode *SubC = nullptr; 15374 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 15375 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 15376 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 15377 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 15378 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 15379 (N1C->isOne() && CC == ISD::SETLT)) && 15380 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 15381 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 15382 15383 EVT XType = N0.getValueType(); 15384 if (SubC && SubC->isNullValue() && XType.isInteger()) { 15385 SDLoc DL(N0); 15386 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 15387 N0, 15388 DAG.getConstant(XType.getSizeInBits() - 1, DL, 15389 getShiftAmountTy(N0.getValueType()))); 15390 SDValue Add = DAG.getNode(ISD::ADD, DL, 15391 XType, N0, Shift); 15392 AddToWorklist(Shift.getNode()); 15393 AddToWorklist(Add.getNode()); 15394 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 15395 } 15396 } 15397 15398 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 15399 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 15400 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 15401 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 15402 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 15403 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 15404 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 15405 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 15406 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 15407 SDValue ValueOnZero = N2; 15408 SDValue Count = N3; 15409 // If the condition is NE instead of E, swap the operands. 15410 if (CC == ISD::SETNE) 15411 std::swap(ValueOnZero, Count); 15412 // Check if the value on zero is a constant equal to the bits in the type. 15413 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 15414 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 15415 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 15416 // legal, combine to just cttz. 15417 if ((Count.getOpcode() == ISD::CTTZ || 15418 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 15419 N0 == Count.getOperand(0) && 15420 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 15421 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 15422 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 15423 // legal, combine to just ctlz. 15424 if ((Count.getOpcode() == ISD::CTLZ || 15425 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 15426 N0 == Count.getOperand(0) && 15427 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 15428 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 15429 } 15430 } 15431 } 15432 15433 return SDValue(); 15434 } 15435 15436 /// This is a stub for TargetLowering::SimplifySetCC. 15437 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 15438 ISD::CondCode Cond, const SDLoc &DL, 15439 bool foldBooleans) { 15440 TargetLowering::DAGCombinerInfo 15441 DagCombineInfo(DAG, Level, false, this); 15442 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 15443 } 15444 15445 /// Given an ISD::SDIV node expressing a divide by constant, return 15446 /// a DAG expression to select that will generate the same value by multiplying 15447 /// by a magic number. 15448 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 15449 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 15450 // when optimising for minimum size, we don't want to expand a div to a mul 15451 // and a shift. 15452 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 15453 return SDValue(); 15454 15455 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15456 if (!C) 15457 return SDValue(); 15458 15459 // Avoid division by zero. 15460 if (C->isNullValue()) 15461 return SDValue(); 15462 15463 std::vector<SDNode*> Built; 15464 SDValue S = 15465 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 15466 15467 for (SDNode *N : Built) 15468 AddToWorklist(N); 15469 return S; 15470 } 15471 15472 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 15473 /// DAG expression that will generate the same value by right shifting. 15474 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 15475 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15476 if (!C) 15477 return SDValue(); 15478 15479 // Avoid division by zero. 15480 if (C->isNullValue()) 15481 return SDValue(); 15482 15483 std::vector<SDNode *> Built; 15484 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 15485 15486 for (SDNode *N : Built) 15487 AddToWorklist(N); 15488 return S; 15489 } 15490 15491 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 15492 /// expression that will generate the same value by multiplying by a magic 15493 /// number. 15494 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 15495 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 15496 // when optimising for minimum size, we don't want to expand a div to a mul 15497 // and a shift. 15498 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 15499 return SDValue(); 15500 15501 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15502 if (!C) 15503 return SDValue(); 15504 15505 // Avoid division by zero. 15506 if (C->isNullValue()) 15507 return SDValue(); 15508 15509 std::vector<SDNode*> Built; 15510 SDValue S = 15511 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 15512 15513 for (SDNode *N : Built) 15514 AddToWorklist(N); 15515 return S; 15516 } 15517 15518 /// Determines the LogBase2 value for a non-null input value using the 15519 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 15520 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 15521 EVT VT = V.getValueType(); 15522 unsigned EltBits = VT.getScalarSizeInBits(); 15523 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 15524 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 15525 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 15526 return LogBase2; 15527 } 15528 15529 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15530 /// For the reciprocal, we need to find the zero of the function: 15531 /// F(X) = A X - 1 [which has a zero at X = 1/A] 15532 /// => 15533 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 15534 /// does not require additional intermediate precision] 15535 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 15536 if (Level >= AfterLegalizeDAG) 15537 return SDValue(); 15538 15539 // TODO: Handle half and/or extended types? 15540 EVT VT = Op.getValueType(); 15541 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 15542 return SDValue(); 15543 15544 // If estimates are explicitly disabled for this function, we're done. 15545 MachineFunction &MF = DAG.getMachineFunction(); 15546 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 15547 if (Enabled == TLI.ReciprocalEstimate::Disabled) 15548 return SDValue(); 15549 15550 // Estimates may be explicitly enabled for this type with a custom number of 15551 // refinement steps. 15552 int Iterations = TLI.getDivRefinementSteps(VT, MF); 15553 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 15554 AddToWorklist(Est.getNode()); 15555 15556 if (Iterations) { 15557 EVT VT = Op.getValueType(); 15558 SDLoc DL(Op); 15559 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 15560 15561 // Newton iterations: Est = Est + Est (1 - Arg * Est) 15562 for (int i = 0; i < Iterations; ++i) { 15563 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 15564 AddToWorklist(NewEst.getNode()); 15565 15566 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 15567 AddToWorklist(NewEst.getNode()); 15568 15569 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 15570 AddToWorklist(NewEst.getNode()); 15571 15572 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 15573 AddToWorklist(Est.getNode()); 15574 } 15575 } 15576 return Est; 15577 } 15578 15579 return SDValue(); 15580 } 15581 15582 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15583 /// For the reciprocal sqrt, we need to find the zero of the function: 15584 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15585 /// => 15586 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 15587 /// As a result, we precompute A/2 prior to the iteration loop. 15588 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 15589 unsigned Iterations, 15590 SDNodeFlags *Flags, bool Reciprocal) { 15591 EVT VT = Arg.getValueType(); 15592 SDLoc DL(Arg); 15593 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 15594 15595 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 15596 // this entire sequence requires only one FP constant. 15597 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 15598 AddToWorklist(HalfArg.getNode()); 15599 15600 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 15601 AddToWorklist(HalfArg.getNode()); 15602 15603 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 15604 for (unsigned i = 0; i < Iterations; ++i) { 15605 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 15606 AddToWorklist(NewEst.getNode()); 15607 15608 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 15609 AddToWorklist(NewEst.getNode()); 15610 15611 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 15612 AddToWorklist(NewEst.getNode()); 15613 15614 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 15615 AddToWorklist(Est.getNode()); 15616 } 15617 15618 // If non-reciprocal square root is requested, multiply the result by Arg. 15619 if (!Reciprocal) { 15620 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 15621 AddToWorklist(Est.getNode()); 15622 } 15623 15624 return Est; 15625 } 15626 15627 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15628 /// For the reciprocal sqrt, we need to find the zero of the function: 15629 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15630 /// => 15631 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 15632 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 15633 unsigned Iterations, 15634 SDNodeFlags *Flags, bool Reciprocal) { 15635 EVT VT = Arg.getValueType(); 15636 SDLoc DL(Arg); 15637 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 15638 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 15639 15640 // This routine must enter the loop below to work correctly 15641 // when (Reciprocal == false). 15642 assert(Iterations > 0); 15643 15644 // Newton iterations for reciprocal square root: 15645 // E = (E * -0.5) * ((A * E) * E + -3.0) 15646 for (unsigned i = 0; i < Iterations; ++i) { 15647 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 15648 AddToWorklist(AE.getNode()); 15649 15650 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 15651 AddToWorklist(AEE.getNode()); 15652 15653 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 15654 AddToWorklist(RHS.getNode()); 15655 15656 // When calculating a square root at the last iteration build: 15657 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 15658 // (notice a common subexpression) 15659 SDValue LHS; 15660 if (Reciprocal || (i + 1) < Iterations) { 15661 // RSQRT: LHS = (E * -0.5) 15662 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 15663 } else { 15664 // SQRT: LHS = (A * E) * -0.5 15665 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 15666 } 15667 AddToWorklist(LHS.getNode()); 15668 15669 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 15670 AddToWorklist(Est.getNode()); 15671 } 15672 15673 return Est; 15674 } 15675 15676 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 15677 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 15678 /// Op can be zero. 15679 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 15680 bool Reciprocal) { 15681 if (Level >= AfterLegalizeDAG) 15682 return SDValue(); 15683 15684 // TODO: Handle half and/or extended types? 15685 EVT VT = Op.getValueType(); 15686 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 15687 return SDValue(); 15688 15689 // If estimates are explicitly disabled for this function, we're done. 15690 MachineFunction &MF = DAG.getMachineFunction(); 15691 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 15692 if (Enabled == TLI.ReciprocalEstimate::Disabled) 15693 return SDValue(); 15694 15695 // Estimates may be explicitly enabled for this type with a custom number of 15696 // refinement steps. 15697 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 15698 15699 bool UseOneConstNR = false; 15700 if (SDValue Est = 15701 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 15702 Reciprocal)) { 15703 AddToWorklist(Est.getNode()); 15704 15705 if (Iterations) { 15706 Est = UseOneConstNR 15707 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 15708 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 15709 15710 if (!Reciprocal) { 15711 // Unfortunately, Est is now NaN if the input was exactly 0.0. 15712 // Select out this case and force the answer to 0.0. 15713 EVT VT = Op.getValueType(); 15714 SDLoc DL(Op); 15715 15716 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 15717 EVT CCVT = getSetCCResultType(VT); 15718 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 15719 AddToWorklist(ZeroCmp.getNode()); 15720 15721 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 15722 ZeroCmp, FPZero, Est); 15723 AddToWorklist(Est.getNode()); 15724 } 15725 } 15726 return Est; 15727 } 15728 15729 return SDValue(); 15730 } 15731 15732 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15733 return buildSqrtEstimateImpl(Op, Flags, true); 15734 } 15735 15736 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15737 return buildSqrtEstimateImpl(Op, Flags, false); 15738 } 15739 15740 /// Return true if base is a frame index, which is known not to alias with 15741 /// anything but itself. Provides base object and offset as results. 15742 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 15743 const GlobalValue *&GV, const void *&CV) { 15744 // Assume it is a primitive operation. 15745 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 15746 15747 // If it's an adding a simple constant then integrate the offset. 15748 if (Base.getOpcode() == ISD::ADD) { 15749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 15750 Base = Base.getOperand(0); 15751 Offset += C->getZExtValue(); 15752 } 15753 } 15754 15755 // Return the underlying GlobalValue, and update the Offset. Return false 15756 // for GlobalAddressSDNode since the same GlobalAddress may be represented 15757 // by multiple nodes with different offsets. 15758 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 15759 GV = G->getGlobal(); 15760 Offset += G->getOffset(); 15761 return false; 15762 } 15763 15764 // Return the underlying Constant value, and update the Offset. Return false 15765 // for ConstantSDNodes since the same constant pool entry may be represented 15766 // by multiple nodes with different offsets. 15767 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 15768 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 15769 : (const void *)C->getConstVal(); 15770 Offset += C->getOffset(); 15771 return false; 15772 } 15773 // If it's any of the following then it can't alias with anything but itself. 15774 return isa<FrameIndexSDNode>(Base); 15775 } 15776 15777 /// Return true if there is any possibility that the two addresses overlap. 15778 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 15779 // If they are the same then they must be aliases. 15780 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 15781 15782 // If they are both volatile then they cannot be reordered. 15783 if (Op0->isVolatile() && Op1->isVolatile()) return true; 15784 15785 // If one operation reads from invariant memory, and the other may store, they 15786 // cannot alias. These should really be checking the equivalent of mayWrite, 15787 // but it only matters for memory nodes other than load /store. 15788 if (Op0->isInvariant() && Op1->writeMem()) 15789 return false; 15790 15791 if (Op1->isInvariant() && Op0->writeMem()) 15792 return false; 15793 15794 // Gather base node and offset information. 15795 SDValue Base1, Base2; 15796 int64_t Offset1, Offset2; 15797 const GlobalValue *GV1, *GV2; 15798 const void *CV1, *CV2; 15799 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 15800 Base1, Offset1, GV1, CV1); 15801 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 15802 Base2, Offset2, GV2, CV2); 15803 15804 // If they have a same base address then check to see if they overlap. 15805 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 15806 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15807 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15808 15809 // It is possible for different frame indices to alias each other, mostly 15810 // when tail call optimization reuses return address slots for arguments. 15811 // To catch this case, look up the actual index of frame indices to compute 15812 // the real alias relationship. 15813 if (isFrameIndex1 && isFrameIndex2) { 15814 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 15815 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 15816 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 15817 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15818 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15819 } 15820 15821 // Otherwise, if we know what the bases are, and they aren't identical, then 15822 // we know they cannot alias. 15823 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 15824 return false; 15825 15826 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 15827 // compared to the size and offset of the access, we may be able to prove they 15828 // do not alias. This check is conservative for now to catch cases created by 15829 // splitting vector types. 15830 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 15831 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 15832 (Op0->getMemoryVT().getSizeInBits() >> 3 == 15833 Op1->getMemoryVT().getSizeInBits() >> 3) && 15834 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 15835 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 15836 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 15837 15838 // There is no overlap between these relatively aligned accesses of similar 15839 // size, return no alias. 15840 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 15841 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 15842 return false; 15843 } 15844 15845 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 15846 ? CombinerGlobalAA 15847 : DAG.getSubtarget().useAA(); 15848 #ifndef NDEBUG 15849 if (CombinerAAOnlyFunc.getNumOccurrences() && 15850 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 15851 UseAA = false; 15852 #endif 15853 if (UseAA && 15854 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 15855 // Use alias analysis information. 15856 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 15857 Op1->getSrcValueOffset()); 15858 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 15859 Op0->getSrcValueOffset() - MinOffset; 15860 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 15861 Op1->getSrcValueOffset() - MinOffset; 15862 AliasResult AAResult = 15863 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 15864 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 15865 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 15866 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 15867 if (AAResult == NoAlias) 15868 return false; 15869 } 15870 15871 // Otherwise we have to assume they alias. 15872 return true; 15873 } 15874 15875 /// Walk up chain skipping non-aliasing memory nodes, 15876 /// looking for aliasing nodes and adding them to the Aliases vector. 15877 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 15878 SmallVectorImpl<SDValue> &Aliases) { 15879 SmallVector<SDValue, 8> Chains; // List of chains to visit. 15880 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 15881 15882 // Get alias information for node. 15883 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 15884 15885 // Starting off. 15886 Chains.push_back(OriginalChain); 15887 unsigned Depth = 0; 15888 15889 // Look at each chain and determine if it is an alias. If so, add it to the 15890 // aliases list. If not, then continue up the chain looking for the next 15891 // candidate. 15892 while (!Chains.empty()) { 15893 SDValue Chain = Chains.pop_back_val(); 15894 15895 // For TokenFactor nodes, look at each operand and only continue up the 15896 // chain until we reach the depth limit. 15897 // 15898 // FIXME: The depth check could be made to return the last non-aliasing 15899 // chain we found before we hit a tokenfactor rather than the original 15900 // chain. 15901 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 15902 Aliases.clear(); 15903 Aliases.push_back(OriginalChain); 15904 return; 15905 } 15906 15907 // Don't bother if we've been before. 15908 if (!Visited.insert(Chain.getNode()).second) 15909 continue; 15910 15911 switch (Chain.getOpcode()) { 15912 case ISD::EntryToken: 15913 // Entry token is ideal chain operand, but handled in FindBetterChain. 15914 break; 15915 15916 case ISD::LOAD: 15917 case ISD::STORE: { 15918 // Get alias information for Chain. 15919 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 15920 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 15921 15922 // If chain is alias then stop here. 15923 if (!(IsLoad && IsOpLoad) && 15924 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 15925 Aliases.push_back(Chain); 15926 } else { 15927 // Look further up the chain. 15928 Chains.push_back(Chain.getOperand(0)); 15929 ++Depth; 15930 } 15931 break; 15932 } 15933 15934 case ISD::TokenFactor: 15935 // We have to check each of the operands of the token factor for "small" 15936 // token factors, so we queue them up. Adding the operands to the queue 15937 // (stack) in reverse order maintains the original order and increases the 15938 // likelihood that getNode will find a matching token factor (CSE.) 15939 if (Chain.getNumOperands() > 16) { 15940 Aliases.push_back(Chain); 15941 break; 15942 } 15943 for (unsigned n = Chain.getNumOperands(); n;) 15944 Chains.push_back(Chain.getOperand(--n)); 15945 ++Depth; 15946 break; 15947 15948 default: 15949 // For all other instructions we will just have to take what we can get. 15950 Aliases.push_back(Chain); 15951 break; 15952 } 15953 } 15954 } 15955 15956 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 15957 /// (aliasing node.) 15958 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 15959 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 15960 15961 // Accumulate all the aliases to this node. 15962 GatherAllAliases(N, OldChain, Aliases); 15963 15964 // If no operands then chain to entry token. 15965 if (Aliases.size() == 0) 15966 return DAG.getEntryNode(); 15967 15968 // If a single operand then chain to it. We don't need to revisit it. 15969 if (Aliases.size() == 1) 15970 return Aliases[0]; 15971 15972 // Construct a custom tailored token factor. 15973 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 15974 } 15975 15976 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 15977 // This holds the base pointer, index, and the offset in bytes from the base 15978 // pointer. 15979 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 15980 15981 // We must have a base and an offset. 15982 if (!BasePtr.Base.getNode()) 15983 return false; 15984 15985 // Do not handle stores to undef base pointers. 15986 if (BasePtr.Base.isUndef()) 15987 return false; 15988 15989 SmallVector<StoreSDNode *, 8> ChainedStores; 15990 ChainedStores.push_back(St); 15991 15992 // Walk up the chain and look for nodes with offsets from the same 15993 // base pointer. Stop when reaching an instruction with a different kind 15994 // or instruction which has a different base pointer. 15995 StoreSDNode *Index = St; 15996 while (Index) { 15997 // If the chain has more than one use, then we can't reorder the mem ops. 15998 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 15999 break; 16000 16001 if (Index->isVolatile() || Index->isIndexed()) 16002 break; 16003 16004 // Find the base pointer and offset for this memory node. 16005 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 16006 16007 // Check that the base pointer is the same as the original one. 16008 if (!Ptr.equalBaseIndex(BasePtr)) 16009 break; 16010 16011 // Find the next memory operand in the chain. If the next operand in the 16012 // chain is a store then move up and continue the scan with the next 16013 // memory operand. If the next operand is a load save it and use alias 16014 // information to check if it interferes with anything. 16015 SDNode *NextInChain = Index->getChain().getNode(); 16016 while (true) { 16017 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 16018 // We found a store node. Use it for the next iteration. 16019 if (STn->isVolatile() || STn->isIndexed()) { 16020 Index = nullptr; 16021 break; 16022 } 16023 ChainedStores.push_back(STn); 16024 Index = STn; 16025 break; 16026 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 16027 NextInChain = Ldn->getChain().getNode(); 16028 continue; 16029 } else { 16030 Index = nullptr; 16031 break; 16032 } 16033 } 16034 } 16035 16036 bool MadeChangeToSt = false; 16037 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 16038 16039 for (StoreSDNode *ChainedStore : ChainedStores) { 16040 SDValue Chain = ChainedStore->getChain(); 16041 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 16042 16043 if (Chain != BetterChain) { 16044 if (ChainedStore == St) 16045 MadeChangeToSt = true; 16046 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 16047 } 16048 } 16049 16050 // Do all replacements after finding the replacements to make to avoid making 16051 // the chains more complicated by introducing new TokenFactors. 16052 for (auto Replacement : BetterChains) 16053 replaceStoreChain(Replacement.first, Replacement.second); 16054 16055 return MadeChangeToSt; 16056 } 16057 16058 /// This is the entry point for the file. 16059 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 16060 CodeGenOpt::Level OptLevel) { 16061 /// This is the main entry point to this class. 16062 DAGCombiner(*this, AA, OptLevel).Run(Level); 16063 } 16064