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 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 57 cl::desc("Enable DAG combiner's use of IR alias analysis")); 58 59 static cl::opt<bool> 60 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 61 cl::desc("Enable DAG combiner's use of TBAA")); 62 63 #ifndef NDEBUG 64 static cl::opt<std::string> 65 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 66 cl::desc("Only use DAG-combiner alias analysis in this" 67 " function")); 68 #endif 69 70 /// Hidden option to stress test load slicing, i.e., when this option 71 /// is enabled, load slicing bypasses most of its profitability guards. 72 static cl::opt<bool> 73 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 74 cl::desc("Bypass the profitability model of load " 75 "slicing"), 76 cl::init(false)); 77 78 static cl::opt<bool> 79 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 80 cl::desc("DAG combiner may split indexing from loads")); 81 82 //------------------------------ DAGCombiner ---------------------------------// 83 84 class DAGCombiner { 85 SelectionDAG &DAG; 86 const TargetLowering &TLI; 87 CombineLevel Level; 88 CodeGenOpt::Level OptLevel; 89 bool LegalOperations; 90 bool LegalTypes; 91 bool ForCodeSize; 92 93 /// \brief Worklist of all of the nodes that need to be simplified. 94 /// 95 /// This must behave as a stack -- new nodes to process are pushed onto the 96 /// back and when processing we pop off of the back. 97 /// 98 /// The worklist will not contain duplicates but may contain null entries 99 /// due to nodes being deleted from the underlying DAG. 100 SmallVector<SDNode *, 64> Worklist; 101 102 /// \brief Mapping from an SDNode to its position on the worklist. 103 /// 104 /// This is used to find and remove nodes from the worklist (by nulling 105 /// them) when they are deleted from the underlying DAG. It relies on 106 /// stable indices of nodes within the worklist. 107 DenseMap<SDNode *, unsigned> WorklistMap; 108 109 /// \brief Set of nodes which have been combined (at least once). 110 /// 111 /// This is used to allow us to reliably add any operands of a DAG node 112 /// which have not yet been combined to the worklist. 113 SmallPtrSet<SDNode *, 32> CombinedNodes; 114 115 // AA - Used for DAG load/store alias analysis. 116 AliasAnalysis &AA; 117 118 /// When an instruction is simplified, add all users of the instruction to 119 /// the work lists because they might get more simplified now. 120 void AddUsersToWorklist(SDNode *N) { 121 for (SDNode *Node : N->uses()) 122 AddToWorklist(Node); 123 } 124 125 /// Call the node-specific routine that folds each particular type of node. 126 SDValue visit(SDNode *N); 127 128 public: 129 /// Add to the worklist making sure its instance is at the back (next to be 130 /// processed.) 131 void AddToWorklist(SDNode *N) { 132 assert(N->getOpcode() != ISD::DELETED_NODE && 133 "Deleted Node added to Worklist"); 134 135 // Skip handle nodes as they can't usefully be combined and confuse the 136 // zero-use deletion strategy. 137 if (N->getOpcode() == ISD::HANDLENODE) 138 return; 139 140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 141 Worklist.push_back(N); 142 } 143 144 /// Remove all instances of N from the worklist. 145 void removeFromWorklist(SDNode *N) { 146 CombinedNodes.erase(N); 147 148 auto It = WorklistMap.find(N); 149 if (It == WorklistMap.end()) 150 return; // Not in the worklist. 151 152 // Null out the entry rather than erasing it to avoid a linear operation. 153 Worklist[It->second] = nullptr; 154 WorklistMap.erase(It); 155 } 156 157 void deleteAndRecombine(SDNode *N); 158 bool recursivelyDeleteUnusedNodes(SDNode *N); 159 160 /// Replaces all uses of the results of one DAG node with new values. 161 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 162 bool AddTo = true); 163 164 /// Replaces all uses of the results of one DAG node with new values. 165 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 166 return CombineTo(N, &Res, 1, AddTo); 167 } 168 169 /// Replaces all uses of the results of one DAG node with new values. 170 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 171 bool AddTo = true) { 172 SDValue To[] = { Res0, Res1 }; 173 return CombineTo(N, To, 2, AddTo); 174 } 175 176 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 177 178 private: 179 180 /// Check the specified integer node value to see if it can be simplified or 181 /// if things it uses can be simplified by bit propagation. 182 /// If so, return true. 183 bool SimplifyDemandedBits(SDValue Op) { 184 unsigned BitWidth = Op.getScalarValueSizeInBits(); 185 APInt Demanded = APInt::getAllOnesValue(BitWidth); 186 return SimplifyDemandedBits(Op, Demanded); 187 } 188 189 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 190 191 bool CombineToPreIndexedLoadStore(SDNode *N); 192 bool CombineToPostIndexedLoadStore(SDNode *N); 193 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 194 bool SliceUpLoad(SDNode *N); 195 196 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 197 /// load. 198 /// 199 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 200 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 201 /// \param EltNo index of the vector element to load. 202 /// \param OriginalLoad load that EVE came from to be replaced. 203 /// \returns EVE on success SDValue() on failure. 204 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 205 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 206 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 207 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 208 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 210 SDValue PromoteIntBinOp(SDValue Op); 211 SDValue PromoteIntShiftOp(SDValue Op); 212 SDValue PromoteExtend(SDValue Op); 213 bool PromoteLoad(SDValue Op); 214 215 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 216 SDValue ExtLoad, const SDLoc &DL, 217 ISD::NodeType ExtType); 218 219 /// Call the node-specific routine that knows how to fold each 220 /// particular type of node. If that doesn't do anything, try the 221 /// target-specific DAG combines. 222 SDValue combine(SDNode *N); 223 224 // Visitation implementation - Implement dag node combining for different 225 // node types. The semantics are as follows: 226 // Return Value: 227 // SDValue.getNode() == 0 - No change was made 228 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 229 // otherwise - N should be replaced by the returned Operand. 230 // 231 SDValue visitTokenFactor(SDNode *N); 232 SDValue visitMERGE_VALUES(SDNode *N); 233 SDValue visitADD(SDNode *N); 234 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 235 SDValue visitSUB(SDNode *N); 236 SDValue visitADDC(SDNode *N); 237 SDValue visitSUBC(SDNode *N); 238 SDValue visitADDE(SDNode *N); 239 SDValue visitSUBE(SDNode *N); 240 SDValue visitMUL(SDNode *N); 241 SDValue useDivRem(SDNode *N); 242 SDValue visitSDIV(SDNode *N); 243 SDValue visitUDIV(SDNode *N); 244 SDValue visitREM(SDNode *N); 245 SDValue visitMULHU(SDNode *N); 246 SDValue visitMULHS(SDNode *N); 247 SDValue visitSMUL_LOHI(SDNode *N); 248 SDValue visitUMUL_LOHI(SDNode *N); 249 SDValue visitSMULO(SDNode *N); 250 SDValue visitUMULO(SDNode *N); 251 SDValue visitIMINMAX(SDNode *N); 252 SDValue visitAND(SDNode *N); 253 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 254 SDValue visitOR(SDNode *N); 255 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 256 SDValue visitXOR(SDNode *N); 257 SDValue SimplifyVBinOp(SDNode *N); 258 SDValue visitSHL(SDNode *N); 259 SDValue visitSRA(SDNode *N); 260 SDValue visitSRL(SDNode *N); 261 SDValue visitRotate(SDNode *N); 262 SDValue visitBSWAP(SDNode *N); 263 SDValue visitBITREVERSE(SDNode *N); 264 SDValue visitCTLZ(SDNode *N); 265 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 266 SDValue visitCTTZ(SDNode *N); 267 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 268 SDValue visitCTPOP(SDNode *N); 269 SDValue visitSELECT(SDNode *N); 270 SDValue visitVSELECT(SDNode *N); 271 SDValue visitSELECT_CC(SDNode *N); 272 SDValue visitSETCC(SDNode *N); 273 SDValue visitSETCCE(SDNode *N); 274 SDValue visitSIGN_EXTEND(SDNode *N); 275 SDValue visitZERO_EXTEND(SDNode *N); 276 SDValue visitANY_EXTEND(SDNode *N); 277 SDValue visitAssertZext(SDNode *N); 278 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 279 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 280 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 281 SDValue visitTRUNCATE(SDNode *N); 282 SDValue visitBITCAST(SDNode *N); 283 SDValue visitBUILD_PAIR(SDNode *N); 284 SDValue visitFADD(SDNode *N); 285 SDValue visitFSUB(SDNode *N); 286 SDValue visitFMUL(SDNode *N); 287 SDValue visitFMA(SDNode *N); 288 SDValue visitFDIV(SDNode *N); 289 SDValue visitFREM(SDNode *N); 290 SDValue visitFSQRT(SDNode *N); 291 SDValue visitFCOPYSIGN(SDNode *N); 292 SDValue visitSINT_TO_FP(SDNode *N); 293 SDValue visitUINT_TO_FP(SDNode *N); 294 SDValue visitFP_TO_SINT(SDNode *N); 295 SDValue visitFP_TO_UINT(SDNode *N); 296 SDValue visitFP_ROUND(SDNode *N); 297 SDValue visitFP_ROUND_INREG(SDNode *N); 298 SDValue visitFP_EXTEND(SDNode *N); 299 SDValue visitFNEG(SDNode *N); 300 SDValue visitFABS(SDNode *N); 301 SDValue visitFCEIL(SDNode *N); 302 SDValue visitFTRUNC(SDNode *N); 303 SDValue visitFFLOOR(SDNode *N); 304 SDValue visitFMINNUM(SDNode *N); 305 SDValue visitFMAXNUM(SDNode *N); 306 SDValue visitBRCOND(SDNode *N); 307 SDValue visitBR_CC(SDNode *N); 308 SDValue visitLOAD(SDNode *N); 309 310 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 311 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 312 313 SDValue visitSTORE(SDNode *N); 314 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 315 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 316 SDValue visitBUILD_VECTOR(SDNode *N); 317 SDValue visitCONCAT_VECTORS(SDNode *N); 318 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 319 SDValue visitVECTOR_SHUFFLE(SDNode *N); 320 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 321 SDValue visitINSERT_SUBVECTOR(SDNode *N); 322 SDValue visitMLOAD(SDNode *N); 323 SDValue visitMSTORE(SDNode *N); 324 SDValue visitMGATHER(SDNode *N); 325 SDValue visitMSCATTER(SDNode *N); 326 SDValue visitFP_TO_FP16(SDNode *N); 327 SDValue visitFP16_TO_FP(SDNode *N); 328 329 SDValue visitFADDForFMACombine(SDNode *N); 330 SDValue visitFSUBForFMACombine(SDNode *N); 331 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 332 333 SDValue XformToShuffleWithZero(SDNode *N); 334 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 335 SDValue RHS); 336 337 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 338 339 SDValue foldSelectOfConstants(SDNode *N); 340 SDValue foldBinOpIntoSelect(SDNode *BO); 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) 423 : MemNode(N), OffsetFromBase(Offset) {} 424 // Ptr to the mem node. 425 LSBaseSDNode *MemNode; 426 // Offset from the base ptr. 427 int64_t OffsetFromBase; 428 }; 429 430 /// This is a helper function for visitMUL to check the profitability 431 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 432 /// MulNode is the original multiply, AddNode is (add x, c1), 433 /// and ConstNode is c2. 434 bool isMulAddWithConstProfitable(SDNode *MulNode, 435 SDValue &AddNode, 436 SDValue &ConstNode); 437 438 439 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 440 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 441 /// the type of the loaded value to be extended. LoadedVT returns the type 442 /// of the original loaded value. NarrowLoad returns whether the load would 443 /// need to be narrowed in order to match. 444 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 445 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 446 bool &NarrowLoad); 447 448 /// This is a helper function for MergeConsecutiveStores. When the source 449 /// elements of the consecutive stores are all constants or all extracted 450 /// vector elements, try to merge them into one larger store. 451 /// \return True if a merged store was created. 452 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 453 EVT MemVT, unsigned NumStores, 454 bool IsConstantSrc, bool UseVector); 455 456 /// This is a helper function for MergeConsecutiveStores. 457 /// Stores that may be merged are placed in StoreNodes. 458 void getStoreMergeCandidates(StoreSDNode *St, 459 SmallVectorImpl<MemOpLink> &StoreNodes); 460 461 /// Helper function for MergeConsecutiveStores. Checks if 462 /// Candidate stores have indirect dependency through their 463 /// operands. \return True if safe to merge 464 bool checkMergeStoreCandidatesForDependencies( 465 SmallVectorImpl<MemOpLink> &StoreNodes); 466 467 /// Merge consecutive store operations into a wide store. 468 /// This optimization uses wide integers or vectors when possible. 469 /// \return number of stores that were merged into a merged store (the 470 /// affected nodes are stored as a prefix in \p StoreNodes). 471 bool MergeConsecutiveStores(StoreSDNode *N); 472 473 /// \brief Try to transform a truncation where C is a constant: 474 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 475 /// 476 /// \p N needs to be a truncation and its first operand an AND. Other 477 /// requirements are checked by the function (e.g. that trunc is 478 /// single-use) and if missed an empty SDValue is returned. 479 SDValue distributeTruncateThroughAnd(SDNode *N); 480 481 public: 482 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 483 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 484 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 485 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 486 } 487 488 /// Runs the dag combiner on all nodes in the work list 489 void Run(CombineLevel AtLevel); 490 491 SelectionDAG &getDAG() const { return DAG; } 492 493 /// Returns a type large enough to hold any valid shift amount - before type 494 /// legalization these can be huge. 495 EVT getShiftAmountTy(EVT LHSTy) { 496 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 497 if (LHSTy.isVector()) 498 return LHSTy; 499 auto &DL = DAG.getDataLayout(); 500 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 501 : TLI.getPointerTy(DL); 502 } 503 504 /// This method returns true if we are running before type legalization or 505 /// if the specified VT is legal. 506 bool isTypeLegal(const EVT &VT) { 507 if (!LegalTypes) return true; 508 return TLI.isTypeLegal(VT); 509 } 510 511 /// Convenience wrapper around TargetLowering::getSetCCResultType 512 EVT getSetCCResultType(EVT VT) const { 513 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 514 } 515 }; 516 } 517 518 519 namespace { 520 /// This class is a DAGUpdateListener that removes any deleted 521 /// nodes from the worklist. 522 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 523 DAGCombiner &DC; 524 public: 525 explicit WorklistRemover(DAGCombiner &dc) 526 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 527 528 void NodeDeleted(SDNode *N, SDNode *E) override { 529 DC.removeFromWorklist(N); 530 } 531 }; 532 } 533 534 //===----------------------------------------------------------------------===// 535 // TargetLowering::DAGCombinerInfo implementation 536 //===----------------------------------------------------------------------===// 537 538 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 539 ((DAGCombiner*)DC)->AddToWorklist(N); 540 } 541 542 SDValue TargetLowering::DAGCombinerInfo:: 543 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 544 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 545 } 546 547 SDValue TargetLowering::DAGCombinerInfo:: 548 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 549 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 550 } 551 552 553 SDValue TargetLowering::DAGCombinerInfo:: 554 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 555 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 556 } 557 558 void TargetLowering::DAGCombinerInfo:: 559 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 560 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 561 } 562 563 //===----------------------------------------------------------------------===// 564 // Helper Functions 565 //===----------------------------------------------------------------------===// 566 567 void DAGCombiner::deleteAndRecombine(SDNode *N) { 568 removeFromWorklist(N); 569 570 // If the operands of this node are only used by the node, they will now be 571 // dead. Make sure to re-visit them and recursively delete dead nodes. 572 for (const SDValue &Op : N->ops()) 573 // For an operand generating multiple values, one of the values may 574 // become dead allowing further simplification (e.g. split index 575 // arithmetic from an indexed load). 576 if (Op->hasOneUse() || Op->getNumValues() > 1) 577 AddToWorklist(Op.getNode()); 578 579 DAG.DeleteNode(N); 580 } 581 582 /// Return 1 if we can compute the negated form of the specified expression for 583 /// the same cost as the expression itself, or 2 if we can compute the negated 584 /// form more cheaply than the expression itself. 585 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 586 const TargetLowering &TLI, 587 const TargetOptions *Options, 588 unsigned Depth = 0) { 589 // fneg is removable even if it has multiple uses. 590 if (Op.getOpcode() == ISD::FNEG) return 2; 591 592 // Don't allow anything with multiple uses. 593 if (!Op.hasOneUse()) return 0; 594 595 // Don't recurse exponentially. 596 if (Depth > 6) return 0; 597 598 switch (Op.getOpcode()) { 599 default: return false; 600 case ISD::ConstantFP: { 601 if (!LegalOperations) 602 return 1; 603 604 // Don't invert constant FP values after legalization unless the target says 605 // the negated constant is legal. 606 EVT VT = Op.getValueType(); 607 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 608 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 609 } 610 case ISD::FADD: 611 // FIXME: determine better conditions for this xform. 612 if (!Options->UnsafeFPMath) return 0; 613 614 // After operation legalization, it might not be legal to create new FSUBs. 615 if (LegalOperations && 616 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 617 return 0; 618 619 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 620 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 621 Options, Depth + 1)) 622 return V; 623 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 624 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 625 Depth + 1); 626 case ISD::FSUB: 627 // We can't turn -(A-B) into B-A when we honor signed zeros. 628 if (!Options->NoSignedZerosFPMath && 629 !Op.getNode()->getFlags()->hasNoSignedZeros()) 630 return 0; 631 632 // fold (fneg (fsub A, B)) -> (fsub B, A) 633 return 1; 634 635 case ISD::FMUL: 636 case ISD::FDIV: 637 if (Options->HonorSignDependentRoundingFPMath()) return 0; 638 639 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 640 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 641 Options, Depth + 1)) 642 return V; 643 644 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 645 Depth + 1); 646 647 case ISD::FP_EXTEND: 648 case ISD::FP_ROUND: 649 case ISD::FSIN: 650 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 651 Depth + 1); 652 } 653 } 654 655 /// If isNegatibleForFree returns true, return the newly negated expression. 656 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 657 bool LegalOperations, unsigned Depth = 0) { 658 const TargetOptions &Options = DAG.getTarget().Options; 659 // fneg is removable even if it has multiple uses. 660 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 661 662 // Don't allow anything with multiple uses. 663 assert(Op.hasOneUse() && "Unknown reuse!"); 664 665 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 666 667 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 668 669 switch (Op.getOpcode()) { 670 default: llvm_unreachable("Unknown code"); 671 case ISD::ConstantFP: { 672 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 673 V.changeSign(); 674 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 675 } 676 case ISD::FADD: 677 // FIXME: determine better conditions for this xform. 678 assert(Options.UnsafeFPMath); 679 680 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 681 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 682 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 683 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 684 GetNegatedExpression(Op.getOperand(0), DAG, 685 LegalOperations, Depth+1), 686 Op.getOperand(1), Flags); 687 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 688 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 689 GetNegatedExpression(Op.getOperand(1), DAG, 690 LegalOperations, Depth+1), 691 Op.getOperand(0), Flags); 692 case ISD::FSUB: 693 // fold (fneg (fsub 0, B)) -> B 694 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 695 if (N0CFP->isZero()) 696 return Op.getOperand(1); 697 698 // fold (fneg (fsub A, B)) -> (fsub B, A) 699 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 700 Op.getOperand(1), Op.getOperand(0), Flags); 701 702 case ISD::FMUL: 703 case ISD::FDIV: 704 assert(!Options.HonorSignDependentRoundingFPMath()); 705 706 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 707 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 708 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 709 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 710 GetNegatedExpression(Op.getOperand(0), DAG, 711 LegalOperations, Depth+1), 712 Op.getOperand(1), Flags); 713 714 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 715 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 716 Op.getOperand(0), 717 GetNegatedExpression(Op.getOperand(1), DAG, 718 LegalOperations, Depth+1), Flags); 719 720 case ISD::FP_EXTEND: 721 case ISD::FSIN: 722 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 723 GetNegatedExpression(Op.getOperand(0), DAG, 724 LegalOperations, Depth+1)); 725 case ISD::FP_ROUND: 726 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 727 GetNegatedExpression(Op.getOperand(0), DAG, 728 LegalOperations, Depth+1), 729 Op.getOperand(1)); 730 } 731 } 732 733 // APInts must be the same size for most operations, this helper 734 // function zero extends the shorter of the pair so that they match. 735 // We provide an Offset so that we can create bitwidths that won't overflow. 736 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 737 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 738 LHS = LHS.zextOrSelf(Bits); 739 RHS = RHS.zextOrSelf(Bits); 740 } 741 742 // Return true if this node is a setcc, or is a select_cc 743 // that selects between the target values used for true and false, making it 744 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 745 // the appropriate nodes based on the type of node we are checking. This 746 // simplifies life a bit for the callers. 747 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 748 SDValue &CC) const { 749 if (N.getOpcode() == ISD::SETCC) { 750 LHS = N.getOperand(0); 751 RHS = N.getOperand(1); 752 CC = N.getOperand(2); 753 return true; 754 } 755 756 if (N.getOpcode() != ISD::SELECT_CC || 757 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 758 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 759 return false; 760 761 if (TLI.getBooleanContents(N.getValueType()) == 762 TargetLowering::UndefinedBooleanContent) 763 return false; 764 765 LHS = N.getOperand(0); 766 RHS = N.getOperand(1); 767 CC = N.getOperand(4); 768 return true; 769 } 770 771 /// Return true if this is a SetCC-equivalent operation with only one use. 772 /// If this is true, it allows the users to invert the operation for free when 773 /// it is profitable to do so. 774 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 775 SDValue N0, N1, N2; 776 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 777 return true; 778 return false; 779 } 780 781 // \brief Returns the SDNode if it is a constant float BuildVector 782 // or constant float. 783 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 784 if (isa<ConstantFPSDNode>(N)) 785 return N.getNode(); 786 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 787 return N.getNode(); 788 return nullptr; 789 } 790 791 // Determines if it is a constant integer or a build vector of constant 792 // integers (and undefs). 793 // Do not permit build vector implicit truncation. 794 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 795 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 796 return !(Const->isOpaque() && NoOpaques); 797 if (N.getOpcode() != ISD::BUILD_VECTOR) 798 return false; 799 unsigned BitWidth = N.getScalarValueSizeInBits(); 800 for (const SDValue &Op : N->op_values()) { 801 if (Op.isUndef()) 802 continue; 803 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 804 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 805 (Const->isOpaque() && NoOpaques)) 806 return false; 807 } 808 return true; 809 } 810 811 // Determines if it is a constant null integer or a splatted vector of a 812 // constant null integer (with no undefs). 813 // Build vector implicit truncation is not an issue for null values. 814 static bool isNullConstantOrNullSplatConstant(SDValue N) { 815 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 816 return Splat->isNullValue(); 817 return false; 818 } 819 820 // Determines if it is a constant integer of one or a splatted vector of a 821 // constant integer of one (with no undefs). 822 // Do not permit build vector implicit truncation. 823 static bool isOneConstantOrOneSplatConstant(SDValue N) { 824 unsigned BitWidth = N.getScalarValueSizeInBits(); 825 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 826 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 827 return false; 828 } 829 830 // Determines if it is a constant integer of all ones or a splatted vector of a 831 // constant integer of all ones (with no undefs). 832 // Do not permit build vector implicit truncation. 833 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 834 unsigned BitWidth = N.getScalarValueSizeInBits(); 835 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 836 return Splat->isAllOnesValue() && 837 Splat->getAPIntValue().getBitWidth() == BitWidth; 838 return false; 839 } 840 841 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 842 // undef's. 843 static bool isAnyConstantBuildVector(const SDNode *N) { 844 return ISD::isBuildVectorOfConstantSDNodes(N) || 845 ISD::isBuildVectorOfConstantFPSDNodes(N); 846 } 847 848 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 849 SDValue N1) { 850 EVT VT = N0.getValueType(); 851 if (N0.getOpcode() == Opc) { 852 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 853 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 854 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 855 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 856 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 857 return SDValue(); 858 } 859 if (N0.hasOneUse()) { 860 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 861 // use 862 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 863 if (!OpNode.getNode()) 864 return SDValue(); 865 AddToWorklist(OpNode.getNode()); 866 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 867 } 868 } 869 } 870 871 if (N1.getOpcode() == Opc) { 872 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 873 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 874 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 875 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 876 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 877 return SDValue(); 878 } 879 if (N1.hasOneUse()) { 880 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 881 // use 882 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 883 if (!OpNode.getNode()) 884 return SDValue(); 885 AddToWorklist(OpNode.getNode()); 886 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 887 } 888 } 889 } 890 891 return SDValue(); 892 } 893 894 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 895 bool AddTo) { 896 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 897 ++NodesCombined; 898 DEBUG(dbgs() << "\nReplacing.1 "; 899 N->dump(&DAG); 900 dbgs() << "\nWith: "; 901 To[0].getNode()->dump(&DAG); 902 dbgs() << " and " << NumTo-1 << " other values\n"); 903 for (unsigned i = 0, e = NumTo; i != e; ++i) 904 assert((!To[i].getNode() || 905 N->getValueType(i) == To[i].getValueType()) && 906 "Cannot combine value to value of different type!"); 907 908 WorklistRemover DeadNodes(*this); 909 DAG.ReplaceAllUsesWith(N, To); 910 if (AddTo) { 911 // Push the new nodes and any users onto the worklist 912 for (unsigned i = 0, e = NumTo; i != e; ++i) { 913 if (To[i].getNode()) { 914 AddToWorklist(To[i].getNode()); 915 AddUsersToWorklist(To[i].getNode()); 916 } 917 } 918 } 919 920 // Finally, if the node is now dead, remove it from the graph. The node 921 // may not be dead if the replacement process recursively simplified to 922 // something else needing this node. 923 if (N->use_empty()) 924 deleteAndRecombine(N); 925 return SDValue(N, 0); 926 } 927 928 void DAGCombiner:: 929 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 930 // Replace all uses. If any nodes become isomorphic to other nodes and 931 // are deleted, make sure to remove them from our worklist. 932 WorklistRemover DeadNodes(*this); 933 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 934 935 // Push the new node and any (possibly new) users onto the worklist. 936 AddToWorklist(TLO.New.getNode()); 937 AddUsersToWorklist(TLO.New.getNode()); 938 939 // Finally, if the node is now dead, remove it from the graph. The node 940 // may not be dead if the replacement process recursively simplified to 941 // something else needing this node. 942 if (TLO.Old.getNode()->use_empty()) 943 deleteAndRecombine(TLO.Old.getNode()); 944 } 945 946 /// Check the specified integer node value to see if it can be simplified or if 947 /// things it uses can be simplified by bit propagation. If so, return true. 948 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 949 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 950 APInt KnownZero, KnownOne; 951 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 952 return false; 953 954 // Revisit the node. 955 AddToWorklist(Op.getNode()); 956 957 // Replace the old value with the new one. 958 ++NodesCombined; 959 DEBUG(dbgs() << "\nReplacing.2 "; 960 TLO.Old.getNode()->dump(&DAG); 961 dbgs() << "\nWith: "; 962 TLO.New.getNode()->dump(&DAG); 963 dbgs() << '\n'); 964 965 CommitTargetLoweringOpt(TLO); 966 return true; 967 } 968 969 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 970 SDLoc DL(Load); 971 EVT VT = Load->getValueType(0); 972 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 973 974 DEBUG(dbgs() << "\nReplacing.9 "; 975 Load->dump(&DAG); 976 dbgs() << "\nWith: "; 977 Trunc.getNode()->dump(&DAG); 978 dbgs() << '\n'); 979 WorklistRemover DeadNodes(*this); 980 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 981 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 982 deleteAndRecombine(Load); 983 AddToWorklist(Trunc.getNode()); 984 } 985 986 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 987 Replace = false; 988 SDLoc DL(Op); 989 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 990 LoadSDNode *LD = cast<LoadSDNode>(Op); 991 EVT MemVT = LD->getMemoryVT(); 992 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 993 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 994 : ISD::EXTLOAD) 995 : LD->getExtensionType(); 996 Replace = true; 997 return DAG.getExtLoad(ExtType, DL, PVT, 998 LD->getChain(), LD->getBasePtr(), 999 MemVT, LD->getMemOperand()); 1000 } 1001 1002 unsigned Opc = Op.getOpcode(); 1003 switch (Opc) { 1004 default: break; 1005 case ISD::AssertSext: 1006 return DAG.getNode(ISD::AssertSext, DL, PVT, 1007 SExtPromoteOperand(Op.getOperand(0), PVT), 1008 Op.getOperand(1)); 1009 case ISD::AssertZext: 1010 return DAG.getNode(ISD::AssertZext, DL, PVT, 1011 ZExtPromoteOperand(Op.getOperand(0), PVT), 1012 Op.getOperand(1)); 1013 case ISD::Constant: { 1014 unsigned ExtOpc = 1015 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1016 return DAG.getNode(ExtOpc, DL, PVT, Op); 1017 } 1018 } 1019 1020 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1021 return SDValue(); 1022 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1023 } 1024 1025 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1026 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1027 return SDValue(); 1028 EVT OldVT = Op.getValueType(); 1029 SDLoc DL(Op); 1030 bool Replace = false; 1031 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1032 if (!NewOp.getNode()) 1033 return SDValue(); 1034 AddToWorklist(NewOp.getNode()); 1035 1036 if (Replace) 1037 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1038 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1039 DAG.getValueType(OldVT)); 1040 } 1041 1042 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1043 EVT OldVT = Op.getValueType(); 1044 SDLoc DL(Op); 1045 bool Replace = false; 1046 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1047 if (!NewOp.getNode()) 1048 return SDValue(); 1049 AddToWorklist(NewOp.getNode()); 1050 1051 if (Replace) 1052 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1053 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1054 } 1055 1056 /// Promote the specified integer binary operation if the target indicates it is 1057 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1058 /// i32 since i16 instructions are longer. 1059 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1060 if (!LegalOperations) 1061 return SDValue(); 1062 1063 EVT VT = Op.getValueType(); 1064 if (VT.isVector() || !VT.isInteger()) 1065 return SDValue(); 1066 1067 // If operation type is 'undesirable', e.g. i16 on x86, consider 1068 // promoting it. 1069 unsigned Opc = Op.getOpcode(); 1070 if (TLI.isTypeDesirableForOp(Opc, VT)) 1071 return SDValue(); 1072 1073 EVT PVT = VT; 1074 // Consult target whether it is a good idea to promote this operation and 1075 // what's the right type to promote it to. 1076 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1077 assert(PVT != VT && "Don't know what type to promote to!"); 1078 1079 bool Replace0 = false; 1080 SDValue N0 = Op.getOperand(0); 1081 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1082 if (!NN0.getNode()) 1083 return SDValue(); 1084 1085 bool Replace1 = false; 1086 SDValue N1 = Op.getOperand(1); 1087 SDValue NN1; 1088 if (N0 == N1) 1089 NN1 = NN0; 1090 else { 1091 NN1 = PromoteOperand(N1, PVT, Replace1); 1092 if (!NN1.getNode()) 1093 return SDValue(); 1094 } 1095 1096 AddToWorklist(NN0.getNode()); 1097 if (NN1.getNode()) 1098 AddToWorklist(NN1.getNode()); 1099 1100 if (Replace0) 1101 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1102 if (Replace1) 1103 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1104 1105 DEBUG(dbgs() << "\nPromoting "; 1106 Op.getNode()->dump(&DAG)); 1107 SDLoc DL(Op); 1108 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1109 DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1110 } 1111 return SDValue(); 1112 } 1113 1114 /// Promote the specified integer shift operation if the target indicates it is 1115 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1116 /// i32 since i16 instructions are longer. 1117 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1118 if (!LegalOperations) 1119 return SDValue(); 1120 1121 EVT VT = Op.getValueType(); 1122 if (VT.isVector() || !VT.isInteger()) 1123 return SDValue(); 1124 1125 // If operation type is 'undesirable', e.g. i16 on x86, consider 1126 // promoting it. 1127 unsigned Opc = Op.getOpcode(); 1128 if (TLI.isTypeDesirableForOp(Opc, VT)) 1129 return SDValue(); 1130 1131 EVT PVT = VT; 1132 // Consult target whether it is a good idea to promote this operation and 1133 // what's the right type to promote it to. 1134 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1135 assert(PVT != VT && "Don't know what type to promote to!"); 1136 1137 bool Replace = false; 1138 SDValue N0 = Op.getOperand(0); 1139 if (Opc == ISD::SRA) 1140 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1141 else if (Opc == ISD::SRL) 1142 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1143 else 1144 N0 = PromoteOperand(N0, PVT, Replace); 1145 if (!N0.getNode()) 1146 return SDValue(); 1147 1148 AddToWorklist(N0.getNode()); 1149 if (Replace) 1150 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1151 1152 DEBUG(dbgs() << "\nPromoting "; 1153 Op.getNode()->dump(&DAG)); 1154 SDLoc DL(Op); 1155 return DAG.getNode(ISD::TRUNCATE, DL, VT, 1156 DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1))); 1157 } 1158 return SDValue(); 1159 } 1160 1161 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1162 if (!LegalOperations) 1163 return SDValue(); 1164 1165 EVT VT = Op.getValueType(); 1166 if (VT.isVector() || !VT.isInteger()) 1167 return SDValue(); 1168 1169 // If operation type is 'undesirable', e.g. i16 on x86, consider 1170 // promoting it. 1171 unsigned Opc = Op.getOpcode(); 1172 if (TLI.isTypeDesirableForOp(Opc, VT)) 1173 return SDValue(); 1174 1175 EVT PVT = VT; 1176 // Consult target whether it is a good idea to promote this operation and 1177 // what's the right type to promote it to. 1178 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1179 assert(PVT != VT && "Don't know what type to promote to!"); 1180 // fold (aext (aext x)) -> (aext x) 1181 // fold (aext (zext x)) -> (zext x) 1182 // fold (aext (sext x)) -> (sext x) 1183 DEBUG(dbgs() << "\nPromoting "; 1184 Op.getNode()->dump(&DAG)); 1185 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1186 } 1187 return SDValue(); 1188 } 1189 1190 bool DAGCombiner::PromoteLoad(SDValue Op) { 1191 if (!LegalOperations) 1192 return false; 1193 1194 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1195 return false; 1196 1197 EVT VT = Op.getValueType(); 1198 if (VT.isVector() || !VT.isInteger()) 1199 return false; 1200 1201 // If operation type is 'undesirable', e.g. i16 on x86, consider 1202 // promoting it. 1203 unsigned Opc = Op.getOpcode(); 1204 if (TLI.isTypeDesirableForOp(Opc, VT)) 1205 return false; 1206 1207 EVT PVT = VT; 1208 // Consult target whether it is a good idea to promote this operation and 1209 // what's the right type to promote it to. 1210 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1211 assert(PVT != VT && "Don't know what type to promote to!"); 1212 1213 SDLoc DL(Op); 1214 SDNode *N = Op.getNode(); 1215 LoadSDNode *LD = cast<LoadSDNode>(N); 1216 EVT MemVT = LD->getMemoryVT(); 1217 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1218 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1219 : ISD::EXTLOAD) 1220 : LD->getExtensionType(); 1221 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1222 LD->getChain(), LD->getBasePtr(), 1223 MemVT, LD->getMemOperand()); 1224 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1225 1226 DEBUG(dbgs() << "\nPromoting "; 1227 N->dump(&DAG); 1228 dbgs() << "\nTo: "; 1229 Result.getNode()->dump(&DAG); 1230 dbgs() << '\n'); 1231 WorklistRemover DeadNodes(*this); 1232 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1233 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1234 deleteAndRecombine(N); 1235 AddToWorklist(Result.getNode()); 1236 return true; 1237 } 1238 return false; 1239 } 1240 1241 /// \brief Recursively delete a node which has no uses and any operands for 1242 /// which it is the only use. 1243 /// 1244 /// Note that this both deletes the nodes and removes them from the worklist. 1245 /// It also adds any nodes who have had a user deleted to the worklist as they 1246 /// may now have only one use and subject to other combines. 1247 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1248 if (!N->use_empty()) 1249 return false; 1250 1251 SmallSetVector<SDNode *, 16> Nodes; 1252 Nodes.insert(N); 1253 do { 1254 N = Nodes.pop_back_val(); 1255 if (!N) 1256 continue; 1257 1258 if (N->use_empty()) { 1259 for (const SDValue &ChildN : N->op_values()) 1260 Nodes.insert(ChildN.getNode()); 1261 1262 removeFromWorklist(N); 1263 DAG.DeleteNode(N); 1264 } else { 1265 AddToWorklist(N); 1266 } 1267 } while (!Nodes.empty()); 1268 return true; 1269 } 1270 1271 //===----------------------------------------------------------------------===// 1272 // Main DAG Combiner implementation 1273 //===----------------------------------------------------------------------===// 1274 1275 void DAGCombiner::Run(CombineLevel AtLevel) { 1276 // set the instance variables, so that the various visit routines may use it. 1277 Level = AtLevel; 1278 LegalOperations = Level >= AfterLegalizeVectorOps; 1279 LegalTypes = Level >= AfterLegalizeTypes; 1280 1281 // Add all the dag nodes to the worklist. 1282 for (SDNode &Node : DAG.allnodes()) 1283 AddToWorklist(&Node); 1284 1285 // Create a dummy node (which is not added to allnodes), that adds a reference 1286 // to the root node, preventing it from being deleted, and tracking any 1287 // changes of the root. 1288 HandleSDNode Dummy(DAG.getRoot()); 1289 1290 // While the worklist isn't empty, find a node and try to combine it. 1291 while (!WorklistMap.empty()) { 1292 SDNode *N; 1293 // The Worklist holds the SDNodes in order, but it may contain null entries. 1294 do { 1295 N = Worklist.pop_back_val(); 1296 } while (!N); 1297 1298 bool GoodWorklistEntry = WorklistMap.erase(N); 1299 (void)GoodWorklistEntry; 1300 assert(GoodWorklistEntry && 1301 "Found a worklist entry without a corresponding map entry!"); 1302 1303 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1304 // N is deleted from the DAG, since they too may now be dead or may have a 1305 // reduced number of uses, allowing other xforms. 1306 if (recursivelyDeleteUnusedNodes(N)) 1307 continue; 1308 1309 WorklistRemover DeadNodes(*this); 1310 1311 // If this combine is running after legalizing the DAG, re-legalize any 1312 // nodes pulled off the worklist. 1313 if (Level == AfterLegalizeDAG) { 1314 SmallSetVector<SDNode *, 16> UpdatedNodes; 1315 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1316 1317 for (SDNode *LN : UpdatedNodes) { 1318 AddToWorklist(LN); 1319 AddUsersToWorklist(LN); 1320 } 1321 if (!NIsValid) 1322 continue; 1323 } 1324 1325 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1326 1327 // Add any operands of the new node which have not yet been combined to the 1328 // worklist as well. Because the worklist uniques things already, this 1329 // won't repeatedly process the same operand. 1330 CombinedNodes.insert(N); 1331 for (const SDValue &ChildN : N->op_values()) 1332 if (!CombinedNodes.count(ChildN.getNode())) 1333 AddToWorklist(ChildN.getNode()); 1334 1335 SDValue RV = combine(N); 1336 1337 if (!RV.getNode()) 1338 continue; 1339 1340 ++NodesCombined; 1341 1342 // If we get back the same node we passed in, rather than a new node or 1343 // zero, we know that the node must have defined multiple values and 1344 // CombineTo was used. Since CombineTo takes care of the worklist 1345 // mechanics for us, we have no work to do in this case. 1346 if (RV.getNode() == N) 1347 continue; 1348 1349 assert(N->getOpcode() != ISD::DELETED_NODE && 1350 RV.getOpcode() != ISD::DELETED_NODE && 1351 "Node was deleted but visit returned new node!"); 1352 1353 DEBUG(dbgs() << " ... into: "; 1354 RV.getNode()->dump(&DAG)); 1355 1356 if (N->getNumValues() == RV.getNode()->getNumValues()) 1357 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1358 else { 1359 assert(N->getValueType(0) == RV.getValueType() && 1360 N->getNumValues() == 1 && "Type mismatch"); 1361 DAG.ReplaceAllUsesWith(N, &RV); 1362 } 1363 1364 // Push the new node and any users onto the worklist 1365 AddToWorklist(RV.getNode()); 1366 AddUsersToWorklist(RV.getNode()); 1367 1368 // Finally, if the node is now dead, remove it from the graph. The node 1369 // may not be dead if the replacement process recursively simplified to 1370 // something else needing this node. This will also take care of adding any 1371 // operands which have lost a user to the worklist. 1372 recursivelyDeleteUnusedNodes(N); 1373 } 1374 1375 // If the root changed (e.g. it was a dead load, update the root). 1376 DAG.setRoot(Dummy.getValue()); 1377 DAG.RemoveDeadNodes(); 1378 } 1379 1380 SDValue DAGCombiner::visit(SDNode *N) { 1381 switch (N->getOpcode()) { 1382 default: break; 1383 case ISD::TokenFactor: return visitTokenFactor(N); 1384 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1385 case ISD::ADD: return visitADD(N); 1386 case ISD::SUB: return visitSUB(N); 1387 case ISD::ADDC: return visitADDC(N); 1388 case ISD::SUBC: return visitSUBC(N); 1389 case ISD::ADDE: return visitADDE(N); 1390 case ISD::SUBE: return visitSUBE(N); 1391 case ISD::MUL: return visitMUL(N); 1392 case ISD::SDIV: return visitSDIV(N); 1393 case ISD::UDIV: return visitUDIV(N); 1394 case ISD::SREM: 1395 case ISD::UREM: return visitREM(N); 1396 case ISD::MULHU: return visitMULHU(N); 1397 case ISD::MULHS: return visitMULHS(N); 1398 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1399 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1400 case ISD::SMULO: return visitSMULO(N); 1401 case ISD::UMULO: return visitUMULO(N); 1402 case ISD::SMIN: 1403 case ISD::SMAX: 1404 case ISD::UMIN: 1405 case ISD::UMAX: return visitIMINMAX(N); 1406 case ISD::AND: return visitAND(N); 1407 case ISD::OR: return visitOR(N); 1408 case ISD::XOR: return visitXOR(N); 1409 case ISD::SHL: return visitSHL(N); 1410 case ISD::SRA: return visitSRA(N); 1411 case ISD::SRL: return visitSRL(N); 1412 case ISD::ROTR: 1413 case ISD::ROTL: return visitRotate(N); 1414 case ISD::BSWAP: return visitBSWAP(N); 1415 case ISD::BITREVERSE: return visitBITREVERSE(N); 1416 case ISD::CTLZ: return visitCTLZ(N); 1417 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1418 case ISD::CTTZ: return visitCTTZ(N); 1419 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1420 case ISD::CTPOP: return visitCTPOP(N); 1421 case ISD::SELECT: return visitSELECT(N); 1422 case ISD::VSELECT: return visitVSELECT(N); 1423 case ISD::SELECT_CC: return visitSELECT_CC(N); 1424 case ISD::SETCC: return visitSETCC(N); 1425 case ISD::SETCCE: return visitSETCCE(N); 1426 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1427 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1428 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1429 case ISD::AssertZext: return visitAssertZext(N); 1430 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1431 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1432 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1433 case ISD::TRUNCATE: return visitTRUNCATE(N); 1434 case ISD::BITCAST: return visitBITCAST(N); 1435 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1436 case ISD::FADD: return visitFADD(N); 1437 case ISD::FSUB: return visitFSUB(N); 1438 case ISD::FMUL: return visitFMUL(N); 1439 case ISD::FMA: return visitFMA(N); 1440 case ISD::FDIV: return visitFDIV(N); 1441 case ISD::FREM: return visitFREM(N); 1442 case ISD::FSQRT: return visitFSQRT(N); 1443 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1444 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1445 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1446 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1447 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1448 case ISD::FP_ROUND: return visitFP_ROUND(N); 1449 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1450 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1451 case ISD::FNEG: return visitFNEG(N); 1452 case ISD::FABS: return visitFABS(N); 1453 case ISD::FFLOOR: return visitFFLOOR(N); 1454 case ISD::FMINNUM: return visitFMINNUM(N); 1455 case ISD::FMAXNUM: return visitFMAXNUM(N); 1456 case ISD::FCEIL: return visitFCEIL(N); 1457 case ISD::FTRUNC: return visitFTRUNC(N); 1458 case ISD::BRCOND: return visitBRCOND(N); 1459 case ISD::BR_CC: return visitBR_CC(N); 1460 case ISD::LOAD: return visitLOAD(N); 1461 case ISD::STORE: return visitSTORE(N); 1462 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1463 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1464 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1465 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1466 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1467 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1468 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1469 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1470 case ISD::MGATHER: return visitMGATHER(N); 1471 case ISD::MLOAD: return visitMLOAD(N); 1472 case ISD::MSCATTER: return visitMSCATTER(N); 1473 case ISD::MSTORE: return visitMSTORE(N); 1474 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1475 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1476 } 1477 return SDValue(); 1478 } 1479 1480 SDValue DAGCombiner::combine(SDNode *N) { 1481 SDValue RV = visit(N); 1482 1483 // If nothing happened, try a target-specific DAG combine. 1484 if (!RV.getNode()) { 1485 assert(N->getOpcode() != ISD::DELETED_NODE && 1486 "Node was deleted but visit returned NULL!"); 1487 1488 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1489 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1490 1491 // Expose the DAG combiner to the target combiner impls. 1492 TargetLowering::DAGCombinerInfo 1493 DagCombineInfo(DAG, Level, false, this); 1494 1495 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1496 } 1497 } 1498 1499 // If nothing happened still, try promoting the operation. 1500 if (!RV.getNode()) { 1501 switch (N->getOpcode()) { 1502 default: break; 1503 case ISD::ADD: 1504 case ISD::SUB: 1505 case ISD::MUL: 1506 case ISD::AND: 1507 case ISD::OR: 1508 case ISD::XOR: 1509 RV = PromoteIntBinOp(SDValue(N, 0)); 1510 break; 1511 case ISD::SHL: 1512 case ISD::SRA: 1513 case ISD::SRL: 1514 RV = PromoteIntShiftOp(SDValue(N, 0)); 1515 break; 1516 case ISD::SIGN_EXTEND: 1517 case ISD::ZERO_EXTEND: 1518 case ISD::ANY_EXTEND: 1519 RV = PromoteExtend(SDValue(N, 0)); 1520 break; 1521 case ISD::LOAD: 1522 if (PromoteLoad(SDValue(N, 0))) 1523 RV = SDValue(N, 0); 1524 break; 1525 } 1526 } 1527 1528 // If N is a commutative binary node, try commuting it to enable more 1529 // sdisel CSE. 1530 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1531 N->getNumValues() == 1) { 1532 SDValue N0 = N->getOperand(0); 1533 SDValue N1 = N->getOperand(1); 1534 1535 // Constant operands are canonicalized to RHS. 1536 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1537 SDValue Ops[] = {N1, N0}; 1538 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1539 N->getFlags()); 1540 if (CSENode) 1541 return SDValue(CSENode, 0); 1542 } 1543 } 1544 1545 return RV; 1546 } 1547 1548 /// Given a node, return its input chain if it has one, otherwise return a null 1549 /// sd operand. 1550 static SDValue getInputChainForNode(SDNode *N) { 1551 if (unsigned NumOps = N->getNumOperands()) { 1552 if (N->getOperand(0).getValueType() == MVT::Other) 1553 return N->getOperand(0); 1554 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1555 return N->getOperand(NumOps-1); 1556 for (unsigned i = 1; i < NumOps-1; ++i) 1557 if (N->getOperand(i).getValueType() == MVT::Other) 1558 return N->getOperand(i); 1559 } 1560 return SDValue(); 1561 } 1562 1563 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1564 // If N has two operands, where one has an input chain equal to the other, 1565 // the 'other' chain is redundant. 1566 if (N->getNumOperands() == 2) { 1567 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1568 return N->getOperand(0); 1569 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1570 return N->getOperand(1); 1571 } 1572 1573 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1574 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1575 SmallPtrSet<SDNode*, 16> SeenOps; 1576 bool Changed = false; // If we should replace this token factor. 1577 1578 // Start out with this token factor. 1579 TFs.push_back(N); 1580 1581 // Iterate through token factors. The TFs grows when new token factors are 1582 // encountered. 1583 for (unsigned i = 0; i < TFs.size(); ++i) { 1584 SDNode *TF = TFs[i]; 1585 1586 // Check each of the operands. 1587 for (const SDValue &Op : TF->op_values()) { 1588 1589 switch (Op.getOpcode()) { 1590 case ISD::EntryToken: 1591 // Entry tokens don't need to be added to the list. They are 1592 // redundant. 1593 Changed = true; 1594 break; 1595 1596 case ISD::TokenFactor: 1597 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1598 // Queue up for processing. 1599 TFs.push_back(Op.getNode()); 1600 // Clean up in case the token factor is removed. 1601 AddToWorklist(Op.getNode()); 1602 Changed = true; 1603 break; 1604 } 1605 LLVM_FALLTHROUGH; 1606 1607 default: 1608 // Only add if it isn't already in the list. 1609 if (SeenOps.insert(Op.getNode()).second) 1610 Ops.push_back(Op); 1611 else 1612 Changed = true; 1613 break; 1614 } 1615 } 1616 } 1617 1618 // Remove Nodes that are chained to another node in the list. Do so 1619 // by walking up chains breath-first stopping when we've seen 1620 // another operand. In general we must climb to the EntryNode, but we can exit 1621 // early if we find all remaining work is associated with just one operand as 1622 // no further pruning is possible. 1623 1624 // List of nodes to search through and original Ops from which they originate. 1625 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1626 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1627 SmallPtrSet<SDNode *, 16> SeenChains; 1628 bool DidPruneOps = false; 1629 1630 unsigned NumLeftToConsider = 0; 1631 for (const SDValue &Op : Ops) { 1632 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1633 OpWorkCount.push_back(1); 1634 } 1635 1636 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1637 // If this is an Op, we can remove the op from the list. Remark any 1638 // search associated with it as from the current OpNumber. 1639 if (SeenOps.count(Op) != 0) { 1640 Changed = true; 1641 DidPruneOps = true; 1642 unsigned OrigOpNumber = 0; 1643 while (Ops[OrigOpNumber].getNode() != Op && OrigOpNumber < Ops.size()) 1644 OrigOpNumber++; 1645 assert((OrigOpNumber != Ops.size()) && 1646 "expected to find TokenFactor Operand"); 1647 // Re-mark worklist from OrigOpNumber to OpNumber 1648 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1649 if (Worklist[i].second == OrigOpNumber) { 1650 Worklist[i].second = OpNumber; 1651 } 1652 } 1653 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1654 OpWorkCount[OrigOpNumber] = 0; 1655 NumLeftToConsider--; 1656 } 1657 // Add if it's a new chain 1658 if (SeenChains.insert(Op).second) { 1659 OpWorkCount[OpNumber]++; 1660 Worklist.push_back(std::make_pair(Op, OpNumber)); 1661 } 1662 }; 1663 1664 for (unsigned i = 0; i < Worklist.size(); ++i) { 1665 // We need at least be consider at least 2 Ops to prune. 1666 if (NumLeftToConsider <= 1) 1667 break; 1668 auto CurNode = Worklist[i].first; 1669 auto CurOpNumber = Worklist[i].second; 1670 assert((OpWorkCount[CurOpNumber] > 0) && 1671 "Node should not appear in worklist"); 1672 switch (CurNode->getOpcode()) { 1673 case ISD::EntryToken: 1674 // Hitting EntryToken is the only way for the search to terminate without 1675 // hitting 1676 // another operand's search. Prevent us from marking this operand 1677 // considered. 1678 NumLeftToConsider++; 1679 break; 1680 case ISD::TokenFactor: 1681 for (const SDValue &Op : CurNode->op_values()) 1682 AddToWorklist(i, Op.getNode(), CurOpNumber); 1683 break; 1684 case ISD::CopyFromReg: 1685 case ISD::CopyToReg: 1686 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1687 break; 1688 default: 1689 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1690 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1691 break; 1692 } 1693 OpWorkCount[CurOpNumber]--; 1694 if (OpWorkCount[CurOpNumber] == 0) 1695 NumLeftToConsider--; 1696 } 1697 1698 SDValue Result; 1699 1700 // If we've changed things around then replace token factor. 1701 if (Changed) { 1702 if (Ops.empty()) { 1703 // The entry token is the only possible outcome. 1704 Result = DAG.getEntryNode(); 1705 } else { 1706 if (DidPruneOps) { 1707 SmallVector<SDValue, 8> PrunedOps; 1708 // 1709 for (const SDValue &Op : Ops) { 1710 if (SeenChains.count(Op.getNode()) == 0) 1711 PrunedOps.push_back(Op); 1712 } 1713 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1714 } else { 1715 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1716 } 1717 } 1718 1719 // Add users to worklist, since we may introduce a lot of new 1720 // chained token factors while removing memory deps. 1721 return CombineTo(N, Result, true /*add to worklist*/); 1722 } 1723 1724 return Result; 1725 } 1726 1727 /// MERGE_VALUES can always be eliminated. 1728 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1729 WorklistRemover DeadNodes(*this); 1730 // Replacing results may cause a different MERGE_VALUES to suddenly 1731 // be CSE'd with N, and carry its uses with it. Iterate until no 1732 // uses remain, to ensure that the node can be safely deleted. 1733 // First add the users of this node to the work list so that they 1734 // can be tried again once they have new operands. 1735 AddUsersToWorklist(N); 1736 do { 1737 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1738 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1739 } while (!N->use_empty()); 1740 deleteAndRecombine(N); 1741 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1742 } 1743 1744 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1745 /// ConstantSDNode pointer else nullptr. 1746 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1747 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1748 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1749 } 1750 1751 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1752 auto BinOpcode = BO->getOpcode(); 1753 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1754 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1755 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1756 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1757 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1758 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1759 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1760 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1761 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1762 "Unexpected binary operator"); 1763 1764 // Bail out if any constants are opaque because we can't constant fold those. 1765 SDValue C1 = BO->getOperand(1); 1766 if (!isConstantOrConstantVector(C1, true) && 1767 !isConstantFPBuildVectorOrConstantFP(C1)) 1768 return SDValue(); 1769 1770 // Don't do this unless the old select is going away. We want to eliminate the 1771 // binary operator, not replace a binop with a select. 1772 // TODO: Handle ISD::SELECT_CC. 1773 SDValue Sel = BO->getOperand(0); 1774 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1775 return SDValue(); 1776 1777 SDValue CT = Sel.getOperand(1); 1778 if (!isConstantOrConstantVector(CT, true) && 1779 !isConstantFPBuildVectorOrConstantFP(CT)) 1780 return SDValue(); 1781 1782 SDValue CF = Sel.getOperand(2); 1783 if (!isConstantOrConstantVector(CF, true) && 1784 !isConstantFPBuildVectorOrConstantFP(CF)) 1785 return SDValue(); 1786 1787 // We have a select-of-constants followed by a binary operator with a 1788 // constant. Eliminate the binop by pulling the constant math into the select. 1789 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1790 EVT VT = Sel.getValueType(); 1791 SDLoc DL(Sel); 1792 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1793 assert((isConstantOrConstantVector(NewCT) || 1794 isConstantFPBuildVectorOrConstantFP(NewCT)) && 1795 "Failed to constant fold a binop with constant operands"); 1796 1797 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1798 assert((isConstantOrConstantVector(NewCF) || 1799 isConstantFPBuildVectorOrConstantFP(NewCF)) && 1800 "Failed to constant fold a binop with constant operands"); 1801 1802 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1803 } 1804 1805 SDValue DAGCombiner::visitADD(SDNode *N) { 1806 SDValue N0 = N->getOperand(0); 1807 SDValue N1 = N->getOperand(1); 1808 EVT VT = N0.getValueType(); 1809 SDLoc DL(N); 1810 1811 // fold vector ops 1812 if (VT.isVector()) { 1813 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1814 return FoldedVOp; 1815 1816 // fold (add x, 0) -> x, vector edition 1817 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1818 return N0; 1819 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1820 return N1; 1821 } 1822 1823 // fold (add x, undef) -> undef 1824 if (N0.isUndef()) 1825 return N0; 1826 1827 if (N1.isUndef()) 1828 return N1; 1829 1830 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1831 // canonicalize constant to RHS 1832 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1833 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1834 // fold (add c1, c2) -> c1+c2 1835 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1836 N1.getNode()); 1837 } 1838 1839 // fold (add x, 0) -> x 1840 if (isNullConstant(N1)) 1841 return N0; 1842 1843 // fold ((c1-A)+c2) -> (c1+c2)-A 1844 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1845 if (N0.getOpcode() == ISD::SUB) 1846 if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1847 return DAG.getNode(ISD::SUB, DL, VT, 1848 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1849 N0.getOperand(1)); 1850 } 1851 } 1852 1853 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1854 return NewSel; 1855 1856 // reassociate add 1857 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1858 return RADD; 1859 1860 // fold ((0-A) + B) -> B-A 1861 if (N0.getOpcode() == ISD::SUB && 1862 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1863 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1864 1865 // fold (A + (0-B)) -> A-B 1866 if (N1.getOpcode() == ISD::SUB && 1867 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1868 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1869 1870 // fold (A+(B-A)) -> B 1871 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1872 return N1.getOperand(0); 1873 1874 // fold ((B-A)+A) -> B 1875 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1876 return N0.getOperand(0); 1877 1878 // fold (A+(B-(A+C))) to (B-C) 1879 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1880 N0 == N1.getOperand(1).getOperand(0)) 1881 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1882 N1.getOperand(1).getOperand(1)); 1883 1884 // fold (A+(B-(C+A))) to (B-C) 1885 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1886 N0 == N1.getOperand(1).getOperand(1)) 1887 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1888 N1.getOperand(1).getOperand(0)); 1889 1890 // fold (A+((B-A)+or-C)) to (B+or-C) 1891 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1892 N1.getOperand(0).getOpcode() == ISD::SUB && 1893 N0 == N1.getOperand(0).getOperand(1)) 1894 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1895 N1.getOperand(1)); 1896 1897 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1898 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1899 SDValue N00 = N0.getOperand(0); 1900 SDValue N01 = N0.getOperand(1); 1901 SDValue N10 = N1.getOperand(0); 1902 SDValue N11 = N1.getOperand(1); 1903 1904 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 1905 return DAG.getNode(ISD::SUB, DL, VT, 1906 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1907 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1908 } 1909 1910 if (SimplifyDemandedBits(SDValue(N, 0))) 1911 return SDValue(N, 0); 1912 1913 // fold (a+b) -> (a|b) iff a and b share no bits. 1914 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1915 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1)) 1916 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 1917 1918 if (SDValue Combined = visitADDLike(N0, N1, N)) 1919 return Combined; 1920 1921 if (SDValue Combined = visitADDLike(N1, N0, N)) 1922 return Combined; 1923 1924 return SDValue(); 1925 } 1926 1927 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 1928 EVT VT = N0.getValueType(); 1929 SDLoc DL(LocReference); 1930 1931 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1932 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1933 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 1934 return DAG.getNode(ISD::SUB, DL, VT, N0, 1935 DAG.getNode(ISD::SHL, DL, VT, 1936 N1.getOperand(0).getOperand(1), 1937 N1.getOperand(1))); 1938 1939 if (N1.getOpcode() == ISD::AND) { 1940 SDValue AndOp0 = N1.getOperand(0); 1941 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1942 unsigned DestBits = VT.getScalarSizeInBits(); 1943 1944 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1945 // and similar xforms where the inner op is either ~0 or 0. 1946 if (NumSignBits == DestBits && 1947 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 1948 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 1949 } 1950 1951 // add (sext i1), X -> sub X, (zext i1) 1952 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1953 N0.getOperand(0).getValueType() == MVT::i1 && 1954 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1955 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1956 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1957 } 1958 1959 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1960 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1961 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1962 if (TN->getVT() == MVT::i1) { 1963 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1964 DAG.getConstant(1, DL, VT)); 1965 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1966 } 1967 } 1968 1969 return SDValue(); 1970 } 1971 1972 SDValue DAGCombiner::visitADDC(SDNode *N) { 1973 SDValue N0 = N->getOperand(0); 1974 SDValue N1 = N->getOperand(1); 1975 EVT VT = N0.getValueType(); 1976 SDLoc DL(N); 1977 1978 // If the flag result is dead, turn this into an ADD. 1979 if (!N->hasAnyUseOfValue(1)) 1980 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 1981 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1982 1983 // canonicalize constant to RHS. 1984 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1985 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1986 if (N0C && !N1C) 1987 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 1988 1989 // fold (addc x, 0) -> x + no carry out 1990 if (isNullConstant(N1)) 1991 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1992 DL, MVT::Glue)); 1993 1994 // If it cannot overflow, transform into an add. 1995 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 1996 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 1997 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1998 1999 return SDValue(); 2000 } 2001 2002 SDValue DAGCombiner::visitADDE(SDNode *N) { 2003 SDValue N0 = N->getOperand(0); 2004 SDValue N1 = N->getOperand(1); 2005 SDValue CarryIn = N->getOperand(2); 2006 2007 // canonicalize constant to RHS 2008 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2010 if (N0C && !N1C) 2011 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2012 N1, N0, CarryIn); 2013 2014 // fold (adde x, y, false) -> (addc x, y) 2015 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2016 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2017 2018 return SDValue(); 2019 } 2020 2021 // Since it may not be valid to emit a fold to zero for vector initializers 2022 // check if we can before folding. 2023 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2024 SelectionDAG &DAG, bool LegalOperations, 2025 bool LegalTypes) { 2026 if (!VT.isVector()) 2027 return DAG.getConstant(0, DL, VT); 2028 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2029 return DAG.getConstant(0, DL, VT); 2030 return SDValue(); 2031 } 2032 2033 SDValue DAGCombiner::visitSUB(SDNode *N) { 2034 SDValue N0 = N->getOperand(0); 2035 SDValue N1 = N->getOperand(1); 2036 EVT VT = N0.getValueType(); 2037 SDLoc DL(N); 2038 2039 // fold vector ops 2040 if (VT.isVector()) { 2041 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2042 return FoldedVOp; 2043 2044 // fold (sub x, 0) -> x, vector edition 2045 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2046 return N0; 2047 } 2048 2049 // fold (sub x, x) -> 0 2050 // FIXME: Refactor this and xor and other similar operations together. 2051 if (N0 == N1) 2052 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2053 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2054 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2055 // fold (sub c1, c2) -> c1-c2 2056 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2057 N1.getNode()); 2058 } 2059 2060 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2061 return NewSel; 2062 2063 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2064 2065 // fold (sub x, c) -> (add x, -c) 2066 if (N1C) { 2067 return DAG.getNode(ISD::ADD, DL, VT, N0, 2068 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2069 } 2070 2071 if (isNullConstantOrNullSplatConstant(N0)) { 2072 unsigned BitWidth = VT.getScalarSizeInBits(); 2073 // Right-shifting everything out but the sign bit followed by negation is 2074 // the same as flipping arithmetic/logical shift type without the negation: 2075 // -(X >>u 31) -> (X >>s 31) 2076 // -(X >>s 31) -> (X >>u 31) 2077 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2078 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2079 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2080 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2081 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2082 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2083 } 2084 } 2085 2086 // 0 - X --> 0 if the sub is NUW. 2087 if (N->getFlags()->hasNoUnsignedWrap()) 2088 return N0; 2089 2090 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) { 2091 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2092 // N1 must be 0 because negating the minimum signed value is undefined. 2093 if (N->getFlags()->hasNoSignedWrap()) 2094 return N0; 2095 2096 // 0 - X --> X if X is 0 or the minimum signed value. 2097 return N1; 2098 } 2099 } 2100 2101 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2102 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2103 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2104 2105 // fold A-(A-B) -> B 2106 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2107 return N1.getOperand(1); 2108 2109 // fold (A+B)-A -> B 2110 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2111 return N0.getOperand(1); 2112 2113 // fold (A+B)-B -> A 2114 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2115 return N0.getOperand(0); 2116 2117 // fold C2-(A+C1) -> (C2-C1)-A 2118 if (N1.getOpcode() == ISD::ADD) { 2119 SDValue N11 = N1.getOperand(1); 2120 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2121 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2122 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2123 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2124 } 2125 } 2126 2127 // fold ((A+(B+or-C))-B) -> A+or-C 2128 if (N0.getOpcode() == ISD::ADD && 2129 (N0.getOperand(1).getOpcode() == ISD::SUB || 2130 N0.getOperand(1).getOpcode() == ISD::ADD) && 2131 N0.getOperand(1).getOperand(0) == N1) 2132 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2133 N0.getOperand(1).getOperand(1)); 2134 2135 // fold ((A+(C+B))-B) -> A+C 2136 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2137 N0.getOperand(1).getOperand(1) == N1) 2138 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2139 N0.getOperand(1).getOperand(0)); 2140 2141 // fold ((A-(B-C))-C) -> A-B 2142 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2143 N0.getOperand(1).getOperand(1) == N1) 2144 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2145 N0.getOperand(1).getOperand(0)); 2146 2147 // If either operand of a sub is undef, the result is undef 2148 if (N0.isUndef()) 2149 return N0; 2150 if (N1.isUndef()) 2151 return N1; 2152 2153 // If the relocation model supports it, consider symbol offsets. 2154 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2155 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2156 // fold (sub Sym, c) -> Sym-c 2157 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2158 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2159 GA->getOffset() - 2160 (uint64_t)N1C->getSExtValue()); 2161 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2162 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2163 if (GA->getGlobal() == GB->getGlobal()) 2164 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2165 DL, VT); 2166 } 2167 2168 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2169 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2170 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2171 if (TN->getVT() == MVT::i1) { 2172 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2173 DAG.getConstant(1, DL, VT)); 2174 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2175 } 2176 } 2177 2178 return SDValue(); 2179 } 2180 2181 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2182 SDValue N0 = N->getOperand(0); 2183 SDValue N1 = N->getOperand(1); 2184 EVT VT = N0.getValueType(); 2185 SDLoc DL(N); 2186 2187 // If the flag result is dead, turn this into an SUB. 2188 if (!N->hasAnyUseOfValue(1)) 2189 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2190 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2191 2192 // fold (subc x, x) -> 0 + no borrow 2193 if (N0 == N1) 2194 return CombineTo(N, DAG.getConstant(0, DL, VT), 2195 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2196 2197 // fold (subc x, 0) -> x + no borrow 2198 if (isNullConstant(N1)) 2199 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2200 2201 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2202 if (isAllOnesConstant(N0)) 2203 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2204 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2205 2206 return SDValue(); 2207 } 2208 2209 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2210 SDValue N0 = N->getOperand(0); 2211 SDValue N1 = N->getOperand(1); 2212 SDValue CarryIn = N->getOperand(2); 2213 2214 // fold (sube x, y, false) -> (subc x, y) 2215 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2216 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2217 2218 return SDValue(); 2219 } 2220 2221 SDValue DAGCombiner::visitMUL(SDNode *N) { 2222 SDValue N0 = N->getOperand(0); 2223 SDValue N1 = N->getOperand(1); 2224 EVT VT = N0.getValueType(); 2225 2226 // fold (mul x, undef) -> 0 2227 if (N0.isUndef() || N1.isUndef()) 2228 return DAG.getConstant(0, SDLoc(N), VT); 2229 2230 bool N0IsConst = false; 2231 bool N1IsConst = false; 2232 bool N1IsOpaqueConst = false; 2233 bool N0IsOpaqueConst = false; 2234 APInt ConstValue0, ConstValue1; 2235 // fold vector ops 2236 if (VT.isVector()) { 2237 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2238 return FoldedVOp; 2239 2240 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2241 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2242 } else { 2243 N0IsConst = isa<ConstantSDNode>(N0); 2244 if (N0IsConst) { 2245 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2246 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2247 } 2248 N1IsConst = isa<ConstantSDNode>(N1); 2249 if (N1IsConst) { 2250 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2251 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2252 } 2253 } 2254 2255 // fold (mul c1, c2) -> c1*c2 2256 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2257 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2258 N0.getNode(), N1.getNode()); 2259 2260 // canonicalize constant to RHS (vector doesn't have to splat) 2261 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2262 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2263 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2264 // fold (mul x, 0) -> 0 2265 if (N1IsConst && ConstValue1 == 0) 2266 return N1; 2267 // We require a splat of the entire scalar bit width for non-contiguous 2268 // bit patterns. 2269 bool IsFullSplat = 2270 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2271 // fold (mul x, 1) -> x 2272 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2273 return N0; 2274 2275 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2276 return NewSel; 2277 2278 // fold (mul x, -1) -> 0-x 2279 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2280 SDLoc DL(N); 2281 return DAG.getNode(ISD::SUB, DL, VT, 2282 DAG.getConstant(0, DL, VT), N0); 2283 } 2284 // fold (mul x, (1 << c)) -> x << c 2285 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2286 IsFullSplat) { 2287 SDLoc DL(N); 2288 return DAG.getNode(ISD::SHL, DL, VT, N0, 2289 DAG.getConstant(ConstValue1.logBase2(), DL, 2290 getShiftAmountTy(N0.getValueType()))); 2291 } 2292 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2293 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2294 IsFullSplat) { 2295 unsigned Log2Val = (-ConstValue1).logBase2(); 2296 SDLoc DL(N); 2297 // FIXME: If the input is something that is easily negated (e.g. a 2298 // single-use add), we should put the negate there. 2299 return DAG.getNode(ISD::SUB, DL, VT, 2300 DAG.getConstant(0, DL, VT), 2301 DAG.getNode(ISD::SHL, DL, VT, N0, 2302 DAG.getConstant(Log2Val, DL, 2303 getShiftAmountTy(N0.getValueType())))); 2304 } 2305 2306 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2307 if (N0.getOpcode() == ISD::SHL && 2308 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2309 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2310 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2311 if (isConstantOrConstantVector(C3)) 2312 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2313 } 2314 2315 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2316 // use. 2317 { 2318 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2319 2320 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2321 if (N0.getOpcode() == ISD::SHL && 2322 isConstantOrConstantVector(N0.getOperand(1)) && 2323 N0.getNode()->hasOneUse()) { 2324 Sh = N0; Y = N1; 2325 } else if (N1.getOpcode() == ISD::SHL && 2326 isConstantOrConstantVector(N1.getOperand(1)) && 2327 N1.getNode()->hasOneUse()) { 2328 Sh = N1; Y = N0; 2329 } 2330 2331 if (Sh.getNode()) { 2332 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2333 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2334 } 2335 } 2336 2337 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2338 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2339 N0.getOpcode() == ISD::ADD && 2340 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2341 isMulAddWithConstProfitable(N, N0, N1)) 2342 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2343 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2344 N0.getOperand(0), N1), 2345 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2346 N0.getOperand(1), N1)); 2347 2348 // reassociate mul 2349 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2350 return RMUL; 2351 2352 return SDValue(); 2353 } 2354 2355 /// Return true if divmod libcall is available. 2356 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2357 const TargetLowering &TLI) { 2358 RTLIB::Libcall LC; 2359 EVT NodeType = Node->getValueType(0); 2360 if (!NodeType.isSimple()) 2361 return false; 2362 switch (NodeType.getSimpleVT().SimpleTy) { 2363 default: return false; // No libcall for vector types. 2364 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2365 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2366 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2367 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2368 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2369 } 2370 2371 return TLI.getLibcallName(LC) != nullptr; 2372 } 2373 2374 /// Issue divrem if both quotient and remainder are needed. 2375 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2376 if (Node->use_empty()) 2377 return SDValue(); // This is a dead node, leave it alone. 2378 2379 unsigned Opcode = Node->getOpcode(); 2380 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2381 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2382 2383 // DivMod lib calls can still work on non-legal types if using lib-calls. 2384 EVT VT = Node->getValueType(0); 2385 if (VT.isVector() || !VT.isInteger()) 2386 return SDValue(); 2387 2388 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2389 return SDValue(); 2390 2391 // If DIVREM is going to get expanded into a libcall, 2392 // but there is no libcall available, then don't combine. 2393 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2394 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2395 return SDValue(); 2396 2397 // If div is legal, it's better to do the normal expansion 2398 unsigned OtherOpcode = 0; 2399 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2400 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2401 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2402 return SDValue(); 2403 } else { 2404 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2405 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2406 return SDValue(); 2407 } 2408 2409 SDValue Op0 = Node->getOperand(0); 2410 SDValue Op1 = Node->getOperand(1); 2411 SDValue combined; 2412 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2413 UE = Op0.getNode()->use_end(); UI != UE;) { 2414 SDNode *User = *UI++; 2415 if (User == Node || User->use_empty()) 2416 continue; 2417 // Convert the other matching node(s), too; 2418 // otherwise, the DIVREM may get target-legalized into something 2419 // target-specific that we won't be able to recognize. 2420 unsigned UserOpc = User->getOpcode(); 2421 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2422 User->getOperand(0) == Op0 && 2423 User->getOperand(1) == Op1) { 2424 if (!combined) { 2425 if (UserOpc == OtherOpcode) { 2426 SDVTList VTs = DAG.getVTList(VT, VT); 2427 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2428 } else if (UserOpc == DivRemOpc) { 2429 combined = SDValue(User, 0); 2430 } else { 2431 assert(UserOpc == Opcode); 2432 continue; 2433 } 2434 } 2435 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2436 CombineTo(User, combined); 2437 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2438 CombineTo(User, combined.getValue(1)); 2439 } 2440 } 2441 return combined; 2442 } 2443 2444 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2445 SDValue N0 = N->getOperand(0); 2446 SDValue N1 = N->getOperand(1); 2447 EVT VT = N->getValueType(0); 2448 2449 // fold vector ops 2450 if (VT.isVector()) 2451 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2452 return FoldedVOp; 2453 2454 SDLoc DL(N); 2455 2456 // fold (sdiv c1, c2) -> c1/c2 2457 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2458 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2459 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2460 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2461 // fold (sdiv X, 1) -> X 2462 if (N1C && N1C->isOne()) 2463 return N0; 2464 // fold (sdiv X, -1) -> 0-X 2465 if (N1C && N1C->isAllOnesValue()) 2466 return DAG.getNode(ISD::SUB, DL, VT, 2467 DAG.getConstant(0, DL, VT), N0); 2468 2469 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2470 return NewSel; 2471 2472 // If we know the sign bits of both operands are zero, strength reduce to a 2473 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2474 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2475 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2476 2477 // fold (sdiv X, pow2) -> simple ops after legalize 2478 // FIXME: We check for the exact bit here because the generic lowering gives 2479 // better results in that case. The target-specific lowering should learn how 2480 // to handle exact sdivs efficiently. 2481 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2482 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2483 (N1C->getAPIntValue().isPowerOf2() || 2484 (-N1C->getAPIntValue()).isPowerOf2())) { 2485 // Target-specific implementation of sdiv x, pow2. 2486 if (SDValue Res = BuildSDIVPow2(N)) 2487 return Res; 2488 2489 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2490 2491 // Splat the sign bit into the register 2492 SDValue SGN = 2493 DAG.getNode(ISD::SRA, DL, VT, N0, 2494 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2495 getShiftAmountTy(N0.getValueType()))); 2496 AddToWorklist(SGN.getNode()); 2497 2498 // Add (N0 < 0) ? abs2 - 1 : 0; 2499 SDValue SRL = 2500 DAG.getNode(ISD::SRL, DL, VT, SGN, 2501 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2502 getShiftAmountTy(SGN.getValueType()))); 2503 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2504 AddToWorklist(SRL.getNode()); 2505 AddToWorklist(ADD.getNode()); // Divide by pow2 2506 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2507 DAG.getConstant(lg2, DL, 2508 getShiftAmountTy(ADD.getValueType()))); 2509 2510 // If we're dividing by a positive value, we're done. Otherwise, we must 2511 // negate the result. 2512 if (N1C->getAPIntValue().isNonNegative()) 2513 return SRA; 2514 2515 AddToWorklist(SRA.getNode()); 2516 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2517 } 2518 2519 // If integer divide is expensive and we satisfy the requirements, emit an 2520 // alternate sequence. Targets may check function attributes for size/speed 2521 // trade-offs. 2522 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2523 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2524 if (SDValue Op = BuildSDIV(N)) 2525 return Op; 2526 2527 // sdiv, srem -> sdivrem 2528 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2529 // true. Otherwise, we break the simplification logic in visitREM(). 2530 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2531 if (SDValue DivRem = useDivRem(N)) 2532 return DivRem; 2533 2534 // undef / X -> 0 2535 if (N0.isUndef()) 2536 return DAG.getConstant(0, DL, VT); 2537 // X / undef -> undef 2538 if (N1.isUndef()) 2539 return N1; 2540 2541 return SDValue(); 2542 } 2543 2544 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2545 SDValue N0 = N->getOperand(0); 2546 SDValue N1 = N->getOperand(1); 2547 EVT VT = N->getValueType(0); 2548 2549 // fold vector ops 2550 if (VT.isVector()) 2551 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2552 return FoldedVOp; 2553 2554 SDLoc DL(N); 2555 2556 // fold (udiv c1, c2) -> c1/c2 2557 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2558 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2559 if (N0C && N1C) 2560 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2561 N0C, N1C)) 2562 return Folded; 2563 2564 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2565 return NewSel; 2566 2567 // fold (udiv x, (1 << c)) -> x >>u c 2568 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2569 DAG.isKnownToBeAPowerOfTwo(N1)) { 2570 SDValue LogBase2 = BuildLogBase2(N1, DL); 2571 AddToWorklist(LogBase2.getNode()); 2572 2573 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2574 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2575 AddToWorklist(Trunc.getNode()); 2576 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2577 } 2578 2579 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2580 if (N1.getOpcode() == ISD::SHL) { 2581 SDValue N10 = N1.getOperand(0); 2582 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2583 DAG.isKnownToBeAPowerOfTwo(N10)) { 2584 SDValue LogBase2 = BuildLogBase2(N10, DL); 2585 AddToWorklist(LogBase2.getNode()); 2586 2587 EVT ADDVT = N1.getOperand(1).getValueType(); 2588 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2589 AddToWorklist(Trunc.getNode()); 2590 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2591 AddToWorklist(Add.getNode()); 2592 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2593 } 2594 } 2595 2596 // fold (udiv x, c) -> alternate 2597 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2598 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2599 if (SDValue Op = BuildUDIV(N)) 2600 return Op; 2601 2602 // sdiv, srem -> sdivrem 2603 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2604 // true. Otherwise, we break the simplification logic in visitREM(). 2605 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2606 if (SDValue DivRem = useDivRem(N)) 2607 return DivRem; 2608 2609 // undef / X -> 0 2610 if (N0.isUndef()) 2611 return DAG.getConstant(0, DL, VT); 2612 // X / undef -> undef 2613 if (N1.isUndef()) 2614 return N1; 2615 2616 return SDValue(); 2617 } 2618 2619 // handles ISD::SREM and ISD::UREM 2620 SDValue DAGCombiner::visitREM(SDNode *N) { 2621 unsigned Opcode = N->getOpcode(); 2622 SDValue N0 = N->getOperand(0); 2623 SDValue N1 = N->getOperand(1); 2624 EVT VT = N->getValueType(0); 2625 bool isSigned = (Opcode == ISD::SREM); 2626 SDLoc DL(N); 2627 2628 // fold (rem c1, c2) -> c1%c2 2629 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2630 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2631 if (N0C && N1C) 2632 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2633 return Folded; 2634 2635 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2636 return NewSel; 2637 2638 if (isSigned) { 2639 // If we know the sign bits of both operands are zero, strength reduce to a 2640 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2641 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2642 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2643 } else { 2644 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 2645 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 2646 // fold (urem x, pow2) -> (and x, pow2-1) 2647 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2648 AddToWorklist(Add.getNode()); 2649 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2650 } 2651 if (N1.getOpcode() == ISD::SHL && 2652 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 2653 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2654 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2655 AddToWorklist(Add.getNode()); 2656 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2657 } 2658 } 2659 2660 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2661 2662 // If X/C can be simplified by the division-by-constant logic, lower 2663 // X%C to the equivalent of X-X/C*C. 2664 // To avoid mangling nodes, this simplification requires that the combine() 2665 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2666 // against this by skipping the simplification if isIntDivCheap(). When 2667 // div is not cheap, combine will not return a DIVREM. Regardless, 2668 // checking cheapness here makes sense since the simplification results in 2669 // fatter code. 2670 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2671 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2672 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2673 AddToWorklist(Div.getNode()); 2674 SDValue OptimizedDiv = combine(Div.getNode()); 2675 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2676 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2677 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2678 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2679 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2680 AddToWorklist(Mul.getNode()); 2681 return Sub; 2682 } 2683 } 2684 2685 // sdiv, srem -> sdivrem 2686 if (SDValue DivRem = useDivRem(N)) 2687 return DivRem.getValue(1); 2688 2689 // undef % X -> 0 2690 if (N0.isUndef()) 2691 return DAG.getConstant(0, DL, VT); 2692 // X % undef -> undef 2693 if (N1.isUndef()) 2694 return N1; 2695 2696 return SDValue(); 2697 } 2698 2699 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2700 SDValue N0 = N->getOperand(0); 2701 SDValue N1 = N->getOperand(1); 2702 EVT VT = N->getValueType(0); 2703 SDLoc DL(N); 2704 2705 // fold (mulhs x, 0) -> 0 2706 if (isNullConstant(N1)) 2707 return N1; 2708 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2709 if (isOneConstant(N1)) { 2710 SDLoc DL(N); 2711 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2712 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 2713 getShiftAmountTy(N0.getValueType()))); 2714 } 2715 // fold (mulhs x, undef) -> 0 2716 if (N0.isUndef() || N1.isUndef()) 2717 return DAG.getConstant(0, SDLoc(N), VT); 2718 2719 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2720 // plus a shift. 2721 if (VT.isSimple() && !VT.isVector()) { 2722 MVT Simple = VT.getSimpleVT(); 2723 unsigned SimpleSize = Simple.getSizeInBits(); 2724 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2725 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2726 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2727 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2728 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2729 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2730 DAG.getConstant(SimpleSize, DL, 2731 getShiftAmountTy(N1.getValueType()))); 2732 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2733 } 2734 } 2735 2736 return SDValue(); 2737 } 2738 2739 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2740 SDValue N0 = N->getOperand(0); 2741 SDValue N1 = N->getOperand(1); 2742 EVT VT = N->getValueType(0); 2743 SDLoc DL(N); 2744 2745 // fold (mulhu x, 0) -> 0 2746 if (isNullConstant(N1)) 2747 return N1; 2748 // fold (mulhu x, 1) -> 0 2749 if (isOneConstant(N1)) 2750 return DAG.getConstant(0, DL, N0.getValueType()); 2751 // fold (mulhu x, undef) -> 0 2752 if (N0.isUndef() || N1.isUndef()) 2753 return DAG.getConstant(0, DL, VT); 2754 2755 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2756 // plus a shift. 2757 if (VT.isSimple() && !VT.isVector()) { 2758 MVT Simple = VT.getSimpleVT(); 2759 unsigned SimpleSize = Simple.getSizeInBits(); 2760 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2761 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2762 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2763 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2764 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2765 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2766 DAG.getConstant(SimpleSize, DL, 2767 getShiftAmountTy(N1.getValueType()))); 2768 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2769 } 2770 } 2771 2772 return SDValue(); 2773 } 2774 2775 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2776 /// give the opcodes for the two computations that are being performed. Return 2777 /// true if a simplification was made. 2778 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2779 unsigned HiOp) { 2780 // If the high half is not needed, just compute the low half. 2781 bool HiExists = N->hasAnyUseOfValue(1); 2782 if (!HiExists && 2783 (!LegalOperations || 2784 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2785 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2786 return CombineTo(N, Res, Res); 2787 } 2788 2789 // If the low half is not needed, just compute the high half. 2790 bool LoExists = N->hasAnyUseOfValue(0); 2791 if (!LoExists && 2792 (!LegalOperations || 2793 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2794 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2795 return CombineTo(N, Res, Res); 2796 } 2797 2798 // If both halves are used, return as it is. 2799 if (LoExists && HiExists) 2800 return SDValue(); 2801 2802 // If the two computed results can be simplified separately, separate them. 2803 if (LoExists) { 2804 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2805 AddToWorklist(Lo.getNode()); 2806 SDValue LoOpt = combine(Lo.getNode()); 2807 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2808 (!LegalOperations || 2809 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2810 return CombineTo(N, LoOpt, LoOpt); 2811 } 2812 2813 if (HiExists) { 2814 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2815 AddToWorklist(Hi.getNode()); 2816 SDValue HiOpt = combine(Hi.getNode()); 2817 if (HiOpt.getNode() && HiOpt != Hi && 2818 (!LegalOperations || 2819 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2820 return CombineTo(N, HiOpt, HiOpt); 2821 } 2822 2823 return SDValue(); 2824 } 2825 2826 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2827 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2828 return Res; 2829 2830 EVT VT = N->getValueType(0); 2831 SDLoc DL(N); 2832 2833 // If the type is twice as wide is legal, transform the mulhu to a wider 2834 // multiply plus a shift. 2835 if (VT.isSimple() && !VT.isVector()) { 2836 MVT Simple = VT.getSimpleVT(); 2837 unsigned SimpleSize = Simple.getSizeInBits(); 2838 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2839 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2840 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2841 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2842 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2843 // Compute the high part as N1. 2844 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2845 DAG.getConstant(SimpleSize, DL, 2846 getShiftAmountTy(Lo.getValueType()))); 2847 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2848 // Compute the low part as N0. 2849 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2850 return CombineTo(N, Lo, Hi); 2851 } 2852 } 2853 2854 return SDValue(); 2855 } 2856 2857 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2858 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2859 return Res; 2860 2861 EVT VT = N->getValueType(0); 2862 SDLoc DL(N); 2863 2864 // If the type is twice as wide is legal, transform the mulhu to a wider 2865 // multiply plus a shift. 2866 if (VT.isSimple() && !VT.isVector()) { 2867 MVT Simple = VT.getSimpleVT(); 2868 unsigned SimpleSize = Simple.getSizeInBits(); 2869 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2870 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2871 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2872 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2873 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2874 // Compute the high part as N1. 2875 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2876 DAG.getConstant(SimpleSize, DL, 2877 getShiftAmountTy(Lo.getValueType()))); 2878 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2879 // Compute the low part as N0. 2880 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2881 return CombineTo(N, Lo, Hi); 2882 } 2883 } 2884 2885 return SDValue(); 2886 } 2887 2888 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2889 // (smulo x, 2) -> (saddo x, x) 2890 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2891 if (C2->getAPIntValue() == 2) 2892 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2893 N->getOperand(0), N->getOperand(0)); 2894 2895 return SDValue(); 2896 } 2897 2898 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2899 // (umulo x, 2) -> (uaddo x, x) 2900 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2901 if (C2->getAPIntValue() == 2) 2902 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2903 N->getOperand(0), N->getOperand(0)); 2904 2905 return SDValue(); 2906 } 2907 2908 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2909 SDValue N0 = N->getOperand(0); 2910 SDValue N1 = N->getOperand(1); 2911 EVT VT = N0.getValueType(); 2912 2913 // fold vector ops 2914 if (VT.isVector()) 2915 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2916 return FoldedVOp; 2917 2918 // fold (add c1, c2) -> c1+c2 2919 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2920 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2921 if (N0C && N1C) 2922 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2923 2924 // canonicalize constant to RHS 2925 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2926 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2927 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2928 2929 return SDValue(); 2930 } 2931 2932 /// If this is a binary operator with two operands of the same opcode, try to 2933 /// simplify it. 2934 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2935 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2936 EVT VT = N0.getValueType(); 2937 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2938 2939 // Bail early if none of these transforms apply. 2940 if (N0.getNumOperands() == 0) return SDValue(); 2941 2942 // For each of OP in AND/OR/XOR: 2943 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2944 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2945 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2946 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2947 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2948 // 2949 // do not sink logical op inside of a vector extend, since it may combine 2950 // into a vsetcc. 2951 EVT Op0VT = N0.getOperand(0).getValueType(); 2952 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2953 N0.getOpcode() == ISD::SIGN_EXTEND || 2954 N0.getOpcode() == ISD::BSWAP || 2955 // Avoid infinite looping with PromoteIntBinOp. 2956 (N0.getOpcode() == ISD::ANY_EXTEND && 2957 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2958 (N0.getOpcode() == ISD::TRUNCATE && 2959 (!TLI.isZExtFree(VT, Op0VT) || 2960 !TLI.isTruncateFree(Op0VT, VT)) && 2961 TLI.isTypeLegal(Op0VT))) && 2962 !VT.isVector() && 2963 Op0VT == N1.getOperand(0).getValueType() && 2964 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2965 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2966 N0.getOperand(0).getValueType(), 2967 N0.getOperand(0), N1.getOperand(0)); 2968 AddToWorklist(ORNode.getNode()); 2969 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2970 } 2971 2972 // For each of OP in SHL/SRL/SRA/AND... 2973 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2974 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2975 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2976 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2977 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2978 N0.getOperand(1) == N1.getOperand(1)) { 2979 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2980 N0.getOperand(0).getValueType(), 2981 N0.getOperand(0), N1.getOperand(0)); 2982 AddToWorklist(ORNode.getNode()); 2983 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2984 ORNode, N0.getOperand(1)); 2985 } 2986 2987 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2988 // Only perform this optimization up until type legalization, before 2989 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2990 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2991 // we don't want to undo this promotion. 2992 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2993 // on scalars. 2994 if ((N0.getOpcode() == ISD::BITCAST || 2995 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2996 Level <= AfterLegalizeTypes) { 2997 SDValue In0 = N0.getOperand(0); 2998 SDValue In1 = N1.getOperand(0); 2999 EVT In0Ty = In0.getValueType(); 3000 EVT In1Ty = In1.getValueType(); 3001 SDLoc DL(N); 3002 // If both incoming values are integers, and the original types are the 3003 // same. 3004 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3005 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3006 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3007 AddToWorklist(Op.getNode()); 3008 return BC; 3009 } 3010 } 3011 3012 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3013 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3014 // If both shuffles use the same mask, and both shuffle within a single 3015 // vector, then it is worthwhile to move the swizzle after the operation. 3016 // The type-legalizer generates this pattern when loading illegal 3017 // vector types from memory. In many cases this allows additional shuffle 3018 // optimizations. 3019 // There are other cases where moving the shuffle after the xor/and/or 3020 // is profitable even if shuffles don't perform a swizzle. 3021 // If both shuffles use the same mask, and both shuffles have the same first 3022 // or second operand, then it might still be profitable to move the shuffle 3023 // after the xor/and/or operation. 3024 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3025 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3026 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3027 3028 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3029 "Inputs to shuffles are not the same type"); 3030 3031 // Check that both shuffles use the same mask. The masks are known to be of 3032 // the same length because the result vector type is the same. 3033 // Check also that shuffles have only one use to avoid introducing extra 3034 // instructions. 3035 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3036 SVN0->getMask().equals(SVN1->getMask())) { 3037 SDValue ShOp = N0->getOperand(1); 3038 3039 // Don't try to fold this node if it requires introducing a 3040 // build vector of all zeros that might be illegal at this stage. 3041 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3042 if (!LegalTypes) 3043 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3044 else 3045 ShOp = SDValue(); 3046 } 3047 3048 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3049 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3050 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3051 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3052 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3053 N0->getOperand(0), N1->getOperand(0)); 3054 AddToWorklist(NewNode.getNode()); 3055 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3056 SVN0->getMask()); 3057 } 3058 3059 // Don't try to fold this node if it requires introducing a 3060 // build vector of all zeros that might be illegal at this stage. 3061 ShOp = N0->getOperand(0); 3062 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3063 if (!LegalTypes) 3064 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3065 else 3066 ShOp = SDValue(); 3067 } 3068 3069 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3070 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3071 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3072 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3073 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3074 N0->getOperand(1), N1->getOperand(1)); 3075 AddToWorklist(NewNode.getNode()); 3076 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3077 SVN0->getMask()); 3078 } 3079 } 3080 } 3081 3082 return SDValue(); 3083 } 3084 3085 /// This contains all DAGCombine rules which reduce two values combined by 3086 /// an And operation to a single value. This makes them reusable in the context 3087 /// of visitSELECT(). Rules involving constants are not included as 3088 /// visitSELECT() already handles those cases. 3089 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 3090 SDNode *LocReference) { 3091 EVT VT = N1.getValueType(); 3092 3093 // fold (and x, undef) -> 0 3094 if (N0.isUndef() || N1.isUndef()) 3095 return DAG.getConstant(0, SDLoc(LocReference), VT); 3096 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 3097 SDValue LL, LR, RL, RR, CC0, CC1; 3098 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3099 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3100 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3101 3102 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3103 LL.getValueType().isInteger()) { 3104 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 3105 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 3106 EVT CCVT = getSetCCResultType(LR.getValueType()); 3107 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3108 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 3109 LR.getValueType(), LL, RL); 3110 AddToWorklist(ORNode.getNode()); 3111 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3112 } 3113 } 3114 if (isAllOnesConstant(LR)) { 3115 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 3116 if (Op1 == ISD::SETEQ) { 3117 EVT CCVT = getSetCCResultType(LR.getValueType()); 3118 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3119 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 3120 LR.getValueType(), LL, RL); 3121 AddToWorklist(ANDNode.getNode()); 3122 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3123 } 3124 } 3125 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 3126 if (Op1 == ISD::SETGT) { 3127 EVT CCVT = getSetCCResultType(LR.getValueType()); 3128 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3129 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 3130 LR.getValueType(), LL, RL); 3131 AddToWorklist(ORNode.getNode()); 3132 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3133 } 3134 } 3135 } 3136 } 3137 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 3138 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 3139 Op0 == Op1 && LL.getValueType().isInteger() && 3140 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3141 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3142 EVT CCVT = getSetCCResultType(LL.getValueType()); 3143 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3144 SDLoc DL(N0); 3145 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 3146 LL, DAG.getConstant(1, DL, 3147 LL.getValueType())); 3148 AddToWorklist(ADDNode.getNode()); 3149 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 3150 DAG.getConstant(2, DL, LL.getValueType()), 3151 ISD::SETUGE); 3152 } 3153 } 3154 // canonicalize equivalent to ll == rl 3155 if (LL == RR && LR == RL) { 3156 Op1 = ISD::getSetCCSwappedOperands(Op1); 3157 std::swap(RL, RR); 3158 } 3159 if (LL == RL && LR == RR) { 3160 bool isInteger = LL.getValueType().isInteger(); 3161 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 3162 if (Result != ISD::SETCC_INVALID && 3163 (!LegalOperations || 3164 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3165 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3166 EVT CCVT = getSetCCResultType(LL.getValueType()); 3167 if (N0.getValueType() == CCVT || 3168 (!LegalOperations && N0.getValueType() == MVT::i1)) 3169 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3170 LL, LR, Result); 3171 } 3172 } 3173 } 3174 3175 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3176 VT.getSizeInBits() <= 64) { 3177 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3178 APInt ADDC = ADDI->getAPIntValue(); 3179 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3180 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3181 // immediate for an add, but it is legal if its top c2 bits are set, 3182 // transform the ADD so the immediate doesn't need to be materialized 3183 // in a register. 3184 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3185 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3186 SRLI->getZExtValue()); 3187 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3188 ADDC |= Mask; 3189 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3190 SDLoc DL(N0); 3191 SDValue NewAdd = 3192 DAG.getNode(ISD::ADD, DL, VT, 3193 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3194 CombineTo(N0.getNode(), NewAdd); 3195 // Return N so it doesn't get rechecked! 3196 return SDValue(LocReference, 0); 3197 } 3198 } 3199 } 3200 } 3201 } 3202 } 3203 3204 // Reduce bit extract of low half of an integer to the narrower type. 3205 // (and (srl i64:x, K), KMask) -> 3206 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3207 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3208 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3209 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3210 unsigned Size = VT.getSizeInBits(); 3211 const APInt &AndMask = CAnd->getAPIntValue(); 3212 unsigned ShiftBits = CShift->getZExtValue(); 3213 3214 // Bail out, this node will probably disappear anyway. 3215 if (ShiftBits == 0) 3216 return SDValue(); 3217 3218 unsigned MaskBits = AndMask.countTrailingOnes(); 3219 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3220 3221 if (APIntOps::isMask(AndMask) && 3222 // Required bits must not span the two halves of the integer and 3223 // must fit in the half size type. 3224 (ShiftBits + MaskBits <= Size / 2) && 3225 TLI.isNarrowingProfitable(VT, HalfVT) && 3226 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3227 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3228 TLI.isTruncateFree(VT, HalfVT) && 3229 TLI.isZExtFree(HalfVT, VT)) { 3230 // The isNarrowingProfitable is to avoid regressions on PPC and 3231 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3232 // on downstream users of this. Those patterns could probably be 3233 // extended to handle extensions mixed in. 3234 3235 SDValue SL(N0); 3236 assert(MaskBits <= Size); 3237 3238 // Extracting the highest bit of the low half. 3239 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3240 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3241 N0.getOperand(0)); 3242 3243 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3244 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3245 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3246 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3247 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3248 } 3249 } 3250 } 3251 } 3252 3253 return SDValue(); 3254 } 3255 3256 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3257 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3258 bool &NarrowLoad) { 3259 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3260 3261 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3262 return false; 3263 3264 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3265 LoadedVT = LoadN->getMemoryVT(); 3266 3267 if (ExtVT == LoadedVT && 3268 (!LegalOperations || 3269 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3270 // ZEXTLOAD will match without needing to change the size of the value being 3271 // loaded. 3272 NarrowLoad = false; 3273 return true; 3274 } 3275 3276 // Do not change the width of a volatile load. 3277 if (LoadN->isVolatile()) 3278 return false; 3279 3280 // Do not generate loads of non-round integer types since these can 3281 // be expensive (and would be wrong if the type is not byte sized). 3282 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3283 return false; 3284 3285 if (LegalOperations && 3286 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3287 return false; 3288 3289 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3290 return false; 3291 3292 NarrowLoad = true; 3293 return true; 3294 } 3295 3296 SDValue DAGCombiner::visitAND(SDNode *N) { 3297 SDValue N0 = N->getOperand(0); 3298 SDValue N1 = N->getOperand(1); 3299 EVT VT = N1.getValueType(); 3300 3301 // x & x --> x 3302 if (N0 == N1) 3303 return N0; 3304 3305 // fold vector ops 3306 if (VT.isVector()) { 3307 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3308 return FoldedVOp; 3309 3310 // fold (and x, 0) -> 0, vector edition 3311 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3312 // do not return N0, because undef node may exist in N0 3313 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3314 SDLoc(N), N0.getValueType()); 3315 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3316 // do not return N1, because undef node may exist in N1 3317 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3318 SDLoc(N), N1.getValueType()); 3319 3320 // fold (and x, -1) -> x, vector edition 3321 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3322 return N1; 3323 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3324 return N0; 3325 } 3326 3327 // fold (and c1, c2) -> c1&c2 3328 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3329 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3330 if (N0C && N1C && !N1C->isOpaque()) 3331 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3332 // canonicalize constant to RHS 3333 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3334 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3335 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3336 // fold (and x, -1) -> x 3337 if (isAllOnesConstant(N1)) 3338 return N0; 3339 // if (and x, c) is known to be zero, return 0 3340 unsigned BitWidth = VT.getScalarSizeInBits(); 3341 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3342 APInt::getAllOnesValue(BitWidth))) 3343 return DAG.getConstant(0, SDLoc(N), VT); 3344 3345 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3346 return NewSel; 3347 3348 // reassociate and 3349 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3350 return RAND; 3351 // fold (and (or x, C), D) -> D if (C & D) == D 3352 if (N1C && N0.getOpcode() == ISD::OR) 3353 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3354 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3355 return N1; 3356 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3357 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3358 SDValue N0Op0 = N0.getOperand(0); 3359 APInt Mask = ~N1C->getAPIntValue(); 3360 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3361 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3362 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3363 N0.getValueType(), N0Op0); 3364 3365 // Replace uses of the AND with uses of the Zero extend node. 3366 CombineTo(N, Zext); 3367 3368 // We actually want to replace all uses of the any_extend with the 3369 // zero_extend, to avoid duplicating things. This will later cause this 3370 // AND to be folded. 3371 CombineTo(N0.getNode(), Zext); 3372 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3373 } 3374 } 3375 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3376 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3377 // already be zero by virtue of the width of the base type of the load. 3378 // 3379 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3380 // more cases. 3381 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3382 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3383 N0.getOperand(0).getOpcode() == ISD::LOAD && 3384 N0.getOperand(0).getResNo() == 0) || 3385 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3386 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3387 N0 : N0.getOperand(0) ); 3388 3389 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3390 // This can be a pure constant or a vector splat, in which case we treat the 3391 // vector as a scalar and use the splat value. 3392 APInt Constant = APInt::getNullValue(1); 3393 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3394 Constant = C->getAPIntValue(); 3395 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3396 APInt SplatValue, SplatUndef; 3397 unsigned SplatBitSize; 3398 bool HasAnyUndefs; 3399 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3400 SplatBitSize, HasAnyUndefs); 3401 if (IsSplat) { 3402 // Undef bits can contribute to a possible optimisation if set, so 3403 // set them. 3404 SplatValue |= SplatUndef; 3405 3406 // The splat value may be something like "0x00FFFFFF", which means 0 for 3407 // the first vector value and FF for the rest, repeating. We need a mask 3408 // that will apply equally to all members of the vector, so AND all the 3409 // lanes of the constant together. 3410 EVT VT = Vector->getValueType(0); 3411 unsigned BitWidth = VT.getScalarSizeInBits(); 3412 3413 // If the splat value has been compressed to a bitlength lower 3414 // than the size of the vector lane, we need to re-expand it to 3415 // the lane size. 3416 if (BitWidth > SplatBitSize) 3417 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3418 SplatBitSize < BitWidth; 3419 SplatBitSize = SplatBitSize * 2) 3420 SplatValue |= SplatValue.shl(SplatBitSize); 3421 3422 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3423 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3424 if (SplatBitSize % BitWidth == 0) { 3425 Constant = APInt::getAllOnesValue(BitWidth); 3426 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3427 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3428 } 3429 } 3430 } 3431 3432 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3433 // actually legal and isn't going to get expanded, else this is a false 3434 // optimisation. 3435 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3436 Load->getValueType(0), 3437 Load->getMemoryVT()); 3438 3439 // Resize the constant to the same size as the original memory access before 3440 // extension. If it is still the AllOnesValue then this AND is completely 3441 // unneeded. 3442 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3443 3444 bool B; 3445 switch (Load->getExtensionType()) { 3446 default: B = false; break; 3447 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3448 case ISD::ZEXTLOAD: 3449 case ISD::NON_EXTLOAD: B = true; break; 3450 } 3451 3452 if (B && Constant.isAllOnesValue()) { 3453 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3454 // preserve semantics once we get rid of the AND. 3455 SDValue NewLoad(Load, 0); 3456 if (Load->getExtensionType() == ISD::EXTLOAD) { 3457 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3458 Load->getValueType(0), SDLoc(Load), 3459 Load->getChain(), Load->getBasePtr(), 3460 Load->getOffset(), Load->getMemoryVT(), 3461 Load->getMemOperand()); 3462 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3463 if (Load->getNumValues() == 3) { 3464 // PRE/POST_INC loads have 3 values. 3465 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3466 NewLoad.getValue(2) }; 3467 CombineTo(Load, To, 3, true); 3468 } else { 3469 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3470 } 3471 } 3472 3473 // Fold the AND away, taking care not to fold to the old load node if we 3474 // replaced it. 3475 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3476 3477 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3478 } 3479 } 3480 3481 // fold (and (load x), 255) -> (zextload x, i8) 3482 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3483 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3484 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3485 (N0.getOpcode() == ISD::ANY_EXTEND && 3486 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3487 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3488 LoadSDNode *LN0 = HasAnyExt 3489 ? cast<LoadSDNode>(N0.getOperand(0)) 3490 : cast<LoadSDNode>(N0); 3491 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3492 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3493 auto NarrowLoad = false; 3494 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3495 EVT ExtVT, LoadedVT; 3496 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3497 NarrowLoad)) { 3498 if (!NarrowLoad) { 3499 SDValue NewLoad = 3500 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3501 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3502 LN0->getMemOperand()); 3503 AddToWorklist(N); 3504 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3505 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3506 } else { 3507 EVT PtrType = LN0->getOperand(1).getValueType(); 3508 3509 unsigned Alignment = LN0->getAlignment(); 3510 SDValue NewPtr = LN0->getBasePtr(); 3511 3512 // For big endian targets, we need to add an offset to the pointer 3513 // to load the correct bytes. For little endian systems, we merely 3514 // need to read fewer bytes from the same pointer. 3515 if (DAG.getDataLayout().isBigEndian()) { 3516 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3517 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3518 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3519 SDLoc DL(LN0); 3520 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3521 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3522 Alignment = MinAlign(Alignment, PtrOff); 3523 } 3524 3525 AddToWorklist(NewPtr.getNode()); 3526 3527 SDValue Load = DAG.getExtLoad( 3528 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3529 LN0->getPointerInfo(), ExtVT, Alignment, 3530 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3531 AddToWorklist(N); 3532 CombineTo(LN0, Load, Load.getValue(1)); 3533 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3534 } 3535 } 3536 } 3537 } 3538 3539 if (SDValue Combined = visitANDLike(N0, N1, N)) 3540 return Combined; 3541 3542 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3543 if (N0.getOpcode() == N1.getOpcode()) 3544 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3545 return Tmp; 3546 3547 // Masking the negated extension of a boolean is just the zero-extended 3548 // boolean: 3549 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3550 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3551 // 3552 // Note: the SimplifyDemandedBits fold below can make an information-losing 3553 // transform, and then we have no way to find this better fold. 3554 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3555 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0)); 3556 SDValue SubRHS = N0.getOperand(1); 3557 if (SubLHS && SubLHS->isNullValue()) { 3558 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3559 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3560 return SubRHS; 3561 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3562 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3563 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3564 } 3565 } 3566 3567 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3568 // fold (and (sra)) -> (and (srl)) when possible. 3569 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 3570 return SDValue(N, 0); 3571 3572 // fold (zext_inreg (extload x)) -> (zextload x) 3573 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3574 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3575 EVT MemVT = LN0->getMemoryVT(); 3576 // If we zero all the possible extended bits, then we can turn this into 3577 // a zextload if we are running before legalize or the operation is legal. 3578 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3579 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3580 BitWidth - MemVT.getScalarSizeInBits())) && 3581 ((!LegalOperations && !LN0->isVolatile()) || 3582 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3583 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3584 LN0->getChain(), LN0->getBasePtr(), 3585 MemVT, LN0->getMemOperand()); 3586 AddToWorklist(N); 3587 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3588 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3589 } 3590 } 3591 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3592 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3593 N0.hasOneUse()) { 3594 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3595 EVT MemVT = LN0->getMemoryVT(); 3596 // If we zero all the possible extended bits, then we can turn this into 3597 // a zextload if we are running before legalize or the operation is legal. 3598 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3599 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3600 BitWidth - MemVT.getScalarSizeInBits())) && 3601 ((!LegalOperations && !LN0->isVolatile()) || 3602 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3603 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3604 LN0->getChain(), LN0->getBasePtr(), 3605 MemVT, LN0->getMemOperand()); 3606 AddToWorklist(N); 3607 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3608 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3609 } 3610 } 3611 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3612 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3613 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3614 N0.getOperand(1), false)) 3615 return BSwap; 3616 } 3617 3618 return SDValue(); 3619 } 3620 3621 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3622 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3623 bool DemandHighBits) { 3624 if (!LegalOperations) 3625 return SDValue(); 3626 3627 EVT VT = N->getValueType(0); 3628 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3629 return SDValue(); 3630 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3631 return SDValue(); 3632 3633 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3634 bool LookPassAnd0 = false; 3635 bool LookPassAnd1 = false; 3636 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3637 std::swap(N0, N1); 3638 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3639 std::swap(N0, N1); 3640 if (N0.getOpcode() == ISD::AND) { 3641 if (!N0.getNode()->hasOneUse()) 3642 return SDValue(); 3643 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3644 if (!N01C || N01C->getZExtValue() != 0xFF00) 3645 return SDValue(); 3646 N0 = N0.getOperand(0); 3647 LookPassAnd0 = true; 3648 } 3649 3650 if (N1.getOpcode() == ISD::AND) { 3651 if (!N1.getNode()->hasOneUse()) 3652 return SDValue(); 3653 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3654 if (!N11C || N11C->getZExtValue() != 0xFF) 3655 return SDValue(); 3656 N1 = N1.getOperand(0); 3657 LookPassAnd1 = true; 3658 } 3659 3660 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3661 std::swap(N0, N1); 3662 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3663 return SDValue(); 3664 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 3665 return SDValue(); 3666 3667 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3668 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3669 if (!N01C || !N11C) 3670 return SDValue(); 3671 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3672 return SDValue(); 3673 3674 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3675 SDValue N00 = N0->getOperand(0); 3676 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3677 if (!N00.getNode()->hasOneUse()) 3678 return SDValue(); 3679 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3680 if (!N001C || N001C->getZExtValue() != 0xFF) 3681 return SDValue(); 3682 N00 = N00.getOperand(0); 3683 LookPassAnd0 = true; 3684 } 3685 3686 SDValue N10 = N1->getOperand(0); 3687 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3688 if (!N10.getNode()->hasOneUse()) 3689 return SDValue(); 3690 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3691 if (!N101C || N101C->getZExtValue() != 0xFF00) 3692 return SDValue(); 3693 N10 = N10.getOperand(0); 3694 LookPassAnd1 = true; 3695 } 3696 3697 if (N00 != N10) 3698 return SDValue(); 3699 3700 // Make sure everything beyond the low halfword gets set to zero since the SRL 3701 // 16 will clear the top bits. 3702 unsigned OpSizeInBits = VT.getSizeInBits(); 3703 if (DemandHighBits && OpSizeInBits > 16) { 3704 // If the left-shift isn't masked out then the only way this is a bswap is 3705 // if all bits beyond the low 8 are 0. In that case the entire pattern 3706 // reduces to a left shift anyway: leave it for other parts of the combiner. 3707 if (!LookPassAnd0) 3708 return SDValue(); 3709 3710 // However, if the right shift isn't masked out then it might be because 3711 // it's not needed. See if we can spot that too. 3712 if (!LookPassAnd1 && 3713 !DAG.MaskedValueIsZero( 3714 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3715 return SDValue(); 3716 } 3717 3718 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3719 if (OpSizeInBits > 16) { 3720 SDLoc DL(N); 3721 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3722 DAG.getConstant(OpSizeInBits - 16, DL, 3723 getShiftAmountTy(VT))); 3724 } 3725 return Res; 3726 } 3727 3728 /// Return true if the specified node is an element that makes up a 32-bit 3729 /// packed halfword byteswap. 3730 /// ((x & 0x000000ff) << 8) | 3731 /// ((x & 0x0000ff00) >> 8) | 3732 /// ((x & 0x00ff0000) << 8) | 3733 /// ((x & 0xff000000) >> 8) 3734 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3735 if (!N.getNode()->hasOneUse()) 3736 return false; 3737 3738 unsigned Opc = N.getOpcode(); 3739 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3740 return false; 3741 3742 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3743 if (!N1C) 3744 return false; 3745 3746 unsigned Num; 3747 switch (N1C->getZExtValue()) { 3748 default: 3749 return false; 3750 case 0xFF: Num = 0; break; 3751 case 0xFF00: Num = 1; break; 3752 case 0xFF0000: Num = 2; break; 3753 case 0xFF000000: Num = 3; break; 3754 } 3755 3756 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3757 SDValue N0 = N.getOperand(0); 3758 if (Opc == ISD::AND) { 3759 if (Num == 0 || Num == 2) { 3760 // (x >> 8) & 0xff 3761 // (x >> 8) & 0xff0000 3762 if (N0.getOpcode() != ISD::SRL) 3763 return false; 3764 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3765 if (!C || C->getZExtValue() != 8) 3766 return false; 3767 } else { 3768 // (x << 8) & 0xff00 3769 // (x << 8) & 0xff000000 3770 if (N0.getOpcode() != ISD::SHL) 3771 return false; 3772 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3773 if (!C || C->getZExtValue() != 8) 3774 return false; 3775 } 3776 } else if (Opc == ISD::SHL) { 3777 // (x & 0xff) << 8 3778 // (x & 0xff0000) << 8 3779 if (Num != 0 && Num != 2) 3780 return false; 3781 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3782 if (!C || C->getZExtValue() != 8) 3783 return false; 3784 } else { // Opc == ISD::SRL 3785 // (x & 0xff00) >> 8 3786 // (x & 0xff000000) >> 8 3787 if (Num != 1 && Num != 3) 3788 return false; 3789 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3790 if (!C || C->getZExtValue() != 8) 3791 return false; 3792 } 3793 3794 if (Parts[Num]) 3795 return false; 3796 3797 Parts[Num] = N0.getOperand(0).getNode(); 3798 return true; 3799 } 3800 3801 /// Match a 32-bit packed halfword bswap. That is 3802 /// ((x & 0x000000ff) << 8) | 3803 /// ((x & 0x0000ff00) >> 8) | 3804 /// ((x & 0x00ff0000) << 8) | 3805 /// ((x & 0xff000000) >> 8) 3806 /// => (rotl (bswap x), 16) 3807 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3808 if (!LegalOperations) 3809 return SDValue(); 3810 3811 EVT VT = N->getValueType(0); 3812 if (VT != MVT::i32) 3813 return SDValue(); 3814 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3815 return SDValue(); 3816 3817 // Look for either 3818 // (or (or (and), (and)), (or (and), (and))) 3819 // (or (or (or (and), (and)), (and)), (and)) 3820 if (N0.getOpcode() != ISD::OR) 3821 return SDValue(); 3822 SDValue N00 = N0.getOperand(0); 3823 SDValue N01 = N0.getOperand(1); 3824 SDNode *Parts[4] = {}; 3825 3826 if (N1.getOpcode() == ISD::OR && 3827 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3828 // (or (or (and), (and)), (or (and), (and))) 3829 SDValue N000 = N00.getOperand(0); 3830 if (!isBSwapHWordElement(N000, Parts)) 3831 return SDValue(); 3832 3833 SDValue N001 = N00.getOperand(1); 3834 if (!isBSwapHWordElement(N001, Parts)) 3835 return SDValue(); 3836 SDValue N010 = N01.getOperand(0); 3837 if (!isBSwapHWordElement(N010, Parts)) 3838 return SDValue(); 3839 SDValue N011 = N01.getOperand(1); 3840 if (!isBSwapHWordElement(N011, Parts)) 3841 return SDValue(); 3842 } else { 3843 // (or (or (or (and), (and)), (and)), (and)) 3844 if (!isBSwapHWordElement(N1, Parts)) 3845 return SDValue(); 3846 if (!isBSwapHWordElement(N01, Parts)) 3847 return SDValue(); 3848 if (N00.getOpcode() != ISD::OR) 3849 return SDValue(); 3850 SDValue N000 = N00.getOperand(0); 3851 if (!isBSwapHWordElement(N000, Parts)) 3852 return SDValue(); 3853 SDValue N001 = N00.getOperand(1); 3854 if (!isBSwapHWordElement(N001, Parts)) 3855 return SDValue(); 3856 } 3857 3858 // Make sure the parts are all coming from the same node. 3859 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3860 return SDValue(); 3861 3862 SDLoc DL(N); 3863 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3864 SDValue(Parts[0], 0)); 3865 3866 // Result of the bswap should be rotated by 16. If it's not legal, then 3867 // do (x << 16) | (x >> 16). 3868 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3869 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3870 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3871 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3872 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3873 return DAG.getNode(ISD::OR, DL, VT, 3874 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3875 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3876 } 3877 3878 /// This contains all DAGCombine rules which reduce two values combined by 3879 /// an Or operation to a single value \see visitANDLike(). 3880 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3881 EVT VT = N1.getValueType(); 3882 // fold (or x, undef) -> -1 3883 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 3884 return DAG.getAllOnesConstant(SDLoc(LocReference), VT); 3885 3886 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3887 SDValue LL, LR, RL, RR, CC0, CC1; 3888 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3889 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3890 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3891 3892 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3893 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3894 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3895 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3896 EVT CCVT = getSetCCResultType(LR.getValueType()); 3897 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3898 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3899 LR.getValueType(), LL, RL); 3900 AddToWorklist(ORNode.getNode()); 3901 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3902 } 3903 } 3904 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3905 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3906 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3907 EVT CCVT = getSetCCResultType(LR.getValueType()); 3908 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3909 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3910 LR.getValueType(), LL, RL); 3911 AddToWorklist(ANDNode.getNode()); 3912 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3913 } 3914 } 3915 } 3916 // canonicalize equivalent to ll == rl 3917 if (LL == RR && LR == RL) { 3918 Op1 = ISD::getSetCCSwappedOperands(Op1); 3919 std::swap(RL, RR); 3920 } 3921 if (LL == RL && LR == RR) { 3922 bool isInteger = LL.getValueType().isInteger(); 3923 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3924 if (Result != ISD::SETCC_INVALID && 3925 (!LegalOperations || 3926 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3927 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3928 EVT CCVT = getSetCCResultType(LL.getValueType()); 3929 if (N0.getValueType() == CCVT || 3930 (!LegalOperations && N0.getValueType() == MVT::i1)) 3931 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3932 LL, LR, Result); 3933 } 3934 } 3935 } 3936 3937 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3938 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3939 // Don't increase # computations. 3940 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3941 // We can only do this xform if we know that bits from X that are set in C2 3942 // but not in C1 are already zero. Likewise for Y. 3943 if (const ConstantSDNode *N0O1C = 3944 getAsNonOpaqueConstant(N0.getOperand(1))) { 3945 if (const ConstantSDNode *N1O1C = 3946 getAsNonOpaqueConstant(N1.getOperand(1))) { 3947 // We can only do this xform if we know that bits from X that are set in 3948 // C2 but not in C1 are already zero. Likewise for Y. 3949 const APInt &LHSMask = N0O1C->getAPIntValue(); 3950 const APInt &RHSMask = N1O1C->getAPIntValue(); 3951 3952 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3953 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3954 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3955 N0.getOperand(0), N1.getOperand(0)); 3956 SDLoc DL(LocReference); 3957 return DAG.getNode(ISD::AND, DL, VT, X, 3958 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3959 } 3960 } 3961 } 3962 } 3963 3964 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3965 if (N0.getOpcode() == ISD::AND && 3966 N1.getOpcode() == ISD::AND && 3967 N0.getOperand(0) == N1.getOperand(0) && 3968 // Don't increase # computations. 3969 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3970 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3971 N0.getOperand(1), N1.getOperand(1)); 3972 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3973 } 3974 3975 return SDValue(); 3976 } 3977 3978 SDValue DAGCombiner::visitOR(SDNode *N) { 3979 SDValue N0 = N->getOperand(0); 3980 SDValue N1 = N->getOperand(1); 3981 EVT VT = N1.getValueType(); 3982 3983 // x | x --> x 3984 if (N0 == N1) 3985 return N0; 3986 3987 // fold vector ops 3988 if (VT.isVector()) { 3989 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3990 return FoldedVOp; 3991 3992 // fold (or x, 0) -> x, vector edition 3993 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3994 return N1; 3995 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3996 return N0; 3997 3998 // fold (or x, -1) -> -1, vector edition 3999 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4000 // do not return N0, because undef node may exist in N0 4001 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4002 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4003 // do not return N1, because undef node may exist in N1 4004 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4005 4006 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4007 // Do this only if the resulting shuffle is legal. 4008 if (isa<ShuffleVectorSDNode>(N0) && 4009 isa<ShuffleVectorSDNode>(N1) && 4010 // Avoid folding a node with illegal type. 4011 TLI.isTypeLegal(VT)) { 4012 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4013 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4014 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4015 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4016 // Ensure both shuffles have a zero input. 4017 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 4018 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4019 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4020 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4021 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4022 bool CanFold = true; 4023 int NumElts = VT.getVectorNumElements(); 4024 SmallVector<int, 4> Mask(NumElts); 4025 4026 for (int i = 0; i != NumElts; ++i) { 4027 int M0 = SV0->getMaskElt(i); 4028 int M1 = SV1->getMaskElt(i); 4029 4030 // Determine if either index is pointing to a zero vector. 4031 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4032 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4033 4034 // If one element is zero and the otherside is undef, keep undef. 4035 // This also handles the case that both are undef. 4036 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4037 Mask[i] = -1; 4038 continue; 4039 } 4040 4041 // Make sure only one of the elements is zero. 4042 if (M0Zero == M1Zero) { 4043 CanFold = false; 4044 break; 4045 } 4046 4047 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4048 4049 // We have a zero and non-zero element. If the non-zero came from 4050 // SV0 make the index a LHS index. If it came from SV1, make it 4051 // a RHS index. We need to mod by NumElts because we don't care 4052 // which operand it came from in the original shuffles. 4053 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4054 } 4055 4056 if (CanFold) { 4057 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4058 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4059 4060 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4061 if (!LegalMask) { 4062 std::swap(NewLHS, NewRHS); 4063 ShuffleVectorSDNode::commuteMask(Mask); 4064 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4065 } 4066 4067 if (LegalMask) 4068 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4069 } 4070 } 4071 } 4072 } 4073 4074 // fold (or c1, c2) -> c1|c2 4075 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4076 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4077 if (N0C && N1C && !N1C->isOpaque()) 4078 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4079 // canonicalize constant to RHS 4080 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4081 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4082 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4083 // fold (or x, 0) -> x 4084 if (isNullConstant(N1)) 4085 return N0; 4086 // fold (or x, -1) -> -1 4087 if (isAllOnesConstant(N1)) 4088 return N1; 4089 4090 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4091 return NewSel; 4092 4093 // fold (or x, c) -> c iff (x & ~c) == 0 4094 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4095 return N1; 4096 4097 if (SDValue Combined = visitORLike(N0, N1, N)) 4098 return Combined; 4099 4100 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4101 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4102 return BSwap; 4103 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4104 return BSwap; 4105 4106 // reassociate or 4107 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4108 return ROR; 4109 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4110 // iff (c1 & c2) == 0. 4111 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4112 isa<ConstantSDNode>(N0.getOperand(1))) { 4113 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 4114 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 4115 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 4116 N1C, C1)) 4117 return DAG.getNode( 4118 ISD::AND, SDLoc(N), VT, 4119 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 4120 return SDValue(); 4121 } 4122 } 4123 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4124 if (N0.getOpcode() == N1.getOpcode()) 4125 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4126 return Tmp; 4127 4128 // See if this is some rotate idiom. 4129 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4130 return SDValue(Rot, 0); 4131 4132 if (SDValue Load = MatchLoadCombine(N)) 4133 return Load; 4134 4135 // Simplify the operands using demanded-bits information. 4136 if (!VT.isVector() && 4137 SimplifyDemandedBits(SDValue(N, 0))) 4138 return SDValue(N, 0); 4139 4140 return SDValue(); 4141 } 4142 4143 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4144 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4145 if (Op.getOpcode() == ISD::AND) { 4146 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4147 Mask = Op.getOperand(1); 4148 Op = Op.getOperand(0); 4149 } else { 4150 return false; 4151 } 4152 } 4153 4154 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4155 Shift = Op; 4156 return true; 4157 } 4158 4159 return false; 4160 } 4161 4162 // Return true if we can prove that, whenever Neg and Pos are both in the 4163 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4164 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4165 // 4166 // (or (shift1 X, Neg), (shift2 X, Pos)) 4167 // 4168 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4169 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4170 // to consider shift amounts with defined behavior. 4171 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4172 // If EltSize is a power of 2 then: 4173 // 4174 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4175 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4176 // 4177 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4178 // for the stronger condition: 4179 // 4180 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4181 // 4182 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4183 // we can just replace Neg with Neg' for the rest of the function. 4184 // 4185 // In other cases we check for the even stronger condition: 4186 // 4187 // Neg == EltSize - Pos [B] 4188 // 4189 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4190 // behavior if Pos == 0 (and consequently Neg == EltSize). 4191 // 4192 // We could actually use [A] whenever EltSize is a power of 2, but the 4193 // only extra cases that it would match are those uninteresting ones 4194 // where Neg and Pos are never in range at the same time. E.g. for 4195 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4196 // as well as (sub 32, Pos), but: 4197 // 4198 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4199 // 4200 // always invokes undefined behavior for 32-bit X. 4201 // 4202 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4203 unsigned MaskLoBits = 0; 4204 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4205 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4206 if (NegC->getAPIntValue() == EltSize - 1) { 4207 Neg = Neg.getOperand(0); 4208 MaskLoBits = Log2_64(EltSize); 4209 } 4210 } 4211 } 4212 4213 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4214 if (Neg.getOpcode() != ISD::SUB) 4215 return false; 4216 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4217 if (!NegC) 4218 return false; 4219 SDValue NegOp1 = Neg.getOperand(1); 4220 4221 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4222 // Pos'. The truncation is redundant for the purpose of the equality. 4223 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4224 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4225 if (PosC->getAPIntValue() == EltSize - 1) 4226 Pos = Pos.getOperand(0); 4227 4228 // The condition we need is now: 4229 // 4230 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4231 // 4232 // If NegOp1 == Pos then we need: 4233 // 4234 // EltSize & Mask == NegC & Mask 4235 // 4236 // (because "x & Mask" is a truncation and distributes through subtraction). 4237 APInt Width; 4238 if (Pos == NegOp1) 4239 Width = NegC->getAPIntValue(); 4240 4241 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4242 // Then the condition we want to prove becomes: 4243 // 4244 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4245 // 4246 // which, again because "x & Mask" is a truncation, becomes: 4247 // 4248 // NegC & Mask == (EltSize - PosC) & Mask 4249 // EltSize & Mask == (NegC + PosC) & Mask 4250 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4251 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4252 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4253 else 4254 return false; 4255 } else 4256 return false; 4257 4258 // Now we just need to check that EltSize & Mask == Width & Mask. 4259 if (MaskLoBits) 4260 // EltSize & Mask is 0 since Mask is EltSize - 1. 4261 return Width.getLoBits(MaskLoBits) == 0; 4262 return Width == EltSize; 4263 } 4264 4265 // A subroutine of MatchRotate used once we have found an OR of two opposite 4266 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4267 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4268 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4269 // Neg with outer conversions stripped away. 4270 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4271 SDValue Neg, SDValue InnerPos, 4272 SDValue InnerNeg, unsigned PosOpcode, 4273 unsigned NegOpcode, const SDLoc &DL) { 4274 // fold (or (shl x, (*ext y)), 4275 // (srl x, (*ext (sub 32, y)))) -> 4276 // (rotl x, y) or (rotr x, (sub 32, y)) 4277 // 4278 // fold (or (shl x, (*ext (sub 32, y))), 4279 // (srl x, (*ext y))) -> 4280 // (rotr x, y) or (rotl x, (sub 32, y)) 4281 EVT VT = Shifted.getValueType(); 4282 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4283 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4284 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4285 HasPos ? Pos : Neg).getNode(); 4286 } 4287 4288 return nullptr; 4289 } 4290 4291 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4292 // idioms for rotate, and if the target supports rotation instructions, generate 4293 // a rot[lr]. 4294 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4295 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4296 EVT VT = LHS.getValueType(); 4297 if (!TLI.isTypeLegal(VT)) return nullptr; 4298 4299 // The target must have at least one rotate flavor. 4300 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4301 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4302 if (!HasROTL && !HasROTR) return nullptr; 4303 4304 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4305 SDValue LHSShift; // The shift. 4306 SDValue LHSMask; // AND value if any. 4307 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4308 return nullptr; // Not part of a rotate. 4309 4310 SDValue RHSShift; // The shift. 4311 SDValue RHSMask; // AND value if any. 4312 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4313 return nullptr; // Not part of a rotate. 4314 4315 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4316 return nullptr; // Not shifting the same value. 4317 4318 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4319 return nullptr; // Shifts must disagree. 4320 4321 // Canonicalize shl to left side in a shl/srl pair. 4322 if (RHSShift.getOpcode() == ISD::SHL) { 4323 std::swap(LHS, RHS); 4324 std::swap(LHSShift, RHSShift); 4325 std::swap(LHSMask, RHSMask); 4326 } 4327 4328 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4329 SDValue LHSShiftArg = LHSShift.getOperand(0); 4330 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4331 SDValue RHSShiftArg = RHSShift.getOperand(0); 4332 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4333 4334 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4335 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4336 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4337 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4338 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4339 if ((LShVal + RShVal) != EltSizeInBits) 4340 return nullptr; 4341 4342 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4343 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4344 4345 // If there is an AND of either shifted operand, apply it to the result. 4346 if (LHSMask.getNode() || RHSMask.getNode()) { 4347 SDValue Mask = DAG.getAllOnesConstant(DL, VT); 4348 4349 if (LHSMask.getNode()) { 4350 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4351 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4352 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4353 DAG.getConstant(RHSBits, DL, VT))); 4354 } 4355 if (RHSMask.getNode()) { 4356 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4357 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4358 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4359 DAG.getConstant(LHSBits, DL, VT))); 4360 } 4361 4362 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4363 } 4364 4365 return Rot.getNode(); 4366 } 4367 4368 // If there is a mask here, and we have a variable shift, we can't be sure 4369 // that we're masking out the right stuff. 4370 if (LHSMask.getNode() || RHSMask.getNode()) 4371 return nullptr; 4372 4373 // If the shift amount is sign/zext/any-extended just peel it off. 4374 SDValue LExtOp0 = LHSShiftAmt; 4375 SDValue RExtOp0 = RHSShiftAmt; 4376 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4377 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4378 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4379 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4380 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4381 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4382 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4383 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4384 LExtOp0 = LHSShiftAmt.getOperand(0); 4385 RExtOp0 = RHSShiftAmt.getOperand(0); 4386 } 4387 4388 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4389 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4390 if (TryL) 4391 return TryL; 4392 4393 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4394 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4395 if (TryR) 4396 return TryR; 4397 4398 return nullptr; 4399 } 4400 4401 namespace { 4402 /// Helper struct to parse and store a memory address as base + index + offset. 4403 /// We ignore sign extensions when it is safe to do so. 4404 /// The following two expressions are not equivalent. To differentiate we need 4405 /// to store whether there was a sign extension involved in the index 4406 /// computation. 4407 /// (load (i64 add (i64 copyfromreg %c) 4408 /// (i64 signextend (add (i8 load %index) 4409 /// (i8 1)))) 4410 /// vs 4411 /// 4412 /// (load (i64 add (i64 copyfromreg %c) 4413 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 4414 /// (i32 1))))) 4415 struct BaseIndexOffset { 4416 SDValue Base; 4417 SDValue Index; 4418 int64_t Offset; 4419 bool IsIndexSignExt; 4420 4421 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 4422 4423 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 4424 bool IsIndexSignExt) : 4425 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 4426 4427 bool equalBaseIndex(const BaseIndexOffset &Other) { 4428 return Other.Base == Base && Other.Index == Index && 4429 Other.IsIndexSignExt == IsIndexSignExt; 4430 } 4431 4432 /// Parses tree in Ptr for base, index, offset addresses. 4433 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG, 4434 int64_t PartialOffset = 0) { 4435 bool IsIndexSignExt = false; 4436 4437 // Split up a folded GlobalAddress+Offset into its component parts. 4438 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 4439 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 4440 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 4441 SDLoc(GA), 4442 GA->getValueType(0), 4443 /*Offset=*/PartialOffset, 4444 /*isTargetGA=*/false, 4445 GA->getTargetFlags()), 4446 SDValue(), 4447 GA->getOffset(), 4448 IsIndexSignExt); 4449 } 4450 4451 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 4452 // instruction, then it could be just the BASE or everything else we don't 4453 // know how to handle. Just use Ptr as BASE and give up. 4454 if (Ptr->getOpcode() != ISD::ADD) 4455 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4456 4457 // We know that we have at least an ADD instruction. Try to pattern match 4458 // the simple case of BASE + OFFSET. 4459 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 4460 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 4461 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset); 4462 } 4463 4464 // Inside a loop the current BASE pointer is calculated using an ADD and a 4465 // MUL instruction. In this case Ptr is the actual BASE pointer. 4466 // (i64 add (i64 %array_ptr) 4467 // (i64 mul (i64 %induction_var) 4468 // (i64 %element_size))) 4469 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 4470 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4471 4472 // Look at Base + Index + Offset cases. 4473 SDValue Base = Ptr->getOperand(0); 4474 SDValue IndexOffset = Ptr->getOperand(1); 4475 4476 // Skip signextends. 4477 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 4478 IndexOffset = IndexOffset->getOperand(0); 4479 IsIndexSignExt = true; 4480 } 4481 4482 // Either the case of Base + Index (no offset) or something else. 4483 if (IndexOffset->getOpcode() != ISD::ADD) 4484 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt); 4485 4486 // Now we have the case of Base + Index + offset. 4487 SDValue Index = IndexOffset->getOperand(0); 4488 SDValue Offset = IndexOffset->getOperand(1); 4489 4490 if (!isa<ConstantSDNode>(Offset)) 4491 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4492 4493 // Ignore signextends. 4494 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 4495 Index = Index->getOperand(0); 4496 IsIndexSignExt = true; 4497 } else IsIndexSignExt = false; 4498 4499 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 4500 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt); 4501 } 4502 }; 4503 } // namespace 4504 4505 namespace { 4506 /// Represents known origin of an individual byte in load combine pattern. The 4507 /// value of the byte is either constant zero or comes from memory. 4508 struct ByteProvider { 4509 // For constant zero providers Load is set to nullptr. For memory providers 4510 // Load represents the node which loads the byte from memory. 4511 // ByteOffset is the offset of the byte in the value produced by the load. 4512 LoadSDNode *Load; 4513 unsigned ByteOffset; 4514 4515 ByteProvider() : Load(nullptr), ByteOffset(0) {} 4516 4517 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4518 return ByteProvider(Load, ByteOffset); 4519 } 4520 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4521 4522 bool isConstantZero() const { return !Load; } 4523 bool isMemory() const { return Load; } 4524 4525 bool operator==(const ByteProvider &Other) const { 4526 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4527 } 4528 4529 private: 4530 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4531 : Load(Load), ByteOffset(ByteOffset) {} 4532 }; 4533 4534 /// Recursively traverses the expression calculating the origin of the requested 4535 /// byte of the given value. Returns None if the provider can't be calculated. 4536 /// 4537 /// For all the values except the root of the expression verifies that the value 4538 /// has exactly one use and if it's not true return None. This way if the origin 4539 /// of the byte is returned it's guaranteed that the values which contribute to 4540 /// the byte are not used outside of this expression. 4541 /// 4542 /// Because the parts of the expression are not allowed to have more than one 4543 /// use this function iterates over trees, not DAGs. So it never visits the same 4544 /// node more than once. 4545 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index, 4546 unsigned Depth, 4547 bool Root = false) { 4548 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4549 if (Depth == 10) 4550 return None; 4551 4552 if (!Root && !Op.hasOneUse()) 4553 return None; 4554 4555 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4556 unsigned BitWidth = Op.getValueSizeInBits(); 4557 if (BitWidth % 8 != 0) 4558 return None; 4559 unsigned ByteWidth = BitWidth / 8; 4560 assert(Index < ByteWidth && "invalid index requested"); 4561 (void) ByteWidth; 4562 4563 switch (Op.getOpcode()) { 4564 case ISD::OR: { 4565 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4566 if (!LHS) 4567 return None; 4568 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4569 if (!RHS) 4570 return None; 4571 4572 if (LHS->isConstantZero()) 4573 return RHS; 4574 else if (RHS->isConstantZero()) 4575 return LHS; 4576 else 4577 return None; 4578 } 4579 case ISD::SHL: { 4580 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4581 if (!ShiftOp) 4582 return None; 4583 4584 uint64_t BitShift = ShiftOp->getZExtValue(); 4585 if (BitShift % 8 != 0) 4586 return None; 4587 uint64_t ByteShift = BitShift / 8; 4588 4589 return Index < ByteShift 4590 ? ByteProvider::getConstantZero() 4591 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4592 Depth + 1); 4593 } 4594 case ISD::ANY_EXTEND: 4595 case ISD::SIGN_EXTEND: 4596 case ISD::ZERO_EXTEND: { 4597 SDValue NarrowOp = Op->getOperand(0); 4598 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4599 if (NarrowBitWidth % 8 != 0) 4600 return None; 4601 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4602 4603 if (Index >= NarrowByteWidth) 4604 return Op.getOpcode() == ISD::ZERO_EXTEND 4605 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4606 : None; 4607 else 4608 return calculateByteProvider(NarrowOp, Index, Depth + 1); 4609 } 4610 case ISD::BSWAP: 4611 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4612 Depth + 1); 4613 case ISD::LOAD: { 4614 auto L = cast<LoadSDNode>(Op.getNode()); 4615 if (L->isVolatile() || L->isIndexed()) 4616 return None; 4617 4618 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 4619 if (NarrowBitWidth % 8 != 0) 4620 return None; 4621 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4622 4623 if (Index >= NarrowByteWidth) 4624 return L->getExtensionType() == ISD::ZEXTLOAD 4625 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4626 : None; 4627 else 4628 return ByteProvider::getMemory(L, Index); 4629 } 4630 } 4631 4632 return None; 4633 } 4634 } // namespace 4635 4636 /// Match a pattern where a wide type scalar value is loaded by several narrow 4637 /// loads and combined by shifts and ors. Fold it into a single load or a load 4638 /// and a BSWAP if the targets supports it. 4639 /// 4640 /// Assuming little endian target: 4641 /// i8 *a = ... 4642 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4643 /// => 4644 /// i32 val = *((i32)a) 4645 /// 4646 /// i8 *a = ... 4647 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4648 /// => 4649 /// i32 val = BSWAP(*((i32)a)) 4650 /// 4651 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4652 /// interact well with the worklist mechanism. When a part of the pattern is 4653 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4654 /// but the root node of the pattern which triggers the load combine is not 4655 /// necessarily a direct user of the changed node. For example, once the address 4656 /// of t28 load is reassociated load combine won't be triggered: 4657 /// t25: i32 = add t4, Constant:i32<2> 4658 /// t26: i64 = sign_extend t25 4659 /// t27: i64 = add t2, t26 4660 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4661 /// t29: i32 = zero_extend t28 4662 /// t32: i32 = shl t29, Constant:i8<8> 4663 /// t33: i32 = or t23, t32 4664 /// As a possible fix visitLoad can check if the load can be a part of a load 4665 /// combine pattern and add corresponding OR roots to the worklist. 4666 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4667 assert(N->getOpcode() == ISD::OR && 4668 "Can only match load combining against OR nodes"); 4669 4670 // Handles simple types only 4671 EVT VT = N->getValueType(0); 4672 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4673 return SDValue(); 4674 unsigned ByteWidth = VT.getSizeInBits() / 8; 4675 4676 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4677 // Before legalize we can introduce too wide illegal loads which will be later 4678 // split into legal sized loads. This enables us to combine i64 load by i8 4679 // patterns to a couple of i32 loads on 32 bit targets. 4680 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4681 return SDValue(); 4682 4683 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4684 unsigned BW, unsigned i) { return i; }; 4685 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4686 unsigned BW, unsigned i) { return BW - i - 1; }; 4687 4688 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4689 auto MemoryByteOffset = [&] (ByteProvider P) { 4690 assert(P.isMemory() && "Must be a memory byte provider"); 4691 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4692 assert(LoadBitWidth % 8 == 0 && 4693 "can only analyze providers for individual bytes not bit"); 4694 unsigned LoadByteWidth = LoadBitWidth / 8; 4695 return IsBigEndianTarget 4696 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4697 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4698 }; 4699 4700 Optional<BaseIndexOffset> Base; 4701 SDValue Chain; 4702 4703 SmallSet<LoadSDNode *, 8> Loads; 4704 Optional<ByteProvider> FirstByteProvider; 4705 int64_t FirstOffset = INT64_MAX; 4706 4707 // Check if all the bytes of the OR we are looking at are loaded from the same 4708 // base address. Collect bytes offsets from Base address in ByteOffsets. 4709 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 4710 for (unsigned i = 0; i < ByteWidth; i++) { 4711 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 4712 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 4713 return SDValue(); 4714 4715 LoadSDNode *L = P->Load; 4716 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 4717 "Must be enforced by calculateByteProvider"); 4718 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 4719 4720 // All loads must share the same chain 4721 SDValue LChain = L->getChain(); 4722 if (!Chain) 4723 Chain = LChain; 4724 else if (Chain != LChain) 4725 return SDValue(); 4726 4727 // Loads must share the same base address 4728 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 4729 if (!Base) 4730 Base = Ptr; 4731 else if (!Base->equalBaseIndex(Ptr)) 4732 return SDValue(); 4733 4734 // Calculate the offset of the current byte from the base address 4735 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P); 4736 ByteOffsets[i] = ByteOffsetFromBase; 4737 4738 // Remember the first byte load 4739 if (ByteOffsetFromBase < FirstOffset) { 4740 FirstByteProvider = P; 4741 FirstOffset = ByteOffsetFromBase; 4742 } 4743 4744 Loads.insert(L); 4745 } 4746 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from " 4747 "memory, so there must be at least one load which produces the value"); 4748 assert(Base && "Base address of the accessed memory location must be set"); 4749 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 4750 4751 // Check if the bytes of the OR we are looking at match with either big or 4752 // little endian value load 4753 bool BigEndian = true, LittleEndian = true; 4754 for (unsigned i = 0; i < ByteWidth; i++) { 4755 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 4756 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 4757 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 4758 if (!BigEndian && !LittleEndian) 4759 return SDValue(); 4760 } 4761 assert((BigEndian != LittleEndian) && "should be either or"); 4762 assert(FirstByteProvider && "must be set"); 4763 4764 // Ensure that the first byte is loaded from zero offset of the first load. 4765 // So the combined value can be loaded from the first load address. 4766 if (MemoryByteOffset(*FirstByteProvider) != 0) 4767 return SDValue(); 4768 LoadSDNode *FirstLoad = FirstByteProvider->Load; 4769 4770 // The node we are looking at matches with the pattern, check if we can 4771 // replace it with a single load and bswap if needed. 4772 4773 // If the load needs byte swap check if the target supports it 4774 bool NeedsBswap = IsBigEndianTarget != BigEndian; 4775 4776 // Before legalize we can introduce illegal bswaps which will be later 4777 // converted to an explicit bswap sequence. This way we end up with a single 4778 // load and byte shuffling instead of several loads and byte shuffling. 4779 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 4780 return SDValue(); 4781 4782 // Check that a load of the wide type is both allowed and fast on the target 4783 bool Fast = false; 4784 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 4785 VT, FirstLoad->getAddressSpace(), 4786 FirstLoad->getAlignment(), &Fast); 4787 if (!Allowed || !Fast) 4788 return SDValue(); 4789 4790 SDValue NewLoad = 4791 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 4792 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 4793 4794 // Transfer chain users from old loads to the new load. 4795 for (LoadSDNode *L : Loads) 4796 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 4797 4798 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 4799 } 4800 4801 SDValue DAGCombiner::visitXOR(SDNode *N) { 4802 SDValue N0 = N->getOperand(0); 4803 SDValue N1 = N->getOperand(1); 4804 EVT VT = N0.getValueType(); 4805 4806 // fold vector ops 4807 if (VT.isVector()) { 4808 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4809 return FoldedVOp; 4810 4811 // fold (xor x, 0) -> x, vector edition 4812 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4813 return N1; 4814 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4815 return N0; 4816 } 4817 4818 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4819 if (N0.isUndef() && N1.isUndef()) 4820 return DAG.getConstant(0, SDLoc(N), VT); 4821 // fold (xor x, undef) -> undef 4822 if (N0.isUndef()) 4823 return N0; 4824 if (N1.isUndef()) 4825 return N1; 4826 // fold (xor c1, c2) -> c1^c2 4827 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4828 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4829 if (N0C && N1C) 4830 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4831 // canonicalize constant to RHS 4832 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4833 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4834 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4835 // fold (xor x, 0) -> x 4836 if (isNullConstant(N1)) 4837 return N0; 4838 4839 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4840 return NewSel; 4841 4842 // reassociate xor 4843 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4844 return RXOR; 4845 4846 // fold !(x cc y) -> (x !cc y) 4847 SDValue LHS, RHS, CC; 4848 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4849 bool isInt = LHS.getValueType().isInteger(); 4850 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4851 isInt); 4852 4853 if (!LegalOperations || 4854 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4855 switch (N0.getOpcode()) { 4856 default: 4857 llvm_unreachable("Unhandled SetCC Equivalent!"); 4858 case ISD::SETCC: 4859 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 4860 case ISD::SELECT_CC: 4861 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 4862 N0.getOperand(3), NotCC); 4863 } 4864 } 4865 } 4866 4867 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4868 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4869 N0.getNode()->hasOneUse() && 4870 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4871 SDValue V = N0.getOperand(0); 4872 SDLoc DL(N0); 4873 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4874 DAG.getConstant(1, DL, V.getValueType())); 4875 AddToWorklist(V.getNode()); 4876 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4877 } 4878 4879 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4880 if (isOneConstant(N1) && VT == MVT::i1 && 4881 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4882 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4883 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4884 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4885 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4886 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4887 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4888 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4889 } 4890 } 4891 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4892 if (isAllOnesConstant(N1) && 4893 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4894 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4895 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4896 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4897 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4898 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4899 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4900 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4901 } 4902 } 4903 // fold (xor (and x, y), y) -> (and (not x), y) 4904 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4905 N0->getOperand(1) == N1) { 4906 SDValue X = N0->getOperand(0); 4907 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4908 AddToWorklist(NotX.getNode()); 4909 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4910 } 4911 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4912 if (N1C && N0.getOpcode() == ISD::XOR) { 4913 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4914 SDLoc DL(N); 4915 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4916 DAG.getConstant(N1C->getAPIntValue() ^ 4917 N00C->getAPIntValue(), DL, VT)); 4918 } 4919 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4920 SDLoc DL(N); 4921 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4922 DAG.getConstant(N1C->getAPIntValue() ^ 4923 N01C->getAPIntValue(), DL, VT)); 4924 } 4925 } 4926 // fold (xor x, x) -> 0 4927 if (N0 == N1) 4928 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4929 4930 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4931 // Here is a concrete example of this equivalence: 4932 // i16 x == 14 4933 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4934 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4935 // 4936 // => 4937 // 4938 // i16 ~1 == 0b1111111111111110 4939 // i16 rol(~1, 14) == 0b1011111111111111 4940 // 4941 // Some additional tips to help conceptualize this transform: 4942 // - Try to see the operation as placing a single zero in a value of all ones. 4943 // - There exists no value for x which would allow the result to contain zero. 4944 // - Values of x larger than the bitwidth are undefined and do not require a 4945 // consistent result. 4946 // - Pushing the zero left requires shifting one bits in from the right. 4947 // A rotate left of ~1 is a nice way of achieving the desired result. 4948 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4949 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4950 SDLoc DL(N); 4951 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4952 N0.getOperand(1)); 4953 } 4954 4955 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4956 if (N0.getOpcode() == N1.getOpcode()) 4957 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4958 return Tmp; 4959 4960 // Simplify the expression using non-local knowledge. 4961 if (!VT.isVector() && 4962 SimplifyDemandedBits(SDValue(N, 0))) 4963 return SDValue(N, 0); 4964 4965 return SDValue(); 4966 } 4967 4968 /// Handle transforms common to the three shifts, when the shift amount is a 4969 /// constant. 4970 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4971 SDNode *LHS = N->getOperand(0).getNode(); 4972 if (!LHS->hasOneUse()) return SDValue(); 4973 4974 // We want to pull some binops through shifts, so that we have (and (shift)) 4975 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4976 // thing happens with address calculations, so it's important to canonicalize 4977 // it. 4978 bool HighBitSet = false; // Can we transform this if the high bit is set? 4979 4980 switch (LHS->getOpcode()) { 4981 default: return SDValue(); 4982 case ISD::OR: 4983 case ISD::XOR: 4984 HighBitSet = false; // We can only transform sra if the high bit is clear. 4985 break; 4986 case ISD::AND: 4987 HighBitSet = true; // We can only transform sra if the high bit is set. 4988 break; 4989 case ISD::ADD: 4990 if (N->getOpcode() != ISD::SHL) 4991 return SDValue(); // only shl(add) not sr[al](add). 4992 HighBitSet = false; // We can only transform sra if the high bit is clear. 4993 break; 4994 } 4995 4996 // We require the RHS of the binop to be a constant and not opaque as well. 4997 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4998 if (!BinOpCst) return SDValue(); 4999 5000 // FIXME: disable this unless the input to the binop is a shift by a constant 5001 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5002 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5003 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5004 BinOpLHSVal->getOpcode() == ISD::SRA || 5005 BinOpLHSVal->getOpcode() == ISD::SRL; 5006 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5007 BinOpLHSVal->getOpcode() == ISD::SELECT; 5008 5009 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5010 !isCopyOrSelect) 5011 return SDValue(); 5012 5013 if (isCopyOrSelect && N->hasOneUse()) 5014 return SDValue(); 5015 5016 EVT VT = N->getValueType(0); 5017 5018 // If this is a signed shift right, and the high bit is modified by the 5019 // logical operation, do not perform the transformation. The highBitSet 5020 // boolean indicates the value of the high bit of the constant which would 5021 // cause it to be modified for this operation. 5022 if (N->getOpcode() == ISD::SRA) { 5023 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5024 if (BinOpRHSSignSet != HighBitSet) 5025 return SDValue(); 5026 } 5027 5028 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5029 return SDValue(); 5030 5031 // Fold the constants, shifting the binop RHS by the shift amount. 5032 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5033 N->getValueType(0), 5034 LHS->getOperand(1), N->getOperand(1)); 5035 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5036 5037 // Create the new shift. 5038 SDValue NewShift = DAG.getNode(N->getOpcode(), 5039 SDLoc(LHS->getOperand(0)), 5040 VT, LHS->getOperand(0), N->getOperand(1)); 5041 5042 // Create the new binop. 5043 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5044 } 5045 5046 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5047 assert(N->getOpcode() == ISD::TRUNCATE); 5048 assert(N->getOperand(0).getOpcode() == ISD::AND); 5049 5050 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5051 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5052 SDValue N01 = N->getOperand(0).getOperand(1); 5053 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5054 SDLoc DL(N); 5055 EVT TruncVT = N->getValueType(0); 5056 SDValue N00 = N->getOperand(0).getOperand(0); 5057 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5058 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5059 AddToWorklist(Trunc00.getNode()); 5060 AddToWorklist(Trunc01.getNode()); 5061 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5062 } 5063 } 5064 5065 return SDValue(); 5066 } 5067 5068 SDValue DAGCombiner::visitRotate(SDNode *N) { 5069 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5070 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 5071 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 5072 if (SDValue NewOp1 = 5073 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 5074 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 5075 N->getOperand(0), NewOp1); 5076 } 5077 return SDValue(); 5078 } 5079 5080 SDValue DAGCombiner::visitSHL(SDNode *N) { 5081 SDValue N0 = N->getOperand(0); 5082 SDValue N1 = N->getOperand(1); 5083 EVT VT = N0.getValueType(); 5084 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5085 5086 // fold vector ops 5087 if (VT.isVector()) { 5088 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5089 return FoldedVOp; 5090 5091 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5092 // If setcc produces all-one true value then: 5093 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5094 if (N1CV && N1CV->isConstant()) { 5095 if (N0.getOpcode() == ISD::AND) { 5096 SDValue N00 = N0->getOperand(0); 5097 SDValue N01 = N0->getOperand(1); 5098 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5099 5100 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5101 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5102 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5103 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5104 N01CV, N1CV)) 5105 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5106 } 5107 } 5108 } 5109 } 5110 5111 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5112 5113 // fold (shl c1, c2) -> c1<<c2 5114 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5115 if (N0C && N1C && !N1C->isOpaque()) 5116 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5117 // fold (shl 0, x) -> 0 5118 if (isNullConstant(N0)) 5119 return N0; 5120 // fold (shl x, c >= size(x)) -> undef 5121 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5122 return DAG.getUNDEF(VT); 5123 // fold (shl x, 0) -> x 5124 if (N1C && N1C->isNullValue()) 5125 return N0; 5126 // fold (shl undef, x) -> 0 5127 if (N0.isUndef()) 5128 return DAG.getConstant(0, SDLoc(N), VT); 5129 5130 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5131 return NewSel; 5132 5133 // if (shl x, c) is known to be zero, return 0 5134 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5135 APInt::getAllOnesValue(OpSizeInBits))) 5136 return DAG.getConstant(0, SDLoc(N), VT); 5137 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5138 if (N1.getOpcode() == ISD::TRUNCATE && 5139 N1.getOperand(0).getOpcode() == ISD::AND) { 5140 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5141 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5142 } 5143 5144 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5145 return SDValue(N, 0); 5146 5147 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5148 if (N1C && N0.getOpcode() == ISD::SHL) { 5149 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5150 SDLoc DL(N); 5151 APInt c1 = N0C1->getAPIntValue(); 5152 APInt c2 = N1C->getAPIntValue(); 5153 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5154 5155 APInt Sum = c1 + c2; 5156 if (Sum.uge(OpSizeInBits)) 5157 return DAG.getConstant(0, DL, VT); 5158 5159 return DAG.getNode( 5160 ISD::SHL, DL, VT, N0.getOperand(0), 5161 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5162 } 5163 } 5164 5165 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5166 // For this to be valid, the second form must not preserve any of the bits 5167 // that are shifted out by the inner shift in the first form. This means 5168 // the outer shift size must be >= the number of bits added by the ext. 5169 // As a corollary, we don't care what kind of ext it is. 5170 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5171 N0.getOpcode() == ISD::ANY_EXTEND || 5172 N0.getOpcode() == ISD::SIGN_EXTEND) && 5173 N0.getOperand(0).getOpcode() == ISD::SHL) { 5174 SDValue N0Op0 = N0.getOperand(0); 5175 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5176 APInt c1 = N0Op0C1->getAPIntValue(); 5177 APInt c2 = N1C->getAPIntValue(); 5178 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5179 5180 EVT InnerShiftVT = N0Op0.getValueType(); 5181 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5182 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5183 SDLoc DL(N0); 5184 APInt Sum = c1 + c2; 5185 if (Sum.uge(OpSizeInBits)) 5186 return DAG.getConstant(0, DL, VT); 5187 5188 return DAG.getNode( 5189 ISD::SHL, DL, VT, 5190 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5191 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5192 } 5193 } 5194 } 5195 5196 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5197 // Only fold this if the inner zext has no other uses to avoid increasing 5198 // the total number of instructions. 5199 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5200 N0.getOperand(0).getOpcode() == ISD::SRL) { 5201 SDValue N0Op0 = N0.getOperand(0); 5202 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5203 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5204 uint64_t c1 = N0Op0C1->getZExtValue(); 5205 uint64_t c2 = N1C->getZExtValue(); 5206 if (c1 == c2) { 5207 SDValue NewOp0 = N0.getOperand(0); 5208 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5209 SDLoc DL(N); 5210 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5211 NewOp0, 5212 DAG.getConstant(c2, DL, CountVT)); 5213 AddToWorklist(NewSHL.getNode()); 5214 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5215 } 5216 } 5217 } 5218 } 5219 5220 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5221 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5222 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5223 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 5224 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5225 uint64_t C1 = N0C1->getZExtValue(); 5226 uint64_t C2 = N1C->getZExtValue(); 5227 SDLoc DL(N); 5228 if (C1 <= C2) 5229 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5230 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5231 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5232 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5233 } 5234 } 5235 5236 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5237 // (and (srl x, (sub c1, c2), MASK) 5238 // Only fold this if the inner shift has no other uses -- if it does, folding 5239 // this will increase the total number of instructions. 5240 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5241 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5242 uint64_t c1 = N0C1->getZExtValue(); 5243 if (c1 < OpSizeInBits) { 5244 uint64_t c2 = N1C->getZExtValue(); 5245 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5246 SDValue Shift; 5247 if (c2 > c1) { 5248 Mask = Mask.shl(c2 - c1); 5249 SDLoc DL(N); 5250 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5251 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5252 } else { 5253 Mask = Mask.lshr(c1 - c2); 5254 SDLoc DL(N); 5255 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5256 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5257 } 5258 SDLoc DL(N0); 5259 return DAG.getNode(ISD::AND, DL, VT, Shift, 5260 DAG.getConstant(Mask, DL, VT)); 5261 } 5262 } 5263 } 5264 5265 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5266 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5267 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5268 SDLoc DL(N); 5269 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5270 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5271 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5272 } 5273 5274 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5275 // Variant of version done on multiply, except mul by a power of 2 is turned 5276 // into a shift. 5277 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 5278 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5279 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5280 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5281 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5282 AddToWorklist(Shl0.getNode()); 5283 AddToWorklist(Shl1.getNode()); 5284 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 5285 } 5286 5287 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5288 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5289 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5290 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5291 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5292 if (isConstantOrConstantVector(Shl)) 5293 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5294 } 5295 5296 if (N1C && !N1C->isOpaque()) 5297 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5298 return NewSHL; 5299 5300 return SDValue(); 5301 } 5302 5303 SDValue DAGCombiner::visitSRA(SDNode *N) { 5304 SDValue N0 = N->getOperand(0); 5305 SDValue N1 = N->getOperand(1); 5306 EVT VT = N0.getValueType(); 5307 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5308 5309 // Arithmetic shifting an all-sign-bit value is a no-op. 5310 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5311 return N0; 5312 5313 // fold vector ops 5314 if (VT.isVector()) 5315 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5316 return FoldedVOp; 5317 5318 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5319 5320 // fold (sra c1, c2) -> (sra c1, c2) 5321 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5322 if (N0C && N1C && !N1C->isOpaque()) 5323 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5324 // fold (sra 0, x) -> 0 5325 if (isNullConstant(N0)) 5326 return N0; 5327 // fold (sra -1, x) -> -1 5328 if (isAllOnesConstant(N0)) 5329 return N0; 5330 // fold (sra x, c >= size(x)) -> undef 5331 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5332 return DAG.getUNDEF(VT); 5333 // fold (sra x, 0) -> x 5334 if (N1C && N1C->isNullValue()) 5335 return N0; 5336 5337 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5338 return NewSel; 5339 5340 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5341 // sext_inreg. 5342 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5343 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5344 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5345 if (VT.isVector()) 5346 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5347 ExtVT, VT.getVectorNumElements()); 5348 if ((!LegalOperations || 5349 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5350 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5351 N0.getOperand(0), DAG.getValueType(ExtVT)); 5352 } 5353 5354 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5355 if (N1C && N0.getOpcode() == ISD::SRA) { 5356 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5357 SDLoc DL(N); 5358 APInt c1 = N0C1->getAPIntValue(); 5359 APInt c2 = N1C->getAPIntValue(); 5360 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5361 5362 APInt Sum = c1 + c2; 5363 if (Sum.uge(OpSizeInBits)) 5364 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 5365 5366 return DAG.getNode( 5367 ISD::SRA, DL, VT, N0.getOperand(0), 5368 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5369 } 5370 } 5371 5372 // fold (sra (shl X, m), (sub result_size, n)) 5373 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5374 // result_size - n != m. 5375 // If truncate is free for the target sext(shl) is likely to result in better 5376 // code. 5377 if (N0.getOpcode() == ISD::SHL && N1C) { 5378 // Get the two constanst of the shifts, CN0 = m, CN = n. 5379 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5380 if (N01C) { 5381 LLVMContext &Ctx = *DAG.getContext(); 5382 // Determine what the truncate's result bitsize and type would be. 5383 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5384 5385 if (VT.isVector()) 5386 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5387 5388 // Determine the residual right-shift amount. 5389 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5390 5391 // If the shift is not a no-op (in which case this should be just a sign 5392 // extend already), the truncated to type is legal, sign_extend is legal 5393 // on that type, and the truncate to that type is both legal and free, 5394 // perform the transform. 5395 if ((ShiftAmt > 0) && 5396 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5397 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5398 TLI.isTruncateFree(VT, TruncVT)) { 5399 5400 SDLoc DL(N); 5401 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5402 getShiftAmountTy(N0.getOperand(0).getValueType())); 5403 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5404 N0.getOperand(0), Amt); 5405 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5406 Shift); 5407 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5408 N->getValueType(0), Trunc); 5409 } 5410 } 5411 } 5412 5413 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5414 if (N1.getOpcode() == ISD::TRUNCATE && 5415 N1.getOperand(0).getOpcode() == ISD::AND) { 5416 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5417 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5418 } 5419 5420 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5421 // if c1 is equal to the number of bits the trunc removes 5422 if (N0.getOpcode() == ISD::TRUNCATE && 5423 (N0.getOperand(0).getOpcode() == ISD::SRL || 5424 N0.getOperand(0).getOpcode() == ISD::SRA) && 5425 N0.getOperand(0).hasOneUse() && 5426 N0.getOperand(0).getOperand(1).hasOneUse() && 5427 N1C) { 5428 SDValue N0Op0 = N0.getOperand(0); 5429 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5430 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5431 EVT LargeVT = N0Op0.getValueType(); 5432 5433 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5434 SDLoc DL(N); 5435 SDValue Amt = 5436 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5437 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5438 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5439 N0Op0.getOperand(0), Amt); 5440 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5441 } 5442 } 5443 } 5444 5445 // Simplify, based on bits shifted out of the LHS. 5446 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5447 return SDValue(N, 0); 5448 5449 5450 // If the sign bit is known to be zero, switch this to a SRL. 5451 if (DAG.SignBitIsZero(N0)) 5452 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5453 5454 if (N1C && !N1C->isOpaque()) 5455 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5456 return NewSRA; 5457 5458 return SDValue(); 5459 } 5460 5461 SDValue DAGCombiner::visitSRL(SDNode *N) { 5462 SDValue N0 = N->getOperand(0); 5463 SDValue N1 = N->getOperand(1); 5464 EVT VT = N0.getValueType(); 5465 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5466 5467 // fold vector ops 5468 if (VT.isVector()) 5469 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5470 return FoldedVOp; 5471 5472 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5473 5474 // fold (srl c1, c2) -> c1 >>u c2 5475 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5476 if (N0C && N1C && !N1C->isOpaque()) 5477 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5478 // fold (srl 0, x) -> 0 5479 if (isNullConstant(N0)) 5480 return N0; 5481 // fold (srl x, c >= size(x)) -> undef 5482 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5483 return DAG.getUNDEF(VT); 5484 // fold (srl x, 0) -> x 5485 if (N1C && N1C->isNullValue()) 5486 return N0; 5487 5488 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5489 return NewSel; 5490 5491 // if (srl x, c) is known to be zero, return 0 5492 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5493 APInt::getAllOnesValue(OpSizeInBits))) 5494 return DAG.getConstant(0, SDLoc(N), VT); 5495 5496 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5497 if (N1C && N0.getOpcode() == ISD::SRL) { 5498 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5499 SDLoc DL(N); 5500 APInt c1 = N0C1->getAPIntValue(); 5501 APInt c2 = N1C->getAPIntValue(); 5502 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5503 5504 APInt Sum = c1 + c2; 5505 if (Sum.uge(OpSizeInBits)) 5506 return DAG.getConstant(0, DL, VT); 5507 5508 return DAG.getNode( 5509 ISD::SRL, DL, VT, N0.getOperand(0), 5510 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5511 } 5512 } 5513 5514 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5515 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5516 N0.getOperand(0).getOpcode() == ISD::SRL && 5517 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 5518 uint64_t c1 = 5519 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 5520 uint64_t c2 = N1C->getZExtValue(); 5521 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5522 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 5523 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5524 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5525 if (c1 + OpSizeInBits == InnerShiftSize) { 5526 SDLoc DL(N0); 5527 if (c1 + c2 >= InnerShiftSize) 5528 return DAG.getConstant(0, DL, VT); 5529 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5530 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5531 N0.getOperand(0)->getOperand(0), 5532 DAG.getConstant(c1 + c2, DL, 5533 ShiftCountVT))); 5534 } 5535 } 5536 5537 // fold (srl (shl x, c), c) -> (and x, cst2) 5538 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5539 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5540 SDLoc DL(N); 5541 SDValue Mask = 5542 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5543 AddToWorklist(Mask.getNode()); 5544 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5545 } 5546 5547 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5548 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5549 // Shifting in all undef bits? 5550 EVT SmallVT = N0.getOperand(0).getValueType(); 5551 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5552 if (N1C->getZExtValue() >= BitSize) 5553 return DAG.getUNDEF(VT); 5554 5555 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5556 uint64_t ShiftAmt = N1C->getZExtValue(); 5557 SDLoc DL0(N0); 5558 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5559 N0.getOperand(0), 5560 DAG.getConstant(ShiftAmt, DL0, 5561 getShiftAmountTy(SmallVT))); 5562 AddToWorklist(SmallShift.getNode()); 5563 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 5564 SDLoc DL(N); 5565 return DAG.getNode(ISD::AND, DL, VT, 5566 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5567 DAG.getConstant(Mask, DL, VT)); 5568 } 5569 } 5570 5571 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5572 // bit, which is unmodified by sra. 5573 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5574 if (N0.getOpcode() == ISD::SRA) 5575 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5576 } 5577 5578 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5579 if (N1C && N0.getOpcode() == ISD::CTLZ && 5580 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5581 APInt KnownZero, KnownOne; 5582 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 5583 5584 // If any of the input bits are KnownOne, then the input couldn't be all 5585 // zeros, thus the result of the srl will always be zero. 5586 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5587 5588 // If all of the bits input the to ctlz node are known to be zero, then 5589 // the result of the ctlz is "32" and the result of the shift is one. 5590 APInt UnknownBits = ~KnownZero; 5591 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5592 5593 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5594 if ((UnknownBits & (UnknownBits - 1)) == 0) { 5595 // Okay, we know that only that the single bit specified by UnknownBits 5596 // could be set on input to the CTLZ node. If this bit is set, the SRL 5597 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5598 // to an SRL/XOR pair, which is likely to simplify more. 5599 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5600 SDValue Op = N0.getOperand(0); 5601 5602 if (ShAmt) { 5603 SDLoc DL(N0); 5604 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5605 DAG.getConstant(ShAmt, DL, 5606 getShiftAmountTy(Op.getValueType()))); 5607 AddToWorklist(Op.getNode()); 5608 } 5609 5610 SDLoc DL(N); 5611 return DAG.getNode(ISD::XOR, DL, VT, 5612 Op, DAG.getConstant(1, DL, VT)); 5613 } 5614 } 5615 5616 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5617 if (N1.getOpcode() == ISD::TRUNCATE && 5618 N1.getOperand(0).getOpcode() == ISD::AND) { 5619 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5620 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5621 } 5622 5623 // fold operands of srl based on knowledge that the low bits are not 5624 // demanded. 5625 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5626 return SDValue(N, 0); 5627 5628 if (N1C && !N1C->isOpaque()) 5629 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5630 return NewSRL; 5631 5632 // Attempt to convert a srl of a load into a narrower zero-extending load. 5633 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5634 return NarrowLoad; 5635 5636 // Here is a common situation. We want to optimize: 5637 // 5638 // %a = ... 5639 // %b = and i32 %a, 2 5640 // %c = srl i32 %b, 1 5641 // brcond i32 %c ... 5642 // 5643 // into 5644 // 5645 // %a = ... 5646 // %b = and %a, 2 5647 // %c = setcc eq %b, 0 5648 // brcond %c ... 5649 // 5650 // However when after the source operand of SRL is optimized into AND, the SRL 5651 // itself may not be optimized further. Look for it and add the BRCOND into 5652 // the worklist. 5653 if (N->hasOneUse()) { 5654 SDNode *Use = *N->use_begin(); 5655 if (Use->getOpcode() == ISD::BRCOND) 5656 AddToWorklist(Use); 5657 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5658 // Also look pass the truncate. 5659 Use = *Use->use_begin(); 5660 if (Use->getOpcode() == ISD::BRCOND) 5661 AddToWorklist(Use); 5662 } 5663 } 5664 5665 return SDValue(); 5666 } 5667 5668 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5669 SDValue N0 = N->getOperand(0); 5670 EVT VT = N->getValueType(0); 5671 5672 // fold (bswap c1) -> c2 5673 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5674 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5675 // fold (bswap (bswap x)) -> x 5676 if (N0.getOpcode() == ISD::BSWAP) 5677 return N0->getOperand(0); 5678 return SDValue(); 5679 } 5680 5681 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5682 SDValue N0 = N->getOperand(0); 5683 EVT VT = N->getValueType(0); 5684 5685 // fold (bitreverse c1) -> c2 5686 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5687 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 5688 // fold (bitreverse (bitreverse x)) -> x 5689 if (N0.getOpcode() == ISD::BITREVERSE) 5690 return N0.getOperand(0); 5691 return SDValue(); 5692 } 5693 5694 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5695 SDValue N0 = N->getOperand(0); 5696 EVT VT = N->getValueType(0); 5697 5698 // fold (ctlz c1) -> c2 5699 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5700 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5701 return SDValue(); 5702 } 5703 5704 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5705 SDValue N0 = N->getOperand(0); 5706 EVT VT = N->getValueType(0); 5707 5708 // fold (ctlz_zero_undef c1) -> c2 5709 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5710 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5711 return SDValue(); 5712 } 5713 5714 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5715 SDValue N0 = N->getOperand(0); 5716 EVT VT = N->getValueType(0); 5717 5718 // fold (cttz c1) -> c2 5719 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5720 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5721 return SDValue(); 5722 } 5723 5724 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5725 SDValue N0 = N->getOperand(0); 5726 EVT VT = N->getValueType(0); 5727 5728 // fold (cttz_zero_undef c1) -> c2 5729 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5730 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5731 return SDValue(); 5732 } 5733 5734 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5735 SDValue N0 = N->getOperand(0); 5736 EVT VT = N->getValueType(0); 5737 5738 // fold (ctpop c1) -> c2 5739 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5740 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5741 return SDValue(); 5742 } 5743 5744 5745 /// \brief Generate Min/Max node 5746 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5747 SDValue RHS, SDValue True, SDValue False, 5748 ISD::CondCode CC, const TargetLowering &TLI, 5749 SelectionDAG &DAG) { 5750 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5751 return SDValue(); 5752 5753 switch (CC) { 5754 case ISD::SETOLT: 5755 case ISD::SETOLE: 5756 case ISD::SETLT: 5757 case ISD::SETLE: 5758 case ISD::SETULT: 5759 case ISD::SETULE: { 5760 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5761 if (TLI.isOperationLegal(Opcode, VT)) 5762 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5763 return SDValue(); 5764 } 5765 case ISD::SETOGT: 5766 case ISD::SETOGE: 5767 case ISD::SETGT: 5768 case ISD::SETGE: 5769 case ISD::SETUGT: 5770 case ISD::SETUGE: { 5771 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5772 if (TLI.isOperationLegal(Opcode, VT)) 5773 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5774 return SDValue(); 5775 } 5776 default: 5777 return SDValue(); 5778 } 5779 } 5780 5781 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 5782 SDValue Cond = N->getOperand(0); 5783 SDValue N1 = N->getOperand(1); 5784 SDValue N2 = N->getOperand(2); 5785 EVT VT = N->getValueType(0); 5786 EVT CondVT = Cond.getValueType(); 5787 SDLoc DL(N); 5788 5789 if (!VT.isInteger()) 5790 return SDValue(); 5791 5792 auto *C1 = dyn_cast<ConstantSDNode>(N1); 5793 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5794 if (!C1 || !C2) 5795 return SDValue(); 5796 5797 // Only do this before legalization to avoid conflicting with target-specific 5798 // transforms in the other direction (create a select from a zext/sext). There 5799 // is also a target-independent combine here in DAGCombiner in the other 5800 // direction for (select Cond, -1, 0) when the condition is not i1. 5801 // TODO: This could be generalized for any 2 constants that differ by 1: 5802 // add ({s/z}ext Cond), C 5803 if (CondVT == MVT::i1 && !LegalOperations) { 5804 if (C1->isNullValue() && C2->isOne()) { 5805 // select Cond, 0, 1 --> zext (!Cond) 5806 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 5807 if (VT != MVT::i1) 5808 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 5809 return NotCond; 5810 } 5811 if (C1->isNullValue() && C2->isAllOnesValue()) { 5812 // select Cond, 0, -1 --> sext (!Cond) 5813 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 5814 if (VT != MVT::i1) 5815 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 5816 return NotCond; 5817 } 5818 if (C1->isOne() && C2->isNullValue()) { 5819 // select Cond, 1, 0 --> zext (Cond) 5820 if (VT != MVT::i1) 5821 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 5822 return Cond; 5823 } 5824 if (C1->isAllOnesValue() && C2->isNullValue()) { 5825 // select Cond, -1, 0 --> sext (Cond) 5826 if (VT != MVT::i1) 5827 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 5828 return Cond; 5829 } 5830 return SDValue(); 5831 } 5832 5833 // fold (select Cond, 0, 1) -> (xor Cond, 1) 5834 // We can't do this reliably if integer based booleans have different contents 5835 // to floating point based booleans. This is because we can't tell whether we 5836 // have an integer-based boolean or a floating-point-based boolean unless we 5837 // can find the SETCC that produced it and inspect its operands. This is 5838 // fairly easy if C is the SETCC node, but it can potentially be 5839 // undiscoverable (or not reasonably discoverable). For example, it could be 5840 // in another basic block or it could require searching a complicated 5841 // expression. 5842 if (CondVT.isInteger() && 5843 TLI.getBooleanContents(false, true) == 5844 TargetLowering::ZeroOrOneBooleanContent && 5845 TLI.getBooleanContents(false, false) == 5846 TargetLowering::ZeroOrOneBooleanContent && 5847 C1->isNullValue() && C2->isOne()) { 5848 SDValue NotCond = 5849 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 5850 if (VT.bitsEq(CondVT)) 5851 return NotCond; 5852 return DAG.getZExtOrTrunc(NotCond, DL, VT); 5853 } 5854 5855 return SDValue(); 5856 } 5857 5858 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5859 SDValue N0 = N->getOperand(0); 5860 SDValue N1 = N->getOperand(1); 5861 SDValue N2 = N->getOperand(2); 5862 EVT VT = N->getValueType(0); 5863 EVT VT0 = N0.getValueType(); 5864 5865 // fold (select C, X, X) -> X 5866 if (N1 == N2) 5867 return N1; 5868 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5869 // fold (select true, X, Y) -> X 5870 // fold (select false, X, Y) -> Y 5871 return !N0C->isNullValue() ? N1 : N2; 5872 } 5873 // fold (select X, X, Y) -> (or X, Y) 5874 // fold (select X, 1, Y) -> (or C, Y) 5875 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5876 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5877 5878 if (SDValue V = foldSelectOfConstants(N)) 5879 return V; 5880 5881 // fold (select C, 0, X) -> (and (not C), X) 5882 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5883 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5884 AddToWorklist(NOTNode.getNode()); 5885 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5886 } 5887 // fold (select C, X, 1) -> (or (not C), X) 5888 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5889 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5890 AddToWorklist(NOTNode.getNode()); 5891 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5892 } 5893 // fold (select X, Y, X) -> (and X, Y) 5894 // fold (select X, Y, 0) -> (and X, Y) 5895 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5896 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5897 5898 // If we can fold this based on the true/false value, do so. 5899 if (SimplifySelectOps(N, N1, N2)) 5900 return SDValue(N, 0); // Don't revisit N. 5901 5902 if (VT0 == MVT::i1) { 5903 // The code in this block deals with the following 2 equivalences: 5904 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5905 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5906 // The target can specify its preferred form with the 5907 // shouldNormalizeToSelectSequence() callback. However we always transform 5908 // to the right anyway if we find the inner select exists in the DAG anyway 5909 // and we always transform to the left side if we know that we can further 5910 // optimize the combination of the conditions. 5911 bool normalizeToSequence 5912 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5913 // select (and Cond0, Cond1), X, Y 5914 // -> select Cond0, (select Cond1, X, Y), Y 5915 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5916 SDValue Cond0 = N0->getOperand(0); 5917 SDValue Cond1 = N0->getOperand(1); 5918 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5919 N1.getValueType(), Cond1, N1, N2); 5920 if (normalizeToSequence || !InnerSelect.use_empty()) 5921 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5922 InnerSelect, N2); 5923 } 5924 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5925 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5926 SDValue Cond0 = N0->getOperand(0); 5927 SDValue Cond1 = N0->getOperand(1); 5928 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5929 N1.getValueType(), Cond1, N1, N2); 5930 if (normalizeToSequence || !InnerSelect.use_empty()) 5931 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5932 InnerSelect); 5933 } 5934 5935 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5936 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5937 SDValue N1_0 = N1->getOperand(0); 5938 SDValue N1_1 = N1->getOperand(1); 5939 SDValue N1_2 = N1->getOperand(2); 5940 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5941 // Create the actual and node if we can generate good code for it. 5942 if (!normalizeToSequence) { 5943 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5944 N0, N1_0); 5945 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5946 N1_1, N2); 5947 } 5948 // Otherwise see if we can optimize the "and" to a better pattern. 5949 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5950 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5951 N1_1, N2); 5952 } 5953 } 5954 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5955 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5956 SDValue N2_0 = N2->getOperand(0); 5957 SDValue N2_1 = N2->getOperand(1); 5958 SDValue N2_2 = N2->getOperand(2); 5959 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5960 // Create the actual or node if we can generate good code for it. 5961 if (!normalizeToSequence) { 5962 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5963 N0, N2_0); 5964 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5965 N1, N2_2); 5966 } 5967 // Otherwise see if we can optimize to a better pattern. 5968 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5969 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5970 N1, N2_2); 5971 } 5972 } 5973 } 5974 5975 // select (xor Cond, 1), X, Y -> select Cond, Y, X 5976 if (VT0 == MVT::i1) { 5977 if (N0->getOpcode() == ISD::XOR) { 5978 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 5979 SDValue Cond0 = N0->getOperand(0); 5980 if (C->isOne()) 5981 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 5982 Cond0, N2, N1); 5983 } 5984 } 5985 } 5986 5987 // fold selects based on a setcc into other things, such as min/max/abs 5988 if (N0.getOpcode() == ISD::SETCC) { 5989 // select x, y (fcmp lt x, y) -> fminnum x, y 5990 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5991 // 5992 // This is OK if we don't care about what happens if either operand is a 5993 // NaN. 5994 // 5995 5996 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5997 // no signed zeros as well as no nans. 5998 const TargetOptions &Options = DAG.getTarget().Options; 5999 if (Options.UnsafeFPMath && 6000 VT.isFloatingPoint() && N0.hasOneUse() && 6001 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6002 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6003 6004 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 6005 N0.getOperand(1), N1, N2, CC, 6006 TLI, DAG)) 6007 return FMinMax; 6008 } 6009 6010 if ((!LegalOperations && 6011 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6012 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6013 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 6014 N0.getOperand(0), N0.getOperand(1), 6015 N1, N2, N0.getOperand(2)); 6016 return SimplifySelect(SDLoc(N), N0, N1, N2); 6017 } 6018 6019 return SDValue(); 6020 } 6021 6022 static 6023 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6024 SDLoc DL(N); 6025 EVT LoVT, HiVT; 6026 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6027 6028 // Split the inputs. 6029 SDValue Lo, Hi, LL, LH, RL, RH; 6030 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6031 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6032 6033 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6034 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6035 6036 return std::make_pair(Lo, Hi); 6037 } 6038 6039 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6040 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6041 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6042 SDLoc DL(N); 6043 SDValue Cond = N->getOperand(0); 6044 SDValue LHS = N->getOperand(1); 6045 SDValue RHS = N->getOperand(2); 6046 EVT VT = N->getValueType(0); 6047 int NumElems = VT.getVectorNumElements(); 6048 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6049 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6050 Cond.getOpcode() == ISD::BUILD_VECTOR); 6051 6052 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6053 // binary ones here. 6054 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6055 return SDValue(); 6056 6057 // We're sure we have an even number of elements due to the 6058 // concat_vectors we have as arguments to vselect. 6059 // Skip BV elements until we find one that's not an UNDEF 6060 // After we find an UNDEF element, keep looping until we get to half the 6061 // length of the BV and see if all the non-undef nodes are the same. 6062 ConstantSDNode *BottomHalf = nullptr; 6063 for (int i = 0; i < NumElems / 2; ++i) { 6064 if (Cond->getOperand(i)->isUndef()) 6065 continue; 6066 6067 if (BottomHalf == nullptr) 6068 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6069 else if (Cond->getOperand(i).getNode() != BottomHalf) 6070 return SDValue(); 6071 } 6072 6073 // Do the same for the second half of the BuildVector 6074 ConstantSDNode *TopHalf = nullptr; 6075 for (int i = NumElems / 2; i < NumElems; ++i) { 6076 if (Cond->getOperand(i)->isUndef()) 6077 continue; 6078 6079 if (TopHalf == nullptr) 6080 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6081 else if (Cond->getOperand(i).getNode() != TopHalf) 6082 return SDValue(); 6083 } 6084 6085 assert(TopHalf && BottomHalf && 6086 "One half of the selector was all UNDEFs and the other was all the " 6087 "same value. This should have been addressed before this function."); 6088 return DAG.getNode( 6089 ISD::CONCAT_VECTORS, DL, VT, 6090 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6091 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6092 } 6093 6094 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6095 6096 if (Level >= AfterLegalizeTypes) 6097 return SDValue(); 6098 6099 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6100 SDValue Mask = MSC->getMask(); 6101 SDValue Data = MSC->getValue(); 6102 SDLoc DL(N); 6103 6104 // If the MSCATTER data type requires splitting and the mask is provided by a 6105 // SETCC, then split both nodes and its operands before legalization. This 6106 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6107 // and enables future optimizations (e.g. min/max pattern matching on X86). 6108 if (Mask.getOpcode() != ISD::SETCC) 6109 return SDValue(); 6110 6111 // Check if any splitting is required. 6112 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6113 TargetLowering::TypeSplitVector) 6114 return SDValue(); 6115 SDValue MaskLo, MaskHi, Lo, Hi; 6116 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6117 6118 EVT LoVT, HiVT; 6119 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6120 6121 SDValue Chain = MSC->getChain(); 6122 6123 EVT MemoryVT = MSC->getMemoryVT(); 6124 unsigned Alignment = MSC->getOriginalAlignment(); 6125 6126 EVT LoMemVT, HiMemVT; 6127 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6128 6129 SDValue DataLo, DataHi; 6130 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6131 6132 SDValue BasePtr = MSC->getBasePtr(); 6133 SDValue IndexLo, IndexHi; 6134 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6135 6136 MachineMemOperand *MMO = DAG.getMachineFunction(). 6137 getMachineMemOperand(MSC->getPointerInfo(), 6138 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6139 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6140 6141 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6142 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6143 DL, OpsLo, MMO); 6144 6145 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6146 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6147 DL, OpsHi, MMO); 6148 6149 AddToWorklist(Lo.getNode()); 6150 AddToWorklist(Hi.getNode()); 6151 6152 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6153 } 6154 6155 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6156 6157 if (Level >= AfterLegalizeTypes) 6158 return SDValue(); 6159 6160 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6161 SDValue Mask = MST->getMask(); 6162 SDValue Data = MST->getValue(); 6163 EVT VT = Data.getValueType(); 6164 SDLoc DL(N); 6165 6166 // If the MSTORE data type requires splitting and the mask is provided by a 6167 // SETCC, then split both nodes and its operands before legalization. This 6168 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6169 // and enables future optimizations (e.g. min/max pattern matching on X86). 6170 if (Mask.getOpcode() == ISD::SETCC) { 6171 6172 // Check if any splitting is required. 6173 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6174 TargetLowering::TypeSplitVector) 6175 return SDValue(); 6176 6177 SDValue MaskLo, MaskHi, Lo, Hi; 6178 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6179 6180 SDValue Chain = MST->getChain(); 6181 SDValue Ptr = MST->getBasePtr(); 6182 6183 EVT MemoryVT = MST->getMemoryVT(); 6184 unsigned Alignment = MST->getOriginalAlignment(); 6185 6186 // if Alignment is equal to the vector size, 6187 // take the half of it for the second part 6188 unsigned SecondHalfAlignment = 6189 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6190 6191 EVT LoMemVT, HiMemVT; 6192 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6193 6194 SDValue DataLo, DataHi; 6195 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6196 6197 MachineMemOperand *MMO = DAG.getMachineFunction(). 6198 getMachineMemOperand(MST->getPointerInfo(), 6199 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6200 Alignment, MST->getAAInfo(), MST->getRanges()); 6201 6202 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6203 MST->isTruncatingStore(), 6204 MST->isCompressingStore()); 6205 6206 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6207 MST->isCompressingStore()); 6208 6209 MMO = DAG.getMachineFunction(). 6210 getMachineMemOperand(MST->getPointerInfo(), 6211 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6212 SecondHalfAlignment, MST->getAAInfo(), 6213 MST->getRanges()); 6214 6215 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6216 MST->isTruncatingStore(), 6217 MST->isCompressingStore()); 6218 6219 AddToWorklist(Lo.getNode()); 6220 AddToWorklist(Hi.getNode()); 6221 6222 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6223 } 6224 return SDValue(); 6225 } 6226 6227 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6228 6229 if (Level >= AfterLegalizeTypes) 6230 return SDValue(); 6231 6232 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 6233 SDValue Mask = MGT->getMask(); 6234 SDLoc DL(N); 6235 6236 // If the MGATHER result requires splitting and the mask is provided by a 6237 // SETCC, then split both nodes and its operands before legalization. This 6238 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6239 // and enables future optimizations (e.g. min/max pattern matching on X86). 6240 6241 if (Mask.getOpcode() != ISD::SETCC) 6242 return SDValue(); 6243 6244 EVT VT = N->getValueType(0); 6245 6246 // Check if any splitting is required. 6247 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6248 TargetLowering::TypeSplitVector) 6249 return SDValue(); 6250 6251 SDValue MaskLo, MaskHi, Lo, Hi; 6252 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6253 6254 SDValue Src0 = MGT->getValue(); 6255 SDValue Src0Lo, Src0Hi; 6256 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6257 6258 EVT LoVT, HiVT; 6259 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6260 6261 SDValue Chain = MGT->getChain(); 6262 EVT MemoryVT = MGT->getMemoryVT(); 6263 unsigned Alignment = MGT->getOriginalAlignment(); 6264 6265 EVT LoMemVT, HiMemVT; 6266 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6267 6268 SDValue BasePtr = MGT->getBasePtr(); 6269 SDValue Index = MGT->getIndex(); 6270 SDValue IndexLo, IndexHi; 6271 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6272 6273 MachineMemOperand *MMO = DAG.getMachineFunction(). 6274 getMachineMemOperand(MGT->getPointerInfo(), 6275 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6276 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6277 6278 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6279 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6280 MMO); 6281 6282 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6283 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6284 MMO); 6285 6286 AddToWorklist(Lo.getNode()); 6287 AddToWorklist(Hi.getNode()); 6288 6289 // Build a factor node to remember that this load is independent of the 6290 // other one. 6291 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6292 Hi.getValue(1)); 6293 6294 // Legalized the chain result - switch anything that used the old chain to 6295 // use the new one. 6296 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6297 6298 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6299 6300 SDValue RetOps[] = { GatherRes, Chain }; 6301 return DAG.getMergeValues(RetOps, DL); 6302 } 6303 6304 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6305 6306 if (Level >= AfterLegalizeTypes) 6307 return SDValue(); 6308 6309 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6310 SDValue Mask = MLD->getMask(); 6311 SDLoc DL(N); 6312 6313 // If the MLOAD result requires splitting and the mask is provided by a 6314 // SETCC, then split both nodes and its operands before legalization. This 6315 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6316 // and enables future optimizations (e.g. min/max pattern matching on X86). 6317 6318 if (Mask.getOpcode() == ISD::SETCC) { 6319 EVT VT = N->getValueType(0); 6320 6321 // Check if any splitting is required. 6322 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6323 TargetLowering::TypeSplitVector) 6324 return SDValue(); 6325 6326 SDValue MaskLo, MaskHi, Lo, Hi; 6327 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6328 6329 SDValue Src0 = MLD->getSrc0(); 6330 SDValue Src0Lo, Src0Hi; 6331 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6332 6333 EVT LoVT, HiVT; 6334 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6335 6336 SDValue Chain = MLD->getChain(); 6337 SDValue Ptr = MLD->getBasePtr(); 6338 EVT MemoryVT = MLD->getMemoryVT(); 6339 unsigned Alignment = MLD->getOriginalAlignment(); 6340 6341 // if Alignment is equal to the vector size, 6342 // take the half of it for the second part 6343 unsigned SecondHalfAlignment = 6344 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6345 Alignment/2 : Alignment; 6346 6347 EVT LoMemVT, HiMemVT; 6348 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6349 6350 MachineMemOperand *MMO = DAG.getMachineFunction(). 6351 getMachineMemOperand(MLD->getPointerInfo(), 6352 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6353 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6354 6355 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6356 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6357 6358 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6359 MLD->isExpandingLoad()); 6360 6361 MMO = DAG.getMachineFunction(). 6362 getMachineMemOperand(MLD->getPointerInfo(), 6363 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6364 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6365 6366 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6367 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6368 6369 AddToWorklist(Lo.getNode()); 6370 AddToWorklist(Hi.getNode()); 6371 6372 // Build a factor node to remember that this load is independent of the 6373 // other one. 6374 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6375 Hi.getValue(1)); 6376 6377 // Legalized the chain result - switch anything that used the old chain to 6378 // use the new one. 6379 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6380 6381 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6382 6383 SDValue RetOps[] = { LoadRes, Chain }; 6384 return DAG.getMergeValues(RetOps, DL); 6385 } 6386 return SDValue(); 6387 } 6388 6389 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6390 SDValue N0 = N->getOperand(0); 6391 SDValue N1 = N->getOperand(1); 6392 SDValue N2 = N->getOperand(2); 6393 SDLoc DL(N); 6394 6395 // fold (vselect C, X, X) -> X 6396 if (N1 == N2) 6397 return N1; 6398 6399 // Canonicalize integer abs. 6400 // vselect (setg[te] X, 0), X, -X -> 6401 // vselect (setgt X, -1), X, -X -> 6402 // vselect (setl[te] X, 0), -X, X -> 6403 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6404 if (N0.getOpcode() == ISD::SETCC) { 6405 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6406 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6407 bool isAbs = false; 6408 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6409 6410 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6411 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6412 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6413 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6414 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6415 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6416 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6417 6418 if (isAbs) { 6419 EVT VT = LHS.getValueType(); 6420 SDValue Shift = DAG.getNode( 6421 ISD::SRA, DL, VT, LHS, 6422 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6423 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6424 AddToWorklist(Shift.getNode()); 6425 AddToWorklist(Add.getNode()); 6426 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6427 } 6428 } 6429 6430 if (SimplifySelectOps(N, N1, N2)) 6431 return SDValue(N, 0); // Don't revisit N. 6432 6433 // If the VSELECT result requires splitting and the mask is provided by a 6434 // SETCC, then split both nodes and its operands before legalization. This 6435 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6436 // and enables future optimizations (e.g. min/max pattern matching on X86). 6437 if (N0.getOpcode() == ISD::SETCC) { 6438 EVT VT = N->getValueType(0); 6439 6440 // Check if any splitting is required. 6441 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6442 TargetLowering::TypeSplitVector) 6443 return SDValue(); 6444 6445 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 6446 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 6447 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 6448 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 6449 6450 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 6451 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 6452 6453 // Add the new VSELECT nodes to the work list in case they need to be split 6454 // again. 6455 AddToWorklist(Lo.getNode()); 6456 AddToWorklist(Hi.getNode()); 6457 6458 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6459 } 6460 6461 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6462 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6463 return N1; 6464 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6465 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6466 return N2; 6467 6468 // The ConvertSelectToConcatVector function is assuming both the above 6469 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6470 // and addressed. 6471 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6472 N2.getOpcode() == ISD::CONCAT_VECTORS && 6473 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6474 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6475 return CV; 6476 } 6477 6478 return SDValue(); 6479 } 6480 6481 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6482 SDValue N0 = N->getOperand(0); 6483 SDValue N1 = N->getOperand(1); 6484 SDValue N2 = N->getOperand(2); 6485 SDValue N3 = N->getOperand(3); 6486 SDValue N4 = N->getOperand(4); 6487 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6488 6489 // fold select_cc lhs, rhs, x, x, cc -> x 6490 if (N2 == N3) 6491 return N2; 6492 6493 // Determine if the condition we're dealing with is constant 6494 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6495 CC, SDLoc(N), false)) { 6496 AddToWorklist(SCC.getNode()); 6497 6498 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6499 if (!SCCC->isNullValue()) 6500 return N2; // cond always true -> true val 6501 else 6502 return N3; // cond always false -> false val 6503 } else if (SCC->isUndef()) { 6504 // When the condition is UNDEF, just return the first operand. This is 6505 // coherent the DAG creation, no setcc node is created in this case 6506 return N2; 6507 } else if (SCC.getOpcode() == ISD::SETCC) { 6508 // Fold to a simpler select_cc 6509 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6510 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6511 SCC.getOperand(2)); 6512 } 6513 } 6514 6515 // If we can fold this based on the true/false value, do so. 6516 if (SimplifySelectOps(N, N2, N3)) 6517 return SDValue(N, 0); // Don't revisit N. 6518 6519 // fold select_cc into other things, such as min/max/abs 6520 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6521 } 6522 6523 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6524 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6525 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6526 SDLoc(N)); 6527 } 6528 6529 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6530 SDValue LHS = N->getOperand(0); 6531 SDValue RHS = N->getOperand(1); 6532 SDValue Carry = N->getOperand(2); 6533 SDValue Cond = N->getOperand(3); 6534 6535 // If Carry is false, fold to a regular SETCC. 6536 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6537 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6538 6539 return SDValue(); 6540 } 6541 6542 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6543 /// a build_vector of constants. 6544 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6545 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6546 /// Vector extends are not folded if operations are legal; this is to 6547 /// avoid introducing illegal build_vector dag nodes. 6548 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6549 SelectionDAG &DAG, bool LegalTypes, 6550 bool LegalOperations) { 6551 unsigned Opcode = N->getOpcode(); 6552 SDValue N0 = N->getOperand(0); 6553 EVT VT = N->getValueType(0); 6554 6555 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6556 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6557 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6558 && "Expected EXTEND dag node in input!"); 6559 6560 // fold (sext c1) -> c1 6561 // fold (zext c1) -> c1 6562 // fold (aext c1) -> c1 6563 if (isa<ConstantSDNode>(N0)) 6564 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6565 6566 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6567 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6568 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6569 EVT SVT = VT.getScalarType(); 6570 if (!(VT.isVector() && 6571 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6572 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6573 return nullptr; 6574 6575 // We can fold this node into a build_vector. 6576 unsigned VTBits = SVT.getSizeInBits(); 6577 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6578 SmallVector<SDValue, 8> Elts; 6579 unsigned NumElts = VT.getVectorNumElements(); 6580 SDLoc DL(N); 6581 6582 for (unsigned i=0; i != NumElts; ++i) { 6583 SDValue Op = N0->getOperand(i); 6584 if (Op->isUndef()) { 6585 Elts.push_back(DAG.getUNDEF(SVT)); 6586 continue; 6587 } 6588 6589 SDLoc DL(Op); 6590 // Get the constant value and if needed trunc it to the size of the type. 6591 // Nodes like build_vector might have constants wider than the scalar type. 6592 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6593 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6594 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6595 else 6596 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6597 } 6598 6599 return DAG.getBuildVector(VT, DL, Elts).getNode(); 6600 } 6601 6602 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 6603 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 6604 // transformation. Returns true if extension are possible and the above 6605 // mentioned transformation is profitable. 6606 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 6607 unsigned ExtOpc, 6608 SmallVectorImpl<SDNode *> &ExtendNodes, 6609 const TargetLowering &TLI) { 6610 bool HasCopyToRegUses = false; 6611 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 6612 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 6613 UE = N0.getNode()->use_end(); 6614 UI != UE; ++UI) { 6615 SDNode *User = *UI; 6616 if (User == N) 6617 continue; 6618 if (UI.getUse().getResNo() != N0.getResNo()) 6619 continue; 6620 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6621 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6622 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6623 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6624 // Sign bits will be lost after a zext. 6625 return false; 6626 bool Add = false; 6627 for (unsigned i = 0; i != 2; ++i) { 6628 SDValue UseOp = User->getOperand(i); 6629 if (UseOp == N0) 6630 continue; 6631 if (!isa<ConstantSDNode>(UseOp)) 6632 return false; 6633 Add = true; 6634 } 6635 if (Add) 6636 ExtendNodes.push_back(User); 6637 continue; 6638 } 6639 // If truncates aren't free and there are users we can't 6640 // extend, it isn't worthwhile. 6641 if (!isTruncFree) 6642 return false; 6643 // Remember if this value is live-out. 6644 if (User->getOpcode() == ISD::CopyToReg) 6645 HasCopyToRegUses = true; 6646 } 6647 6648 if (HasCopyToRegUses) { 6649 bool BothLiveOut = false; 6650 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6651 UI != UE; ++UI) { 6652 SDUse &Use = UI.getUse(); 6653 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6654 BothLiveOut = true; 6655 break; 6656 } 6657 } 6658 if (BothLiveOut) 6659 // Both unextended and extended values are live out. There had better be 6660 // a good reason for the transformation. 6661 return ExtendNodes.size(); 6662 } 6663 return true; 6664 } 6665 6666 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 6667 SDValue Trunc, SDValue ExtLoad, 6668 const SDLoc &DL, ISD::NodeType ExtType) { 6669 // Extend SetCC uses if necessary. 6670 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 6671 SDNode *SetCC = SetCCs[i]; 6672 SmallVector<SDValue, 4> Ops; 6673 6674 for (unsigned j = 0; j != 2; ++j) { 6675 SDValue SOp = SetCC->getOperand(j); 6676 if (SOp == Trunc) 6677 Ops.push_back(ExtLoad); 6678 else 6679 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 6680 } 6681 6682 Ops.push_back(SetCC->getOperand(2)); 6683 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6684 } 6685 } 6686 6687 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 6688 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 6689 SDValue N0 = N->getOperand(0); 6690 EVT DstVT = N->getValueType(0); 6691 EVT SrcVT = N0.getValueType(); 6692 6693 assert((N->getOpcode() == ISD::SIGN_EXTEND || 6694 N->getOpcode() == ISD::ZERO_EXTEND) && 6695 "Unexpected node type (not an extend)!"); 6696 6697 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 6698 // For example, on a target with legal v4i32, but illegal v8i32, turn: 6699 // (v8i32 (sext (v8i16 (load x)))) 6700 // into: 6701 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6702 // (v4i32 (sextload (x + 16))))) 6703 // Where uses of the original load, i.e.: 6704 // (v8i16 (load x)) 6705 // are replaced with: 6706 // (v8i16 (truncate 6707 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6708 // (v4i32 (sextload (x + 16))))))) 6709 // 6710 // This combine is only applicable to illegal, but splittable, vectors. 6711 // All legal types, and illegal non-vector types, are handled elsewhere. 6712 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 6713 // 6714 if (N0->getOpcode() != ISD::LOAD) 6715 return SDValue(); 6716 6717 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6718 6719 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 6720 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 6721 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 6722 return SDValue(); 6723 6724 SmallVector<SDNode *, 4> SetCCs; 6725 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 6726 return SDValue(); 6727 6728 ISD::LoadExtType ExtType = 6729 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 6730 6731 // Try to split the vector types to get down to legal types. 6732 EVT SplitSrcVT = SrcVT; 6733 EVT SplitDstVT = DstVT; 6734 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 6735 SplitSrcVT.getVectorNumElements() > 1) { 6736 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 6737 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 6738 } 6739 6740 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 6741 return SDValue(); 6742 6743 SDLoc DL(N); 6744 const unsigned NumSplits = 6745 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 6746 const unsigned Stride = SplitSrcVT.getStoreSize(); 6747 SmallVector<SDValue, 4> Loads; 6748 SmallVector<SDValue, 4> Chains; 6749 6750 SDValue BasePtr = LN0->getBasePtr(); 6751 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6752 const unsigned Offset = Idx * Stride; 6753 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 6754 6755 SDValue SplitLoad = DAG.getExtLoad( 6756 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 6757 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 6758 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6759 6760 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6761 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6762 6763 Loads.push_back(SplitLoad.getValue(0)); 6764 Chains.push_back(SplitLoad.getValue(1)); 6765 } 6766 6767 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6768 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6769 6770 // Simplify TF. 6771 AddToWorklist(NewChain.getNode()); 6772 6773 CombineTo(N, NewValue); 6774 6775 // Replace uses of the original load (before extension) 6776 // with a truncate of the concatenated sextloaded vectors. 6777 SDValue Trunc = 6778 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6779 CombineTo(N0.getNode(), Trunc, NewChain); 6780 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6781 (ISD::NodeType)N->getOpcode()); 6782 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6783 } 6784 6785 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6786 SDValue N0 = N->getOperand(0); 6787 EVT VT = N->getValueType(0); 6788 SDLoc DL(N); 6789 6790 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6791 LegalOperations)) 6792 return SDValue(Res, 0); 6793 6794 // fold (sext (sext x)) -> (sext x) 6795 // fold (sext (aext x)) -> (sext x) 6796 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6797 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 6798 6799 if (N0.getOpcode() == ISD::TRUNCATE) { 6800 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6801 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6802 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6803 SDNode *oye = N0.getOperand(0).getNode(); 6804 if (NarrowLoad.getNode() != N0.getNode()) { 6805 CombineTo(N0.getNode(), NarrowLoad); 6806 // CombineTo deleted the truncate, if needed, but not what's under it. 6807 AddToWorklist(oye); 6808 } 6809 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6810 } 6811 6812 // See if the value being truncated is already sign extended. If so, just 6813 // eliminate the trunc/sext pair. 6814 SDValue Op = N0.getOperand(0); 6815 unsigned OpBits = Op.getScalarValueSizeInBits(); 6816 unsigned MidBits = N0.getScalarValueSizeInBits(); 6817 unsigned DestBits = VT.getScalarSizeInBits(); 6818 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6819 6820 if (OpBits == DestBits) { 6821 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6822 // bits, it is already ready. 6823 if (NumSignBits > DestBits-MidBits) 6824 return Op; 6825 } else if (OpBits < DestBits) { 6826 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6827 // bits, just sext from i32. 6828 if (NumSignBits > OpBits-MidBits) 6829 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 6830 } else { 6831 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6832 // bits, just truncate to i32. 6833 if (NumSignBits > OpBits-MidBits) 6834 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 6835 } 6836 6837 // fold (sext (truncate x)) -> (sextinreg x). 6838 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6839 N0.getValueType())) { 6840 if (OpBits < DestBits) 6841 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6842 else if (OpBits > DestBits) 6843 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6844 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 6845 DAG.getValueType(N0.getValueType())); 6846 } 6847 } 6848 6849 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6850 // Only generate vector extloads when 1) they're legal, and 2) they are 6851 // deemed desirable by the target. 6852 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6853 ((!LegalOperations && !VT.isVector() && 6854 !cast<LoadSDNode>(N0)->isVolatile()) || 6855 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6856 bool DoXform = true; 6857 SmallVector<SDNode*, 4> SetCCs; 6858 if (!N0.hasOneUse()) 6859 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6860 if (VT.isVector()) 6861 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6862 if (DoXform) { 6863 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6864 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 6865 LN0->getBasePtr(), N0.getValueType(), 6866 LN0->getMemOperand()); 6867 CombineTo(N, ExtLoad); 6868 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6869 N0.getValueType(), ExtLoad); 6870 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6871 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 6872 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6873 } 6874 } 6875 6876 // fold (sext (load x)) to multiple smaller sextloads. 6877 // Only on illegal but splittable vectors. 6878 if (SDValue ExtLoad = CombineExtLoad(N)) 6879 return ExtLoad; 6880 6881 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6882 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6883 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6884 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6885 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6886 EVT MemVT = LN0->getMemoryVT(); 6887 if ((!LegalOperations && !LN0->isVolatile()) || 6888 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6889 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 6890 LN0->getBasePtr(), MemVT, 6891 LN0->getMemOperand()); 6892 CombineTo(N, ExtLoad); 6893 CombineTo(N0.getNode(), 6894 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6895 N0.getValueType(), ExtLoad), 6896 ExtLoad.getValue(1)); 6897 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6898 } 6899 } 6900 6901 // fold (sext (and/or/xor (load x), cst)) -> 6902 // (and/or/xor (sextload x), (sext cst)) 6903 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6904 N0.getOpcode() == ISD::XOR) && 6905 isa<LoadSDNode>(N0.getOperand(0)) && 6906 N0.getOperand(1).getOpcode() == ISD::Constant && 6907 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6908 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6909 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6910 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6911 bool DoXform = true; 6912 SmallVector<SDNode*, 4> SetCCs; 6913 if (!N0.hasOneUse()) 6914 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6915 SetCCs, TLI); 6916 if (DoXform) { 6917 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6918 LN0->getChain(), LN0->getBasePtr(), 6919 LN0->getMemoryVT(), 6920 LN0->getMemOperand()); 6921 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6922 Mask = Mask.sext(VT.getSizeInBits()); 6923 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6924 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6925 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6926 SDLoc(N0.getOperand(0)), 6927 N0.getOperand(0).getValueType(), ExtLoad); 6928 CombineTo(N, And); 6929 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6930 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 6931 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6932 } 6933 } 6934 } 6935 6936 if (N0.getOpcode() == ISD::SETCC) { 6937 SDValue N00 = N0.getOperand(0); 6938 SDValue N01 = N0.getOperand(1); 6939 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6940 EVT N00VT = N0.getOperand(0).getValueType(); 6941 6942 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6943 // Only do this before legalize for now. 6944 if (VT.isVector() && !LegalOperations && 6945 TLI.getBooleanContents(N00VT) == 6946 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6947 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6948 // of the same size as the compared operands. Only optimize sext(setcc()) 6949 // if this is the case. 6950 EVT SVT = getSetCCResultType(N00VT); 6951 6952 // We know that the # elements of the results is the same as the 6953 // # elements of the compare (and the # elements of the compare result 6954 // for that matter). Check to see that they are the same size. If so, 6955 // we know that the element size of the sext'd result matches the 6956 // element size of the compare operands. 6957 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6958 return DAG.getSetCC(DL, VT, N00, N01, CC); 6959 6960 // If the desired elements are smaller or larger than the source 6961 // elements, we can use a matching integer vector type and then 6962 // truncate/sign extend. 6963 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 6964 if (SVT == MatchingVecType) { 6965 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 6966 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 6967 } 6968 } 6969 6970 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 6971 // Here, T can be 1 or -1, depending on the type of the setcc and 6972 // getBooleanContents(). 6973 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 6974 6975 // To determine the "true" side of the select, we need to know the high bit 6976 // of the value returned by the setcc if it evaluates to true. 6977 // If the type of the setcc is i1, then the true case of the select is just 6978 // sext(i1 1), that is, -1. 6979 // If the type of the setcc is larger (say, i8) then the value of the high 6980 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 6981 // of the appropriate width. 6982 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 6983 : TLI.getConstTrueVal(DAG, VT, DL); 6984 SDValue Zero = DAG.getConstant(0, DL, VT); 6985 if (SDValue SCC = 6986 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 6987 return SCC; 6988 6989 if (!VT.isVector()) { 6990 EVT SetCCVT = getSetCCResultType(N00VT); 6991 // Don't do this transform for i1 because there's a select transform 6992 // that would reverse it. 6993 // TODO: We should not do this transform at all without a target hook 6994 // because a sext is likely cheaper than a select? 6995 if (SetCCVT.getScalarSizeInBits() != 1 && 6996 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 6997 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 6998 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 6999 } 7000 } 7001 } 7002 7003 // fold (sext x) -> (zext x) if the sign bit is known zero. 7004 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7005 DAG.SignBitIsZero(N0)) 7006 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7007 7008 return SDValue(); 7009 } 7010 7011 // isTruncateOf - If N is a truncate of some other value, return true, record 7012 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 7013 // This function computes KnownZero to avoid a duplicated call to 7014 // computeKnownBits in the caller. 7015 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7016 APInt &KnownZero) { 7017 APInt KnownOne; 7018 if (N->getOpcode() == ISD::TRUNCATE) { 7019 Op = N->getOperand(0); 7020 DAG.computeKnownBits(Op, KnownZero, KnownOne); 7021 return true; 7022 } 7023 7024 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7025 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7026 return false; 7027 7028 SDValue Op0 = N->getOperand(0); 7029 SDValue Op1 = N->getOperand(1); 7030 assert(Op0.getValueType() == Op1.getValueType()); 7031 7032 if (isNullConstant(Op0)) 7033 Op = Op1; 7034 else if (isNullConstant(Op1)) 7035 Op = Op0; 7036 else 7037 return false; 7038 7039 DAG.computeKnownBits(Op, KnownZero, KnownOne); 7040 7041 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 7042 return false; 7043 7044 return true; 7045 } 7046 7047 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7048 SDValue N0 = N->getOperand(0); 7049 EVT VT = N->getValueType(0); 7050 7051 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7052 LegalOperations)) 7053 return SDValue(Res, 0); 7054 7055 // fold (zext (zext x)) -> (zext x) 7056 // fold (zext (aext x)) -> (zext x) 7057 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7058 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7059 N0.getOperand(0)); 7060 7061 // fold (zext (truncate x)) -> (zext x) or 7062 // (zext (truncate x)) -> (truncate x) 7063 // This is valid when the truncated bits of x are already zero. 7064 // FIXME: We should extend this to work for vectors too. 7065 SDValue Op; 7066 APInt KnownZero; 7067 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 7068 APInt TruncatedBits = 7069 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7070 APInt(Op.getValueSizeInBits(), 0) : 7071 APInt::getBitsSet(Op.getValueSizeInBits(), 7072 N0.getValueSizeInBits(), 7073 std::min(Op.getValueSizeInBits(), 7074 VT.getSizeInBits())); 7075 if (TruncatedBits == (KnownZero & TruncatedBits)) { 7076 if (VT.bitsGT(Op.getValueType())) 7077 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 7078 if (VT.bitsLT(Op.getValueType())) 7079 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 7080 7081 return Op; 7082 } 7083 } 7084 7085 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7086 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 7087 if (N0.getOpcode() == ISD::TRUNCATE) { 7088 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7089 SDNode *oye = N0.getOperand(0).getNode(); 7090 if (NarrowLoad.getNode() != N0.getNode()) { 7091 CombineTo(N0.getNode(), NarrowLoad); 7092 // CombineTo deleted the truncate, if needed, but not what's under it. 7093 AddToWorklist(oye); 7094 } 7095 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7096 } 7097 } 7098 7099 // fold (zext (truncate x)) -> (and x, mask) 7100 if (N0.getOpcode() == ISD::TRUNCATE) { 7101 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7102 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7103 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7104 SDNode *oye = N0.getOperand(0).getNode(); 7105 if (NarrowLoad.getNode() != N0.getNode()) { 7106 CombineTo(N0.getNode(), NarrowLoad); 7107 // CombineTo deleted the truncate, if needed, but not what's under it. 7108 AddToWorklist(oye); 7109 } 7110 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7111 } 7112 7113 EVT SrcVT = N0.getOperand(0).getValueType(); 7114 EVT MinVT = N0.getValueType(); 7115 7116 // Try to mask before the extension to avoid having to generate a larger mask, 7117 // possibly over several sub-vectors. 7118 if (SrcVT.bitsLT(VT)) { 7119 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7120 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7121 SDValue Op = N0.getOperand(0); 7122 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7123 AddToWorklist(Op.getNode()); 7124 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7125 } 7126 } 7127 7128 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7129 SDValue Op = N0.getOperand(0); 7130 if (SrcVT.bitsLT(VT)) { 7131 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 7132 AddToWorklist(Op.getNode()); 7133 } else if (SrcVT.bitsGT(VT)) { 7134 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 7135 AddToWorklist(Op.getNode()); 7136 } 7137 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7138 } 7139 } 7140 7141 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7142 // if either of the casts is not free. 7143 if (N0.getOpcode() == ISD::AND && 7144 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7145 N0.getOperand(1).getOpcode() == ISD::Constant && 7146 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7147 N0.getValueType()) || 7148 !TLI.isZExtFree(N0.getValueType(), VT))) { 7149 SDValue X = N0.getOperand(0).getOperand(0); 7150 if (X.getValueType().bitsLT(VT)) { 7151 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 7152 } else if (X.getValueType().bitsGT(VT)) { 7153 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7154 } 7155 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7156 Mask = Mask.zext(VT.getSizeInBits()); 7157 SDLoc DL(N); 7158 return DAG.getNode(ISD::AND, DL, VT, 7159 X, DAG.getConstant(Mask, DL, VT)); 7160 } 7161 7162 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7163 // Only generate vector extloads when 1) they're legal, and 2) they are 7164 // deemed desirable by the target. 7165 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7166 ((!LegalOperations && !VT.isVector() && 7167 !cast<LoadSDNode>(N0)->isVolatile()) || 7168 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7169 bool DoXform = true; 7170 SmallVector<SDNode*, 4> SetCCs; 7171 if (!N0.hasOneUse()) 7172 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7173 if (VT.isVector()) 7174 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7175 if (DoXform) { 7176 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7177 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7178 LN0->getChain(), 7179 LN0->getBasePtr(), N0.getValueType(), 7180 LN0->getMemOperand()); 7181 CombineTo(N, ExtLoad); 7182 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7183 N0.getValueType(), ExtLoad); 7184 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7185 7186 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7187 ISD::ZERO_EXTEND); 7188 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7189 } 7190 } 7191 7192 // fold (zext (load x)) to multiple smaller zextloads. 7193 // Only on illegal but splittable vectors. 7194 if (SDValue ExtLoad = CombineExtLoad(N)) 7195 return ExtLoad; 7196 7197 // fold (zext (and/or/xor (load x), cst)) -> 7198 // (and/or/xor (zextload x), (zext cst)) 7199 // Unless (and (load x) cst) will match as a zextload already and has 7200 // additional users. 7201 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7202 N0.getOpcode() == ISD::XOR) && 7203 isa<LoadSDNode>(N0.getOperand(0)) && 7204 N0.getOperand(1).getOpcode() == ISD::Constant && 7205 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7206 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7207 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7208 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7209 bool DoXform = true; 7210 SmallVector<SDNode*, 4> SetCCs; 7211 if (!N0.hasOneUse()) { 7212 if (N0.getOpcode() == ISD::AND) { 7213 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7214 auto NarrowLoad = false; 7215 EVT LoadResultTy = AndC->getValueType(0); 7216 EVT ExtVT, LoadedVT; 7217 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7218 NarrowLoad)) 7219 DoXform = false; 7220 } 7221 if (DoXform) 7222 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7223 ISD::ZERO_EXTEND, SetCCs, TLI); 7224 } 7225 if (DoXform) { 7226 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7227 LN0->getChain(), LN0->getBasePtr(), 7228 LN0->getMemoryVT(), 7229 LN0->getMemOperand()); 7230 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7231 Mask = Mask.zext(VT.getSizeInBits()); 7232 SDLoc DL(N); 7233 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7234 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7235 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7236 SDLoc(N0.getOperand(0)), 7237 N0.getOperand(0).getValueType(), ExtLoad); 7238 CombineTo(N, And); 7239 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7240 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 7241 ISD::ZERO_EXTEND); 7242 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7243 } 7244 } 7245 } 7246 7247 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7248 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7249 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7250 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7251 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7252 EVT MemVT = LN0->getMemoryVT(); 7253 if ((!LegalOperations && !LN0->isVolatile()) || 7254 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7255 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7256 LN0->getChain(), 7257 LN0->getBasePtr(), MemVT, 7258 LN0->getMemOperand()); 7259 CombineTo(N, ExtLoad); 7260 CombineTo(N0.getNode(), 7261 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7262 ExtLoad), 7263 ExtLoad.getValue(1)); 7264 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7265 } 7266 } 7267 7268 if (N0.getOpcode() == ISD::SETCC) { 7269 // Only do this before legalize for now. 7270 if (!LegalOperations && VT.isVector() && 7271 N0.getValueType().getVectorElementType() == MVT::i1) { 7272 EVT N00VT = N0.getOperand(0).getValueType(); 7273 if (getSetCCResultType(N00VT) == N0.getValueType()) 7274 return SDValue(); 7275 7276 // We know that the # elements of the results is the same as the # 7277 // elements of the compare (and the # elements of the compare result for 7278 // that matter). Check to see that they are the same size. If so, we know 7279 // that the element size of the sext'd result matches the element size of 7280 // the compare operands. 7281 SDLoc DL(N); 7282 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7283 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7284 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7285 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7286 N0.getOperand(1), N0.getOperand(2)); 7287 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7288 } 7289 7290 // If the desired elements are smaller or larger than the source 7291 // elements we can use a matching integer vector type and then 7292 // truncate/sign extend. 7293 EVT MatchingElementType = EVT::getIntegerVT( 7294 *DAG.getContext(), N00VT.getScalarSizeInBits()); 7295 EVT MatchingVectorType = EVT::getVectorVT( 7296 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 7297 SDValue VsetCC = 7298 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7299 N0.getOperand(1), N0.getOperand(2)); 7300 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7301 VecOnes); 7302 } 7303 7304 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7305 SDLoc DL(N); 7306 if (SDValue SCC = SimplifySelectCC( 7307 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7308 DAG.getConstant(0, DL, VT), 7309 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7310 return SCC; 7311 } 7312 7313 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7314 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7315 isa<ConstantSDNode>(N0.getOperand(1)) && 7316 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7317 N0.hasOneUse()) { 7318 SDValue ShAmt = N0.getOperand(1); 7319 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7320 if (N0.getOpcode() == ISD::SHL) { 7321 SDValue InnerZExt = N0.getOperand(0); 7322 // If the original shl may be shifting out bits, do not perform this 7323 // transformation. 7324 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7325 InnerZExt.getOperand(0).getValueSizeInBits(); 7326 if (ShAmtVal > KnownZeroBits) 7327 return SDValue(); 7328 } 7329 7330 SDLoc DL(N); 7331 7332 // Ensure that the shift amount is wide enough for the shifted value. 7333 if (VT.getSizeInBits() >= 256) 7334 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7335 7336 return DAG.getNode(N0.getOpcode(), DL, VT, 7337 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7338 ShAmt); 7339 } 7340 7341 return SDValue(); 7342 } 7343 7344 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7345 SDValue N0 = N->getOperand(0); 7346 EVT VT = N->getValueType(0); 7347 7348 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7349 LegalOperations)) 7350 return SDValue(Res, 0); 7351 7352 // fold (aext (aext x)) -> (aext x) 7353 // fold (aext (zext x)) -> (zext x) 7354 // fold (aext (sext x)) -> (sext x) 7355 if (N0.getOpcode() == ISD::ANY_EXTEND || 7356 N0.getOpcode() == ISD::ZERO_EXTEND || 7357 N0.getOpcode() == ISD::SIGN_EXTEND) 7358 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7359 7360 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7361 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7362 if (N0.getOpcode() == ISD::TRUNCATE) { 7363 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7364 SDNode *oye = N0.getOperand(0).getNode(); 7365 if (NarrowLoad.getNode() != N0.getNode()) { 7366 CombineTo(N0.getNode(), NarrowLoad); 7367 // CombineTo deleted the truncate, if needed, but not what's under it. 7368 AddToWorklist(oye); 7369 } 7370 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7371 } 7372 } 7373 7374 // fold (aext (truncate x)) 7375 if (N0.getOpcode() == ISD::TRUNCATE) { 7376 SDValue TruncOp = N0.getOperand(0); 7377 if (TruncOp.getValueType() == VT) 7378 return TruncOp; // x iff x size == zext size. 7379 if (TruncOp.getValueType().bitsGT(VT)) 7380 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 7381 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 7382 } 7383 7384 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7385 // if the trunc is not free. 7386 if (N0.getOpcode() == ISD::AND && 7387 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7388 N0.getOperand(1).getOpcode() == ISD::Constant && 7389 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7390 N0.getValueType())) { 7391 SDLoc DL(N); 7392 SDValue X = N0.getOperand(0).getOperand(0); 7393 if (X.getValueType().bitsLT(VT)) { 7394 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); 7395 } else if (X.getValueType().bitsGT(VT)) { 7396 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X); 7397 } 7398 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7399 Mask = Mask.zext(VT.getSizeInBits()); 7400 return DAG.getNode(ISD::AND, DL, VT, 7401 X, DAG.getConstant(Mask, DL, VT)); 7402 } 7403 7404 // fold (aext (load x)) -> (aext (truncate (extload x))) 7405 // None of the supported targets knows how to perform load and any_ext 7406 // on vectors in one instruction. We only perform this transformation on 7407 // scalars. 7408 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7409 ISD::isUNINDEXEDLoad(N0.getNode()) && 7410 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7411 bool DoXform = true; 7412 SmallVector<SDNode*, 4> SetCCs; 7413 if (!N0.hasOneUse()) 7414 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7415 if (DoXform) { 7416 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7417 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7418 LN0->getChain(), 7419 LN0->getBasePtr(), N0.getValueType(), 7420 LN0->getMemOperand()); 7421 CombineTo(N, ExtLoad); 7422 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7423 N0.getValueType(), ExtLoad); 7424 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7425 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7426 ISD::ANY_EXTEND); 7427 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7428 } 7429 } 7430 7431 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7432 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7433 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7434 if (N0.getOpcode() == ISD::LOAD && 7435 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7436 N0.hasOneUse()) { 7437 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7438 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7439 EVT MemVT = LN0->getMemoryVT(); 7440 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7441 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7442 VT, LN0->getChain(), LN0->getBasePtr(), 7443 MemVT, LN0->getMemOperand()); 7444 CombineTo(N, ExtLoad); 7445 CombineTo(N0.getNode(), 7446 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7447 N0.getValueType(), ExtLoad), 7448 ExtLoad.getValue(1)); 7449 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7450 } 7451 } 7452 7453 if (N0.getOpcode() == ISD::SETCC) { 7454 // For vectors: 7455 // aext(setcc) -> vsetcc 7456 // aext(setcc) -> truncate(vsetcc) 7457 // aext(setcc) -> aext(vsetcc) 7458 // Only do this before legalize for now. 7459 if (VT.isVector() && !LegalOperations) { 7460 EVT N0VT = N0.getOperand(0).getValueType(); 7461 // We know that the # elements of the results is the same as the 7462 // # elements of the compare (and the # elements of the compare result 7463 // for that matter). Check to see that they are the same size. If so, 7464 // we know that the element size of the sext'd result matches the 7465 // element size of the compare operands. 7466 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 7467 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7468 N0.getOperand(1), 7469 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7470 // If the desired elements are smaller or larger than the source 7471 // elements we can use a matching integer vector type and then 7472 // truncate/any extend 7473 else { 7474 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 7475 SDValue VsetCC = 7476 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7477 N0.getOperand(1), 7478 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7479 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7480 } 7481 } 7482 7483 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7484 SDLoc DL(N); 7485 if (SDValue SCC = SimplifySelectCC( 7486 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7487 DAG.getConstant(0, DL, VT), 7488 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7489 return SCC; 7490 } 7491 7492 return SDValue(); 7493 } 7494 7495 SDValue DAGCombiner::visitAssertZext(SDNode *N) { 7496 SDValue N0 = N->getOperand(0); 7497 SDValue N1 = N->getOperand(1); 7498 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7499 7500 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt) 7501 if (N0.getOpcode() == ISD::AssertZext && 7502 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7503 return N0; 7504 7505 return SDValue(); 7506 } 7507 7508 /// See if the specified operand can be simplified with the knowledge that only 7509 /// the bits specified by Mask are used. If so, return the simpler operand, 7510 /// otherwise return a null SDValue. 7511 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 7512 switch (V.getOpcode()) { 7513 default: break; 7514 case ISD::Constant: { 7515 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 7516 assert(CV && "Const value should be ConstSDNode."); 7517 const APInt &CVal = CV->getAPIntValue(); 7518 APInt NewVal = CVal & Mask; 7519 if (NewVal != CVal) 7520 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 7521 break; 7522 } 7523 case ISD::OR: 7524 case ISD::XOR: 7525 // If the LHS or RHS don't contribute bits to the or, drop them. 7526 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 7527 return V.getOperand(1); 7528 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 7529 return V.getOperand(0); 7530 break; 7531 case ISD::SRL: 7532 // Only look at single-use SRLs. 7533 if (!V.getNode()->hasOneUse()) 7534 break; 7535 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 7536 // See if we can recursively simplify the LHS. 7537 unsigned Amt = RHSC->getZExtValue(); 7538 7539 // Watch out for shift count overflow though. 7540 if (Amt >= Mask.getBitWidth()) break; 7541 APInt NewMask = Mask << Amt; 7542 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 7543 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 7544 SimplifyLHS, V.getOperand(1)); 7545 } 7546 } 7547 return SDValue(); 7548 } 7549 7550 /// If the result of a wider load is shifted to right of N bits and then 7551 /// truncated to a narrower type and where N is a multiple of number of bits of 7552 /// the narrower type, transform it to a narrower load from address + N / num of 7553 /// bits of new type. If the result is to be extended, also fold the extension 7554 /// to form a extending load. 7555 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7556 unsigned Opc = N->getOpcode(); 7557 7558 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7559 SDValue N0 = N->getOperand(0); 7560 EVT VT = N->getValueType(0); 7561 EVT ExtVT = VT; 7562 7563 // This transformation isn't valid for vector loads. 7564 if (VT.isVector()) 7565 return SDValue(); 7566 7567 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7568 // extended to VT. 7569 if (Opc == ISD::SIGN_EXTEND_INREG) { 7570 ExtType = ISD::SEXTLOAD; 7571 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7572 } else if (Opc == ISD::SRL) { 7573 // Another special-case: SRL is basically zero-extending a narrower value. 7574 ExtType = ISD::ZEXTLOAD; 7575 N0 = SDValue(N, 0); 7576 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7577 if (!N01) return SDValue(); 7578 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 7579 VT.getSizeInBits() - N01->getZExtValue()); 7580 } 7581 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 7582 return SDValue(); 7583 7584 unsigned EVTBits = ExtVT.getSizeInBits(); 7585 7586 // Do not generate loads of non-round integer types since these can 7587 // be expensive (and would be wrong if the type is not byte sized). 7588 if (!ExtVT.isRound()) 7589 return SDValue(); 7590 7591 unsigned ShAmt = 0; 7592 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 7593 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7594 ShAmt = N01->getZExtValue(); 7595 // Is the shift amount a multiple of size of VT? 7596 if ((ShAmt & (EVTBits-1)) == 0) { 7597 N0 = N0.getOperand(0); 7598 // Is the load width a multiple of size of VT? 7599 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 7600 return SDValue(); 7601 } 7602 7603 // At this point, we must have a load or else we can't do the transform. 7604 if (!isa<LoadSDNode>(N0)) return SDValue(); 7605 7606 // Because a SRL must be assumed to *need* to zero-extend the high bits 7607 // (as opposed to anyext the high bits), we can't combine the zextload 7608 // lowering of SRL and an sextload. 7609 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 7610 return SDValue(); 7611 7612 // If the shift amount is larger than the input type then we're not 7613 // accessing any of the loaded bytes. If the load was a zextload/extload 7614 // then the result of the shift+trunc is zero/undef (handled elsewhere). 7615 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 7616 return SDValue(); 7617 } 7618 } 7619 7620 // If the load is shifted left (and the result isn't shifted back right), 7621 // we can fold the truncate through the shift. 7622 unsigned ShLeftAmt = 0; 7623 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7624 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 7625 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7626 ShLeftAmt = N01->getZExtValue(); 7627 N0 = N0.getOperand(0); 7628 } 7629 } 7630 7631 // If we haven't found a load, we can't narrow it. Don't transform one with 7632 // multiple uses, this would require adding a new load. 7633 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 7634 return SDValue(); 7635 7636 // Don't change the width of a volatile load. 7637 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7638 if (LN0->isVolatile()) 7639 return SDValue(); 7640 7641 // Verify that we are actually reducing a load width here. 7642 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 7643 return SDValue(); 7644 7645 // For the transform to be legal, the load must produce only two values 7646 // (the value loaded and the chain). Don't transform a pre-increment 7647 // load, for example, which produces an extra value. Otherwise the 7648 // transformation is not equivalent, and the downstream logic to replace 7649 // uses gets things wrong. 7650 if (LN0->getNumValues() > 2) 7651 return SDValue(); 7652 7653 // If the load that we're shrinking is an extload and we're not just 7654 // discarding the extension we can't simply shrink the load. Bail. 7655 // TODO: It would be possible to merge the extensions in some cases. 7656 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 7657 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 7658 return SDValue(); 7659 7660 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 7661 return SDValue(); 7662 7663 EVT PtrType = N0.getOperand(1).getValueType(); 7664 7665 if (PtrType == MVT::Untyped || PtrType.isExtended()) 7666 // It's not possible to generate a constant of extended or untyped type. 7667 return SDValue(); 7668 7669 // For big endian targets, we need to adjust the offset to the pointer to 7670 // load the correct bytes. 7671 if (DAG.getDataLayout().isBigEndian()) { 7672 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 7673 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 7674 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 7675 } 7676 7677 uint64_t PtrOff = ShAmt / 8; 7678 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 7679 SDLoc DL(LN0); 7680 // The original load itself didn't wrap, so an offset within it doesn't. 7681 SDNodeFlags Flags; 7682 Flags.setNoUnsignedWrap(true); 7683 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 7684 PtrType, LN0->getBasePtr(), 7685 DAG.getConstant(PtrOff, DL, PtrType), 7686 &Flags); 7687 AddToWorklist(NewPtr.getNode()); 7688 7689 SDValue Load; 7690 if (ExtType == ISD::NON_EXTLOAD) 7691 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 7692 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 7693 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7694 else 7695 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 7696 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 7697 NewAlign, LN0->getMemOperand()->getFlags(), 7698 LN0->getAAInfo()); 7699 7700 // Replace the old load's chain with the new load's chain. 7701 WorklistRemover DeadNodes(*this); 7702 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7703 7704 // Shift the result left, if we've swallowed a left shift. 7705 SDValue Result = Load; 7706 if (ShLeftAmt != 0) { 7707 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 7708 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 7709 ShImmTy = VT; 7710 // If the shift amount is as large as the result size (but, presumably, 7711 // no larger than the source) then the useful bits of the result are 7712 // zero; we can't simply return the shortened shift, because the result 7713 // of that operation is undefined. 7714 SDLoc DL(N0); 7715 if (ShLeftAmt >= VT.getSizeInBits()) 7716 Result = DAG.getConstant(0, DL, VT); 7717 else 7718 Result = DAG.getNode(ISD::SHL, DL, VT, 7719 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 7720 } 7721 7722 // Return the new loaded value. 7723 return Result; 7724 } 7725 7726 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 7727 SDValue N0 = N->getOperand(0); 7728 SDValue N1 = N->getOperand(1); 7729 EVT VT = N->getValueType(0); 7730 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7731 unsigned VTBits = VT.getScalarSizeInBits(); 7732 unsigned EVTBits = EVT.getScalarSizeInBits(); 7733 7734 if (N0.isUndef()) 7735 return DAG.getUNDEF(VT); 7736 7737 // fold (sext_in_reg c1) -> c1 7738 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7739 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 7740 7741 // If the input is already sign extended, just drop the extension. 7742 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 7743 return N0; 7744 7745 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 7746 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 7747 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 7748 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7749 N0.getOperand(0), N1); 7750 7751 // fold (sext_in_reg (sext x)) -> (sext x) 7752 // fold (sext_in_reg (aext x)) -> (sext x) 7753 // if x is small enough. 7754 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 7755 SDValue N00 = N0.getOperand(0); 7756 if (N00.getScalarValueSizeInBits() <= EVTBits && 7757 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7758 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7759 } 7760 7761 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 7762 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 7763 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 7764 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 7765 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 7766 if (!LegalOperations || 7767 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 7768 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 7769 } 7770 7771 // fold (sext_in_reg (zext x)) -> (sext x) 7772 // iff we are extending the source sign bit. 7773 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 7774 SDValue N00 = N0.getOperand(0); 7775 if (N00.getScalarValueSizeInBits() == EVTBits && 7776 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7777 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7778 } 7779 7780 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 7781 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 7782 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 7783 7784 // fold operands of sext_in_reg based on knowledge that the top bits are not 7785 // demanded. 7786 if (SimplifyDemandedBits(SDValue(N, 0))) 7787 return SDValue(N, 0); 7788 7789 // fold (sext_in_reg (load x)) -> (smaller sextload x) 7790 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 7791 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 7792 return NarrowLoad; 7793 7794 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7795 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7796 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7797 if (N0.getOpcode() == ISD::SRL) { 7798 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7799 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7800 // We can turn this into an SRA iff the input to the SRL is already sign 7801 // extended enough. 7802 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7803 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7804 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7805 N0.getOperand(0), N0.getOperand(1)); 7806 } 7807 } 7808 7809 // fold (sext_inreg (extload x)) -> (sextload x) 7810 if (ISD::isEXTLoad(N0.getNode()) && 7811 ISD::isUNINDEXEDLoad(N0.getNode()) && 7812 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7813 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7814 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7815 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7816 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7817 LN0->getChain(), 7818 LN0->getBasePtr(), EVT, 7819 LN0->getMemOperand()); 7820 CombineTo(N, ExtLoad); 7821 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7822 AddToWorklist(ExtLoad.getNode()); 7823 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7824 } 7825 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7826 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7827 N0.hasOneUse() && 7828 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7829 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7830 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7831 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7832 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7833 LN0->getChain(), 7834 LN0->getBasePtr(), EVT, 7835 LN0->getMemOperand()); 7836 CombineTo(N, ExtLoad); 7837 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7838 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7839 } 7840 7841 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7842 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7843 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7844 N0.getOperand(1), false)) 7845 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7846 BSwap, N1); 7847 } 7848 7849 return SDValue(); 7850 } 7851 7852 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7853 SDValue N0 = N->getOperand(0); 7854 EVT VT = N->getValueType(0); 7855 7856 if (N0.isUndef()) 7857 return DAG.getUNDEF(VT); 7858 7859 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7860 LegalOperations)) 7861 return SDValue(Res, 0); 7862 7863 return SDValue(); 7864 } 7865 7866 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7867 SDValue N0 = N->getOperand(0); 7868 EVT VT = N->getValueType(0); 7869 7870 if (N0.isUndef()) 7871 return DAG.getUNDEF(VT); 7872 7873 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7874 LegalOperations)) 7875 return SDValue(Res, 0); 7876 7877 return SDValue(); 7878 } 7879 7880 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7881 SDValue N0 = N->getOperand(0); 7882 EVT VT = N->getValueType(0); 7883 bool isLE = DAG.getDataLayout().isLittleEndian(); 7884 7885 // noop truncate 7886 if (N0.getValueType() == N->getValueType(0)) 7887 return N0; 7888 // fold (truncate c1) -> c1 7889 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7890 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7891 // fold (truncate (truncate x)) -> (truncate x) 7892 if (N0.getOpcode() == ISD::TRUNCATE) 7893 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7894 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7895 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7896 N0.getOpcode() == ISD::SIGN_EXTEND || 7897 N0.getOpcode() == ISD::ANY_EXTEND) { 7898 // if the source is smaller than the dest, we still need an extend. 7899 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7900 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7901 // if the source is larger than the dest, than we just need the truncate. 7902 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7903 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7904 // if the source and dest are the same type, we can drop both the extend 7905 // and the truncate. 7906 return N0.getOperand(0); 7907 } 7908 7909 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 7910 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 7911 return SDValue(); 7912 7913 // Fold extract-and-trunc into a narrow extract. For example: 7914 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7915 // i32 y = TRUNCATE(i64 x) 7916 // -- becomes -- 7917 // v16i8 b = BITCAST (v2i64 val) 7918 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7919 // 7920 // Note: We only run this optimization after type legalization (which often 7921 // creates this pattern) and before operation legalization after which 7922 // we need to be more careful about the vector instructions that we generate. 7923 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7924 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7925 7926 EVT VecTy = N0.getOperand(0).getValueType(); 7927 EVT ExTy = N0.getValueType(); 7928 EVT TrTy = N->getValueType(0); 7929 7930 unsigned NumElem = VecTy.getVectorNumElements(); 7931 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7932 7933 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7934 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7935 7936 SDValue EltNo = N0->getOperand(1); 7937 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7938 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7939 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7940 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7941 7942 SDLoc DL(N); 7943 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7944 DAG.getBitcast(NVT, N0.getOperand(0)), 7945 DAG.getConstant(Index, DL, IndexTy)); 7946 } 7947 } 7948 7949 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7950 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 7951 EVT SrcVT = N0.getValueType(); 7952 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7953 TLI.isTruncateFree(SrcVT, VT)) { 7954 SDLoc SL(N0); 7955 SDValue Cond = N0.getOperand(0); 7956 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7957 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7958 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7959 } 7960 } 7961 7962 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 7963 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7964 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7965 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7966 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7967 uint64_t Amt = CAmt->getZExtValue(); 7968 unsigned Size = VT.getScalarSizeInBits(); 7969 7970 if (Amt < Size) { 7971 SDLoc SL(N); 7972 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7973 7974 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7975 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7976 DAG.getConstant(Amt, SL, AmtVT)); 7977 } 7978 } 7979 } 7980 7981 // Fold a series of buildvector, bitcast, and truncate if possible. 7982 // For example fold 7983 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7984 // (2xi32 (buildvector x, y)). 7985 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7986 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7987 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7988 N0.getOperand(0).hasOneUse()) { 7989 7990 SDValue BuildVect = N0.getOperand(0); 7991 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7992 EVT TruncVecEltTy = VT.getVectorElementType(); 7993 7994 // Check that the element types match. 7995 if (BuildVectEltTy == TruncVecEltTy) { 7996 // Now we only need to compute the offset of the truncated elements. 7997 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7998 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7999 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8000 8001 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8002 "Invalid number of elements"); 8003 8004 SmallVector<SDValue, 8> Opnds; 8005 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8006 Opnds.push_back(BuildVect.getOperand(i)); 8007 8008 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8009 } 8010 } 8011 8012 // See if we can simplify the input to this truncate through knowledge that 8013 // only the low bits are being used. 8014 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8015 // Currently we only perform this optimization on scalars because vectors 8016 // may have different active low bits. 8017 if (!VT.isVector()) { 8018 if (SDValue Shorter = 8019 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 8020 VT.getSizeInBits()))) 8021 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8022 } 8023 8024 // fold (truncate (load x)) -> (smaller load x) 8025 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8026 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8027 if (SDValue Reduced = ReduceLoadWidth(N)) 8028 return Reduced; 8029 8030 // Handle the case where the load remains an extending load even 8031 // after truncation. 8032 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8033 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8034 if (!LN0->isVolatile() && 8035 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8036 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8037 VT, LN0->getChain(), LN0->getBasePtr(), 8038 LN0->getMemoryVT(), 8039 LN0->getMemOperand()); 8040 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8041 return NewLoad; 8042 } 8043 } 8044 } 8045 8046 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8047 // where ... are all 'undef'. 8048 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8049 SmallVector<EVT, 8> VTs; 8050 SDValue V; 8051 unsigned Idx = 0; 8052 unsigned NumDefs = 0; 8053 8054 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8055 SDValue X = N0.getOperand(i); 8056 if (!X.isUndef()) { 8057 V = X; 8058 Idx = i; 8059 NumDefs++; 8060 } 8061 // Stop if more than one members are non-undef. 8062 if (NumDefs > 1) 8063 break; 8064 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8065 VT.getVectorElementType(), 8066 X.getValueType().getVectorNumElements())); 8067 } 8068 8069 if (NumDefs == 0) 8070 return DAG.getUNDEF(VT); 8071 8072 if (NumDefs == 1) { 8073 assert(V.getNode() && "The single defined operand is empty!"); 8074 SmallVector<SDValue, 8> Opnds; 8075 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8076 if (i != Idx) { 8077 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8078 continue; 8079 } 8080 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8081 AddToWorklist(NV.getNode()); 8082 Opnds.push_back(NV); 8083 } 8084 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8085 } 8086 } 8087 8088 // Fold truncate of a bitcast of a vector to an extract of the low vector 8089 // element. 8090 // 8091 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 8092 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8093 SDValue VecSrc = N0.getOperand(0); 8094 EVT SrcVT = VecSrc.getValueType(); 8095 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8096 (!LegalOperations || 8097 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8098 SDLoc SL(N); 8099 8100 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8101 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8102 VecSrc, DAG.getConstant(0, SL, IdxVT)); 8103 } 8104 } 8105 8106 // Simplify the operands using demanded-bits information. 8107 if (!VT.isVector() && 8108 SimplifyDemandedBits(SDValue(N, 0))) 8109 return SDValue(N, 0); 8110 8111 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8112 // When the adde's carry is not used. 8113 if (N0.getOpcode() == ISD::ADDE && N0.hasOneUse() && 8114 !N0.getNode()->hasAnyUseOfValue(1) && 8115 (!LegalOperations || TLI.isOperationLegal(ISD::ADDE, VT))) { 8116 SDLoc SL(N); 8117 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8118 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8119 return DAG.getNode(ISD::ADDE, SL, DAG.getVTList(VT, MVT::Glue), 8120 X, Y, N0.getOperand(2)); 8121 } 8122 8123 return SDValue(); 8124 } 8125 8126 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8127 SDValue Elt = N->getOperand(i); 8128 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8129 return Elt.getNode(); 8130 return Elt.getOperand(Elt.getResNo()).getNode(); 8131 } 8132 8133 /// build_pair (load, load) -> load 8134 /// if load locations are consecutive. 8135 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8136 assert(N->getOpcode() == ISD::BUILD_PAIR); 8137 8138 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8139 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8140 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8141 LD1->getAddressSpace() != LD2->getAddressSpace()) 8142 return SDValue(); 8143 EVT LD1VT = LD1->getValueType(0); 8144 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 8145 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8146 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8147 unsigned Align = LD1->getAlignment(); 8148 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8149 VT.getTypeForEVT(*DAG.getContext())); 8150 8151 if (NewAlign <= Align && 8152 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8153 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8154 LD1->getPointerInfo(), Align); 8155 } 8156 8157 return SDValue(); 8158 } 8159 8160 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8161 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8162 // and Lo parts; on big-endian machines it doesn't. 8163 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8164 } 8165 8166 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8167 const TargetLowering &TLI) { 8168 // If this is not a bitcast to an FP type or if the target doesn't have 8169 // IEEE754-compliant FP logic, we're done. 8170 EVT VT = N->getValueType(0); 8171 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8172 return SDValue(); 8173 8174 // TODO: Use splat values for the constant-checking below and remove this 8175 // restriction. 8176 SDValue N0 = N->getOperand(0); 8177 EVT SourceVT = N0.getValueType(); 8178 if (SourceVT.isVector()) 8179 return SDValue(); 8180 8181 unsigned FPOpcode; 8182 APInt SignMask; 8183 switch (N0.getOpcode()) { 8184 case ISD::AND: 8185 FPOpcode = ISD::FABS; 8186 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 8187 break; 8188 case ISD::XOR: 8189 FPOpcode = ISD::FNEG; 8190 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 8191 break; 8192 // TODO: ISD::OR --> ISD::FNABS? 8193 default: 8194 return SDValue(); 8195 } 8196 8197 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8198 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8199 SDValue LogicOp0 = N0.getOperand(0); 8200 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8201 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8202 LogicOp0.getOpcode() == ISD::BITCAST && 8203 LogicOp0->getOperand(0).getValueType() == VT) 8204 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8205 8206 return SDValue(); 8207 } 8208 8209 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8210 SDValue N0 = N->getOperand(0); 8211 EVT VT = N->getValueType(0); 8212 8213 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8214 // Only do this before legalize, since afterward the target may be depending 8215 // on the bitconvert. 8216 // First check to see if this is all constant. 8217 if (!LegalTypes && 8218 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8219 VT.isVector()) { 8220 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8221 8222 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8223 assert(!DestEltVT.isVector() && 8224 "Element type of vector ValueType must not be vector!"); 8225 if (isSimple) 8226 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8227 } 8228 8229 // If the input is a constant, let getNode fold it. 8230 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8231 // If we can't allow illegal operations, we need to check that this is just 8232 // a fp -> int or int -> conversion and that the resulting operation will 8233 // be legal. 8234 if (!LegalOperations || 8235 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8236 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8237 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8238 TLI.isOperationLegal(ISD::Constant, VT))) 8239 return DAG.getBitcast(VT, N0); 8240 } 8241 8242 // (conv (conv x, t1), t2) -> (conv x, t2) 8243 if (N0.getOpcode() == ISD::BITCAST) 8244 return DAG.getBitcast(VT, N0.getOperand(0)); 8245 8246 // fold (conv (load x)) -> (load (conv*)x) 8247 // If the resultant load doesn't need a higher alignment than the original! 8248 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8249 // Do not change the width of a volatile load. 8250 !cast<LoadSDNode>(N0)->isVolatile() && 8251 // Do not remove the cast if the types differ in endian layout. 8252 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8253 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8254 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8255 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8256 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8257 unsigned OrigAlign = LN0->getAlignment(); 8258 8259 bool Fast = false; 8260 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8261 LN0->getAddressSpace(), OrigAlign, &Fast) && 8262 Fast) { 8263 SDValue Load = 8264 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8265 LN0->getPointerInfo(), OrigAlign, 8266 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8267 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8268 return Load; 8269 } 8270 } 8271 8272 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8273 return V; 8274 8275 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8276 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8277 // 8278 // For ppc_fp128: 8279 // fold (bitcast (fneg x)) -> 8280 // flipbit = signbit 8281 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8282 // 8283 // fold (bitcast (fabs x)) -> 8284 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8285 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8286 // This often reduces constant pool loads. 8287 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8288 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8289 N0.getNode()->hasOneUse() && VT.isInteger() && 8290 !VT.isVector() && !N0.getValueType().isVector()) { 8291 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8292 AddToWorklist(NewConv.getNode()); 8293 8294 SDLoc DL(N); 8295 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8296 assert(VT.getSizeInBits() == 128); 8297 SDValue SignBit = DAG.getConstant( 8298 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8299 SDValue FlipBit; 8300 if (N0.getOpcode() == ISD::FNEG) { 8301 FlipBit = SignBit; 8302 AddToWorklist(FlipBit.getNode()); 8303 } else { 8304 assert(N0.getOpcode() == ISD::FABS); 8305 SDValue Hi = 8306 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8307 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8308 SDLoc(NewConv))); 8309 AddToWorklist(Hi.getNode()); 8310 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8311 AddToWorklist(FlipBit.getNode()); 8312 } 8313 SDValue FlipBits = 8314 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8315 AddToWorklist(FlipBits.getNode()); 8316 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8317 } 8318 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 8319 if (N0.getOpcode() == ISD::FNEG) 8320 return DAG.getNode(ISD::XOR, DL, VT, 8321 NewConv, DAG.getConstant(SignBit, DL, VT)); 8322 assert(N0.getOpcode() == ISD::FABS); 8323 return DAG.getNode(ISD::AND, DL, VT, 8324 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8325 } 8326 8327 // fold (bitconvert (fcopysign cst, x)) -> 8328 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8329 // Note that we don't handle (copysign x, cst) because this can always be 8330 // folded to an fneg or fabs. 8331 // 8332 // For ppc_fp128: 8333 // fold (bitcast (fcopysign cst, x)) -> 8334 // flipbit = (and (extract_element 8335 // (xor (bitcast cst), (bitcast x)), 0), 8336 // signbit) 8337 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8338 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8339 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8340 VT.isInteger() && !VT.isVector()) { 8341 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8342 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8343 if (isTypeLegal(IntXVT)) { 8344 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8345 AddToWorklist(X.getNode()); 8346 8347 // If X has a different width than the result/lhs, sext it or truncate it. 8348 unsigned VTWidth = VT.getSizeInBits(); 8349 if (OrigXWidth < VTWidth) { 8350 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8351 AddToWorklist(X.getNode()); 8352 } else if (OrigXWidth > VTWidth) { 8353 // To get the sign bit in the right place, we have to shift it right 8354 // before truncating. 8355 SDLoc DL(X); 8356 X = DAG.getNode(ISD::SRL, DL, 8357 X.getValueType(), X, 8358 DAG.getConstant(OrigXWidth-VTWidth, DL, 8359 X.getValueType())); 8360 AddToWorklist(X.getNode()); 8361 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8362 AddToWorklist(X.getNode()); 8363 } 8364 8365 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8366 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 8367 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8368 AddToWorklist(Cst.getNode()); 8369 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8370 AddToWorklist(X.getNode()); 8371 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8372 AddToWorklist(XorResult.getNode()); 8373 SDValue XorResult64 = DAG.getNode( 8374 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8375 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8376 SDLoc(XorResult))); 8377 AddToWorklist(XorResult64.getNode()); 8378 SDValue FlipBit = 8379 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8380 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8381 AddToWorklist(FlipBit.getNode()); 8382 SDValue FlipBits = 8383 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8384 AddToWorklist(FlipBits.getNode()); 8385 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8386 } 8387 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 8388 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8389 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8390 AddToWorklist(X.getNode()); 8391 8392 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8393 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8394 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8395 AddToWorklist(Cst.getNode()); 8396 8397 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8398 } 8399 } 8400 8401 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8402 if (N0.getOpcode() == ISD::BUILD_PAIR) 8403 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8404 return CombineLD; 8405 8406 // Remove double bitcasts from shuffles - this is often a legacy of 8407 // XformToShuffleWithZero being used to combine bitmaskings (of 8408 // float vectors bitcast to integer vectors) into shuffles. 8409 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8410 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8411 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8412 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8413 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8414 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8415 8416 // If operands are a bitcast, peek through if it casts the original VT. 8417 // If operands are a constant, just bitcast back to original VT. 8418 auto PeekThroughBitcast = [&](SDValue Op) { 8419 if (Op.getOpcode() == ISD::BITCAST && 8420 Op.getOperand(0).getValueType() == VT) 8421 return SDValue(Op.getOperand(0)); 8422 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8423 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8424 return DAG.getBitcast(VT, Op); 8425 return SDValue(); 8426 }; 8427 8428 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8429 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8430 if (!(SV0 && SV1)) 8431 return SDValue(); 8432 8433 int MaskScale = 8434 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8435 SmallVector<int, 8> NewMask; 8436 for (int M : SVN->getMask()) 8437 for (int i = 0; i != MaskScale; ++i) 8438 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8439 8440 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8441 if (!LegalMask) { 8442 std::swap(SV0, SV1); 8443 ShuffleVectorSDNode::commuteMask(NewMask); 8444 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8445 } 8446 8447 if (LegalMask) 8448 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8449 } 8450 8451 return SDValue(); 8452 } 8453 8454 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8455 EVT VT = N->getValueType(0); 8456 return CombineConsecutiveLoads(N, VT); 8457 } 8458 8459 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8460 /// operands. DstEltVT indicates the destination element value type. 8461 SDValue DAGCombiner:: 8462 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8463 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8464 8465 // If this is already the right type, we're done. 8466 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8467 8468 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8469 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8470 8471 // If this is a conversion of N elements of one type to N elements of another 8472 // type, convert each element. This handles FP<->INT cases. 8473 if (SrcBitSize == DstBitSize) { 8474 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8475 BV->getValueType(0).getVectorNumElements()); 8476 8477 // Due to the FP element handling below calling this routine recursively, 8478 // we can end up with a scalar-to-vector node here. 8479 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8480 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8481 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8482 8483 SmallVector<SDValue, 8> Ops; 8484 for (SDValue Op : BV->op_values()) { 8485 // If the vector element type is not legal, the BUILD_VECTOR operands 8486 // are promoted and implicitly truncated. Make that explicit here. 8487 if (Op.getValueType() != SrcEltVT) 8488 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8489 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8490 AddToWorklist(Ops.back().getNode()); 8491 } 8492 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8493 } 8494 8495 // Otherwise, we're growing or shrinking the elements. To avoid having to 8496 // handle annoying details of growing/shrinking FP values, we convert them to 8497 // int first. 8498 if (SrcEltVT.isFloatingPoint()) { 8499 // Convert the input float vector to a int vector where the elements are the 8500 // same sizes. 8501 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8502 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8503 SrcEltVT = IntVT; 8504 } 8505 8506 // Now we know the input is an integer vector. If the output is a FP type, 8507 // convert to integer first, then to FP of the right size. 8508 if (DstEltVT.isFloatingPoint()) { 8509 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8510 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8511 8512 // Next, convert to FP elements of the same size. 8513 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 8514 } 8515 8516 SDLoc DL(BV); 8517 8518 // Okay, we know the src/dst types are both integers of differing types. 8519 // Handling growing first. 8520 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 8521 if (SrcBitSize < DstBitSize) { 8522 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 8523 8524 SmallVector<SDValue, 8> Ops; 8525 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 8526 i += NumInputsPerOutput) { 8527 bool isLE = DAG.getDataLayout().isLittleEndian(); 8528 APInt NewBits = APInt(DstBitSize, 0); 8529 bool EltIsUndef = true; 8530 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 8531 // Shift the previously computed bits over. 8532 NewBits <<= SrcBitSize; 8533 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 8534 if (Op.isUndef()) continue; 8535 EltIsUndef = false; 8536 8537 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 8538 zextOrTrunc(SrcBitSize).zext(DstBitSize); 8539 } 8540 8541 if (EltIsUndef) 8542 Ops.push_back(DAG.getUNDEF(DstEltVT)); 8543 else 8544 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 8545 } 8546 8547 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 8548 return DAG.getBuildVector(VT, DL, Ops); 8549 } 8550 8551 // Finally, this must be the case where we are shrinking elements: each input 8552 // turns into multiple outputs. 8553 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 8554 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8555 NumOutputsPerInput*BV->getNumOperands()); 8556 SmallVector<SDValue, 8> Ops; 8557 8558 for (const SDValue &Op : BV->op_values()) { 8559 if (Op.isUndef()) { 8560 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 8561 continue; 8562 } 8563 8564 APInt OpVal = cast<ConstantSDNode>(Op)-> 8565 getAPIntValue().zextOrTrunc(SrcBitSize); 8566 8567 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 8568 APInt ThisVal = OpVal.trunc(DstBitSize); 8569 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 8570 OpVal = OpVal.lshr(DstBitSize); 8571 } 8572 8573 // For big endian targets, swap the order of the pieces of each element. 8574 if (DAG.getDataLayout().isBigEndian()) 8575 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 8576 } 8577 8578 return DAG.getBuildVector(VT, DL, Ops); 8579 } 8580 8581 /// Try to perform FMA combining on a given FADD node. 8582 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 8583 SDValue N0 = N->getOperand(0); 8584 SDValue N1 = N->getOperand(1); 8585 EVT VT = N->getValueType(0); 8586 SDLoc SL(N); 8587 8588 const TargetOptions &Options = DAG.getTarget().Options; 8589 bool AllowFusion = 8590 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8591 8592 // Floating-point multiply-add with intermediate rounding. 8593 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8594 8595 // Floating-point multiply-add without intermediate rounding. 8596 bool HasFMA = 8597 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8598 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8599 8600 // No valid opcode, do not combine. 8601 if (!HasFMAD && !HasFMA) 8602 return SDValue(); 8603 8604 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8605 ; 8606 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8607 return SDValue(); 8608 8609 // Always prefer FMAD to FMA for precision. 8610 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8611 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8612 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8613 8614 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 8615 // prefer to fold the multiply with fewer uses. 8616 if (Aggressive && N0.getOpcode() == ISD::FMUL && 8617 N1.getOpcode() == ISD::FMUL) { 8618 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 8619 std::swap(N0, N1); 8620 } 8621 8622 // fold (fadd (fmul x, y), z) -> (fma x, y, 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), N1); 8627 } 8628 8629 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 8630 // Note: Commutes FADD operands. 8631 if (N1.getOpcode() == ISD::FMUL && 8632 (Aggressive || N1->hasOneUse())) { 8633 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8634 N1.getOperand(0), N1.getOperand(1), N0); 8635 } 8636 8637 // Look through FP_EXTEND nodes to do more combining. 8638 if (AllowFusion && LookThroughFPExt) { 8639 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 8640 if (N0.getOpcode() == ISD::FP_EXTEND) { 8641 SDValue N00 = N0.getOperand(0); 8642 if (N00.getOpcode() == ISD::FMUL) 8643 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8644 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8645 N00.getOperand(0)), 8646 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8647 N00.getOperand(1)), N1); 8648 } 8649 8650 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 8651 // Note: Commutes FADD operands. 8652 if (N1.getOpcode() == ISD::FP_EXTEND) { 8653 SDValue N10 = N1.getOperand(0); 8654 if (N10.getOpcode() == ISD::FMUL) 8655 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8656 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8657 N10.getOperand(0)), 8658 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8659 N10.getOperand(1)), N0); 8660 } 8661 } 8662 8663 // More folding opportunities when target permits. 8664 if (Aggressive) { 8665 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 8666 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8667 // are currently only supported on binary nodes. 8668 if (Options.UnsafeFPMath && 8669 N0.getOpcode() == PreferredFusedOpcode && 8670 N0.getOperand(2).getOpcode() == ISD::FMUL && 8671 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8672 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8673 N0.getOperand(0), N0.getOperand(1), 8674 DAG.getNode(PreferredFusedOpcode, SL, VT, 8675 N0.getOperand(2).getOperand(0), 8676 N0.getOperand(2).getOperand(1), 8677 N1)); 8678 } 8679 8680 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 8681 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8682 // are currently only supported on binary nodes. 8683 if (Options.UnsafeFPMath && 8684 N1->getOpcode() == PreferredFusedOpcode && 8685 N1.getOperand(2).getOpcode() == ISD::FMUL && 8686 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 8687 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8688 N1.getOperand(0), N1.getOperand(1), 8689 DAG.getNode(PreferredFusedOpcode, SL, VT, 8690 N1.getOperand(2).getOperand(0), 8691 N1.getOperand(2).getOperand(1), 8692 N0)); 8693 } 8694 8695 if (AllowFusion && LookThroughFPExt) { 8696 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 8697 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 8698 auto FoldFAddFMAFPExtFMul = [&] ( 8699 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8700 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 8701 DAG.getNode(PreferredFusedOpcode, SL, VT, 8702 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8703 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8704 Z)); 8705 }; 8706 if (N0.getOpcode() == PreferredFusedOpcode) { 8707 SDValue N02 = N0.getOperand(2); 8708 if (N02.getOpcode() == ISD::FP_EXTEND) { 8709 SDValue N020 = N02.getOperand(0); 8710 if (N020.getOpcode() == ISD::FMUL) 8711 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 8712 N020.getOperand(0), N020.getOperand(1), 8713 N1); 8714 } 8715 } 8716 8717 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 8718 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 8719 // FIXME: This turns two single-precision and one double-precision 8720 // operation into two double-precision operations, which might not be 8721 // interesting for all targets, especially GPUs. 8722 auto FoldFAddFPExtFMAFMul = [&] ( 8723 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8724 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8725 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 8726 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 8727 DAG.getNode(PreferredFusedOpcode, SL, VT, 8728 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8729 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8730 Z)); 8731 }; 8732 if (N0.getOpcode() == ISD::FP_EXTEND) { 8733 SDValue N00 = N0.getOperand(0); 8734 if (N00.getOpcode() == PreferredFusedOpcode) { 8735 SDValue N002 = N00.getOperand(2); 8736 if (N002.getOpcode() == ISD::FMUL) 8737 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 8738 N002.getOperand(0), N002.getOperand(1), 8739 N1); 8740 } 8741 } 8742 8743 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 8744 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 8745 if (N1.getOpcode() == PreferredFusedOpcode) { 8746 SDValue N12 = N1.getOperand(2); 8747 if (N12.getOpcode() == ISD::FP_EXTEND) { 8748 SDValue N120 = N12.getOperand(0); 8749 if (N120.getOpcode() == ISD::FMUL) 8750 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 8751 N120.getOperand(0), N120.getOperand(1), 8752 N0); 8753 } 8754 } 8755 8756 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 8757 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 8758 // FIXME: This turns two single-precision and one double-precision 8759 // operation into two double-precision operations, which might not be 8760 // interesting for all targets, especially GPUs. 8761 if (N1.getOpcode() == ISD::FP_EXTEND) { 8762 SDValue N10 = N1.getOperand(0); 8763 if (N10.getOpcode() == PreferredFusedOpcode) { 8764 SDValue N102 = N10.getOperand(2); 8765 if (N102.getOpcode() == ISD::FMUL) 8766 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 8767 N102.getOperand(0), N102.getOperand(1), 8768 N0); 8769 } 8770 } 8771 } 8772 } 8773 8774 return SDValue(); 8775 } 8776 8777 /// Try to perform FMA combining on a given FSUB node. 8778 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 8779 SDValue N0 = N->getOperand(0); 8780 SDValue N1 = N->getOperand(1); 8781 EVT VT = N->getValueType(0); 8782 SDLoc SL(N); 8783 8784 const TargetOptions &Options = DAG.getTarget().Options; 8785 bool AllowFusion = 8786 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8787 8788 // Floating-point multiply-add with intermediate rounding. 8789 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8790 8791 // Floating-point multiply-add without intermediate rounding. 8792 bool HasFMA = 8793 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8794 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8795 8796 // No valid opcode, do not combine. 8797 if (!HasFMAD && !HasFMA) 8798 return SDValue(); 8799 8800 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8801 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8802 return SDValue(); 8803 8804 // Always prefer FMAD to FMA for precision. 8805 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8806 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8807 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8808 8809 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 8810 if (N0.getOpcode() == ISD::FMUL && 8811 (Aggressive || N0->hasOneUse())) { 8812 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8813 N0.getOperand(0), N0.getOperand(1), 8814 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8815 } 8816 8817 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 8818 // Note: Commutes FSUB operands. 8819 if (N1.getOpcode() == ISD::FMUL && 8820 (Aggressive || N1->hasOneUse())) 8821 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8822 DAG.getNode(ISD::FNEG, SL, VT, 8823 N1.getOperand(0)), 8824 N1.getOperand(1), N0); 8825 8826 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 8827 if (N0.getOpcode() == ISD::FNEG && 8828 N0.getOperand(0).getOpcode() == ISD::FMUL && 8829 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 8830 SDValue N00 = N0.getOperand(0).getOperand(0); 8831 SDValue N01 = N0.getOperand(0).getOperand(1); 8832 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8833 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 8834 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8835 } 8836 8837 // Look through FP_EXTEND nodes to do more combining. 8838 if (AllowFusion && LookThroughFPExt) { 8839 // fold (fsub (fpext (fmul x, y)), z) 8840 // -> (fma (fpext x), (fpext y), (fneg z)) 8841 if (N0.getOpcode() == ISD::FP_EXTEND) { 8842 SDValue N00 = N0.getOperand(0); 8843 if (N00.getOpcode() == ISD::FMUL) 8844 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8845 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8846 N00.getOperand(0)), 8847 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8848 N00.getOperand(1)), 8849 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8850 } 8851 8852 // fold (fsub x, (fpext (fmul y, z))) 8853 // -> (fma (fneg (fpext y)), (fpext z), x) 8854 // Note: Commutes FSUB operands. 8855 if (N1.getOpcode() == ISD::FP_EXTEND) { 8856 SDValue N10 = N1.getOperand(0); 8857 if (N10.getOpcode() == ISD::FMUL) 8858 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8859 DAG.getNode(ISD::FNEG, SL, VT, 8860 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8861 N10.getOperand(0))), 8862 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8863 N10.getOperand(1)), 8864 N0); 8865 } 8866 8867 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8868 // -> (fneg (fma (fpext x), (fpext y), z)) 8869 // Note: This could be removed with appropriate canonicalization of the 8870 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8871 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8872 // from implementing the canonicalization in visitFSUB. 8873 if (N0.getOpcode() == ISD::FP_EXTEND) { 8874 SDValue N00 = N0.getOperand(0); 8875 if (N00.getOpcode() == ISD::FNEG) { 8876 SDValue N000 = N00.getOperand(0); 8877 if (N000.getOpcode() == ISD::FMUL) { 8878 return DAG.getNode(ISD::FNEG, SL, VT, 8879 DAG.getNode(PreferredFusedOpcode, SL, VT, 8880 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8881 N000.getOperand(0)), 8882 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8883 N000.getOperand(1)), 8884 N1)); 8885 } 8886 } 8887 } 8888 8889 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8890 // -> (fneg (fma (fpext x)), (fpext y), z) 8891 // Note: This could be removed with appropriate canonicalization of the 8892 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8893 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8894 // from implementing the canonicalization in visitFSUB. 8895 if (N0.getOpcode() == ISD::FNEG) { 8896 SDValue N00 = N0.getOperand(0); 8897 if (N00.getOpcode() == ISD::FP_EXTEND) { 8898 SDValue N000 = N00.getOperand(0); 8899 if (N000.getOpcode() == ISD::FMUL) { 8900 return DAG.getNode(ISD::FNEG, SL, VT, 8901 DAG.getNode(PreferredFusedOpcode, SL, VT, 8902 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8903 N000.getOperand(0)), 8904 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8905 N000.getOperand(1)), 8906 N1)); 8907 } 8908 } 8909 } 8910 8911 } 8912 8913 // More folding opportunities when target permits. 8914 if (Aggressive) { 8915 // fold (fsub (fma x, y, (fmul u, v)), z) 8916 // -> (fma x, y (fma u, v, (fneg z))) 8917 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8918 // are currently only supported on binary nodes. 8919 if (Options.UnsafeFPMath && 8920 N0.getOpcode() == PreferredFusedOpcode && 8921 N0.getOperand(2).getOpcode() == ISD::FMUL && 8922 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8923 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8924 N0.getOperand(0), N0.getOperand(1), 8925 DAG.getNode(PreferredFusedOpcode, SL, VT, 8926 N0.getOperand(2).getOperand(0), 8927 N0.getOperand(2).getOperand(1), 8928 DAG.getNode(ISD::FNEG, SL, VT, 8929 N1))); 8930 } 8931 8932 // fold (fsub x, (fma y, z, (fmul u, v))) 8933 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8934 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8935 // are currently only supported on binary nodes. 8936 if (Options.UnsafeFPMath && 8937 N1.getOpcode() == PreferredFusedOpcode && 8938 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8939 SDValue N20 = N1.getOperand(2).getOperand(0); 8940 SDValue N21 = N1.getOperand(2).getOperand(1); 8941 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8942 DAG.getNode(ISD::FNEG, SL, VT, 8943 N1.getOperand(0)), 8944 N1.getOperand(1), 8945 DAG.getNode(PreferredFusedOpcode, SL, VT, 8946 DAG.getNode(ISD::FNEG, SL, VT, N20), 8947 8948 N21, N0)); 8949 } 8950 8951 if (AllowFusion && LookThroughFPExt) { 8952 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8953 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8954 if (N0.getOpcode() == PreferredFusedOpcode) { 8955 SDValue N02 = N0.getOperand(2); 8956 if (N02.getOpcode() == ISD::FP_EXTEND) { 8957 SDValue N020 = N02.getOperand(0); 8958 if (N020.getOpcode() == ISD::FMUL) 8959 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8960 N0.getOperand(0), N0.getOperand(1), 8961 DAG.getNode(PreferredFusedOpcode, SL, VT, 8962 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8963 N020.getOperand(0)), 8964 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8965 N020.getOperand(1)), 8966 DAG.getNode(ISD::FNEG, SL, VT, 8967 N1))); 8968 } 8969 } 8970 8971 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8972 // -> (fma (fpext x), (fpext y), 8973 // (fma (fpext u), (fpext v), (fneg z))) 8974 // FIXME: This turns two single-precision and one double-precision 8975 // operation into two double-precision operations, which might not be 8976 // interesting for all targets, especially GPUs. 8977 if (N0.getOpcode() == ISD::FP_EXTEND) { 8978 SDValue N00 = N0.getOperand(0); 8979 if (N00.getOpcode() == PreferredFusedOpcode) { 8980 SDValue N002 = N00.getOperand(2); 8981 if (N002.getOpcode() == ISD::FMUL) 8982 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8983 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8984 N00.getOperand(0)), 8985 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8986 N00.getOperand(1)), 8987 DAG.getNode(PreferredFusedOpcode, SL, VT, 8988 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8989 N002.getOperand(0)), 8990 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8991 N002.getOperand(1)), 8992 DAG.getNode(ISD::FNEG, SL, VT, 8993 N1))); 8994 } 8995 } 8996 8997 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8998 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8999 if (N1.getOpcode() == PreferredFusedOpcode && 9000 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9001 SDValue N120 = N1.getOperand(2).getOperand(0); 9002 if (N120.getOpcode() == ISD::FMUL) { 9003 SDValue N1200 = N120.getOperand(0); 9004 SDValue N1201 = N120.getOperand(1); 9005 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9006 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9007 N1.getOperand(1), 9008 DAG.getNode(PreferredFusedOpcode, SL, VT, 9009 DAG.getNode(ISD::FNEG, SL, VT, 9010 DAG.getNode(ISD::FP_EXTEND, SL, 9011 VT, N1200)), 9012 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9013 N1201), 9014 N0)); 9015 } 9016 } 9017 9018 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9019 // -> (fma (fneg (fpext y)), (fpext z), 9020 // (fma (fneg (fpext u)), (fpext v), x)) 9021 // FIXME: This turns two single-precision and one double-precision 9022 // operation into two double-precision operations, which might not be 9023 // interesting for all targets, especially GPUs. 9024 if (N1.getOpcode() == ISD::FP_EXTEND && 9025 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9026 SDValue N100 = N1.getOperand(0).getOperand(0); 9027 SDValue N101 = N1.getOperand(0).getOperand(1); 9028 SDValue N102 = N1.getOperand(0).getOperand(2); 9029 if (N102.getOpcode() == ISD::FMUL) { 9030 SDValue N1020 = N102.getOperand(0); 9031 SDValue N1021 = N102.getOperand(1); 9032 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9033 DAG.getNode(ISD::FNEG, SL, VT, 9034 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9035 N100)), 9036 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9037 DAG.getNode(PreferredFusedOpcode, SL, VT, 9038 DAG.getNode(ISD::FNEG, SL, VT, 9039 DAG.getNode(ISD::FP_EXTEND, SL, 9040 VT, N1020)), 9041 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9042 N1021), 9043 N0)); 9044 } 9045 } 9046 } 9047 } 9048 9049 return SDValue(); 9050 } 9051 9052 /// Try to perform FMA combining on a given FMUL node based on the distributive 9053 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9054 /// subtraction instead of addition). 9055 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9056 SDValue N0 = N->getOperand(0); 9057 SDValue N1 = N->getOperand(1); 9058 EVT VT = N->getValueType(0); 9059 SDLoc SL(N); 9060 9061 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9062 9063 const TargetOptions &Options = DAG.getTarget().Options; 9064 9065 // The transforms below are incorrect when x == 0 and y == inf, because the 9066 // intermediate multiplication produces a nan. 9067 if (!Options.NoInfsFPMath) 9068 return SDValue(); 9069 9070 // Floating-point multiply-add without intermediate rounding. 9071 bool HasFMA = 9072 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9073 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9074 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9075 9076 // Floating-point multiply-add with intermediate rounding. This can result 9077 // in a less precise result due to the changed rounding order. 9078 bool HasFMAD = Options.UnsafeFPMath && 9079 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9080 9081 // No valid opcode, do not combine. 9082 if (!HasFMAD && !HasFMA) 9083 return SDValue(); 9084 9085 // Always prefer FMAD to FMA for precision. 9086 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9087 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9088 9089 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9090 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9091 auto FuseFADD = [&](SDValue X, SDValue Y) { 9092 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9093 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9094 if (XC1 && XC1->isExactlyValue(+1.0)) 9095 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9096 if (XC1 && XC1->isExactlyValue(-1.0)) 9097 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9098 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9099 } 9100 return SDValue(); 9101 }; 9102 9103 if (SDValue FMA = FuseFADD(N0, N1)) 9104 return FMA; 9105 if (SDValue FMA = FuseFADD(N1, N0)) 9106 return FMA; 9107 9108 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9109 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9110 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9111 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9112 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9113 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9114 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9115 if (XC0 && XC0->isExactlyValue(+1.0)) 9116 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9117 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9118 Y); 9119 if (XC0 && XC0->isExactlyValue(-1.0)) 9120 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9121 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9122 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9123 9124 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9125 if (XC1 && XC1->isExactlyValue(+1.0)) 9126 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9127 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9128 if (XC1 && XC1->isExactlyValue(-1.0)) 9129 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9130 } 9131 return SDValue(); 9132 }; 9133 9134 if (SDValue FMA = FuseFSUB(N0, N1)) 9135 return FMA; 9136 if (SDValue FMA = FuseFSUB(N1, N0)) 9137 return FMA; 9138 9139 return SDValue(); 9140 } 9141 9142 SDValue DAGCombiner::visitFADD(SDNode *N) { 9143 SDValue N0 = N->getOperand(0); 9144 SDValue N1 = N->getOperand(1); 9145 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9146 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9147 EVT VT = N->getValueType(0); 9148 SDLoc DL(N); 9149 const TargetOptions &Options = DAG.getTarget().Options; 9150 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9151 9152 // fold vector ops 9153 if (VT.isVector()) 9154 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9155 return FoldedVOp; 9156 9157 // fold (fadd c1, c2) -> c1 + c2 9158 if (N0CFP && N1CFP) 9159 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9160 9161 // canonicalize constant to RHS 9162 if (N0CFP && !N1CFP) 9163 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9164 9165 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9166 return NewSel; 9167 9168 // fold (fadd A, (fneg B)) -> (fsub A, B) 9169 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9170 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9171 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9172 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9173 9174 // fold (fadd (fneg A), B) -> (fsub B, A) 9175 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9176 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9177 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9178 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9179 9180 // FIXME: Auto-upgrade the target/function-level option. 9181 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 9182 // fold (fadd A, 0) -> A 9183 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9184 if (N1C->isZero()) 9185 return N0; 9186 } 9187 9188 // If 'unsafe math' is enabled, fold lots of things. 9189 if (Options.UnsafeFPMath) { 9190 // No FP constant should be created after legalization as Instruction 9191 // Selection pass has a hard time dealing with FP constants. 9192 bool AllowNewConst = (Level < AfterLegalizeDAG); 9193 9194 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9195 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9196 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9197 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9198 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9199 Flags), 9200 Flags); 9201 9202 // If allowed, fold (fadd (fneg x), x) -> 0.0 9203 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9204 return DAG.getConstantFP(0.0, DL, VT); 9205 9206 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9207 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9208 return DAG.getConstantFP(0.0, DL, VT); 9209 9210 // We can fold chains of FADD's of the same value into multiplications. 9211 // This transform is not safe in general because we are reducing the number 9212 // of rounding steps. 9213 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9214 if (N0.getOpcode() == ISD::FMUL) { 9215 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9216 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9217 9218 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9219 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9220 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9221 DAG.getConstantFP(1.0, DL, VT), Flags); 9222 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9223 } 9224 9225 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9226 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9227 N1.getOperand(0) == N1.getOperand(1) && 9228 N0.getOperand(0) == N1.getOperand(0)) { 9229 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9230 DAG.getConstantFP(2.0, DL, VT), Flags); 9231 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9232 } 9233 } 9234 9235 if (N1.getOpcode() == ISD::FMUL) { 9236 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9237 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9238 9239 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9240 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9241 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9242 DAG.getConstantFP(1.0, DL, VT), Flags); 9243 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9244 } 9245 9246 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9247 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9248 N0.getOperand(0) == N0.getOperand(1) && 9249 N1.getOperand(0) == N0.getOperand(0)) { 9250 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9251 DAG.getConstantFP(2.0, DL, VT), Flags); 9252 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9253 } 9254 } 9255 9256 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9257 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9258 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9259 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9260 (N0.getOperand(0) == N1)) { 9261 return DAG.getNode(ISD::FMUL, DL, VT, 9262 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9263 } 9264 } 9265 9266 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9267 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9268 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9269 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9270 N1.getOperand(0) == N0) { 9271 return DAG.getNode(ISD::FMUL, DL, VT, 9272 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9273 } 9274 } 9275 9276 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9277 if (AllowNewConst && 9278 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9279 N0.getOperand(0) == N0.getOperand(1) && 9280 N1.getOperand(0) == N1.getOperand(1) && 9281 N0.getOperand(0) == N1.getOperand(0)) { 9282 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9283 DAG.getConstantFP(4.0, DL, VT), Flags); 9284 } 9285 } 9286 } // enable-unsafe-fp-math 9287 9288 // FADD -> FMA combines: 9289 if (SDValue Fused = visitFADDForFMACombine(N)) { 9290 AddToWorklist(Fused.getNode()); 9291 return Fused; 9292 } 9293 return SDValue(); 9294 } 9295 9296 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9297 SDValue N0 = N->getOperand(0); 9298 SDValue N1 = N->getOperand(1); 9299 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9300 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9301 EVT VT = N->getValueType(0); 9302 SDLoc DL(N); 9303 const TargetOptions &Options = DAG.getTarget().Options; 9304 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9305 9306 // fold vector ops 9307 if (VT.isVector()) 9308 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9309 return FoldedVOp; 9310 9311 // fold (fsub c1, c2) -> c1-c2 9312 if (N0CFP && N1CFP) 9313 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9314 9315 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9316 return NewSel; 9317 9318 // fold (fsub A, (fneg B)) -> (fadd A, B) 9319 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9320 return DAG.getNode(ISD::FADD, DL, VT, N0, 9321 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9322 9323 // FIXME: Auto-upgrade the target/function-level option. 9324 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) { 9325 // (fsub 0, B) -> -B 9326 if (N0CFP && N0CFP->isZero()) { 9327 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9328 return GetNegatedExpression(N1, DAG, LegalOperations); 9329 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9330 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9331 } 9332 } 9333 9334 // If 'unsafe math' is enabled, fold lots of things. 9335 if (Options.UnsafeFPMath) { 9336 // (fsub A, 0) -> A 9337 if (N1CFP && N1CFP->isZero()) 9338 return N0; 9339 9340 // (fsub x, x) -> 0.0 9341 if (N0 == N1) 9342 return DAG.getConstantFP(0.0f, DL, VT); 9343 9344 // (fsub x, (fadd x, y)) -> (fneg y) 9345 // (fsub x, (fadd y, x)) -> (fneg y) 9346 if (N1.getOpcode() == ISD::FADD) { 9347 SDValue N10 = N1->getOperand(0); 9348 SDValue N11 = N1->getOperand(1); 9349 9350 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9351 return GetNegatedExpression(N11, DAG, LegalOperations); 9352 9353 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9354 return GetNegatedExpression(N10, DAG, LegalOperations); 9355 } 9356 } 9357 9358 // FSUB -> FMA combines: 9359 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9360 AddToWorklist(Fused.getNode()); 9361 return Fused; 9362 } 9363 9364 return SDValue(); 9365 } 9366 9367 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9368 SDValue N0 = N->getOperand(0); 9369 SDValue N1 = N->getOperand(1); 9370 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9371 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9372 EVT VT = N->getValueType(0); 9373 SDLoc DL(N); 9374 const TargetOptions &Options = DAG.getTarget().Options; 9375 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9376 9377 // fold vector ops 9378 if (VT.isVector()) { 9379 // This just handles C1 * C2 for vectors. Other vector folds are below. 9380 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9381 return FoldedVOp; 9382 } 9383 9384 // fold (fmul c1, c2) -> c1*c2 9385 if (N0CFP && N1CFP) 9386 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9387 9388 // canonicalize constant to RHS 9389 if (isConstantFPBuildVectorOrConstantFP(N0) && 9390 !isConstantFPBuildVectorOrConstantFP(N1)) 9391 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9392 9393 // fold (fmul A, 1.0) -> A 9394 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9395 return N0; 9396 9397 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9398 return NewSel; 9399 9400 if (Options.UnsafeFPMath) { 9401 // fold (fmul A, 0) -> 0 9402 if (N1CFP && N1CFP->isZero()) 9403 return N1; 9404 9405 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9406 if (N0.getOpcode() == ISD::FMUL) { 9407 // Fold scalars or any vector constants (not just splats). 9408 // This fold is done in general by InstCombine, but extra fmul insts 9409 // may have been generated during lowering. 9410 SDValue N00 = N0.getOperand(0); 9411 SDValue N01 = N0.getOperand(1); 9412 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9413 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9414 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9415 9416 // Check 1: Make sure that the first operand of the inner multiply is NOT 9417 // a constant. Otherwise, we may induce infinite looping. 9418 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9419 // Check 2: Make sure that the second operand of the inner multiply and 9420 // the second operand of the outer multiply are constants. 9421 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9422 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9423 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9424 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9425 } 9426 } 9427 } 9428 9429 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9430 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9431 // during an early run of DAGCombiner can prevent folding with fmuls 9432 // inserted during lowering. 9433 if (N0.getOpcode() == ISD::FADD && 9434 (N0.getOperand(0) == N0.getOperand(1)) && 9435 N0.hasOneUse()) { 9436 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9437 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9438 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9439 } 9440 } 9441 9442 // fold (fmul X, 2.0) -> (fadd X, X) 9443 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9444 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9445 9446 // fold (fmul X, -1.0) -> (fneg X) 9447 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9448 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9449 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9450 9451 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9452 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9453 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9454 // Both can be negated for free, check to see if at least one is cheaper 9455 // negated. 9456 if (LHSNeg == 2 || RHSNeg == 2) 9457 return DAG.getNode(ISD::FMUL, DL, VT, 9458 GetNegatedExpression(N0, DAG, LegalOperations), 9459 GetNegatedExpression(N1, DAG, LegalOperations), 9460 Flags); 9461 } 9462 } 9463 9464 // FMUL -> FMA combines: 9465 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 9466 AddToWorklist(Fused.getNode()); 9467 return Fused; 9468 } 9469 9470 return SDValue(); 9471 } 9472 9473 SDValue DAGCombiner::visitFMA(SDNode *N) { 9474 SDValue N0 = N->getOperand(0); 9475 SDValue N1 = N->getOperand(1); 9476 SDValue N2 = N->getOperand(2); 9477 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9478 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9479 EVT VT = N->getValueType(0); 9480 SDLoc DL(N); 9481 const TargetOptions &Options = DAG.getTarget().Options; 9482 9483 // Constant fold FMA. 9484 if (isa<ConstantFPSDNode>(N0) && 9485 isa<ConstantFPSDNode>(N1) && 9486 isa<ConstantFPSDNode>(N2)) { 9487 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 9488 } 9489 9490 if (Options.UnsafeFPMath) { 9491 if (N0CFP && N0CFP->isZero()) 9492 return N2; 9493 if (N1CFP && N1CFP->isZero()) 9494 return N2; 9495 } 9496 // TODO: The FMA node should have flags that propagate to these nodes. 9497 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9498 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 9499 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9500 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 9501 9502 // Canonicalize (fma c, x, y) -> (fma x, c, y) 9503 if (isConstantFPBuildVectorOrConstantFP(N0) && 9504 !isConstantFPBuildVectorOrConstantFP(N1)) 9505 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 9506 9507 // TODO: FMA nodes should have flags that propagate to the created nodes. 9508 // For now, create a Flags object for use with all unsafe math transforms. 9509 SDNodeFlags Flags; 9510 Flags.setUnsafeAlgebra(true); 9511 9512 if (Options.UnsafeFPMath) { 9513 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 9514 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 9515 isConstantFPBuildVectorOrConstantFP(N1) && 9516 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 9517 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9518 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 9519 &Flags), &Flags); 9520 } 9521 9522 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 9523 if (N0.getOpcode() == ISD::FMUL && 9524 isConstantFPBuildVectorOrConstantFP(N1) && 9525 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 9526 return DAG.getNode(ISD::FMA, DL, VT, 9527 N0.getOperand(0), 9528 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 9529 &Flags), 9530 N2); 9531 } 9532 } 9533 9534 // (fma x, 1, y) -> (fadd x, y) 9535 // (fma x, -1, y) -> (fadd (fneg x), y) 9536 if (N1CFP) { 9537 if (N1CFP->isExactlyValue(1.0)) 9538 // TODO: The FMA node should have flags that propagate to this node. 9539 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 9540 9541 if (N1CFP->isExactlyValue(-1.0) && 9542 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 9543 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 9544 AddToWorklist(RHSNeg.getNode()); 9545 // TODO: The FMA node should have flags that propagate to this node. 9546 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 9547 } 9548 } 9549 9550 if (Options.UnsafeFPMath) { 9551 // (fma x, c, x) -> (fmul x, (c+1)) 9552 if (N1CFP && N0 == N2) { 9553 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9554 DAG.getNode(ISD::FADD, DL, VT, N1, 9555 DAG.getConstantFP(1.0, DL, VT), &Flags), 9556 &Flags); 9557 } 9558 9559 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 9560 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 9561 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9562 DAG.getNode(ISD::FADD, DL, VT, N1, 9563 DAG.getConstantFP(-1.0, DL, VT), &Flags), 9564 &Flags); 9565 } 9566 } 9567 9568 return SDValue(); 9569 } 9570 9571 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9572 // reciprocal. 9573 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 9574 // Notice that this is not always beneficial. One reason is different targets 9575 // may have different costs for FDIV and FMUL, so sometimes the cost of two 9576 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 9577 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 9578 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 9579 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 9580 const SDNodeFlags *Flags = N->getFlags(); 9581 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 9582 return SDValue(); 9583 9584 // Skip if current node is a reciprocal. 9585 SDValue N0 = N->getOperand(0); 9586 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9587 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9588 return SDValue(); 9589 9590 // Exit early if the target does not want this transform or if there can't 9591 // possibly be enough uses of the divisor to make the transform worthwhile. 9592 SDValue N1 = N->getOperand(1); 9593 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 9594 if (!MinUses || N1->use_size() < MinUses) 9595 return SDValue(); 9596 9597 // Find all FDIV users of the same divisor. 9598 // Use a set because duplicates may be present in the user list. 9599 SetVector<SDNode *> Users; 9600 for (auto *U : N1->uses()) { 9601 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 9602 // This division is eligible for optimization only if global unsafe math 9603 // is enabled or if this division allows reciprocal formation. 9604 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 9605 Users.insert(U); 9606 } 9607 } 9608 9609 // Now that we have the actual number of divisor uses, make sure it meets 9610 // the minimum threshold specified by the target. 9611 if (Users.size() < MinUses) 9612 return SDValue(); 9613 9614 EVT VT = N->getValueType(0); 9615 SDLoc DL(N); 9616 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 9617 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 9618 9619 // Dividend / Divisor -> Dividend * Reciprocal 9620 for (auto *U : Users) { 9621 SDValue Dividend = U->getOperand(0); 9622 if (Dividend != FPOne) { 9623 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 9624 Reciprocal, Flags); 9625 CombineTo(U, NewNode); 9626 } else if (U != Reciprocal.getNode()) { 9627 // In the absence of fast-math-flags, this user node is always the 9628 // same node as Reciprocal, but with FMF they may be different nodes. 9629 CombineTo(U, Reciprocal); 9630 } 9631 } 9632 return SDValue(N, 0); // N was replaced. 9633 } 9634 9635 SDValue DAGCombiner::visitFDIV(SDNode *N) { 9636 SDValue N0 = N->getOperand(0); 9637 SDValue N1 = N->getOperand(1); 9638 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9639 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9640 EVT VT = N->getValueType(0); 9641 SDLoc DL(N); 9642 const TargetOptions &Options = DAG.getTarget().Options; 9643 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 9644 9645 // fold vector ops 9646 if (VT.isVector()) 9647 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9648 return FoldedVOp; 9649 9650 // fold (fdiv c1, c2) -> c1/c2 9651 if (N0CFP && N1CFP) 9652 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 9653 9654 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9655 return NewSel; 9656 9657 if (Options.UnsafeFPMath) { 9658 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 9659 if (N1CFP) { 9660 // Compute the reciprocal 1.0 / c2. 9661 const APFloat &N1APF = N1CFP->getValueAPF(); 9662 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 9663 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 9664 // Only do the transform if the reciprocal is a legal fp immediate that 9665 // isn't too nasty (eg NaN, denormal, ...). 9666 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 9667 (!LegalOperations || 9668 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 9669 // backend)... we should handle this gracefully after Legalize. 9670 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 9671 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 9672 TLI.isFPImmLegal(Recip, VT))) 9673 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9674 DAG.getConstantFP(Recip, DL, VT), Flags); 9675 } 9676 9677 // If this FDIV is part of a reciprocal square root, it may be folded 9678 // into a target-specific square root estimate instruction. 9679 if (N1.getOpcode() == ISD::FSQRT) { 9680 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 9681 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9682 } 9683 } else if (N1.getOpcode() == ISD::FP_EXTEND && 9684 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9685 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9686 Flags)) { 9687 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 9688 AddToWorklist(RV.getNode()); 9689 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9690 } 9691 } else if (N1.getOpcode() == ISD::FP_ROUND && 9692 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9693 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9694 Flags)) { 9695 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 9696 AddToWorklist(RV.getNode()); 9697 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9698 } 9699 } else if (N1.getOpcode() == ISD::FMUL) { 9700 // Look through an FMUL. Even though this won't remove the FDIV directly, 9701 // it's still worthwhile to get rid of the FSQRT if possible. 9702 SDValue SqrtOp; 9703 SDValue OtherOp; 9704 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9705 SqrtOp = N1.getOperand(0); 9706 OtherOp = N1.getOperand(1); 9707 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 9708 SqrtOp = N1.getOperand(1); 9709 OtherOp = N1.getOperand(0); 9710 } 9711 if (SqrtOp.getNode()) { 9712 // We found a FSQRT, so try to make this fold: 9713 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 9714 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 9715 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 9716 AddToWorklist(RV.getNode()); 9717 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9718 } 9719 } 9720 } 9721 9722 // Fold into a reciprocal estimate and multiply instead of a real divide. 9723 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 9724 AddToWorklist(RV.getNode()); 9725 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9726 } 9727 } 9728 9729 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 9730 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9731 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9732 // Both can be negated for free, check to see if at least one is cheaper 9733 // negated. 9734 if (LHSNeg == 2 || RHSNeg == 2) 9735 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 9736 GetNegatedExpression(N0, DAG, LegalOperations), 9737 GetNegatedExpression(N1, DAG, LegalOperations), 9738 Flags); 9739 } 9740 } 9741 9742 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 9743 return CombineRepeatedDivisors; 9744 9745 return SDValue(); 9746 } 9747 9748 SDValue DAGCombiner::visitFREM(SDNode *N) { 9749 SDValue N0 = N->getOperand(0); 9750 SDValue N1 = N->getOperand(1); 9751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9752 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9753 EVT VT = N->getValueType(0); 9754 9755 // fold (frem c1, c2) -> fmod(c1,c2) 9756 if (N0CFP && N1CFP) 9757 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 9758 &cast<BinaryWithFlagsSDNode>(N)->Flags); 9759 9760 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9761 return NewSel; 9762 9763 return SDValue(); 9764 } 9765 9766 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 9767 if (!DAG.getTarget().Options.UnsafeFPMath) 9768 return SDValue(); 9769 9770 SDValue N0 = N->getOperand(0); 9771 if (TLI.isFsqrtCheap(N0, DAG)) 9772 return SDValue(); 9773 9774 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 9775 // For now, create a Flags object for use with all unsafe math transforms. 9776 SDNodeFlags Flags; 9777 Flags.setUnsafeAlgebra(true); 9778 return buildSqrtEstimate(N0, &Flags); 9779 } 9780 9781 /// copysign(x, fp_extend(y)) -> copysign(x, y) 9782 /// copysign(x, fp_round(y)) -> copysign(x, y) 9783 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 9784 SDValue N1 = N->getOperand(1); 9785 if ((N1.getOpcode() == ISD::FP_EXTEND || 9786 N1.getOpcode() == ISD::FP_ROUND)) { 9787 // Do not optimize out type conversion of f128 type yet. 9788 // For some targets like x86_64, configuration is changed to keep one f128 9789 // value in one SSE register, but instruction selection cannot handle 9790 // FCOPYSIGN on SSE registers yet. 9791 EVT N1VT = N1->getValueType(0); 9792 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 9793 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 9794 } 9795 return false; 9796 } 9797 9798 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 9799 SDValue N0 = N->getOperand(0); 9800 SDValue N1 = N->getOperand(1); 9801 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9802 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9803 EVT VT = N->getValueType(0); 9804 9805 if (N0CFP && N1CFP) // Constant fold 9806 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 9807 9808 if (N1CFP) { 9809 const APFloat &V = N1CFP->getValueAPF(); 9810 // copysign(x, c1) -> fabs(x) iff ispos(c1) 9811 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 9812 if (!V.isNegative()) { 9813 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 9814 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9815 } else { 9816 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9817 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9818 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 9819 } 9820 } 9821 9822 // copysign(fabs(x), y) -> copysign(x, y) 9823 // copysign(fneg(x), y) -> copysign(x, y) 9824 // copysign(copysign(x,z), y) -> copysign(x, y) 9825 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 9826 N0.getOpcode() == ISD::FCOPYSIGN) 9827 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 9828 9829 // copysign(x, abs(y)) -> abs(x) 9830 if (N1.getOpcode() == ISD::FABS) 9831 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9832 9833 // copysign(x, copysign(y,z)) -> copysign(x, z) 9834 if (N1.getOpcode() == ISD::FCOPYSIGN) 9835 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 9836 9837 // copysign(x, fp_extend(y)) -> copysign(x, y) 9838 // copysign(x, fp_round(y)) -> copysign(x, y) 9839 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 9840 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 9841 9842 return SDValue(); 9843 } 9844 9845 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 9846 SDValue N0 = N->getOperand(0); 9847 EVT VT = N->getValueType(0); 9848 EVT OpVT = N0.getValueType(); 9849 9850 // fold (sint_to_fp c1) -> c1fp 9851 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9852 // ...but only if the target supports immediate floating-point values 9853 (!LegalOperations || 9854 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9855 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9856 9857 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 9858 // but UINT_TO_FP is legal on this target, try to convert. 9859 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 9860 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 9861 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 9862 if (DAG.SignBitIsZero(N0)) 9863 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9864 } 9865 9866 // The next optimizations are desirable only if SELECT_CC can be lowered. 9867 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9868 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9869 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 9870 !VT.isVector() && 9871 (!LegalOperations || 9872 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9873 SDLoc DL(N); 9874 SDValue Ops[] = 9875 { N0.getOperand(0), N0.getOperand(1), 9876 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9877 N0.getOperand(2) }; 9878 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9879 } 9880 9881 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9882 // (select_cc x, y, 1.0, 0.0,, cc) 9883 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9884 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9885 (!LegalOperations || 9886 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9887 SDLoc DL(N); 9888 SDValue Ops[] = 9889 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9890 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9891 N0.getOperand(0).getOperand(2) }; 9892 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9893 } 9894 } 9895 9896 return SDValue(); 9897 } 9898 9899 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9900 SDValue N0 = N->getOperand(0); 9901 EVT VT = N->getValueType(0); 9902 EVT OpVT = N0.getValueType(); 9903 9904 // fold (uint_to_fp c1) -> c1fp 9905 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9906 // ...but only if the target supports immediate floating-point values 9907 (!LegalOperations || 9908 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9909 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9910 9911 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9912 // but SINT_TO_FP is legal on this target, try to convert. 9913 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9914 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9915 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9916 if (DAG.SignBitIsZero(N0)) 9917 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9918 } 9919 9920 // The next optimizations are desirable only if SELECT_CC can be lowered. 9921 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9922 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9923 9924 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9925 (!LegalOperations || 9926 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9927 SDLoc DL(N); 9928 SDValue Ops[] = 9929 { N0.getOperand(0), N0.getOperand(1), 9930 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9931 N0.getOperand(2) }; 9932 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9933 } 9934 } 9935 9936 return SDValue(); 9937 } 9938 9939 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9940 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9941 SDValue N0 = N->getOperand(0); 9942 EVT VT = N->getValueType(0); 9943 9944 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9945 return SDValue(); 9946 9947 SDValue Src = N0.getOperand(0); 9948 EVT SrcVT = Src.getValueType(); 9949 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9950 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9951 9952 // We can safely assume the conversion won't overflow the output range, 9953 // because (for example) (uint8_t)18293.f is undefined behavior. 9954 9955 // Since we can assume the conversion won't overflow, our decision as to 9956 // whether the input will fit in the float should depend on the minimum 9957 // of the input range and output range. 9958 9959 // This means this is also safe for a signed input and unsigned output, since 9960 // a negative input would lead to undefined behavior. 9961 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9962 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9963 unsigned ActualSize = std::min(InputSize, OutputSize); 9964 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9965 9966 // We can only fold away the float conversion if the input range can be 9967 // represented exactly in the float range. 9968 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9969 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9970 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9971 : ISD::ZERO_EXTEND; 9972 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9973 } 9974 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9975 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9976 return DAG.getBitcast(VT, Src); 9977 } 9978 return SDValue(); 9979 } 9980 9981 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9982 SDValue N0 = N->getOperand(0); 9983 EVT VT = N->getValueType(0); 9984 9985 // fold (fp_to_sint c1fp) -> c1 9986 if (isConstantFPBuildVectorOrConstantFP(N0)) 9987 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9988 9989 return FoldIntToFPToInt(N, DAG); 9990 } 9991 9992 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9993 SDValue N0 = N->getOperand(0); 9994 EVT VT = N->getValueType(0); 9995 9996 // fold (fp_to_uint c1fp) -> c1 9997 if (isConstantFPBuildVectorOrConstantFP(N0)) 9998 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9999 10000 return FoldIntToFPToInt(N, DAG); 10001 } 10002 10003 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10004 SDValue N0 = N->getOperand(0); 10005 SDValue N1 = N->getOperand(1); 10006 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10007 EVT VT = N->getValueType(0); 10008 10009 // fold (fp_round c1fp) -> c1fp 10010 if (N0CFP) 10011 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10012 10013 // fold (fp_round (fp_extend x)) -> x 10014 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10015 return N0.getOperand(0); 10016 10017 // fold (fp_round (fp_round x)) -> (fp_round x) 10018 if (N0.getOpcode() == ISD::FP_ROUND) { 10019 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10020 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10021 10022 // Skip this folding if it results in an fp_round from f80 to f16. 10023 // 10024 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10025 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10026 // instructions from f32 or f64. Moreover, the first (value-preserving) 10027 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10028 // x86. 10029 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10030 return SDValue(); 10031 10032 // If the first fp_round isn't a value preserving truncation, it might 10033 // introduce a tie in the second fp_round, that wouldn't occur in the 10034 // single-step fp_round we want to fold to. 10035 // In other words, double rounding isn't the same as rounding. 10036 // Also, this is a value preserving truncation iff both fp_round's are. 10037 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10038 SDLoc DL(N); 10039 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10040 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10041 } 10042 } 10043 10044 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10045 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10046 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10047 N0.getOperand(0), N1); 10048 AddToWorklist(Tmp.getNode()); 10049 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10050 Tmp, N0.getOperand(1)); 10051 } 10052 10053 return SDValue(); 10054 } 10055 10056 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10057 SDValue N0 = N->getOperand(0); 10058 EVT VT = N->getValueType(0); 10059 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10060 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10061 10062 // fold (fp_round_inreg c1fp) -> c1fp 10063 if (N0CFP && isTypeLegal(EVT)) { 10064 SDLoc DL(N); 10065 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10066 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10067 } 10068 10069 return SDValue(); 10070 } 10071 10072 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10073 SDValue N0 = N->getOperand(0); 10074 EVT VT = N->getValueType(0); 10075 10076 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10077 if (N->hasOneUse() && 10078 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10079 return SDValue(); 10080 10081 // fold (fp_extend c1fp) -> c1fp 10082 if (isConstantFPBuildVectorOrConstantFP(N0)) 10083 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10084 10085 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10086 if (N0.getOpcode() == ISD::FP16_TO_FP && 10087 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10088 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10089 10090 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10091 // value of X. 10092 if (N0.getOpcode() == ISD::FP_ROUND 10093 && N0.getConstantOperandVal(1) == 1) { 10094 SDValue In = N0.getOperand(0); 10095 if (In.getValueType() == VT) return In; 10096 if (VT.bitsLT(In.getValueType())) 10097 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10098 In, N0.getOperand(1)); 10099 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10100 } 10101 10102 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10103 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10104 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10105 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10106 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10107 LN0->getChain(), 10108 LN0->getBasePtr(), N0.getValueType(), 10109 LN0->getMemOperand()); 10110 CombineTo(N, ExtLoad); 10111 CombineTo(N0.getNode(), 10112 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10113 N0.getValueType(), ExtLoad, 10114 DAG.getIntPtrConstant(1, SDLoc(N0))), 10115 ExtLoad.getValue(1)); 10116 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10117 } 10118 10119 return SDValue(); 10120 } 10121 10122 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10123 SDValue N0 = N->getOperand(0); 10124 EVT VT = N->getValueType(0); 10125 10126 // fold (fceil c1) -> fceil(c1) 10127 if (isConstantFPBuildVectorOrConstantFP(N0)) 10128 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10129 10130 return SDValue(); 10131 } 10132 10133 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10134 SDValue N0 = N->getOperand(0); 10135 EVT VT = N->getValueType(0); 10136 10137 // fold (ftrunc c1) -> ftrunc(c1) 10138 if (isConstantFPBuildVectorOrConstantFP(N0)) 10139 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10140 10141 return SDValue(); 10142 } 10143 10144 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10145 SDValue N0 = N->getOperand(0); 10146 EVT VT = N->getValueType(0); 10147 10148 // fold (ffloor c1) -> ffloor(c1) 10149 if (isConstantFPBuildVectorOrConstantFP(N0)) 10150 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10151 10152 return SDValue(); 10153 } 10154 10155 // FIXME: FNEG and FABS have a lot in common; refactor. 10156 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10157 SDValue N0 = N->getOperand(0); 10158 EVT VT = N->getValueType(0); 10159 10160 // Constant fold FNEG. 10161 if (isConstantFPBuildVectorOrConstantFP(N0)) 10162 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10163 10164 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10165 &DAG.getTarget().Options)) 10166 return GetNegatedExpression(N0, DAG, LegalOperations); 10167 10168 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10169 // constant pool values. 10170 if (!TLI.isFNegFree(VT) && 10171 N0.getOpcode() == ISD::BITCAST && 10172 N0.getNode()->hasOneUse()) { 10173 SDValue Int = N0.getOperand(0); 10174 EVT IntVT = Int.getValueType(); 10175 if (IntVT.isInteger() && !IntVT.isVector()) { 10176 APInt SignMask; 10177 if (N0.getValueType().isVector()) { 10178 // For a vector, get a mask such as 0x80... per scalar element 10179 // and splat it. 10180 SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits()); 10181 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10182 } else { 10183 // For a scalar, just generate 0x80... 10184 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 10185 } 10186 SDLoc DL0(N0); 10187 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10188 DAG.getConstant(SignMask, DL0, IntVT)); 10189 AddToWorklist(Int.getNode()); 10190 return DAG.getBitcast(VT, Int); 10191 } 10192 } 10193 10194 // (fneg (fmul c, x)) -> (fmul -c, x) 10195 if (N0.getOpcode() == ISD::FMUL && 10196 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10197 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10198 if (CFP1) { 10199 APFloat CVal = CFP1->getValueAPF(); 10200 CVal.changeSign(); 10201 if (Level >= AfterLegalizeDAG && 10202 (TLI.isFPImmLegal(CVal, VT) || 10203 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10204 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10205 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10206 N0.getOperand(1)), 10207 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 10208 } 10209 } 10210 10211 return SDValue(); 10212 } 10213 10214 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10215 SDValue N0 = N->getOperand(0); 10216 SDValue N1 = N->getOperand(1); 10217 EVT VT = N->getValueType(0); 10218 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10219 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10220 10221 if (N0CFP && N1CFP) { 10222 const APFloat &C0 = N0CFP->getValueAPF(); 10223 const APFloat &C1 = N1CFP->getValueAPF(); 10224 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10225 } 10226 10227 // Canonicalize to constant on RHS. 10228 if (isConstantFPBuildVectorOrConstantFP(N0) && 10229 !isConstantFPBuildVectorOrConstantFP(N1)) 10230 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10231 10232 return SDValue(); 10233 } 10234 10235 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10236 SDValue N0 = N->getOperand(0); 10237 SDValue N1 = N->getOperand(1); 10238 EVT VT = N->getValueType(0); 10239 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10240 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10241 10242 if (N0CFP && N1CFP) { 10243 const APFloat &C0 = N0CFP->getValueAPF(); 10244 const APFloat &C1 = N1CFP->getValueAPF(); 10245 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10246 } 10247 10248 // Canonicalize to constant on RHS. 10249 if (isConstantFPBuildVectorOrConstantFP(N0) && 10250 !isConstantFPBuildVectorOrConstantFP(N1)) 10251 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10252 10253 return SDValue(); 10254 } 10255 10256 SDValue DAGCombiner::visitFABS(SDNode *N) { 10257 SDValue N0 = N->getOperand(0); 10258 EVT VT = N->getValueType(0); 10259 10260 // fold (fabs c1) -> fabs(c1) 10261 if (isConstantFPBuildVectorOrConstantFP(N0)) 10262 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10263 10264 // fold (fabs (fabs x)) -> (fabs x) 10265 if (N0.getOpcode() == ISD::FABS) 10266 return N->getOperand(0); 10267 10268 // fold (fabs (fneg x)) -> (fabs x) 10269 // fold (fabs (fcopysign x, y)) -> (fabs x) 10270 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10271 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10272 10273 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10274 // constant pool values. 10275 if (!TLI.isFAbsFree(VT) && 10276 N0.getOpcode() == ISD::BITCAST && 10277 N0.getNode()->hasOneUse()) { 10278 SDValue Int = N0.getOperand(0); 10279 EVT IntVT = Int.getValueType(); 10280 if (IntVT.isInteger() && !IntVT.isVector()) { 10281 APInt SignMask; 10282 if (N0.getValueType().isVector()) { 10283 // For a vector, get a mask such as 0x7f... per scalar element 10284 // and splat it. 10285 SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits()); 10286 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10287 } else { 10288 // For a scalar, just generate 0x7f... 10289 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 10290 } 10291 SDLoc DL(N0); 10292 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10293 DAG.getConstant(SignMask, DL, IntVT)); 10294 AddToWorklist(Int.getNode()); 10295 return DAG.getBitcast(N->getValueType(0), Int); 10296 } 10297 } 10298 10299 return SDValue(); 10300 } 10301 10302 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10303 SDValue Chain = N->getOperand(0); 10304 SDValue N1 = N->getOperand(1); 10305 SDValue N2 = N->getOperand(2); 10306 10307 // If N is a constant we could fold this into a fallthrough or unconditional 10308 // branch. However that doesn't happen very often in normal code, because 10309 // Instcombine/SimplifyCFG should have handled the available opportunities. 10310 // If we did this folding here, it would be necessary to update the 10311 // MachineBasicBlock CFG, which is awkward. 10312 10313 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10314 // on the target. 10315 if (N1.getOpcode() == ISD::SETCC && 10316 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10317 N1.getOperand(0).getValueType())) { 10318 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10319 Chain, N1.getOperand(2), 10320 N1.getOperand(0), N1.getOperand(1), N2); 10321 } 10322 10323 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10324 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10325 (N1.getOperand(0).hasOneUse() && 10326 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10327 SDNode *Trunc = nullptr; 10328 if (N1.getOpcode() == ISD::TRUNCATE) { 10329 // Look pass the truncate. 10330 Trunc = N1.getNode(); 10331 N1 = N1.getOperand(0); 10332 } 10333 10334 // Match this pattern so that we can generate simpler code: 10335 // 10336 // %a = ... 10337 // %b = and i32 %a, 2 10338 // %c = srl i32 %b, 1 10339 // brcond i32 %c ... 10340 // 10341 // into 10342 // 10343 // %a = ... 10344 // %b = and i32 %a, 2 10345 // %c = setcc eq %b, 0 10346 // brcond %c ... 10347 // 10348 // This applies only when the AND constant value has one bit set and the 10349 // SRL constant is equal to the log2 of the AND constant. The back-end is 10350 // smart enough to convert the result into a TEST/JMP sequence. 10351 SDValue Op0 = N1.getOperand(0); 10352 SDValue Op1 = N1.getOperand(1); 10353 10354 if (Op0.getOpcode() == ISD::AND && 10355 Op1.getOpcode() == ISD::Constant) { 10356 SDValue AndOp1 = Op0.getOperand(1); 10357 10358 if (AndOp1.getOpcode() == ISD::Constant) { 10359 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10360 10361 if (AndConst.isPowerOf2() && 10362 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10363 SDLoc DL(N); 10364 SDValue SetCC = 10365 DAG.getSetCC(DL, 10366 getSetCCResultType(Op0.getValueType()), 10367 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10368 ISD::SETNE); 10369 10370 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10371 MVT::Other, Chain, SetCC, N2); 10372 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10373 // will convert it back to (X & C1) >> C2. 10374 CombineTo(N, NewBRCond, false); 10375 // Truncate is dead. 10376 if (Trunc) 10377 deleteAndRecombine(Trunc); 10378 // Replace the uses of SRL with SETCC 10379 WorklistRemover DeadNodes(*this); 10380 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10381 deleteAndRecombine(N1.getNode()); 10382 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10383 } 10384 } 10385 } 10386 10387 if (Trunc) 10388 // Restore N1 if the above transformation doesn't match. 10389 N1 = N->getOperand(1); 10390 } 10391 10392 // Transform br(xor(x, y)) -> br(x != y) 10393 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 10394 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 10395 SDNode *TheXor = N1.getNode(); 10396 SDValue Op0 = TheXor->getOperand(0); 10397 SDValue Op1 = TheXor->getOperand(1); 10398 if (Op0.getOpcode() == Op1.getOpcode()) { 10399 // Avoid missing important xor optimizations. 10400 if (SDValue Tmp = visitXOR(TheXor)) { 10401 if (Tmp.getNode() != TheXor) { 10402 DEBUG(dbgs() << "\nReplacing.8 "; 10403 TheXor->dump(&DAG); 10404 dbgs() << "\nWith: "; 10405 Tmp.getNode()->dump(&DAG); 10406 dbgs() << '\n'); 10407 WorklistRemover DeadNodes(*this); 10408 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 10409 deleteAndRecombine(TheXor); 10410 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10411 MVT::Other, Chain, Tmp, N2); 10412 } 10413 10414 // visitXOR has changed XOR's operands or replaced the XOR completely, 10415 // bail out. 10416 return SDValue(N, 0); 10417 } 10418 } 10419 10420 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 10421 bool Equal = false; 10422 if (isOneConstant(Op0) && Op0.hasOneUse() && 10423 Op0.getOpcode() == ISD::XOR) { 10424 TheXor = Op0.getNode(); 10425 Equal = true; 10426 } 10427 10428 EVT SetCCVT = N1.getValueType(); 10429 if (LegalTypes) 10430 SetCCVT = getSetCCResultType(SetCCVT); 10431 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 10432 SetCCVT, 10433 Op0, Op1, 10434 Equal ? ISD::SETEQ : ISD::SETNE); 10435 // Replace the uses of XOR with SETCC 10436 WorklistRemover DeadNodes(*this); 10437 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10438 deleteAndRecombine(N1.getNode()); 10439 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10440 MVT::Other, Chain, SetCC, N2); 10441 } 10442 } 10443 10444 return SDValue(); 10445 } 10446 10447 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 10448 // 10449 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 10450 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 10451 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 10452 10453 // If N is a constant we could fold this into a fallthrough or unconditional 10454 // branch. However that doesn't happen very often in normal code, because 10455 // Instcombine/SimplifyCFG should have handled the available opportunities. 10456 // If we did this folding here, it would be necessary to update the 10457 // MachineBasicBlock CFG, which is awkward. 10458 10459 // Use SimplifySetCC to simplify SETCC's. 10460 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 10461 CondLHS, CondRHS, CC->get(), SDLoc(N), 10462 false); 10463 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 10464 10465 // fold to a simpler setcc 10466 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 10467 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10468 N->getOperand(0), Simp.getOperand(2), 10469 Simp.getOperand(0), Simp.getOperand(1), 10470 N->getOperand(4)); 10471 10472 return SDValue(); 10473 } 10474 10475 /// Return true if 'Use' is a load or a store that uses N as its base pointer 10476 /// and that N may be folded in the load / store addressing mode. 10477 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 10478 SelectionDAG &DAG, 10479 const TargetLowering &TLI) { 10480 EVT VT; 10481 unsigned AS; 10482 10483 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 10484 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 10485 return false; 10486 VT = LD->getMemoryVT(); 10487 AS = LD->getAddressSpace(); 10488 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 10489 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 10490 return false; 10491 VT = ST->getMemoryVT(); 10492 AS = ST->getAddressSpace(); 10493 } else 10494 return false; 10495 10496 TargetLowering::AddrMode AM; 10497 if (N->getOpcode() == ISD::ADD) { 10498 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10499 if (Offset) 10500 // [reg +/- imm] 10501 AM.BaseOffs = Offset->getSExtValue(); 10502 else 10503 // [reg +/- reg] 10504 AM.Scale = 1; 10505 } else if (N->getOpcode() == ISD::SUB) { 10506 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10507 if (Offset) 10508 // [reg +/- imm] 10509 AM.BaseOffs = -Offset->getSExtValue(); 10510 else 10511 // [reg +/- reg] 10512 AM.Scale = 1; 10513 } else 10514 return false; 10515 10516 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 10517 VT.getTypeForEVT(*DAG.getContext()), AS); 10518 } 10519 10520 /// Try turning a load/store into a pre-indexed load/store when the base 10521 /// pointer is an add or subtract and it has other uses besides the load/store. 10522 /// After the transformation, the new indexed load/store has effectively folded 10523 /// the add/subtract in and all of its other uses are redirected to the 10524 /// new load/store. 10525 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 10526 if (Level < AfterLegalizeDAG) 10527 return false; 10528 10529 bool isLoad = true; 10530 SDValue Ptr; 10531 EVT VT; 10532 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10533 if (LD->isIndexed()) 10534 return false; 10535 VT = LD->getMemoryVT(); 10536 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 10537 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 10538 return false; 10539 Ptr = LD->getBasePtr(); 10540 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10541 if (ST->isIndexed()) 10542 return false; 10543 VT = ST->getMemoryVT(); 10544 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 10545 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 10546 return false; 10547 Ptr = ST->getBasePtr(); 10548 isLoad = false; 10549 } else { 10550 return false; 10551 } 10552 10553 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 10554 // out. There is no reason to make this a preinc/predec. 10555 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 10556 Ptr.getNode()->hasOneUse()) 10557 return false; 10558 10559 // Ask the target to do addressing mode selection. 10560 SDValue BasePtr; 10561 SDValue Offset; 10562 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10563 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 10564 return false; 10565 10566 // Backends without true r+i pre-indexed forms may need to pass a 10567 // constant base with a variable offset so that constant coercion 10568 // will work with the patterns in canonical form. 10569 bool Swapped = false; 10570 if (isa<ConstantSDNode>(BasePtr)) { 10571 std::swap(BasePtr, Offset); 10572 Swapped = true; 10573 } 10574 10575 // Don't create a indexed load / store with zero offset. 10576 if (isNullConstant(Offset)) 10577 return false; 10578 10579 // Try turning it into a pre-indexed load / store except when: 10580 // 1) The new base ptr is a frame index. 10581 // 2) If N is a store and the new base ptr is either the same as or is a 10582 // predecessor of the value being stored. 10583 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 10584 // that would create a cycle. 10585 // 4) All uses are load / store ops that use it as old base ptr. 10586 10587 // Check #1. Preinc'ing a frame index would require copying the stack pointer 10588 // (plus the implicit offset) to a register to preinc anyway. 10589 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10590 return false; 10591 10592 // Check #2. 10593 if (!isLoad) { 10594 SDValue Val = cast<StoreSDNode>(N)->getValue(); 10595 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 10596 return false; 10597 } 10598 10599 // Caches for hasPredecessorHelper. 10600 SmallPtrSet<const SDNode *, 32> Visited; 10601 SmallVector<const SDNode *, 16> Worklist; 10602 Worklist.push_back(N); 10603 10604 // If the offset is a constant, there may be other adds of constants that 10605 // can be folded with this one. We should do this to avoid having to keep 10606 // a copy of the original base pointer. 10607 SmallVector<SDNode *, 16> OtherUses; 10608 if (isa<ConstantSDNode>(Offset)) 10609 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 10610 UE = BasePtr.getNode()->use_end(); 10611 UI != UE; ++UI) { 10612 SDUse &Use = UI.getUse(); 10613 // Skip the use that is Ptr and uses of other results from BasePtr's 10614 // node (important for nodes that return multiple results). 10615 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 10616 continue; 10617 10618 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 10619 continue; 10620 10621 if (Use.getUser()->getOpcode() != ISD::ADD && 10622 Use.getUser()->getOpcode() != ISD::SUB) { 10623 OtherUses.clear(); 10624 break; 10625 } 10626 10627 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 10628 if (!isa<ConstantSDNode>(Op1)) { 10629 OtherUses.clear(); 10630 break; 10631 } 10632 10633 // FIXME: In some cases, we can be smarter about this. 10634 if (Op1.getValueType() != Offset.getValueType()) { 10635 OtherUses.clear(); 10636 break; 10637 } 10638 10639 OtherUses.push_back(Use.getUser()); 10640 } 10641 10642 if (Swapped) 10643 std::swap(BasePtr, Offset); 10644 10645 // Now check for #3 and #4. 10646 bool RealUse = false; 10647 10648 for (SDNode *Use : Ptr.getNode()->uses()) { 10649 if (Use == N) 10650 continue; 10651 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 10652 return false; 10653 10654 // If Ptr may be folded in addressing mode of other use, then it's 10655 // not profitable to do this transformation. 10656 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 10657 RealUse = true; 10658 } 10659 10660 if (!RealUse) 10661 return false; 10662 10663 SDValue Result; 10664 if (isLoad) 10665 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10666 BasePtr, Offset, AM); 10667 else 10668 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10669 BasePtr, Offset, AM); 10670 ++PreIndexedNodes; 10671 ++NodesCombined; 10672 DEBUG(dbgs() << "\nReplacing.4 "; 10673 N->dump(&DAG); 10674 dbgs() << "\nWith: "; 10675 Result.getNode()->dump(&DAG); 10676 dbgs() << '\n'); 10677 WorklistRemover DeadNodes(*this); 10678 if (isLoad) { 10679 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10680 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10681 } else { 10682 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10683 } 10684 10685 // Finally, since the node is now dead, remove it from the graph. 10686 deleteAndRecombine(N); 10687 10688 if (Swapped) 10689 std::swap(BasePtr, Offset); 10690 10691 // Replace other uses of BasePtr that can be updated to use Ptr 10692 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 10693 unsigned OffsetIdx = 1; 10694 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 10695 OffsetIdx = 0; 10696 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 10697 BasePtr.getNode() && "Expected BasePtr operand"); 10698 10699 // We need to replace ptr0 in the following expression: 10700 // x0 * offset0 + y0 * ptr0 = t0 10701 // knowing that 10702 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 10703 // 10704 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 10705 // indexed load/store and the expresion that needs to be re-written. 10706 // 10707 // Therefore, we have: 10708 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 10709 10710 ConstantSDNode *CN = 10711 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 10712 int X0, X1, Y0, Y1; 10713 const APInt &Offset0 = CN->getAPIntValue(); 10714 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 10715 10716 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 10717 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 10718 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 10719 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 10720 10721 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 10722 10723 APInt CNV = Offset0; 10724 if (X0 < 0) CNV = -CNV; 10725 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 10726 else CNV = CNV - Offset1; 10727 10728 SDLoc DL(OtherUses[i]); 10729 10730 // We can now generate the new expression. 10731 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 10732 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 10733 10734 SDValue NewUse = DAG.getNode(Opcode, 10735 DL, 10736 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 10737 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 10738 deleteAndRecombine(OtherUses[i]); 10739 } 10740 10741 // Replace the uses of Ptr with uses of the updated base value. 10742 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 10743 deleteAndRecombine(Ptr.getNode()); 10744 10745 return true; 10746 } 10747 10748 /// Try to combine a load/store with a add/sub of the base pointer node into a 10749 /// post-indexed load/store. The transformation folded the add/subtract into the 10750 /// new indexed load/store effectively and all of its uses are redirected to the 10751 /// new load/store. 10752 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 10753 if (Level < AfterLegalizeDAG) 10754 return false; 10755 10756 bool isLoad = true; 10757 SDValue Ptr; 10758 EVT VT; 10759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10760 if (LD->isIndexed()) 10761 return false; 10762 VT = LD->getMemoryVT(); 10763 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 10764 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 10765 return false; 10766 Ptr = LD->getBasePtr(); 10767 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10768 if (ST->isIndexed()) 10769 return false; 10770 VT = ST->getMemoryVT(); 10771 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 10772 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 10773 return false; 10774 Ptr = ST->getBasePtr(); 10775 isLoad = false; 10776 } else { 10777 return false; 10778 } 10779 10780 if (Ptr.getNode()->hasOneUse()) 10781 return false; 10782 10783 for (SDNode *Op : Ptr.getNode()->uses()) { 10784 if (Op == N || 10785 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 10786 continue; 10787 10788 SDValue BasePtr; 10789 SDValue Offset; 10790 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10791 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 10792 // Don't create a indexed load / store with zero offset. 10793 if (isNullConstant(Offset)) 10794 continue; 10795 10796 // Try turning it into a post-indexed load / store except when 10797 // 1) All uses are load / store ops that use it as base ptr (and 10798 // it may be folded as addressing mmode). 10799 // 2) Op must be independent of N, i.e. Op is neither a predecessor 10800 // nor a successor of N. Otherwise, if Op is folded that would 10801 // create a cycle. 10802 10803 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10804 continue; 10805 10806 // Check for #1. 10807 bool TryNext = false; 10808 for (SDNode *Use : BasePtr.getNode()->uses()) { 10809 if (Use == Ptr.getNode()) 10810 continue; 10811 10812 // If all the uses are load / store addresses, then don't do the 10813 // transformation. 10814 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 10815 bool RealUse = false; 10816 for (SDNode *UseUse : Use->uses()) { 10817 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 10818 RealUse = true; 10819 } 10820 10821 if (!RealUse) { 10822 TryNext = true; 10823 break; 10824 } 10825 } 10826 } 10827 10828 if (TryNext) 10829 continue; 10830 10831 // Check for #2 10832 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 10833 SDValue Result = isLoad 10834 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10835 BasePtr, Offset, AM) 10836 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10837 BasePtr, Offset, AM); 10838 ++PostIndexedNodes; 10839 ++NodesCombined; 10840 DEBUG(dbgs() << "\nReplacing.5 "; 10841 N->dump(&DAG); 10842 dbgs() << "\nWith: "; 10843 Result.getNode()->dump(&DAG); 10844 dbgs() << '\n'); 10845 WorklistRemover DeadNodes(*this); 10846 if (isLoad) { 10847 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10848 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10849 } else { 10850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10851 } 10852 10853 // Finally, since the node is now dead, remove it from the graph. 10854 deleteAndRecombine(N); 10855 10856 // Replace the uses of Use with uses of the updated base value. 10857 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 10858 Result.getValue(isLoad ? 1 : 0)); 10859 deleteAndRecombine(Op); 10860 return true; 10861 } 10862 } 10863 } 10864 10865 return false; 10866 } 10867 10868 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 10869 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 10870 ISD::MemIndexedMode AM = LD->getAddressingMode(); 10871 assert(AM != ISD::UNINDEXED); 10872 SDValue BP = LD->getOperand(1); 10873 SDValue Inc = LD->getOperand(2); 10874 10875 // Some backends use TargetConstants for load offsets, but don't expect 10876 // TargetConstants in general ADD nodes. We can convert these constants into 10877 // regular Constants (if the constant is not opaque). 10878 assert((Inc.getOpcode() != ISD::TargetConstant || 10879 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10880 "Cannot split out indexing using opaque target constants"); 10881 if (Inc.getOpcode() == ISD::TargetConstant) { 10882 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10883 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10884 ConstInc->getValueType(0)); 10885 } 10886 10887 unsigned Opc = 10888 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10889 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10890 } 10891 10892 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10893 LoadSDNode *LD = cast<LoadSDNode>(N); 10894 SDValue Chain = LD->getChain(); 10895 SDValue Ptr = LD->getBasePtr(); 10896 10897 // If load is not volatile and there are no uses of the loaded value (and 10898 // the updated indexed value in case of indexed loads), change uses of the 10899 // chain value into uses of the chain input (i.e. delete the dead load). 10900 if (!LD->isVolatile()) { 10901 if (N->getValueType(1) == MVT::Other) { 10902 // Unindexed loads. 10903 if (!N->hasAnyUseOfValue(0)) { 10904 // It's not safe to use the two value CombineTo variant here. e.g. 10905 // v1, chain2 = load chain1, loc 10906 // v2, chain3 = load chain2, loc 10907 // v3 = add v2, c 10908 // Now we replace use of chain2 with chain1. This makes the second load 10909 // isomorphic to the one we are deleting, and thus makes this load live. 10910 DEBUG(dbgs() << "\nReplacing.6 "; 10911 N->dump(&DAG); 10912 dbgs() << "\nWith chain: "; 10913 Chain.getNode()->dump(&DAG); 10914 dbgs() << "\n"); 10915 WorklistRemover DeadNodes(*this); 10916 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10917 10918 if (N->use_empty()) 10919 deleteAndRecombine(N); 10920 10921 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10922 } 10923 } else { 10924 // Indexed loads. 10925 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10926 10927 // If this load has an opaque TargetConstant offset, then we cannot split 10928 // the indexing into an add/sub directly (that TargetConstant may not be 10929 // valid for a different type of node, and we cannot convert an opaque 10930 // target constant into a regular constant). 10931 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10932 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10933 10934 if (!N->hasAnyUseOfValue(0) && 10935 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10936 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10937 SDValue Index; 10938 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10939 Index = SplitIndexingFromLoad(LD); 10940 // Try to fold the base pointer arithmetic into subsequent loads and 10941 // stores. 10942 AddUsersToWorklist(N); 10943 } else 10944 Index = DAG.getUNDEF(N->getValueType(1)); 10945 DEBUG(dbgs() << "\nReplacing.7 "; 10946 N->dump(&DAG); 10947 dbgs() << "\nWith: "; 10948 Undef.getNode()->dump(&DAG); 10949 dbgs() << " and 2 other values\n"); 10950 WorklistRemover DeadNodes(*this); 10951 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10952 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10953 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10954 deleteAndRecombine(N); 10955 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10956 } 10957 } 10958 } 10959 10960 // If this load is directly stored, replace the load value with the stored 10961 // value. 10962 // TODO: Handle store large -> read small portion. 10963 // TODO: Handle TRUNCSTORE/LOADEXT 10964 if (OptLevel != CodeGenOpt::None && 10965 ISD::isNormalLoad(N) && !LD->isVolatile()) { 10966 // We can forward a direct store or a store off of a tokenfactor. 10967 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10968 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10969 if (PrevST->getBasePtr() == Ptr && 10970 PrevST->getValue().getValueType() == N->getValueType(0)) 10971 return CombineTo(N, PrevST->getOperand(1), Chain); 10972 } 10973 } 10974 10975 // Try to infer better alignment information than the load already has. 10976 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10977 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10978 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10979 SDValue NewLoad = DAG.getExtLoad( 10980 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10981 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10982 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10983 if (NewLoad.getNode() != N) 10984 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10985 } 10986 } 10987 } 10988 10989 if (LD->isUnindexed()) { 10990 // Walk up chain skipping non-aliasing memory nodes. 10991 SDValue BetterChain = FindBetterChain(N, Chain); 10992 10993 // If there is a better chain. 10994 if (Chain != BetterChain) { 10995 SDValue ReplLoad; 10996 10997 // Replace the chain to void dependency. 10998 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10999 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11000 BetterChain, Ptr, LD->getMemOperand()); 11001 } else { 11002 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11003 LD->getValueType(0), 11004 BetterChain, Ptr, LD->getMemoryVT(), 11005 LD->getMemOperand()); 11006 } 11007 11008 // Create token factor to keep old chain connected. 11009 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11010 MVT::Other, Chain, ReplLoad.getValue(1)); 11011 11012 // Make sure the new and old chains are cleaned up. 11013 AddToWorklist(Token.getNode()); 11014 11015 // Replace uses with load result and token factor. Don't add users 11016 // to work list. 11017 return CombineTo(N, ReplLoad.getValue(0), Token, false); 11018 } 11019 } 11020 11021 // Try transforming N to an indexed load. 11022 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11023 return SDValue(N, 0); 11024 11025 // Try to slice up N to more direct loads if the slices are mapped to 11026 // different register banks or pairing can take place. 11027 if (SliceUpLoad(N)) 11028 return SDValue(N, 0); 11029 11030 return SDValue(); 11031 } 11032 11033 namespace { 11034 /// \brief Helper structure used to slice a load in smaller loads. 11035 /// Basically a slice is obtained from the following sequence: 11036 /// Origin = load Ty1, Base 11037 /// Shift = srl Ty1 Origin, CstTy Amount 11038 /// Inst = trunc Shift to Ty2 11039 /// 11040 /// Then, it will be rewriten into: 11041 /// Slice = load SliceTy, Base + SliceOffset 11042 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11043 /// 11044 /// SliceTy is deduced from the number of bits that are actually used to 11045 /// build Inst. 11046 struct LoadedSlice { 11047 /// \brief Helper structure used to compute the cost of a slice. 11048 struct Cost { 11049 /// Are we optimizing for code size. 11050 bool ForCodeSize; 11051 /// Various cost. 11052 unsigned Loads; 11053 unsigned Truncates; 11054 unsigned CrossRegisterBanksCopies; 11055 unsigned ZExts; 11056 unsigned Shift; 11057 11058 Cost(bool ForCodeSize = false) 11059 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 11060 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 11061 11062 /// \brief Get the cost of one isolated slice. 11063 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11064 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 11065 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 11066 EVT TruncType = LS.Inst->getValueType(0); 11067 EVT LoadedType = LS.getLoadedType(); 11068 if (TruncType != LoadedType && 11069 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11070 ZExts = 1; 11071 } 11072 11073 /// \brief Account for slicing gain in the current cost. 11074 /// Slicing provide a few gains like removing a shift or a 11075 /// truncate. This method allows to grow the cost of the original 11076 /// load with the gain from this slice. 11077 void addSliceGain(const LoadedSlice &LS) { 11078 // Each slice saves a truncate. 11079 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11080 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11081 LS.Inst->getValueType(0))) 11082 ++Truncates; 11083 // If there is a shift amount, this slice gets rid of it. 11084 if (LS.Shift) 11085 ++Shift; 11086 // If this slice can merge a cross register bank copy, account for it. 11087 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11088 ++CrossRegisterBanksCopies; 11089 } 11090 11091 Cost &operator+=(const Cost &RHS) { 11092 Loads += RHS.Loads; 11093 Truncates += RHS.Truncates; 11094 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11095 ZExts += RHS.ZExts; 11096 Shift += RHS.Shift; 11097 return *this; 11098 } 11099 11100 bool operator==(const Cost &RHS) const { 11101 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11102 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11103 ZExts == RHS.ZExts && Shift == RHS.Shift; 11104 } 11105 11106 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11107 11108 bool operator<(const Cost &RHS) const { 11109 // Assume cross register banks copies are as expensive as loads. 11110 // FIXME: Do we want some more target hooks? 11111 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11112 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11113 // Unless we are optimizing for code size, consider the 11114 // expensive operation first. 11115 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11116 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11117 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11118 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11119 } 11120 11121 bool operator>(const Cost &RHS) const { return RHS < *this; } 11122 11123 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11124 11125 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11126 }; 11127 // The last instruction that represent the slice. This should be a 11128 // truncate instruction. 11129 SDNode *Inst; 11130 // The original load instruction. 11131 LoadSDNode *Origin; 11132 // The right shift amount in bits from the original load. 11133 unsigned Shift; 11134 // The DAG from which Origin came from. 11135 // This is used to get some contextual information about legal types, etc. 11136 SelectionDAG *DAG; 11137 11138 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11139 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11140 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11141 11142 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11143 /// \return Result is \p BitWidth and has used bits set to 1 and 11144 /// not used bits set to 0. 11145 APInt getUsedBits() const { 11146 // Reproduce the trunc(lshr) sequence: 11147 // - Start from the truncated value. 11148 // - Zero extend to the desired bit width. 11149 // - Shift left. 11150 assert(Origin && "No original load to compare against."); 11151 unsigned BitWidth = Origin->getValueSizeInBits(0); 11152 assert(Inst && "This slice is not bound to an instruction"); 11153 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11154 "Extracted slice is bigger than the whole type!"); 11155 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11156 UsedBits.setAllBits(); 11157 UsedBits = UsedBits.zext(BitWidth); 11158 UsedBits <<= Shift; 11159 return UsedBits; 11160 } 11161 11162 /// \brief Get the size of the slice to be loaded in bytes. 11163 unsigned getLoadedSize() const { 11164 unsigned SliceSize = getUsedBits().countPopulation(); 11165 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11166 return SliceSize / 8; 11167 } 11168 11169 /// \brief Get the type that will be loaded for this slice. 11170 /// Note: This may not be the final type for the slice. 11171 EVT getLoadedType() const { 11172 assert(DAG && "Missing context"); 11173 LLVMContext &Ctxt = *DAG->getContext(); 11174 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11175 } 11176 11177 /// \brief Get the alignment of the load used for this slice. 11178 unsigned getAlignment() const { 11179 unsigned Alignment = Origin->getAlignment(); 11180 unsigned Offset = getOffsetFromBase(); 11181 if (Offset != 0) 11182 Alignment = MinAlign(Alignment, Alignment + Offset); 11183 return Alignment; 11184 } 11185 11186 /// \brief Check if this slice can be rewritten with legal operations. 11187 bool isLegal() const { 11188 // An invalid slice is not legal. 11189 if (!Origin || !Inst || !DAG) 11190 return false; 11191 11192 // Offsets are for indexed load only, we do not handle that. 11193 if (!Origin->getOffset().isUndef()) 11194 return false; 11195 11196 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11197 11198 // Check that the type is legal. 11199 EVT SliceType = getLoadedType(); 11200 if (!TLI.isTypeLegal(SliceType)) 11201 return false; 11202 11203 // Check that the load is legal for this type. 11204 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11205 return false; 11206 11207 // Check that the offset can be computed. 11208 // 1. Check its type. 11209 EVT PtrType = Origin->getBasePtr().getValueType(); 11210 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11211 return false; 11212 11213 // 2. Check that it fits in the immediate. 11214 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11215 return false; 11216 11217 // 3. Check that the computation is legal. 11218 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11219 return false; 11220 11221 // Check that the zext is legal if it needs one. 11222 EVT TruncateType = Inst->getValueType(0); 11223 if (TruncateType != SliceType && 11224 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11225 return false; 11226 11227 return true; 11228 } 11229 11230 /// \brief Get the offset in bytes of this slice in the original chunk of 11231 /// bits. 11232 /// \pre DAG != nullptr. 11233 uint64_t getOffsetFromBase() const { 11234 assert(DAG && "Missing context."); 11235 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11236 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11237 uint64_t Offset = Shift / 8; 11238 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11239 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11240 "The size of the original loaded type is not a multiple of a" 11241 " byte."); 11242 // If Offset is bigger than TySizeInBytes, it means we are loading all 11243 // zeros. This should have been optimized before in the process. 11244 assert(TySizeInBytes > Offset && 11245 "Invalid shift amount for given loaded size"); 11246 if (IsBigEndian) 11247 Offset = TySizeInBytes - Offset - getLoadedSize(); 11248 return Offset; 11249 } 11250 11251 /// \brief Generate the sequence of instructions to load the slice 11252 /// represented by this object and redirect the uses of this slice to 11253 /// this new sequence of instructions. 11254 /// \pre this->Inst && this->Origin are valid Instructions and this 11255 /// object passed the legal check: LoadedSlice::isLegal returned true. 11256 /// \return The last instruction of the sequence used to load the slice. 11257 SDValue loadSlice() const { 11258 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11259 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11260 SDValue BaseAddr = OldBaseAddr; 11261 // Get the offset in that chunk of bytes w.r.t. the endianness. 11262 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11263 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11264 if (Offset) { 11265 // BaseAddr = BaseAddr + Offset. 11266 EVT ArithType = BaseAddr.getValueType(); 11267 SDLoc DL(Origin); 11268 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11269 DAG->getConstant(Offset, DL, ArithType)); 11270 } 11271 11272 // Create the type of the loaded slice according to its size. 11273 EVT SliceType = getLoadedType(); 11274 11275 // Create the load for the slice. 11276 SDValue LastInst = 11277 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11278 Origin->getPointerInfo().getWithOffset(Offset), 11279 getAlignment(), Origin->getMemOperand()->getFlags()); 11280 // If the final type is not the same as the loaded type, this means that 11281 // we have to pad with zero. Create a zero extend for that. 11282 EVT FinalType = Inst->getValueType(0); 11283 if (SliceType != FinalType) 11284 LastInst = 11285 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11286 return LastInst; 11287 } 11288 11289 /// \brief Check if this slice can be merged with an expensive cross register 11290 /// bank copy. E.g., 11291 /// i = load i32 11292 /// f = bitcast i32 i to float 11293 bool canMergeExpensiveCrossRegisterBankCopy() const { 11294 if (!Inst || !Inst->hasOneUse()) 11295 return false; 11296 SDNode *Use = *Inst->use_begin(); 11297 if (Use->getOpcode() != ISD::BITCAST) 11298 return false; 11299 assert(DAG && "Missing context"); 11300 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11301 EVT ResVT = Use->getValueType(0); 11302 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11303 const TargetRegisterClass *ArgRC = 11304 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11305 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11306 return false; 11307 11308 // At this point, we know that we perform a cross-register-bank copy. 11309 // Check if it is expensive. 11310 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11311 // Assume bitcasts are cheap, unless both register classes do not 11312 // explicitly share a common sub class. 11313 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11314 return false; 11315 11316 // Check if it will be merged with the load. 11317 // 1. Check the alignment constraint. 11318 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11319 ResVT.getTypeForEVT(*DAG->getContext())); 11320 11321 if (RequiredAlignment > getAlignment()) 11322 return false; 11323 11324 // 2. Check that the load is a legal operation for that type. 11325 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11326 return false; 11327 11328 // 3. Check that we do not have a zext in the way. 11329 if (Inst->getValueType(0) != getLoadedType()) 11330 return false; 11331 11332 return true; 11333 } 11334 }; 11335 } 11336 11337 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11338 /// \p UsedBits looks like 0..0 1..1 0..0. 11339 static bool areUsedBitsDense(const APInt &UsedBits) { 11340 // If all the bits are one, this is dense! 11341 if (UsedBits.isAllOnesValue()) 11342 return true; 11343 11344 // Get rid of the unused bits on the right. 11345 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11346 // Get rid of the unused bits on the left. 11347 if (NarrowedUsedBits.countLeadingZeros()) 11348 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11349 // Check that the chunk of bits is completely used. 11350 return NarrowedUsedBits.isAllOnesValue(); 11351 } 11352 11353 /// \brief Check whether or not \p First and \p Second are next to each other 11354 /// in memory. This means that there is no hole between the bits loaded 11355 /// by \p First and the bits loaded by \p Second. 11356 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11357 const LoadedSlice &Second) { 11358 assert(First.Origin == Second.Origin && First.Origin && 11359 "Unable to match different memory origins."); 11360 APInt UsedBits = First.getUsedBits(); 11361 assert((UsedBits & Second.getUsedBits()) == 0 && 11362 "Slices are not supposed to overlap."); 11363 UsedBits |= Second.getUsedBits(); 11364 return areUsedBitsDense(UsedBits); 11365 } 11366 11367 /// \brief Adjust the \p GlobalLSCost according to the target 11368 /// paring capabilities and the layout of the slices. 11369 /// \pre \p GlobalLSCost should account for at least as many loads as 11370 /// there is in the slices in \p LoadedSlices. 11371 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11372 LoadedSlice::Cost &GlobalLSCost) { 11373 unsigned NumberOfSlices = LoadedSlices.size(); 11374 // If there is less than 2 elements, no pairing is possible. 11375 if (NumberOfSlices < 2) 11376 return; 11377 11378 // Sort the slices so that elements that are likely to be next to each 11379 // other in memory are next to each other in the list. 11380 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11381 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11382 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11383 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11384 }); 11385 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11386 // First (resp. Second) is the first (resp. Second) potentially candidate 11387 // to be placed in a paired load. 11388 const LoadedSlice *First = nullptr; 11389 const LoadedSlice *Second = nullptr; 11390 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 11391 // Set the beginning of the pair. 11392 First = Second) { 11393 11394 Second = &LoadedSlices[CurrSlice]; 11395 11396 // If First is NULL, it means we start a new pair. 11397 // Get to the next slice. 11398 if (!First) 11399 continue; 11400 11401 EVT LoadedType = First->getLoadedType(); 11402 11403 // If the types of the slices are different, we cannot pair them. 11404 if (LoadedType != Second->getLoadedType()) 11405 continue; 11406 11407 // Check if the target supplies paired loads for this type. 11408 unsigned RequiredAlignment = 0; 11409 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 11410 // move to the next pair, this type is hopeless. 11411 Second = nullptr; 11412 continue; 11413 } 11414 // Check if we meet the alignment requirement. 11415 if (RequiredAlignment > First->getAlignment()) 11416 continue; 11417 11418 // Check that both loads are next to each other in memory. 11419 if (!areSlicesNextToEachOther(*First, *Second)) 11420 continue; 11421 11422 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 11423 --GlobalLSCost.Loads; 11424 // Move to the next pair. 11425 Second = nullptr; 11426 } 11427 } 11428 11429 /// \brief Check the profitability of all involved LoadedSlice. 11430 /// Currently, it is considered profitable if there is exactly two 11431 /// involved slices (1) which are (2) next to each other in memory, and 11432 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 11433 /// 11434 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 11435 /// the elements themselves. 11436 /// 11437 /// FIXME: When the cost model will be mature enough, we can relax 11438 /// constraints (1) and (2). 11439 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11440 const APInt &UsedBits, bool ForCodeSize) { 11441 unsigned NumberOfSlices = LoadedSlices.size(); 11442 if (StressLoadSlicing) 11443 return NumberOfSlices > 1; 11444 11445 // Check (1). 11446 if (NumberOfSlices != 2) 11447 return false; 11448 11449 // Check (2). 11450 if (!areUsedBitsDense(UsedBits)) 11451 return false; 11452 11453 // Check (3). 11454 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 11455 // The original code has one big load. 11456 OrigCost.Loads = 1; 11457 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 11458 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 11459 // Accumulate the cost of all the slices. 11460 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 11461 GlobalSlicingCost += SliceCost; 11462 11463 // Account as cost in the original configuration the gain obtained 11464 // with the current slices. 11465 OrigCost.addSliceGain(LS); 11466 } 11467 11468 // If the target supports paired load, adjust the cost accordingly. 11469 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 11470 return OrigCost > GlobalSlicingCost; 11471 } 11472 11473 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 11474 /// operations, split it in the various pieces being extracted. 11475 /// 11476 /// This sort of thing is introduced by SROA. 11477 /// This slicing takes care not to insert overlapping loads. 11478 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 11479 bool DAGCombiner::SliceUpLoad(SDNode *N) { 11480 if (Level < AfterLegalizeDAG) 11481 return false; 11482 11483 LoadSDNode *LD = cast<LoadSDNode>(N); 11484 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 11485 !LD->getValueType(0).isInteger()) 11486 return false; 11487 11488 // Keep track of already used bits to detect overlapping values. 11489 // In that case, we will just abort the transformation. 11490 APInt UsedBits(LD->getValueSizeInBits(0), 0); 11491 11492 SmallVector<LoadedSlice, 4> LoadedSlices; 11493 11494 // Check if this load is used as several smaller chunks of bits. 11495 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 11496 // of computation for each trunc. 11497 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 11498 UI != UIEnd; ++UI) { 11499 // Skip the uses of the chain. 11500 if (UI.getUse().getResNo() != 0) 11501 continue; 11502 11503 SDNode *User = *UI; 11504 unsigned Shift = 0; 11505 11506 // Check if this is a trunc(lshr). 11507 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 11508 isa<ConstantSDNode>(User->getOperand(1))) { 11509 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 11510 User = *User->use_begin(); 11511 } 11512 11513 // At this point, User is a Truncate, iff we encountered, trunc or 11514 // trunc(lshr). 11515 if (User->getOpcode() != ISD::TRUNCATE) 11516 return false; 11517 11518 // The width of the type must be a power of 2 and greater than 8-bits. 11519 // Otherwise the load cannot be represented in LLVM IR. 11520 // Moreover, if we shifted with a non-8-bits multiple, the slice 11521 // will be across several bytes. We do not support that. 11522 unsigned Width = User->getValueSizeInBits(0); 11523 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 11524 return 0; 11525 11526 // Build the slice for this chain of computations. 11527 LoadedSlice LS(User, LD, Shift, &DAG); 11528 APInt CurrentUsedBits = LS.getUsedBits(); 11529 11530 // Check if this slice overlaps with another. 11531 if ((CurrentUsedBits & UsedBits) != 0) 11532 return false; 11533 // Update the bits used globally. 11534 UsedBits |= CurrentUsedBits; 11535 11536 // Check if the new slice would be legal. 11537 if (!LS.isLegal()) 11538 return false; 11539 11540 // Record the slice. 11541 LoadedSlices.push_back(LS); 11542 } 11543 11544 // Abort slicing if it does not seem to be profitable. 11545 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 11546 return false; 11547 11548 ++SlicedLoads; 11549 11550 // Rewrite each chain to use an independent load. 11551 // By construction, each chain can be represented by a unique load. 11552 11553 // Prepare the argument for the new token factor for all the slices. 11554 SmallVector<SDValue, 8> ArgChains; 11555 for (SmallVectorImpl<LoadedSlice>::const_iterator 11556 LSIt = LoadedSlices.begin(), 11557 LSItEnd = LoadedSlices.end(); 11558 LSIt != LSItEnd; ++LSIt) { 11559 SDValue SliceInst = LSIt->loadSlice(); 11560 CombineTo(LSIt->Inst, SliceInst, true); 11561 if (SliceInst.getOpcode() != ISD::LOAD) 11562 SliceInst = SliceInst.getOperand(0); 11563 assert(SliceInst->getOpcode() == ISD::LOAD && 11564 "It takes more than a zext to get to the loaded slice!!"); 11565 ArgChains.push_back(SliceInst.getValue(1)); 11566 } 11567 11568 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 11569 ArgChains); 11570 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11571 AddToWorklist(Chain.getNode()); 11572 return true; 11573 } 11574 11575 /// Check to see if V is (and load (ptr), imm), where the load is having 11576 /// specific bytes cleared out. If so, return the byte size being masked out 11577 /// and the shift amount. 11578 static std::pair<unsigned, unsigned> 11579 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 11580 std::pair<unsigned, unsigned> Result(0, 0); 11581 11582 // Check for the structure we're looking for. 11583 if (V->getOpcode() != ISD::AND || 11584 !isa<ConstantSDNode>(V->getOperand(1)) || 11585 !ISD::isNormalLoad(V->getOperand(0).getNode())) 11586 return Result; 11587 11588 // Check the chain and pointer. 11589 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 11590 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 11591 11592 // The store should be chained directly to the load or be an operand of a 11593 // tokenfactor. 11594 if (LD == Chain.getNode()) 11595 ; // ok. 11596 else if (Chain->getOpcode() != ISD::TokenFactor) 11597 return Result; // Fail. 11598 else { 11599 bool isOk = false; 11600 for (const SDValue &ChainOp : Chain->op_values()) 11601 if (ChainOp.getNode() == LD) { 11602 isOk = true; 11603 break; 11604 } 11605 if (!isOk) return Result; 11606 } 11607 11608 // This only handles simple types. 11609 if (V.getValueType() != MVT::i16 && 11610 V.getValueType() != MVT::i32 && 11611 V.getValueType() != MVT::i64) 11612 return Result; 11613 11614 // Check the constant mask. Invert it so that the bits being masked out are 11615 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 11616 // follow the sign bit for uniformity. 11617 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 11618 unsigned NotMaskLZ = countLeadingZeros(NotMask); 11619 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 11620 unsigned NotMaskTZ = countTrailingZeros(NotMask); 11621 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 11622 if (NotMaskLZ == 64) return Result; // All zero mask. 11623 11624 // See if we have a continuous run of bits. If so, we have 0*1+0* 11625 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 11626 return Result; 11627 11628 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 11629 if (V.getValueType() != MVT::i64 && NotMaskLZ) 11630 NotMaskLZ -= 64-V.getValueSizeInBits(); 11631 11632 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 11633 switch (MaskedBytes) { 11634 case 1: 11635 case 2: 11636 case 4: break; 11637 default: return Result; // All one mask, or 5-byte mask. 11638 } 11639 11640 // Verify that the first bit starts at a multiple of mask so that the access 11641 // is aligned the same as the access width. 11642 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 11643 11644 Result.first = MaskedBytes; 11645 Result.second = NotMaskTZ/8; 11646 return Result; 11647 } 11648 11649 11650 /// Check to see if IVal is something that provides a value as specified by 11651 /// MaskInfo. If so, replace the specified store with a narrower store of 11652 /// truncated IVal. 11653 static SDNode * 11654 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 11655 SDValue IVal, StoreSDNode *St, 11656 DAGCombiner *DC) { 11657 unsigned NumBytes = MaskInfo.first; 11658 unsigned ByteShift = MaskInfo.second; 11659 SelectionDAG &DAG = DC->getDAG(); 11660 11661 // Check to see if IVal is all zeros in the part being masked in by the 'or' 11662 // that uses this. If not, this is not a replacement. 11663 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 11664 ByteShift*8, (ByteShift+NumBytes)*8); 11665 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 11666 11667 // Check that it is legal on the target to do this. It is legal if the new 11668 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 11669 // legalization. 11670 MVT VT = MVT::getIntegerVT(NumBytes*8); 11671 if (!DC->isTypeLegal(VT)) 11672 return nullptr; 11673 11674 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 11675 // shifted by ByteShift and truncated down to NumBytes. 11676 if (ByteShift) { 11677 SDLoc DL(IVal); 11678 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 11679 DAG.getConstant(ByteShift*8, DL, 11680 DC->getShiftAmountTy(IVal.getValueType()))); 11681 } 11682 11683 // Figure out the offset for the store and the alignment of the access. 11684 unsigned StOffset; 11685 unsigned NewAlign = St->getAlignment(); 11686 11687 if (DAG.getDataLayout().isLittleEndian()) 11688 StOffset = ByteShift; 11689 else 11690 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 11691 11692 SDValue Ptr = St->getBasePtr(); 11693 if (StOffset) { 11694 SDLoc DL(IVal); 11695 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 11696 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 11697 NewAlign = MinAlign(NewAlign, StOffset); 11698 } 11699 11700 // Truncate down to the new size. 11701 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 11702 11703 ++OpsNarrowed; 11704 return DAG 11705 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 11706 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 11707 .getNode(); 11708 } 11709 11710 11711 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 11712 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 11713 /// narrowing the load and store if it would end up being a win for performance 11714 /// or code size. 11715 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 11716 StoreSDNode *ST = cast<StoreSDNode>(N); 11717 if (ST->isVolatile()) 11718 return SDValue(); 11719 11720 SDValue Chain = ST->getChain(); 11721 SDValue Value = ST->getValue(); 11722 SDValue Ptr = ST->getBasePtr(); 11723 EVT VT = Value.getValueType(); 11724 11725 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 11726 return SDValue(); 11727 11728 unsigned Opc = Value.getOpcode(); 11729 11730 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 11731 // is a byte mask indicating a consecutive number of bytes, check to see if 11732 // Y is known to provide just those bytes. If so, we try to replace the 11733 // load + replace + store sequence with a single (narrower) store, which makes 11734 // the load dead. 11735 if (Opc == ISD::OR) { 11736 std::pair<unsigned, unsigned> MaskedLoad; 11737 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 11738 if (MaskedLoad.first) 11739 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11740 Value.getOperand(1), ST,this)) 11741 return SDValue(NewST, 0); 11742 11743 // Or is commutative, so try swapping X and Y. 11744 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 11745 if (MaskedLoad.first) 11746 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 11747 Value.getOperand(0), ST,this)) 11748 return SDValue(NewST, 0); 11749 } 11750 11751 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 11752 Value.getOperand(1).getOpcode() != ISD::Constant) 11753 return SDValue(); 11754 11755 SDValue N0 = Value.getOperand(0); 11756 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 11757 Chain == SDValue(N0.getNode(), 1)) { 11758 LoadSDNode *LD = cast<LoadSDNode>(N0); 11759 if (LD->getBasePtr() != Ptr || 11760 LD->getPointerInfo().getAddrSpace() != 11761 ST->getPointerInfo().getAddrSpace()) 11762 return SDValue(); 11763 11764 // Find the type to narrow it the load / op / store to. 11765 SDValue N1 = Value.getOperand(1); 11766 unsigned BitWidth = N1.getValueSizeInBits(); 11767 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 11768 if (Opc == ISD::AND) 11769 Imm ^= APInt::getAllOnesValue(BitWidth); 11770 if (Imm == 0 || Imm.isAllOnesValue()) 11771 return SDValue(); 11772 unsigned ShAmt = Imm.countTrailingZeros(); 11773 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 11774 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 11775 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11776 // The narrowing should be profitable, the load/store operation should be 11777 // legal (or custom) and the store size should be equal to the NewVT width. 11778 while (NewBW < BitWidth && 11779 (NewVT.getStoreSizeInBits() != NewBW || 11780 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 11781 !TLI.isNarrowingProfitable(VT, NewVT))) { 11782 NewBW = NextPowerOf2(NewBW); 11783 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 11784 } 11785 if (NewBW >= BitWidth) 11786 return SDValue(); 11787 11788 // If the lsb changed does not start at the type bitwidth boundary, 11789 // start at the previous one. 11790 if (ShAmt % NewBW) 11791 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 11792 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 11793 std::min(BitWidth, ShAmt + NewBW)); 11794 if ((Imm & Mask) == Imm) { 11795 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 11796 if (Opc == ISD::AND) 11797 NewImm ^= APInt::getAllOnesValue(NewBW); 11798 uint64_t PtrOff = ShAmt / 8; 11799 // For big endian targets, we need to adjust the offset to the pointer to 11800 // load the correct bytes. 11801 if (DAG.getDataLayout().isBigEndian()) 11802 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 11803 11804 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 11805 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 11806 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 11807 return SDValue(); 11808 11809 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 11810 Ptr.getValueType(), Ptr, 11811 DAG.getConstant(PtrOff, SDLoc(LD), 11812 Ptr.getValueType())); 11813 SDValue NewLD = 11814 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 11815 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 11816 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11817 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 11818 DAG.getConstant(NewImm, SDLoc(Value), 11819 NewVT)); 11820 SDValue NewST = 11821 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 11822 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 11823 11824 AddToWorklist(NewPtr.getNode()); 11825 AddToWorklist(NewLD.getNode()); 11826 AddToWorklist(NewVal.getNode()); 11827 WorklistRemover DeadNodes(*this); 11828 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 11829 ++OpsNarrowed; 11830 return NewST; 11831 } 11832 } 11833 11834 return SDValue(); 11835 } 11836 11837 /// For a given floating point load / store pair, if the load value isn't used 11838 /// by any other operations, then consider transforming the pair to integer 11839 /// load / store operations if the target deems the transformation profitable. 11840 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 11841 StoreSDNode *ST = cast<StoreSDNode>(N); 11842 SDValue Chain = ST->getChain(); 11843 SDValue Value = ST->getValue(); 11844 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 11845 Value.hasOneUse() && 11846 Chain == SDValue(Value.getNode(), 1)) { 11847 LoadSDNode *LD = cast<LoadSDNode>(Value); 11848 EVT VT = LD->getMemoryVT(); 11849 if (!VT.isFloatingPoint() || 11850 VT != ST->getMemoryVT() || 11851 LD->isNonTemporal() || 11852 ST->isNonTemporal() || 11853 LD->getPointerInfo().getAddrSpace() != 0 || 11854 ST->getPointerInfo().getAddrSpace() != 0) 11855 return SDValue(); 11856 11857 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 11858 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 11859 !TLI.isOperationLegal(ISD::STORE, IntVT) || 11860 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 11861 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 11862 return SDValue(); 11863 11864 unsigned LDAlign = LD->getAlignment(); 11865 unsigned STAlign = ST->getAlignment(); 11866 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11867 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11868 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11869 return SDValue(); 11870 11871 SDValue NewLD = 11872 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11873 LD->getPointerInfo(), LDAlign); 11874 11875 SDValue NewST = 11876 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11877 ST->getPointerInfo(), STAlign); 11878 11879 AddToWorklist(NewLD.getNode()); 11880 AddToWorklist(NewST.getNode()); 11881 WorklistRemover DeadNodes(*this); 11882 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11883 ++LdStFP2Int; 11884 return NewST; 11885 } 11886 11887 return SDValue(); 11888 } 11889 11890 // This is a helper function for visitMUL to check the profitability 11891 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11892 // MulNode is the original multiply, AddNode is (add x, c1), 11893 // and ConstNode is c2. 11894 // 11895 // If the (add x, c1) has multiple uses, we could increase 11896 // the number of adds if we make this transformation. 11897 // It would only be worth doing this if we can remove a 11898 // multiply in the process. Check for that here. 11899 // To illustrate: 11900 // (A + c1) * c3 11901 // (A + c2) * c3 11902 // We're checking for cases where we have common "c3 * A" expressions. 11903 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11904 SDValue &AddNode, 11905 SDValue &ConstNode) { 11906 APInt Val; 11907 11908 // If the add only has one use, this would be OK to do. 11909 if (AddNode.getNode()->hasOneUse()) 11910 return true; 11911 11912 // Walk all the users of the constant with which we're multiplying. 11913 for (SDNode *Use : ConstNode->uses()) { 11914 11915 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11916 continue; 11917 11918 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11919 SDNode *OtherOp; 11920 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11921 11922 // OtherOp is what we're multiplying against the constant. 11923 if (Use->getOperand(0) == ConstNode) 11924 OtherOp = Use->getOperand(1).getNode(); 11925 else 11926 OtherOp = Use->getOperand(0).getNode(); 11927 11928 // Check to see if multiply is with the same operand of our "add". 11929 // 11930 // ConstNode = CONST 11931 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11932 // ... 11933 // AddNode = (A + c1) <-- MulVar is A. 11934 // = AddNode * ConstNode <-- current visiting instruction. 11935 // 11936 // If we make this transformation, we will have a common 11937 // multiply (ConstNode * A) that we can save. 11938 if (OtherOp == MulVar) 11939 return true; 11940 11941 // Now check to see if a future expansion will give us a common 11942 // multiply. 11943 // 11944 // ConstNode = CONST 11945 // AddNode = (A + c1) 11946 // ... = AddNode * ConstNode <-- current visiting instruction. 11947 // ... 11948 // OtherOp = (A + c2) 11949 // Use = OtherOp * ConstNode <-- visiting Use. 11950 // 11951 // If we make this transformation, we will have a common 11952 // multiply (CONST * A) after we also do the same transformation 11953 // to the "t2" instruction. 11954 if (OtherOp->getOpcode() == ISD::ADD && 11955 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11956 OtherOp->getOperand(0).getNode() == MulVar) 11957 return true; 11958 } 11959 } 11960 11961 // Didn't find a case where this would be profitable. 11962 return false; 11963 } 11964 11965 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11966 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11967 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11968 // Make sure we have something to merge. 11969 if (NumStores < 2) 11970 return false; 11971 11972 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11973 11974 // The latest Node in the DAG. 11975 SDLoc DL(StoreNodes[0].MemNode); 11976 11977 SDValue StoredVal; 11978 if (UseVector) { 11979 bool IsVec = MemVT.isVector(); 11980 unsigned Elts = NumStores; 11981 if (IsVec) { 11982 // When merging vector stores, get the total number of elements. 11983 Elts *= MemVT.getVectorNumElements(); 11984 } 11985 // Get the type for the merged vector store. 11986 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11987 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11988 11989 if (IsConstantSrc) { 11990 SmallVector<SDValue, 8> BuildVector; 11991 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11992 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 11993 SDValue Val = St->getValue(); 11994 if (MemVT.getScalarType().isInteger()) 11995 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue())) 11996 Val = DAG.getConstant( 11997 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(), 11998 SDLoc(CFP), MemVT); 11999 BuildVector.push_back(Val); 12000 } 12001 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector); 12002 } else { 12003 SmallVector<SDValue, 8> Ops; 12004 for (unsigned i = 0; i < NumStores; ++i) { 12005 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12006 SDValue Val = St->getValue(); 12007 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 12008 if (Val.getValueType() != MemVT) 12009 return false; 12010 Ops.push_back(Val); 12011 } 12012 12013 // Build the extracted vector elements back into a vector. 12014 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 12015 DL, Ty, Ops); } 12016 } else { 12017 // We should always use a vector store when merging extracted vector 12018 // elements, so this path implies a store of constants. 12019 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12020 12021 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 12022 APInt StoreInt(SizeInBits, 0); 12023 12024 // Construct a single integer constant which is made of the smaller 12025 // constant inputs. 12026 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12027 for (unsigned i = 0; i < NumStores; ++i) { 12028 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12029 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12030 12031 SDValue Val = St->getValue(); 12032 StoreInt <<= ElementSizeBytes * 8; 12033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12034 StoreInt |= C->getAPIntValue().zext(SizeInBits); 12035 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12036 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 12037 } else { 12038 llvm_unreachable("Invalid constant element type"); 12039 } 12040 } 12041 12042 // Create the new Load and Store operations. 12043 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12044 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12045 } 12046 12047 SmallVector<SDValue, 8> Chains; 12048 12049 // Gather all Chains we're inheriting. As generally all chains are 12050 // equal, do minor check to remove obvious redundancies. 12051 Chains.push_back(StoreNodes[0].MemNode->getChain()); 12052 for (unsigned i = 1; i < NumStores; ++i) 12053 if (StoreNodes[0].MemNode->getChain() != StoreNodes[i].MemNode->getChain()) 12054 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12055 12056 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12057 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 12058 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 12059 FirstInChain->getBasePtr(), 12060 FirstInChain->getPointerInfo(), 12061 FirstInChain->getAlignment()); 12062 12063 // Replace all merged stores with the new store. 12064 for (unsigned i = 0; i < NumStores; ++i) 12065 CombineTo(StoreNodes[i].MemNode, NewStore); 12066 12067 AddToWorklist(NewChain.getNode()); 12068 return true; 12069 } 12070 12071 void DAGCombiner::getStoreMergeCandidates( 12072 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12073 // This holds the base pointer, index, and the offset in bytes from the base 12074 // pointer. 12075 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12076 EVT MemVT = St->getMemoryVT(); 12077 12078 // We must have a base and an offset. 12079 if (!BasePtr.Base.getNode()) 12080 return; 12081 12082 // Do not handle stores to undef base pointers. 12083 if (BasePtr.Base.isUndef()) 12084 return; 12085 12086 // We looking for a root node which is an ancestor to all mergable 12087 // stores. We search up through a load, to our root and then down 12088 // through all children. For instance we will find Store{1,2,3} if 12089 // St is Store1, Store2. or Store3 where the root is not a load 12090 // which always true for nonvolatile ops. TODO: Expand 12091 // the search to find all valid candidates through multiple layers of loads. 12092 // 12093 // Root 12094 // |-------|-------| 12095 // Load Load Store3 12096 // | | 12097 // Store1 Store2 12098 // 12099 // FIXME: We should be able to climb and 12100 // descend TokenFactors to find candidates as well. 12101 12102 SDNode *RootNode = (St->getChain()).getNode(); 12103 12104 // Set of Parents of Candidates 12105 std::set<SDNode *> CandidateParents; 12106 12107 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 12108 RootNode = Ldn->getChain().getNode(); 12109 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12110 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 12111 CandidateParents.insert(*I); 12112 } else 12113 CandidateParents.insert(RootNode); 12114 12115 bool IsLoadSrc = isa<LoadSDNode>(St->getValue()); 12116 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) || 12117 isa<ConstantFPSDNode>(St->getValue()); 12118 bool IsExtractVecSrc = 12119 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12120 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR); 12121 auto CorrectValueKind = [&](StoreSDNode *Other) -> bool { 12122 if (IsLoadSrc) 12123 return isa<LoadSDNode>(Other->getValue()); 12124 if (IsConstantSrc) 12125 return (isa<ConstantSDNode>(Other->getValue()) || 12126 isa<ConstantFPSDNode>(Other->getValue())); 12127 if (IsExtractVecSrc) 12128 return (Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12129 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR); 12130 return false; 12131 }; 12132 12133 // check all parents of mergable children 12134 for (auto P = CandidateParents.begin(); P != CandidateParents.end(); ++P) 12135 for (auto I = (*P)->use_begin(), E = (*P)->use_end(); I != E; ++I) 12136 if (I.getOperandNo() == 0) 12137 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 12138 if (OtherST->isVolatile() || OtherST->isIndexed()) 12139 continue; 12140 // We can merge constant floats to equivalent integers 12141 if (OtherST->getMemoryVT() != MemVT) 12142 if (!(MemVT.isInteger() && MemVT.bitsEq(OtherST->getMemoryVT()) && 12143 isa<ConstantFPSDNode>(OtherST->getValue()))) 12144 continue; 12145 BaseIndexOffset Ptr = 12146 BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 12147 if (Ptr.equalBaseIndex(BasePtr) && CorrectValueKind(OtherST)) 12148 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset)); 12149 } 12150 } 12151 12152 // We need to check that merging these stores does not cause a loop 12153 // in the DAG. Any store candidate may depend on another candidate 12154 // indirectly through its operand (we already consider dependencies 12155 // through the chain). Check in parallel by searching up from 12156 // non-chain operands of candidates. 12157 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12158 SmallVectorImpl<MemOpLink> &StoreNodes) { 12159 SmallPtrSet<const SDNode *, 16> Visited; 12160 SmallVector<const SDNode *, 8> Worklist; 12161 // search ops of store candidates 12162 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 12163 SDNode *n = StoreNodes[i].MemNode; 12164 // Potential loops may happen only through non-chain operands 12165 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12166 Worklist.push_back(n->getOperand(j).getNode()); 12167 } 12168 // search through DAG. We can stop early if we find a storenode 12169 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 12170 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 12171 return false; 12172 } 12173 return true; 12174 } 12175 12176 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 12177 if (OptLevel == CodeGenOpt::None) 12178 return false; 12179 12180 EVT MemVT = St->getMemoryVT(); 12181 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12182 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12183 Attribute::NoImplicitFloat); 12184 12185 // This function cannot currently deal with non-byte-sized memory sizes. 12186 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12187 return false; 12188 12189 if (!MemVT.isSimple()) 12190 return false; 12191 12192 // Perform an early exit check. Do not bother looking at stored values that 12193 // are not constants, loads, or extracted vector elements. 12194 SDValue StoredVal = St->getValue(); 12195 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12196 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12197 isa<ConstantFPSDNode>(StoredVal); 12198 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12199 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12200 12201 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12202 return false; 12203 12204 // Don't merge vectors into wider vectors if the source data comes from loads. 12205 // TODO: This restriction can be lifted by using logic similar to the 12206 // ExtractVecSrc case. 12207 if (MemVT.isVector() && IsLoadSrc) 12208 return false; 12209 12210 SmallVector<MemOpLink, 8> StoreNodes; 12211 // Find potential store merge candidates by searching through chain sub-DAG 12212 getStoreMergeCandidates(St, StoreNodes); 12213 12214 // Check if there is anything to merge. 12215 if (StoreNodes.size() < 2) 12216 return false; 12217 12218 // Check that we can merge these candidates without causing a cycle 12219 if (!checkMergeStoreCandidatesForDependencies(StoreNodes)) 12220 return false; 12221 12222 // Sort the memory operands according to their distance from the 12223 // base pointer. 12224 std::sort(StoreNodes.begin(), StoreNodes.end(), 12225 [](MemOpLink LHS, MemOpLink RHS) { 12226 return LHS.OffsetFromBase < RHS.OffsetFromBase; 12227 }); 12228 12229 // Scan the memory operations on the chain and find the first non-consecutive 12230 // store memory address. 12231 unsigned NumConsecutiveStores = 0; 12232 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12233 12234 // Check that the addresses are consecutive starting from the second 12235 // element in the list of stores. 12236 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 12237 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12238 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12239 break; 12240 NumConsecutiveStores = i + 1; 12241 } 12242 12243 if (NumConsecutiveStores < 2) 12244 return false; 12245 12246 // The node with the lowest store address. 12247 LLVMContext &Context = *DAG.getContext(); 12248 const DataLayout &DL = DAG.getDataLayout(); 12249 12250 // Store the constants into memory as one consecutive store. 12251 if (IsConstantSrc) { 12252 bool RV = false; 12253 while (NumConsecutiveStores > 1) { 12254 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12255 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12256 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12257 unsigned LastLegalType = 0; 12258 unsigned LastLegalVectorType = 0; 12259 bool NonZero = false; 12260 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12261 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 12262 SDValue StoredVal = ST->getValue(); 12263 12264 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 12265 NonZero |= !C->isNullValue(); 12266 } else if (ConstantFPSDNode *C = 12267 dyn_cast<ConstantFPSDNode>(StoredVal)) { 12268 NonZero |= !C->getConstantFPValue()->isNullValue(); 12269 } else { 12270 // Non-constant. 12271 break; 12272 } 12273 12274 // Find a legal type for the constant store. 12275 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 12276 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12277 bool IsFast = false; 12278 if (TLI.isTypeLegal(StoreTy) && 12279 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12280 FirstStoreAlign, &IsFast) && 12281 IsFast) { 12282 LastLegalType = i + 1; 12283 // Or check whether a truncstore is legal. 12284 } else if (TLI.getTypeAction(Context, StoreTy) == 12285 TargetLowering::TypePromoteInteger) { 12286 EVT LegalizedStoredValueTy = 12287 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 12288 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12289 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12290 FirstStoreAS, FirstStoreAlign, &IsFast) && 12291 IsFast) { 12292 LastLegalType = i + 1; 12293 } 12294 } 12295 12296 // We only use vectors if the constant is known to be zero or the target 12297 // allows it and the function is not marked with the noimplicitfloat 12298 // attribute. 12299 if ((!NonZero || 12300 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 12301 !NoVectors) { 12302 // Find a legal type for the vector store. 12303 EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1); 12304 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) && 12305 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12306 FirstStoreAlign, &IsFast) && 12307 IsFast) 12308 LastLegalVectorType = i + 1; 12309 } 12310 } 12311 12312 // Check if we found a legal integer type that creates a meaningful merge. 12313 if (LastLegalType < 2 && LastLegalVectorType < 2) 12314 break; 12315 12316 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 12317 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 12318 12319 bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 12320 true, UseVector); 12321 if (!Merged) 12322 break; 12323 // Remove merged stores for next iteration. 12324 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12325 RV = true; 12326 NumConsecutiveStores -= NumElem; 12327 } 12328 return RV; 12329 } 12330 12331 // When extracting multiple vector elements, try to store them 12332 // in one vector store rather than a sequence of scalar stores. 12333 if (IsExtractVecSrc) { 12334 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12335 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12336 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12337 unsigned NumStoresToMerge = 0; 12338 bool IsVec = MemVT.isVector(); 12339 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12340 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12341 unsigned StoreValOpcode = St->getValue().getOpcode(); 12342 // This restriction could be loosened. 12343 // Bail out if any stored values are not elements extracted from a vector. 12344 // It should be possible to handle mixed sources, but load sources need 12345 // more careful handling (see the block of code below that handles 12346 // consecutive loads). 12347 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 12348 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 12349 return false; 12350 12351 // Find a legal type for the vector store. 12352 unsigned Elts = i + 1; 12353 if (IsVec) { 12354 // When merging vector stores, get the total number of elements. 12355 Elts *= MemVT.getVectorNumElements(); 12356 } 12357 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12358 bool IsFast; 12359 if (TLI.isTypeLegal(Ty) && 12360 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12361 FirstStoreAlign, &IsFast) && IsFast) 12362 NumStoresToMerge = i + 1; 12363 } 12364 12365 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 12366 false, true); 12367 } 12368 12369 // Below we handle the case of multiple consecutive stores that 12370 // come from multiple consecutive loads. We merge them into a single 12371 // wide load and a single wide store. 12372 12373 // Look for load nodes which are used by the stored values. 12374 SmallVector<MemOpLink, 8> LoadNodes; 12375 12376 // Find acceptable loads. Loads need to have the same chain (token factor), 12377 // must not be zext, volatile, indexed, and they must be consecutive. 12378 BaseIndexOffset LdBasePtr; 12379 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12380 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12381 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 12382 if (!Ld) break; 12383 12384 // Loads must only have one use. 12385 if (!Ld->hasNUsesOfValue(1, 0)) 12386 break; 12387 12388 // The memory operands must not be volatile. 12389 if (Ld->isVolatile() || Ld->isIndexed()) 12390 break; 12391 12392 // We do not accept ext loads. 12393 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 12394 break; 12395 12396 // The stored memory type must be the same. 12397 if (Ld->getMemoryVT() != MemVT) 12398 break; 12399 12400 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12401 // If this is not the first ptr that we check. 12402 if (LdBasePtr.Base.getNode()) { 12403 // The base ptr must be the same. 12404 if (!LdPtr.equalBaseIndex(LdBasePtr)) 12405 break; 12406 } else { 12407 // Check that all other base pointers are the same as this one. 12408 LdBasePtr = LdPtr; 12409 } 12410 12411 // We found a potential memory operand to merge. 12412 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset)); 12413 } 12414 12415 if (LoadNodes.size() < 2) 12416 return false; 12417 12418 // If we have load/store pair instructions and we only have two values, 12419 // don't bother. 12420 unsigned RequiredAlignment; 12421 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 12422 St->getAlignment() >= RequiredAlignment) 12423 return false; 12424 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12425 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12426 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12427 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 12428 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 12429 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 12430 12431 // Scan the memory operations on the chain and find the first non-consecutive 12432 // load memory address. These variables hold the index in the store node 12433 // array. 12434 unsigned LastConsecutiveLoad = 0; 12435 // This variable refers to the size and not index in the array. 12436 unsigned LastLegalVectorType = 0; 12437 unsigned LastLegalIntegerType = 0; 12438 StartAddress = LoadNodes[0].OffsetFromBase; 12439 SDValue FirstChain = FirstLoad->getChain(); 12440 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 12441 // All loads must share the same chain. 12442 if (LoadNodes[i].MemNode->getChain() != FirstChain) 12443 break; 12444 12445 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 12446 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12447 break; 12448 LastConsecutiveLoad = i; 12449 // Find a legal type for the vector store. 12450 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 12451 bool IsFastSt, IsFastLd; 12452 if (TLI.isTypeLegal(StoreTy) && 12453 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12454 FirstStoreAlign, &IsFastSt) && IsFastSt && 12455 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12456 FirstLoadAlign, &IsFastLd) && IsFastLd) { 12457 LastLegalVectorType = i + 1; 12458 } 12459 12460 // Find a legal type for the integer store. 12461 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 12462 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12463 if (TLI.isTypeLegal(StoreTy) && 12464 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12465 FirstStoreAlign, &IsFastSt) && IsFastSt && 12466 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12467 FirstLoadAlign, &IsFastLd) && IsFastLd) 12468 LastLegalIntegerType = i + 1; 12469 // Or check whether a truncstore and extload is legal. 12470 else if (TLI.getTypeAction(Context, StoreTy) == 12471 TargetLowering::TypePromoteInteger) { 12472 EVT LegalizedStoredValueTy = 12473 TLI.getTypeToTransformTo(Context, StoreTy); 12474 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12475 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12476 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12477 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 12478 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12479 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 12480 IsFastSt && 12481 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12482 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 12483 IsFastLd) 12484 LastLegalIntegerType = i+1; 12485 } 12486 } 12487 12488 // Only use vector types if the vector type is larger than the integer type. 12489 // If they are the same, use integers. 12490 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 12491 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 12492 12493 // We add +1 here because the LastXXX variables refer to location while 12494 // the NumElem refers to array/index size. 12495 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 12496 NumElem = std::min(LastLegalType, NumElem); 12497 12498 if (NumElem < 2) 12499 return false; 12500 12501 // Collect the chains from all merged stores. Because the common case 12502 // all chains are the same, check if we match the first Chain. 12503 SmallVector<SDValue, 8> MergeStoreChains; 12504 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 12505 for (unsigned i = 1; i < NumElem; ++i) 12506 if (StoreNodes[0].MemNode->getChain() != StoreNodes[i].MemNode->getChain()) 12507 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 12508 12509 // Find if it is better to use vectors or integers to load and store 12510 // to memory. 12511 EVT JointMemOpVT; 12512 if (UseVectorTy) { 12513 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 12514 } else { 12515 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 12516 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 12517 } 12518 12519 SDLoc LoadDL(LoadNodes[0].MemNode); 12520 SDLoc StoreDL(StoreNodes[0].MemNode); 12521 12522 // The merged loads are required to have the same incoming chain, so 12523 // using the first's chain is acceptable. 12524 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 12525 FirstLoad->getBasePtr(), 12526 FirstLoad->getPointerInfo(), FirstLoadAlign); 12527 12528 SDValue NewStoreChain = 12529 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 12530 12531 AddToWorklist(NewStoreChain.getNode()); 12532 12533 SDValue NewStore = 12534 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 12535 FirstInChain->getPointerInfo(), FirstStoreAlign); 12536 12537 // Transfer chain users from old loads to the new load. 12538 for (unsigned i = 0; i < NumElem; ++i) { 12539 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 12540 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 12541 SDValue(NewLoad.getNode(), 1)); 12542 } 12543 12544 // Replace the all stores with the new store. 12545 for (unsigned i = 0; i < NumElem; ++i) 12546 CombineTo(StoreNodes[i].MemNode, NewStore); 12547 return true; 12548 } 12549 12550 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 12551 SDLoc SL(ST); 12552 SDValue ReplStore; 12553 12554 // Replace the chain to avoid dependency. 12555 if (ST->isTruncatingStore()) { 12556 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 12557 ST->getBasePtr(), ST->getMemoryVT(), 12558 ST->getMemOperand()); 12559 } else { 12560 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 12561 ST->getMemOperand()); 12562 } 12563 12564 // Create token to keep both nodes around. 12565 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 12566 MVT::Other, ST->getChain(), ReplStore); 12567 12568 // Make sure the new and old chains are cleaned up. 12569 AddToWorklist(Token.getNode()); 12570 12571 // Don't add users to work list. 12572 return CombineTo(ST, Token, false); 12573 } 12574 12575 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 12576 SDValue Value = ST->getValue(); 12577 if (Value.getOpcode() == ISD::TargetConstantFP) 12578 return SDValue(); 12579 12580 SDLoc DL(ST); 12581 12582 SDValue Chain = ST->getChain(); 12583 SDValue Ptr = ST->getBasePtr(); 12584 12585 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 12586 12587 // NOTE: If the original store is volatile, this transform must not increase 12588 // the number of stores. For example, on x86-32 an f64 can be stored in one 12589 // processor operation but an i64 (which is not legal) requires two. So the 12590 // transform should not be done in this case. 12591 12592 SDValue Tmp; 12593 switch (CFP->getSimpleValueType(0).SimpleTy) { 12594 default: 12595 llvm_unreachable("Unknown FP type"); 12596 case MVT::f16: // We don't do this for these yet. 12597 case MVT::f80: 12598 case MVT::f128: 12599 case MVT::ppcf128: 12600 return SDValue(); 12601 case MVT::f32: 12602 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 12603 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12604 ; 12605 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 12606 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 12607 MVT::i32); 12608 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 12609 } 12610 12611 return SDValue(); 12612 case MVT::f64: 12613 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 12614 !ST->isVolatile()) || 12615 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 12616 ; 12617 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 12618 getZExtValue(), SDLoc(CFP), MVT::i64); 12619 return DAG.getStore(Chain, DL, Tmp, 12620 Ptr, ST->getMemOperand()); 12621 } 12622 12623 if (!ST->isVolatile() && 12624 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12625 // Many FP stores are not made apparent until after legalize, e.g. for 12626 // argument passing. Since this is so common, custom legalize the 12627 // 64-bit integer store into two 32-bit stores. 12628 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 12629 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 12630 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 12631 if (DAG.getDataLayout().isBigEndian()) 12632 std::swap(Lo, Hi); 12633 12634 unsigned Alignment = ST->getAlignment(); 12635 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12636 AAMDNodes AAInfo = ST->getAAInfo(); 12637 12638 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12639 ST->getAlignment(), MMOFlags, AAInfo); 12640 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12641 DAG.getConstant(4, DL, Ptr.getValueType())); 12642 Alignment = MinAlign(Alignment, 4U); 12643 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 12644 ST->getPointerInfo().getWithOffset(4), 12645 Alignment, MMOFlags, AAInfo); 12646 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12647 St0, St1); 12648 } 12649 12650 return SDValue(); 12651 } 12652 } 12653 12654 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12655 StoreSDNode *ST = cast<StoreSDNode>(N); 12656 SDValue Chain = ST->getChain(); 12657 SDValue Value = ST->getValue(); 12658 SDValue Ptr = ST->getBasePtr(); 12659 12660 // If this is a store of a bit convert, store the input value if the 12661 // resultant store does not need a higher alignment than the original. 12662 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12663 ST->isUnindexed()) { 12664 EVT SVT = Value.getOperand(0).getValueType(); 12665 if (((!LegalOperations && !ST->isVolatile()) || 12666 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12667 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12668 unsigned OrigAlign = ST->getAlignment(); 12669 bool Fast = false; 12670 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12671 ST->getAddressSpace(), OrigAlign, &Fast) && 12672 Fast) { 12673 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12674 ST->getPointerInfo(), OrigAlign, 12675 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12676 } 12677 } 12678 } 12679 12680 // Turn 'store undef, Ptr' -> nothing. 12681 if (Value.isUndef() && ST->isUnindexed()) 12682 return Chain; 12683 12684 // Try to infer better alignment information than the store already has. 12685 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12686 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12687 if (Align > ST->getAlignment()) { 12688 SDValue NewStore = 12689 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12690 ST->getMemoryVT(), Align, 12691 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12692 if (NewStore.getNode() != N) 12693 return CombineTo(ST, NewStore, true); 12694 } 12695 } 12696 } 12697 12698 // Try transforming a pair floating point load / store ops to integer 12699 // load / store ops. 12700 if (SDValue NewST = TransformFPLoadStorePair(N)) 12701 return NewST; 12702 12703 if (ST->isUnindexed()) { 12704 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12705 // adjacent stores. 12706 if (findBetterNeighborChains(ST)) { 12707 // replaceStoreChain uses CombineTo, which handled all of the worklist 12708 // manipulation. Return the original node to not do anything else. 12709 return SDValue(ST, 0); 12710 } 12711 Chain = ST->getChain(); 12712 } 12713 12714 // Try transforming N to an indexed store. 12715 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12716 return SDValue(N, 0); 12717 12718 // FIXME: is there such a thing as a truncating indexed store? 12719 if (ST->isTruncatingStore() && ST->isUnindexed() && 12720 Value.getValueType().isInteger()) { 12721 // See if we can simplify the input to this truncstore with knowledge that 12722 // only the low bits are being used. For example: 12723 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12724 SDValue Shorter = GetDemandedBits( 12725 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12726 ST->getMemoryVT().getScalarSizeInBits())); 12727 AddToWorklist(Value.getNode()); 12728 if (Shorter.getNode()) 12729 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12730 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12731 12732 // Otherwise, see if we can simplify the operation with 12733 // SimplifyDemandedBits, which only works if the value has a single use. 12734 if (SimplifyDemandedBits( 12735 Value, 12736 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 12737 ST->getMemoryVT().getScalarSizeInBits()))) { 12738 // Re-visit the store if anything changed and the store hasn't been merged 12739 // with another node (N is deleted) SimplifyDemandedBits will add Value's 12740 // node back to the worklist if necessary, but we also need to re-visit 12741 // the Store node itself. 12742 if (N->getOpcode() != ISD::DELETED_NODE) 12743 AddToWorklist(N); 12744 return SDValue(N, 0); 12745 } 12746 } 12747 12748 // If this is a load followed by a store to the same location, then the store 12749 // is dead/noop. 12750 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12751 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12752 ST->isUnindexed() && !ST->isVolatile() && 12753 // There can't be any side effects between the load and store, such as 12754 // a call or store. 12755 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12756 // The store is dead, remove it. 12757 return Chain; 12758 } 12759 } 12760 12761 // If this is a store followed by a store with the same value to the same 12762 // location, then the store is dead/noop. 12763 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12764 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12765 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12766 ST1->isUnindexed() && !ST1->isVolatile()) { 12767 // The store is dead, remove it. 12768 return Chain; 12769 } 12770 } 12771 12772 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12773 // truncating store. We can do this even if this is already a truncstore. 12774 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12775 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12776 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12777 ST->getMemoryVT())) { 12778 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12779 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12780 } 12781 12782 // Only perform this optimization before the types are legal, because we 12783 // don't want to perform this optimization on every DAGCombine invocation. 12784 if (!LegalTypes) { 12785 for (;;) { 12786 // There can be multiple store sequences on the same chain. 12787 // Keep trying to merge store sequences until we are unable to do so 12788 // or until we merge the last store on the chain. 12789 bool Changed = MergeConsecutiveStores(ST); 12790 if (!Changed) break; 12791 // Return N as merge only uses CombineTo and no worklist clean 12792 // up is necessary. 12793 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 12794 return SDValue(N, 0); 12795 } 12796 } 12797 12798 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12799 // 12800 // Make sure to do this only after attempting to merge stores in order to 12801 // avoid changing the types of some subset of stores due to visit order, 12802 // preventing their merging. 12803 if (isa<ConstantFPSDNode>(ST->getValue())) { 12804 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12805 return NewSt; 12806 } 12807 12808 if (SDValue NewSt = splitMergedValStore(ST)) 12809 return NewSt; 12810 12811 return ReduceLoadOpStoreWidth(N); 12812 } 12813 12814 /// For the instruction sequence of store below, F and I values 12815 /// are bundled together as an i64 value before being stored into memory. 12816 /// Sometimes it is more efficent to generate separate stores for F and I, 12817 /// which can remove the bitwise instructions or sink them to colder places. 12818 /// 12819 /// (store (or (zext (bitcast F to i32) to i64), 12820 /// (shl (zext I to i64), 32)), addr) --> 12821 /// (store F, addr) and (store I, addr+4) 12822 /// 12823 /// Similarly, splitting for other merged store can also be beneficial, like: 12824 /// For pair of {i32, i32}, i64 store --> two i32 stores. 12825 /// For pair of {i32, i16}, i64 store --> two i32 stores. 12826 /// For pair of {i16, i16}, i32 store --> two i16 stores. 12827 /// For pair of {i16, i8}, i32 store --> two i16 stores. 12828 /// For pair of {i8, i8}, i16 store --> two i8 stores. 12829 /// 12830 /// We allow each target to determine specifically which kind of splitting is 12831 /// supported. 12832 /// 12833 /// The store patterns are commonly seen from the simple code snippet below 12834 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 12835 /// void goo(const std::pair<int, float> &); 12836 /// hoo() { 12837 /// ... 12838 /// goo(std::make_pair(tmp, ftmp)); 12839 /// ... 12840 /// } 12841 /// 12842 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 12843 if (OptLevel == CodeGenOpt::None) 12844 return SDValue(); 12845 12846 SDValue Val = ST->getValue(); 12847 SDLoc DL(ST); 12848 12849 // Match OR operand. 12850 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 12851 return SDValue(); 12852 12853 // Match SHL operand and get Lower and Higher parts of Val. 12854 SDValue Op1 = Val.getOperand(0); 12855 SDValue Op2 = Val.getOperand(1); 12856 SDValue Lo, Hi; 12857 if (Op1.getOpcode() != ISD::SHL) { 12858 std::swap(Op1, Op2); 12859 if (Op1.getOpcode() != ISD::SHL) 12860 return SDValue(); 12861 } 12862 Lo = Op2; 12863 Hi = Op1.getOperand(0); 12864 if (!Op1.hasOneUse()) 12865 return SDValue(); 12866 12867 // Match shift amount to HalfValBitSize. 12868 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 12869 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 12870 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 12871 return SDValue(); 12872 12873 // Lo and Hi are zero-extended from int with size less equal than 32 12874 // to i64. 12875 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 12876 !Lo.getOperand(0).getValueType().isScalarInteger() || 12877 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 12878 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 12879 !Hi.getOperand(0).getValueType().isScalarInteger() || 12880 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 12881 return SDValue(); 12882 12883 // Use the EVT of low and high parts before bitcast as the input 12884 // of target query. 12885 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 12886 ? Lo.getOperand(0).getValueType() 12887 : Lo.getValueType(); 12888 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 12889 ? Hi.getOperand(0).getValueType() 12890 : Hi.getValueType(); 12891 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 12892 return SDValue(); 12893 12894 // Start to split store. 12895 unsigned Alignment = ST->getAlignment(); 12896 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12897 AAMDNodes AAInfo = ST->getAAInfo(); 12898 12899 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 12900 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 12901 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 12902 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 12903 12904 SDValue Chain = ST->getChain(); 12905 SDValue Ptr = ST->getBasePtr(); 12906 // Lower value store. 12907 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12908 ST->getAlignment(), MMOFlags, AAInfo); 12909 Ptr = 12910 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12911 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 12912 // Higher value store. 12913 SDValue St1 = 12914 DAG.getStore(St0, DL, Hi, Ptr, 12915 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 12916 Alignment / 2, MMOFlags, AAInfo); 12917 return St1; 12918 } 12919 12920 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12921 SDValue InVec = N->getOperand(0); 12922 SDValue InVal = N->getOperand(1); 12923 SDValue EltNo = N->getOperand(2); 12924 SDLoc DL(N); 12925 12926 // If the inserted element is an UNDEF, just use the input vector. 12927 if (InVal.isUndef()) 12928 return InVec; 12929 12930 EVT VT = InVec.getValueType(); 12931 12932 // Check that we know which element is being inserted 12933 if (!isa<ConstantSDNode>(EltNo)) 12934 return SDValue(); 12935 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12936 12937 // Canonicalize insert_vector_elt dag nodes. 12938 // Example: 12939 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12940 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12941 // 12942 // Do this only if the child insert_vector node has one use; also 12943 // do this only if indices are both constants and Idx1 < Idx0. 12944 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12945 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12946 unsigned OtherElt = 12947 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12948 if (Elt < OtherElt) { 12949 // Swap nodes. 12950 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 12951 InVec.getOperand(0), InVal, EltNo); 12952 AddToWorklist(NewOp.getNode()); 12953 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12954 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12955 } 12956 } 12957 12958 // If we can't generate a legal BUILD_VECTOR, exit 12959 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12960 return SDValue(); 12961 12962 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12963 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12964 // vector elements. 12965 SmallVector<SDValue, 8> Ops; 12966 // Do not combine these two vectors if the output vector will not replace 12967 // the input vector. 12968 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12969 Ops.append(InVec.getNode()->op_begin(), 12970 InVec.getNode()->op_end()); 12971 } else if (InVec.isUndef()) { 12972 unsigned NElts = VT.getVectorNumElements(); 12973 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12974 } else { 12975 return SDValue(); 12976 } 12977 12978 // Insert the element 12979 if (Elt < Ops.size()) { 12980 // All the operands of BUILD_VECTOR must have the same type; 12981 // we enforce that here. 12982 EVT OpVT = Ops[0].getValueType(); 12983 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 12984 } 12985 12986 // Return the new vector 12987 return DAG.getBuildVector(VT, DL, Ops); 12988 } 12989 12990 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12991 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12992 assert(!OriginalLoad->isVolatile()); 12993 12994 EVT ResultVT = EVE->getValueType(0); 12995 EVT VecEltVT = InVecVT.getVectorElementType(); 12996 unsigned Align = OriginalLoad->getAlignment(); 12997 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12998 VecEltVT.getTypeForEVT(*DAG.getContext())); 12999 13000 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 13001 return SDValue(); 13002 13003 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 13004 ISD::NON_EXTLOAD : ISD::EXTLOAD; 13005 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 13006 return SDValue(); 13007 13008 Align = NewAlign; 13009 13010 SDValue NewPtr = OriginalLoad->getBasePtr(); 13011 SDValue Offset; 13012 EVT PtrType = NewPtr.getValueType(); 13013 MachinePointerInfo MPI; 13014 SDLoc DL(EVE); 13015 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 13016 int Elt = ConstEltNo->getZExtValue(); 13017 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 13018 Offset = DAG.getConstant(PtrOff, DL, PtrType); 13019 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 13020 } else { 13021 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 13022 Offset = DAG.getNode( 13023 ISD::MUL, DL, PtrType, Offset, 13024 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 13025 MPI = OriginalLoad->getPointerInfo(); 13026 } 13027 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 13028 13029 // The replacement we need to do here is a little tricky: we need to 13030 // replace an extractelement of a load with a load. 13031 // Use ReplaceAllUsesOfValuesWith to do the replacement. 13032 // Note that this replacement assumes that the extractvalue is the only 13033 // use of the load; that's okay because we don't want to perform this 13034 // transformation in other cases anyway. 13035 SDValue Load; 13036 SDValue Chain; 13037 if (ResultVT.bitsGT(VecEltVT)) { 13038 // If the result type of vextract is wider than the load, then issue an 13039 // extending load instead. 13040 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 13041 VecEltVT) 13042 ? ISD::ZEXTLOAD 13043 : ISD::EXTLOAD; 13044 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 13045 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 13046 Align, OriginalLoad->getMemOperand()->getFlags(), 13047 OriginalLoad->getAAInfo()); 13048 Chain = Load.getValue(1); 13049 } else { 13050 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 13051 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 13052 OriginalLoad->getAAInfo()); 13053 Chain = Load.getValue(1); 13054 if (ResultVT.bitsLT(VecEltVT)) 13055 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 13056 else 13057 Load = DAG.getBitcast(ResultVT, Load); 13058 } 13059 WorklistRemover DeadNodes(*this); 13060 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 13061 SDValue To[] = { Load, Chain }; 13062 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 13063 // Since we're explicitly calling ReplaceAllUses, add the new node to the 13064 // worklist explicitly as well. 13065 AddToWorklist(Load.getNode()); 13066 AddUsersToWorklist(Load.getNode()); // Add users too 13067 // Make sure to revisit this node to clean it up; it will usually be dead. 13068 AddToWorklist(EVE); 13069 ++OpsNarrowed; 13070 return SDValue(EVE, 0); 13071 } 13072 13073 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 13074 // (vextract (scalar_to_vector val, 0) -> val 13075 SDValue InVec = N->getOperand(0); 13076 EVT VT = InVec.getValueType(); 13077 EVT NVT = N->getValueType(0); 13078 13079 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 13080 // Check if the result type doesn't match the inserted element type. A 13081 // SCALAR_TO_VECTOR may truncate the inserted element and the 13082 // EXTRACT_VECTOR_ELT may widen the extracted vector. 13083 SDValue InOp = InVec.getOperand(0); 13084 if (InOp.getValueType() != NVT) { 13085 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13086 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 13087 } 13088 return InOp; 13089 } 13090 13091 SDValue EltNo = N->getOperand(1); 13092 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 13093 13094 // extract_vector_elt (build_vector x, y), 1 -> y 13095 if (ConstEltNo && 13096 InVec.getOpcode() == ISD::BUILD_VECTOR && 13097 TLI.isTypeLegal(VT) && 13098 (InVec.hasOneUse() || 13099 TLI.aggressivelyPreferBuildVectorSources(VT))) { 13100 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 13101 EVT InEltVT = Elt.getValueType(); 13102 13103 // Sometimes build_vector's scalar input types do not match result type. 13104 if (NVT == InEltVT) 13105 return Elt; 13106 13107 // TODO: It may be useful to truncate if free if the build_vector implicitly 13108 // converts. 13109 } 13110 13111 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 13112 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 13113 ConstEltNo->isNullValue() && VT.isInteger()) { 13114 SDValue BCSrc = InVec.getOperand(0); 13115 if (BCSrc.getValueType().isScalarInteger()) 13116 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 13117 } 13118 13119 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 13120 // 13121 // This only really matters if the index is non-constant since other combines 13122 // on the constant elements already work. 13123 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 13124 EltNo == InVec.getOperand(2)) { 13125 SDValue Elt = InVec.getOperand(1); 13126 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 13127 } 13128 13129 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 13130 // We only perform this optimization before the op legalization phase because 13131 // we may introduce new vector instructions which are not backed by TD 13132 // patterns. For example on AVX, extracting elements from a wide vector 13133 // without using extract_subvector. However, if we can find an underlying 13134 // scalar value, then we can always use that. 13135 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 13136 int NumElem = VT.getVectorNumElements(); 13137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 13138 // Find the new index to extract from. 13139 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 13140 13141 // Extracting an undef index is undef. 13142 if (OrigElt == -1) 13143 return DAG.getUNDEF(NVT); 13144 13145 // Select the right vector half to extract from. 13146 SDValue SVInVec; 13147 if (OrigElt < NumElem) { 13148 SVInVec = InVec->getOperand(0); 13149 } else { 13150 SVInVec = InVec->getOperand(1); 13151 OrigElt -= NumElem; 13152 } 13153 13154 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 13155 SDValue InOp = SVInVec.getOperand(OrigElt); 13156 if (InOp.getValueType() != NVT) { 13157 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13158 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 13159 } 13160 13161 return InOp; 13162 } 13163 13164 // FIXME: We should handle recursing on other vector shuffles and 13165 // scalar_to_vector here as well. 13166 13167 if (!LegalOperations) { 13168 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13169 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 13170 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 13171 } 13172 } 13173 13174 bool BCNumEltsChanged = false; 13175 EVT ExtVT = VT.getVectorElementType(); 13176 EVT LVT = ExtVT; 13177 13178 // If the result of load has to be truncated, then it's not necessarily 13179 // profitable. 13180 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 13181 return SDValue(); 13182 13183 if (InVec.getOpcode() == ISD::BITCAST) { 13184 // Don't duplicate a load with other uses. 13185 if (!InVec.hasOneUse()) 13186 return SDValue(); 13187 13188 EVT BCVT = InVec.getOperand(0).getValueType(); 13189 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 13190 return SDValue(); 13191 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 13192 BCNumEltsChanged = true; 13193 InVec = InVec.getOperand(0); 13194 ExtVT = BCVT.getVectorElementType(); 13195 } 13196 13197 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 13198 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 13199 ISD::isNormalLoad(InVec.getNode()) && 13200 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 13201 SDValue Index = N->getOperand(1); 13202 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 13203 if (!OrigLoad->isVolatile()) { 13204 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 13205 OrigLoad); 13206 } 13207 } 13208 } 13209 13210 // Perform only after legalization to ensure build_vector / vector_shuffle 13211 // optimizations have already been done. 13212 if (!LegalOperations) return SDValue(); 13213 13214 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 13215 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 13216 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 13217 13218 if (ConstEltNo) { 13219 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13220 13221 LoadSDNode *LN0 = nullptr; 13222 const ShuffleVectorSDNode *SVN = nullptr; 13223 if (ISD::isNormalLoad(InVec.getNode())) { 13224 LN0 = cast<LoadSDNode>(InVec); 13225 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 13226 InVec.getOperand(0).getValueType() == ExtVT && 13227 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 13228 // Don't duplicate a load with other uses. 13229 if (!InVec.hasOneUse()) 13230 return SDValue(); 13231 13232 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 13233 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 13234 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 13235 // => 13236 // (load $addr+1*size) 13237 13238 // Don't duplicate a load with other uses. 13239 if (!InVec.hasOneUse()) 13240 return SDValue(); 13241 13242 // If the bit convert changed the number of elements, it is unsafe 13243 // to examine the mask. 13244 if (BCNumEltsChanged) 13245 return SDValue(); 13246 13247 // Select the input vector, guarding against out of range extract vector. 13248 unsigned NumElems = VT.getVectorNumElements(); 13249 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 13250 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 13251 13252 if (InVec.getOpcode() == ISD::BITCAST) { 13253 // Don't duplicate a load with other uses. 13254 if (!InVec.hasOneUse()) 13255 return SDValue(); 13256 13257 InVec = InVec.getOperand(0); 13258 } 13259 if (ISD::isNormalLoad(InVec.getNode())) { 13260 LN0 = cast<LoadSDNode>(InVec); 13261 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 13262 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 13263 } 13264 } 13265 13266 // Make sure we found a non-volatile load and the extractelement is 13267 // the only use. 13268 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 13269 return SDValue(); 13270 13271 // If Idx was -1 above, Elt is going to be -1, so just return undef. 13272 if (Elt == -1) 13273 return DAG.getUNDEF(LVT); 13274 13275 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 13276 } 13277 13278 return SDValue(); 13279 } 13280 13281 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 13282 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 13283 // We perform this optimization post type-legalization because 13284 // the type-legalizer often scalarizes integer-promoted vectors. 13285 // Performing this optimization before may create bit-casts which 13286 // will be type-legalized to complex code sequences. 13287 // We perform this optimization only before the operation legalizer because we 13288 // may introduce illegal operations. 13289 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 13290 return SDValue(); 13291 13292 unsigned NumInScalars = N->getNumOperands(); 13293 SDLoc DL(N); 13294 EVT VT = N->getValueType(0); 13295 13296 // Check to see if this is a BUILD_VECTOR of a bunch of values 13297 // which come from any_extend or zero_extend nodes. If so, we can create 13298 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 13299 // optimizations. We do not handle sign-extend because we can't fill the sign 13300 // using shuffles. 13301 EVT SourceType = MVT::Other; 13302 bool AllAnyExt = true; 13303 13304 for (unsigned i = 0; i != NumInScalars; ++i) { 13305 SDValue In = N->getOperand(i); 13306 // Ignore undef inputs. 13307 if (In.isUndef()) continue; 13308 13309 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 13310 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 13311 13312 // Abort if the element is not an extension. 13313 if (!ZeroExt && !AnyExt) { 13314 SourceType = MVT::Other; 13315 break; 13316 } 13317 13318 // The input is a ZeroExt or AnyExt. Check the original type. 13319 EVT InTy = In.getOperand(0).getValueType(); 13320 13321 // Check that all of the widened source types are the same. 13322 if (SourceType == MVT::Other) 13323 // First time. 13324 SourceType = InTy; 13325 else if (InTy != SourceType) { 13326 // Multiple income types. Abort. 13327 SourceType = MVT::Other; 13328 break; 13329 } 13330 13331 // Check if all of the extends are ANY_EXTENDs. 13332 AllAnyExt &= AnyExt; 13333 } 13334 13335 // In order to have valid types, all of the inputs must be extended from the 13336 // same source type and all of the inputs must be any or zero extend. 13337 // Scalar sizes must be a power of two. 13338 EVT OutScalarTy = VT.getScalarType(); 13339 bool ValidTypes = SourceType != MVT::Other && 13340 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 13341 isPowerOf2_32(SourceType.getSizeInBits()); 13342 13343 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 13344 // turn into a single shuffle instruction. 13345 if (!ValidTypes) 13346 return SDValue(); 13347 13348 bool isLE = DAG.getDataLayout().isLittleEndian(); 13349 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 13350 assert(ElemRatio > 1 && "Invalid element size ratio"); 13351 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 13352 DAG.getConstant(0, DL, SourceType); 13353 13354 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 13355 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 13356 13357 // Populate the new build_vector 13358 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13359 SDValue Cast = N->getOperand(i); 13360 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 13361 Cast.getOpcode() == ISD::ZERO_EXTEND || 13362 Cast.isUndef()) && "Invalid cast opcode"); 13363 SDValue In; 13364 if (Cast.isUndef()) 13365 In = DAG.getUNDEF(SourceType); 13366 else 13367 In = Cast->getOperand(0); 13368 unsigned Index = isLE ? (i * ElemRatio) : 13369 (i * ElemRatio + (ElemRatio - 1)); 13370 13371 assert(Index < Ops.size() && "Invalid index"); 13372 Ops[Index] = In; 13373 } 13374 13375 // The type of the new BUILD_VECTOR node. 13376 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 13377 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 13378 "Invalid vector size"); 13379 // Check if the new vector type is legal. 13380 if (!isTypeLegal(VecVT)) return SDValue(); 13381 13382 // Make the new BUILD_VECTOR. 13383 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 13384 13385 // The new BUILD_VECTOR node has the potential to be further optimized. 13386 AddToWorklist(BV.getNode()); 13387 // Bitcast to the desired type. 13388 return DAG.getBitcast(VT, BV); 13389 } 13390 13391 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 13392 EVT VT = N->getValueType(0); 13393 13394 unsigned NumInScalars = N->getNumOperands(); 13395 SDLoc DL(N); 13396 13397 EVT SrcVT = MVT::Other; 13398 unsigned Opcode = ISD::DELETED_NODE; 13399 unsigned NumDefs = 0; 13400 13401 for (unsigned i = 0; i != NumInScalars; ++i) { 13402 SDValue In = N->getOperand(i); 13403 unsigned Opc = In.getOpcode(); 13404 13405 if (Opc == ISD::UNDEF) 13406 continue; 13407 13408 // If all scalar values are floats and converted from integers. 13409 if (Opcode == ISD::DELETED_NODE && 13410 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 13411 Opcode = Opc; 13412 } 13413 13414 if (Opc != Opcode) 13415 return SDValue(); 13416 13417 EVT InVT = In.getOperand(0).getValueType(); 13418 13419 // If all scalar values are typed differently, bail out. It's chosen to 13420 // simplify BUILD_VECTOR of integer types. 13421 if (SrcVT == MVT::Other) 13422 SrcVT = InVT; 13423 if (SrcVT != InVT) 13424 return SDValue(); 13425 NumDefs++; 13426 } 13427 13428 // If the vector has just one element defined, it's not worth to fold it into 13429 // a vectorized one. 13430 if (NumDefs < 2) 13431 return SDValue(); 13432 13433 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 13434 && "Should only handle conversion from integer to float."); 13435 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 13436 13437 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 13438 13439 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 13440 return SDValue(); 13441 13442 // Just because the floating-point vector type is legal does not necessarily 13443 // mean that the corresponding integer vector type is. 13444 if (!isTypeLegal(NVT)) 13445 return SDValue(); 13446 13447 SmallVector<SDValue, 8> Opnds; 13448 for (unsigned i = 0; i != NumInScalars; ++i) { 13449 SDValue In = N->getOperand(i); 13450 13451 if (In.isUndef()) 13452 Opnds.push_back(DAG.getUNDEF(SrcVT)); 13453 else 13454 Opnds.push_back(In.getOperand(0)); 13455 } 13456 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 13457 AddToWorklist(BV.getNode()); 13458 13459 return DAG.getNode(Opcode, DL, VT, BV); 13460 } 13461 13462 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 13463 ArrayRef<int> VectorMask, 13464 SDValue VecIn1, SDValue VecIn2, 13465 unsigned LeftIdx) { 13466 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13467 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 13468 13469 EVT VT = N->getValueType(0); 13470 EVT InVT1 = VecIn1.getValueType(); 13471 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 13472 13473 unsigned Vec2Offset = InVT1.getVectorNumElements(); 13474 unsigned NumElems = VT.getVectorNumElements(); 13475 unsigned ShuffleNumElems = NumElems; 13476 13477 // We can't generate a shuffle node with mismatched input and output types. 13478 // Try to make the types match the type of the output. 13479 if (InVT1 != VT || InVT2 != VT) { 13480 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 13481 // If the output vector length is a multiple of both input lengths, 13482 // we can concatenate them and pad the rest with undefs. 13483 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 13484 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 13485 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 13486 ConcatOps[0] = VecIn1; 13487 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 13488 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 13489 VecIn2 = SDValue(); 13490 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 13491 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 13492 return SDValue(); 13493 13494 if (!VecIn2.getNode()) { 13495 // If we only have one input vector, and it's twice the size of the 13496 // output, split it in two. 13497 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 13498 DAG.getConstant(NumElems, DL, IdxTy)); 13499 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 13500 // Since we now have shorter input vectors, adjust the offset of the 13501 // second vector's start. 13502 Vec2Offset = NumElems; 13503 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 13504 // VecIn1 is wider than the output, and we have another, possibly 13505 // smaller input. Pad the smaller input with undefs, shuffle at the 13506 // input vector width, and extract the output. 13507 // The shuffle type is different than VT, so check legality again. 13508 if (LegalOperations && 13509 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 13510 return SDValue(); 13511 13512 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 13513 // lower it back into a BUILD_VECTOR. So if the inserted type is 13514 // illegal, don't even try. 13515 if (InVT1 != InVT2) { 13516 if (!TLI.isTypeLegal(InVT2)) 13517 return SDValue(); 13518 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 13519 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 13520 } 13521 ShuffleNumElems = NumElems * 2; 13522 } else { 13523 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 13524 // than VecIn1. We can't handle this for now - this case will disappear 13525 // when we start sorting the vectors by type. 13526 return SDValue(); 13527 } 13528 } else { 13529 // TODO: Support cases where the length mismatch isn't exactly by a 13530 // factor of 2. 13531 // TODO: Move this check upwards, so that if we have bad type 13532 // mismatches, we don't create any DAG nodes. 13533 return SDValue(); 13534 } 13535 } 13536 13537 // Initialize mask to undef. 13538 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 13539 13540 // Only need to run up to the number of elements actually used, not the 13541 // total number of elements in the shuffle - if we are shuffling a wider 13542 // vector, the high lanes should be set to undef. 13543 for (unsigned i = 0; i != NumElems; ++i) { 13544 if (VectorMask[i] <= 0) 13545 continue; 13546 13547 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 13548 if (VectorMask[i] == (int)LeftIdx) { 13549 Mask[i] = ExtIndex; 13550 } else if (VectorMask[i] == (int)LeftIdx + 1) { 13551 Mask[i] = Vec2Offset + ExtIndex; 13552 } 13553 } 13554 13555 // The type the input vectors may have changed above. 13556 InVT1 = VecIn1.getValueType(); 13557 13558 // If we already have a VecIn2, it should have the same type as VecIn1. 13559 // If we don't, get an undef/zero vector of the appropriate type. 13560 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 13561 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 13562 13563 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 13564 if (ShuffleNumElems > NumElems) 13565 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 13566 13567 return Shuffle; 13568 } 13569 13570 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 13571 // operations. If the types of the vectors we're extracting from allow it, 13572 // turn this into a vector_shuffle node. 13573 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 13574 SDLoc DL(N); 13575 EVT VT = N->getValueType(0); 13576 13577 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 13578 if (!isTypeLegal(VT)) 13579 return SDValue(); 13580 13581 // May only combine to shuffle after legalize if shuffle is legal. 13582 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 13583 return SDValue(); 13584 13585 bool UsesZeroVector = false; 13586 unsigned NumElems = N->getNumOperands(); 13587 13588 // Record, for each element of the newly built vector, which input vector 13589 // that element comes from. -1 stands for undef, 0 for the zero vector, 13590 // and positive values for the input vectors. 13591 // VectorMask maps each element to its vector number, and VecIn maps vector 13592 // numbers to their initial SDValues. 13593 13594 SmallVector<int, 8> VectorMask(NumElems, -1); 13595 SmallVector<SDValue, 8> VecIn; 13596 VecIn.push_back(SDValue()); 13597 13598 for (unsigned i = 0; i != NumElems; ++i) { 13599 SDValue Op = N->getOperand(i); 13600 13601 if (Op.isUndef()) 13602 continue; 13603 13604 // See if we can use a blend with a zero vector. 13605 // TODO: Should we generalize this to a blend with an arbitrary constant 13606 // vector? 13607 if (isNullConstant(Op) || isNullFPConstant(Op)) { 13608 UsesZeroVector = true; 13609 VectorMask[i] = 0; 13610 continue; 13611 } 13612 13613 // Not an undef or zero. If the input is something other than an 13614 // EXTRACT_VECTOR_ELT with a constant index, bail out. 13615 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13616 !isa<ConstantSDNode>(Op.getOperand(1))) 13617 return SDValue(); 13618 13619 SDValue ExtractedFromVec = Op.getOperand(0); 13620 13621 // All inputs must have the same element type as the output. 13622 if (VT.getVectorElementType() != 13623 ExtractedFromVec.getValueType().getVectorElementType()) 13624 return SDValue(); 13625 13626 // Have we seen this input vector before? 13627 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 13628 // a map back from SDValues to numbers isn't worth it. 13629 unsigned Idx = std::distance( 13630 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 13631 if (Idx == VecIn.size()) 13632 VecIn.push_back(ExtractedFromVec); 13633 13634 VectorMask[i] = Idx; 13635 } 13636 13637 // If we didn't find at least one input vector, bail out. 13638 if (VecIn.size() < 2) 13639 return SDValue(); 13640 13641 // TODO: We want to sort the vectors by descending length, so that adjacent 13642 // pairs have similar length, and the longer vector is always first in the 13643 // pair. 13644 13645 // TODO: Should this fire if some of the input vectors has illegal type (like 13646 // it does now), or should we let legalization run its course first? 13647 13648 // Shuffle phase: 13649 // Take pairs of vectors, and shuffle them so that the result has elements 13650 // from these vectors in the correct places. 13651 // For example, given: 13652 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 13653 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 13654 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 13655 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 13656 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 13657 // We will generate: 13658 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 13659 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 13660 SmallVector<SDValue, 4> Shuffles; 13661 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 13662 unsigned LeftIdx = 2 * In + 1; 13663 SDValue VecLeft = VecIn[LeftIdx]; 13664 SDValue VecRight = 13665 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 13666 13667 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 13668 VecRight, LeftIdx)) 13669 Shuffles.push_back(Shuffle); 13670 else 13671 return SDValue(); 13672 } 13673 13674 // If we need the zero vector as an "ingredient" in the blend tree, add it 13675 // to the list of shuffles. 13676 if (UsesZeroVector) 13677 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 13678 : DAG.getConstantFP(0.0, DL, VT)); 13679 13680 // If we only have one shuffle, we're done. 13681 if (Shuffles.size() == 1) 13682 return Shuffles[0]; 13683 13684 // Update the vector mask to point to the post-shuffle vectors. 13685 for (int &Vec : VectorMask) 13686 if (Vec == 0) 13687 Vec = Shuffles.size() - 1; 13688 else 13689 Vec = (Vec - 1) / 2; 13690 13691 // More than one shuffle. Generate a binary tree of blends, e.g. if from 13692 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 13693 // generate: 13694 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 13695 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 13696 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 13697 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 13698 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 13699 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 13700 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 13701 13702 // Make sure the initial size of the shuffle list is even. 13703 if (Shuffles.size() % 2) 13704 Shuffles.push_back(DAG.getUNDEF(VT)); 13705 13706 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 13707 if (CurSize % 2) { 13708 Shuffles[CurSize] = DAG.getUNDEF(VT); 13709 CurSize++; 13710 } 13711 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 13712 int Left = 2 * In; 13713 int Right = 2 * In + 1; 13714 SmallVector<int, 8> Mask(NumElems, -1); 13715 for (unsigned i = 0; i != NumElems; ++i) { 13716 if (VectorMask[i] == Left) { 13717 Mask[i] = i; 13718 VectorMask[i] = In; 13719 } else if (VectorMask[i] == Right) { 13720 Mask[i] = i + NumElems; 13721 VectorMask[i] = In; 13722 } 13723 } 13724 13725 Shuffles[In] = 13726 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 13727 } 13728 } 13729 13730 return Shuffles[0]; 13731 } 13732 13733 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 13734 EVT VT = N->getValueType(0); 13735 13736 // A vector built entirely of undefs is undef. 13737 if (ISD::allOperandsUndef(N)) 13738 return DAG.getUNDEF(VT); 13739 13740 // Check if we can express BUILD VECTOR via subvector extract. 13741 if (!LegalTypes && (N->getNumOperands() > 1)) { 13742 SDValue Op0 = N->getOperand(0); 13743 auto checkElem = [&](SDValue Op) -> uint64_t { 13744 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 13745 (Op0.getOperand(0) == Op.getOperand(0))) 13746 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 13747 return CNode->getZExtValue(); 13748 return -1; 13749 }; 13750 13751 int Offset = checkElem(Op0); 13752 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 13753 if (Offset + i != checkElem(N->getOperand(i))) { 13754 Offset = -1; 13755 break; 13756 } 13757 } 13758 13759 if ((Offset == 0) && 13760 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 13761 return Op0.getOperand(0); 13762 if ((Offset != -1) && 13763 ((Offset % N->getValueType(0).getVectorNumElements()) == 13764 0)) // IDX must be multiple of output size. 13765 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 13766 Op0.getOperand(0), Op0.getOperand(1)); 13767 } 13768 13769 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 13770 return V; 13771 13772 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 13773 return V; 13774 13775 if (SDValue V = reduceBuildVecToShuffle(N)) 13776 return V; 13777 13778 return SDValue(); 13779 } 13780 13781 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 13782 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13783 EVT OpVT = N->getOperand(0).getValueType(); 13784 13785 // If the operands are legal vectors, leave them alone. 13786 if (TLI.isTypeLegal(OpVT)) 13787 return SDValue(); 13788 13789 SDLoc DL(N); 13790 EVT VT = N->getValueType(0); 13791 SmallVector<SDValue, 8> Ops; 13792 13793 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 13794 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13795 13796 // Keep track of what we encounter. 13797 bool AnyInteger = false; 13798 bool AnyFP = false; 13799 for (const SDValue &Op : N->ops()) { 13800 if (ISD::BITCAST == Op.getOpcode() && 13801 !Op.getOperand(0).getValueType().isVector()) 13802 Ops.push_back(Op.getOperand(0)); 13803 else if (ISD::UNDEF == Op.getOpcode()) 13804 Ops.push_back(ScalarUndef); 13805 else 13806 return SDValue(); 13807 13808 // Note whether we encounter an integer or floating point scalar. 13809 // If it's neither, bail out, it could be something weird like x86mmx. 13810 EVT LastOpVT = Ops.back().getValueType(); 13811 if (LastOpVT.isFloatingPoint()) 13812 AnyFP = true; 13813 else if (LastOpVT.isInteger()) 13814 AnyInteger = true; 13815 else 13816 return SDValue(); 13817 } 13818 13819 // If any of the operands is a floating point scalar bitcast to a vector, 13820 // use floating point types throughout, and bitcast everything. 13821 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 13822 if (AnyFP) { 13823 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 13824 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13825 if (AnyInteger) { 13826 for (SDValue &Op : Ops) { 13827 if (Op.getValueType() == SVT) 13828 continue; 13829 if (Op.isUndef()) 13830 Op = ScalarUndef; 13831 else 13832 Op = DAG.getBitcast(SVT, Op); 13833 } 13834 } 13835 } 13836 13837 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 13838 VT.getSizeInBits() / SVT.getSizeInBits()); 13839 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 13840 } 13841 13842 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 13843 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 13844 // most two distinct vectors the same size as the result, attempt to turn this 13845 // into a legal shuffle. 13846 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 13847 EVT VT = N->getValueType(0); 13848 EVT OpVT = N->getOperand(0).getValueType(); 13849 int NumElts = VT.getVectorNumElements(); 13850 int NumOpElts = OpVT.getVectorNumElements(); 13851 13852 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 13853 SmallVector<int, 8> Mask; 13854 13855 for (SDValue Op : N->ops()) { 13856 // Peek through any bitcast. 13857 while (Op.getOpcode() == ISD::BITCAST) 13858 Op = Op.getOperand(0); 13859 13860 // UNDEF nodes convert to UNDEF shuffle mask values. 13861 if (Op.isUndef()) { 13862 Mask.append((unsigned)NumOpElts, -1); 13863 continue; 13864 } 13865 13866 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13867 return SDValue(); 13868 13869 // What vector are we extracting the subvector from and at what index? 13870 SDValue ExtVec = Op.getOperand(0); 13871 13872 // We want the EVT of the original extraction to correctly scale the 13873 // extraction index. 13874 EVT ExtVT = ExtVec.getValueType(); 13875 13876 // Peek through any bitcast. 13877 while (ExtVec.getOpcode() == ISD::BITCAST) 13878 ExtVec = ExtVec.getOperand(0); 13879 13880 // UNDEF nodes convert to UNDEF shuffle mask values. 13881 if (ExtVec.isUndef()) { 13882 Mask.append((unsigned)NumOpElts, -1); 13883 continue; 13884 } 13885 13886 if (!isa<ConstantSDNode>(Op.getOperand(1))) 13887 return SDValue(); 13888 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 13889 13890 // Ensure that we are extracting a subvector from a vector the same 13891 // size as the result. 13892 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 13893 return SDValue(); 13894 13895 // Scale the subvector index to account for any bitcast. 13896 int NumExtElts = ExtVT.getVectorNumElements(); 13897 if (0 == (NumExtElts % NumElts)) 13898 ExtIdx /= (NumExtElts / NumElts); 13899 else if (0 == (NumElts % NumExtElts)) 13900 ExtIdx *= (NumElts / NumExtElts); 13901 else 13902 return SDValue(); 13903 13904 // At most we can reference 2 inputs in the final shuffle. 13905 if (SV0.isUndef() || SV0 == ExtVec) { 13906 SV0 = ExtVec; 13907 for (int i = 0; i != NumOpElts; ++i) 13908 Mask.push_back(i + ExtIdx); 13909 } else if (SV1.isUndef() || SV1 == ExtVec) { 13910 SV1 = ExtVec; 13911 for (int i = 0; i != NumOpElts; ++i) 13912 Mask.push_back(i + ExtIdx + NumElts); 13913 } else { 13914 return SDValue(); 13915 } 13916 } 13917 13918 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13919 return SDValue(); 13920 13921 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13922 DAG.getBitcast(VT, SV1), Mask); 13923 } 13924 13925 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13926 // If we only have one input vector, we don't need to do any concatenation. 13927 if (N->getNumOperands() == 1) 13928 return N->getOperand(0); 13929 13930 // Check if all of the operands are undefs. 13931 EVT VT = N->getValueType(0); 13932 if (ISD::allOperandsUndef(N)) 13933 return DAG.getUNDEF(VT); 13934 13935 // Optimize concat_vectors where all but the first of the vectors are undef. 13936 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13937 return Op.isUndef(); 13938 })) { 13939 SDValue In = N->getOperand(0); 13940 assert(In.getValueType().isVector() && "Must concat vectors"); 13941 13942 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13943 if (In->getOpcode() == ISD::BITCAST && 13944 !In->getOperand(0)->getValueType(0).isVector()) { 13945 SDValue Scalar = In->getOperand(0); 13946 13947 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13948 // look through the trunc so we can still do the transform: 13949 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13950 if (Scalar->getOpcode() == ISD::TRUNCATE && 13951 !TLI.isTypeLegal(Scalar.getValueType()) && 13952 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13953 Scalar = Scalar->getOperand(0); 13954 13955 EVT SclTy = Scalar->getValueType(0); 13956 13957 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13958 return SDValue(); 13959 13960 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13961 VT.getSizeInBits() / SclTy.getSizeInBits()); 13962 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13963 return SDValue(); 13964 13965 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 13966 return DAG.getBitcast(VT, Res); 13967 } 13968 } 13969 13970 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13971 // We have already tested above for an UNDEF only concatenation. 13972 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13973 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13974 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13975 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13976 }; 13977 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13978 SmallVector<SDValue, 8> Opnds; 13979 EVT SVT = VT.getScalarType(); 13980 13981 EVT MinVT = SVT; 13982 if (!SVT.isFloatingPoint()) { 13983 // If BUILD_VECTOR are from built from integer, they may have different 13984 // operand types. Get the smallest type and truncate all operands to it. 13985 bool FoundMinVT = false; 13986 for (const SDValue &Op : N->ops()) 13987 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13988 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13989 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13990 FoundMinVT = true; 13991 } 13992 assert(FoundMinVT && "Concat vector type mismatch"); 13993 } 13994 13995 for (const SDValue &Op : N->ops()) { 13996 EVT OpVT = Op.getValueType(); 13997 unsigned NumElts = OpVT.getVectorNumElements(); 13998 13999 if (ISD::UNDEF == Op.getOpcode()) 14000 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 14001 14002 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14003 if (SVT.isFloatingPoint()) { 14004 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 14005 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 14006 } else { 14007 for (unsigned i = 0; i != NumElts; ++i) 14008 Opnds.push_back( 14009 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 14010 } 14011 } 14012 } 14013 14014 assert(VT.getVectorNumElements() == Opnds.size() && 14015 "Concat vector type mismatch"); 14016 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 14017 } 14018 14019 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 14020 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 14021 return V; 14022 14023 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 14024 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14025 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 14026 return V; 14027 14028 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 14029 // nodes often generate nop CONCAT_VECTOR nodes. 14030 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 14031 // place the incoming vectors at the exact same location. 14032 SDValue SingleSource = SDValue(); 14033 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 14034 14035 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14036 SDValue Op = N->getOperand(i); 14037 14038 if (Op.isUndef()) 14039 continue; 14040 14041 // Check if this is the identity extract: 14042 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14043 return SDValue(); 14044 14045 // Find the single incoming vector for the extract_subvector. 14046 if (SingleSource.getNode()) { 14047 if (Op.getOperand(0) != SingleSource) 14048 return SDValue(); 14049 } else { 14050 SingleSource = Op.getOperand(0); 14051 14052 // Check the source type is the same as the type of the result. 14053 // If not, this concat may extend the vector, so we can not 14054 // optimize it away. 14055 if (SingleSource.getValueType() != N->getValueType(0)) 14056 return SDValue(); 14057 } 14058 14059 unsigned IdentityIndex = i * PartNumElem; 14060 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14061 // The extract index must be constant. 14062 if (!CS) 14063 return SDValue(); 14064 14065 // Check that we are reading from the identity index. 14066 if (CS->getZExtValue() != IdentityIndex) 14067 return SDValue(); 14068 } 14069 14070 if (SingleSource.getNode()) 14071 return SingleSource; 14072 14073 return SDValue(); 14074 } 14075 14076 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 14077 EVT NVT = N->getValueType(0); 14078 SDValue V = N->getOperand(0); 14079 14080 // Extract from UNDEF is UNDEF. 14081 if (V.isUndef()) 14082 return DAG.getUNDEF(NVT); 14083 14084 // Combine: 14085 // (extract_subvec (concat V1, V2, ...), i) 14086 // Into: 14087 // Vi if possible 14088 // Only operand 0 is checked as 'concat' assumes all inputs of the same 14089 // type. 14090 if (V->getOpcode() == ISD::CONCAT_VECTORS && 14091 isa<ConstantSDNode>(N->getOperand(1)) && 14092 V->getOperand(0).getValueType() == NVT) { 14093 unsigned Idx = N->getConstantOperandVal(1); 14094 unsigned NumElems = NVT.getVectorNumElements(); 14095 assert((Idx % NumElems) == 0 && 14096 "IDX in concat is not a multiple of the result vector length."); 14097 return V->getOperand(Idx / NumElems); 14098 } 14099 14100 // Skip bitcasting 14101 if (V->getOpcode() == ISD::BITCAST) 14102 V = V.getOperand(0); 14103 14104 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 14105 // Handle only simple case where vector being inserted and vector 14106 // being extracted are of same size. 14107 EVT SmallVT = V->getOperand(1).getValueType(); 14108 if (!NVT.bitsEq(SmallVT)) 14109 return SDValue(); 14110 14111 // Only handle cases where both indexes are constants. 14112 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14113 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14114 14115 if (InsIdx && ExtIdx) { 14116 // Combine: 14117 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 14118 // Into: 14119 // indices are equal or bit offsets are equal => V1 14120 // otherwise => (extract_subvec V1, ExtIdx) 14121 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 14122 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 14123 return DAG.getBitcast(NVT, V->getOperand(1)); 14124 return DAG.getNode( 14125 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 14126 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 14127 N->getOperand(1)); 14128 } 14129 } 14130 14131 return SDValue(); 14132 } 14133 14134 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 14135 SDValue V, SelectionDAG &DAG) { 14136 SDLoc DL(V); 14137 EVT VT = V.getValueType(); 14138 14139 switch (V.getOpcode()) { 14140 default: 14141 return V; 14142 14143 case ISD::CONCAT_VECTORS: { 14144 EVT OpVT = V->getOperand(0).getValueType(); 14145 int OpSize = OpVT.getVectorNumElements(); 14146 SmallBitVector OpUsedElements(OpSize, false); 14147 bool FoundSimplification = false; 14148 SmallVector<SDValue, 4> NewOps; 14149 NewOps.reserve(V->getNumOperands()); 14150 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 14151 SDValue Op = V->getOperand(i); 14152 bool OpUsed = false; 14153 for (int j = 0; j < OpSize; ++j) 14154 if (UsedElements[i * OpSize + j]) { 14155 OpUsedElements[j] = true; 14156 OpUsed = true; 14157 } 14158 NewOps.push_back( 14159 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 14160 : DAG.getUNDEF(OpVT)); 14161 FoundSimplification |= Op == NewOps.back(); 14162 OpUsedElements.reset(); 14163 } 14164 if (FoundSimplification) 14165 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 14166 return V; 14167 } 14168 14169 case ISD::INSERT_SUBVECTOR: { 14170 SDValue BaseV = V->getOperand(0); 14171 SDValue SubV = V->getOperand(1); 14172 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14173 if (!IdxN) 14174 return V; 14175 14176 int SubSize = SubV.getValueType().getVectorNumElements(); 14177 int Idx = IdxN->getZExtValue(); 14178 bool SubVectorUsed = false; 14179 SmallBitVector SubUsedElements(SubSize, false); 14180 for (int i = 0; i < SubSize; ++i) 14181 if (UsedElements[i + Idx]) { 14182 SubVectorUsed = true; 14183 SubUsedElements[i] = true; 14184 UsedElements[i + Idx] = false; 14185 } 14186 14187 // Now recurse on both the base and sub vectors. 14188 SDValue SimplifiedSubV = 14189 SubVectorUsed 14190 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 14191 : DAG.getUNDEF(SubV.getValueType()); 14192 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 14193 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 14194 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 14195 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 14196 return V; 14197 } 14198 } 14199 } 14200 14201 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 14202 SDValue N1, SelectionDAG &DAG) { 14203 EVT VT = SVN->getValueType(0); 14204 int NumElts = VT.getVectorNumElements(); 14205 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 14206 for (int M : SVN->getMask()) 14207 if (M >= 0 && M < NumElts) 14208 N0UsedElements[M] = true; 14209 else if (M >= NumElts) 14210 N1UsedElements[M - NumElts] = true; 14211 14212 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 14213 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 14214 if (S0 == N0 && S1 == N1) 14215 return SDValue(); 14216 14217 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 14218 } 14219 14220 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 14221 // or turn a shuffle of a single concat into simpler shuffle then concat. 14222 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 14223 EVT VT = N->getValueType(0); 14224 unsigned NumElts = VT.getVectorNumElements(); 14225 14226 SDValue N0 = N->getOperand(0); 14227 SDValue N1 = N->getOperand(1); 14228 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14229 14230 SmallVector<SDValue, 4> Ops; 14231 EVT ConcatVT = N0.getOperand(0).getValueType(); 14232 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 14233 unsigned NumConcats = NumElts / NumElemsPerConcat; 14234 14235 // Special case: shuffle(concat(A,B)) can be more efficiently represented 14236 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 14237 // half vector elements. 14238 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 14239 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 14240 SVN->getMask().end(), [](int i) { return i == -1; })) { 14241 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 14242 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 14243 N1 = DAG.getUNDEF(ConcatVT); 14244 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 14245 } 14246 14247 // Look at every vector that's inserted. We're looking for exact 14248 // subvector-sized copies from a concatenated vector 14249 for (unsigned I = 0; I != NumConcats; ++I) { 14250 // Make sure we're dealing with a copy. 14251 unsigned Begin = I * NumElemsPerConcat; 14252 bool AllUndef = true, NoUndef = true; 14253 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 14254 if (SVN->getMaskElt(J) >= 0) 14255 AllUndef = false; 14256 else 14257 NoUndef = false; 14258 } 14259 14260 if (NoUndef) { 14261 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 14262 return SDValue(); 14263 14264 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 14265 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 14266 return SDValue(); 14267 14268 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 14269 if (FirstElt < N0.getNumOperands()) 14270 Ops.push_back(N0.getOperand(FirstElt)); 14271 else 14272 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 14273 14274 } else if (AllUndef) { 14275 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 14276 } else { // Mixed with general masks and undefs, can't do optimization. 14277 return SDValue(); 14278 } 14279 } 14280 14281 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14282 } 14283 14284 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14285 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14286 // 14287 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 14288 // a simplification in some sense, but it isn't appropriate in general: some 14289 // BUILD_VECTORs are substantially cheaper than others. The general case 14290 // of a BUILD_VECTOR requires inserting each element individually (or 14291 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 14292 // all constants is a single constant pool load. A BUILD_VECTOR where each 14293 // element is identical is a splat. A BUILD_VECTOR where most of the operands 14294 // are undef lowers to a small number of element insertions. 14295 // 14296 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 14297 // We don't fold shuffles where one side is a non-zero constant, and we don't 14298 // fold shuffles if the resulting BUILD_VECTOR would have duplicate 14299 // non-constant operands. This seems to work out reasonably well in practice. 14300 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 14301 SelectionDAG &DAG, 14302 const TargetLowering &TLI) { 14303 EVT VT = SVN->getValueType(0); 14304 unsigned NumElts = VT.getVectorNumElements(); 14305 SDValue N0 = SVN->getOperand(0); 14306 SDValue N1 = SVN->getOperand(1); 14307 14308 if (!N0->hasOneUse() || !N1->hasOneUse()) 14309 return SDValue(); 14310 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 14311 // discussed above. 14312 if (!N1.isUndef()) { 14313 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 14314 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 14315 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 14316 return SDValue(); 14317 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 14318 return SDValue(); 14319 } 14320 14321 SmallVector<SDValue, 8> Ops; 14322 SmallSet<SDValue, 16> DuplicateOps; 14323 for (int M : SVN->getMask()) { 14324 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 14325 if (M >= 0) { 14326 int Idx = M < (int)NumElts ? M : M - NumElts; 14327 SDValue &S = (M < (int)NumElts ? N0 : N1); 14328 if (S.getOpcode() == ISD::BUILD_VECTOR) { 14329 Op = S.getOperand(Idx); 14330 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14331 if (Idx == 0) 14332 Op = S.getOperand(0); 14333 } else { 14334 // Operand can't be combined - bail out. 14335 return SDValue(); 14336 } 14337 } 14338 14339 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is 14340 // fine, but it's likely to generate low-quality code if the target can't 14341 // reconstruct an appropriate shuffle. 14342 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 14343 if (!DuplicateOps.insert(Op).second) 14344 return SDValue(); 14345 14346 Ops.push_back(Op); 14347 } 14348 // BUILD_VECTOR requires all inputs to be of the same type, find the 14349 // maximum type and extend them all. 14350 EVT SVT = VT.getScalarType(); 14351 if (SVT.isInteger()) 14352 for (SDValue &Op : Ops) 14353 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 14354 if (SVT != VT.getScalarType()) 14355 for (SDValue &Op : Ops) 14356 Op = TLI.isZExtFree(Op.getValueType(), SVT) 14357 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 14358 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 14359 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 14360 } 14361 14362 // Match shuffles that can be converted to any_vector_extend_in_reg. 14363 // This is often generated during legalization. 14364 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 14365 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 14366 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 14367 SelectionDAG &DAG, 14368 const TargetLowering &TLI, 14369 bool LegalOperations) { 14370 EVT VT = SVN->getValueType(0); 14371 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14372 14373 // TODO Add support for big-endian when we have a test case. 14374 if (!VT.isInteger() || IsBigEndian) 14375 return SDValue(); 14376 14377 unsigned NumElts = VT.getVectorNumElements(); 14378 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14379 ArrayRef<int> Mask = SVN->getMask(); 14380 SDValue N0 = SVN->getOperand(0); 14381 14382 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 14383 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 14384 for (unsigned i = 0; i != NumElts; ++i) { 14385 if (Mask[i] < 0) 14386 continue; 14387 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 14388 continue; 14389 return false; 14390 } 14391 return true; 14392 }; 14393 14394 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 14395 // power-of-2 extensions as they are the most likely. 14396 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 14397 if (!isAnyExtend(Scale)) 14398 continue; 14399 14400 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 14401 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 14402 if (!LegalOperations || 14403 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 14404 return DAG.getBitcast(VT, 14405 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 14406 } 14407 14408 return SDValue(); 14409 } 14410 14411 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 14412 // each source element of a large type into the lowest elements of a smaller 14413 // destination type. This is often generated during legalization. 14414 // If the source node itself was a '*_extend_vector_inreg' node then we should 14415 // then be able to remove it. 14416 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) { 14417 EVT VT = SVN->getValueType(0); 14418 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14419 14420 // TODO Add support for big-endian when we have a test case. 14421 if (!VT.isInteger() || IsBigEndian) 14422 return SDValue(); 14423 14424 SDValue N0 = SVN->getOperand(0); 14425 while (N0.getOpcode() == ISD::BITCAST) 14426 N0 = N0.getOperand(0); 14427 14428 unsigned Opcode = N0.getOpcode(); 14429 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 14430 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 14431 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 14432 return SDValue(); 14433 14434 SDValue N00 = N0.getOperand(0); 14435 ArrayRef<int> Mask = SVN->getMask(); 14436 unsigned NumElts = VT.getVectorNumElements(); 14437 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14438 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 14439 14440 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 14441 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 14442 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 14443 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 14444 for (unsigned i = 0; i != NumElts; ++i) { 14445 if (Mask[i] < 0) 14446 continue; 14447 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 14448 continue; 14449 return false; 14450 } 14451 return true; 14452 }; 14453 14454 // At the moment we just handle the case where we've truncated back to the 14455 // same size as before the extension. 14456 // TODO: handle more extension/truncation cases as cases arise. 14457 if (EltSizeInBits != ExtSrcSizeInBits) 14458 return SDValue(); 14459 14460 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for 14461 // power-of-2 truncations as they are the most likely. 14462 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) 14463 if (isTruncate(Scale)) 14464 return DAG.getBitcast(VT, N00); 14465 14466 return SDValue(); 14467 } 14468 14469 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 14470 EVT VT = N->getValueType(0); 14471 unsigned NumElts = VT.getVectorNumElements(); 14472 14473 SDValue N0 = N->getOperand(0); 14474 SDValue N1 = N->getOperand(1); 14475 14476 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 14477 14478 // Canonicalize shuffle undef, undef -> undef 14479 if (N0.isUndef() && N1.isUndef()) 14480 return DAG.getUNDEF(VT); 14481 14482 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14483 14484 // Canonicalize shuffle v, v -> v, undef 14485 if (N0 == N1) { 14486 SmallVector<int, 8> NewMask; 14487 for (unsigned i = 0; i != NumElts; ++i) { 14488 int Idx = SVN->getMaskElt(i); 14489 if (Idx >= (int)NumElts) Idx -= NumElts; 14490 NewMask.push_back(Idx); 14491 } 14492 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 14493 } 14494 14495 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 14496 if (N0.isUndef()) 14497 return DAG.getCommutedVectorShuffle(*SVN); 14498 14499 // Remove references to rhs if it is undef 14500 if (N1.isUndef()) { 14501 bool Changed = false; 14502 SmallVector<int, 8> NewMask; 14503 for (unsigned i = 0; i != NumElts; ++i) { 14504 int Idx = SVN->getMaskElt(i); 14505 if (Idx >= (int)NumElts) { 14506 Idx = -1; 14507 Changed = true; 14508 } 14509 NewMask.push_back(Idx); 14510 } 14511 if (Changed) 14512 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 14513 } 14514 14515 // If it is a splat, check if the argument vector is another splat or a 14516 // build_vector. 14517 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 14518 SDNode *V = N0.getNode(); 14519 14520 // If this is a bit convert that changes the element type of the vector but 14521 // not the number of vector elements, look through it. Be careful not to 14522 // look though conversions that change things like v4f32 to v2f64. 14523 if (V->getOpcode() == ISD::BITCAST) { 14524 SDValue ConvInput = V->getOperand(0); 14525 if (ConvInput.getValueType().isVector() && 14526 ConvInput.getValueType().getVectorNumElements() == NumElts) 14527 V = ConvInput.getNode(); 14528 } 14529 14530 if (V->getOpcode() == ISD::BUILD_VECTOR) { 14531 assert(V->getNumOperands() == NumElts && 14532 "BUILD_VECTOR has wrong number of operands"); 14533 SDValue Base; 14534 bool AllSame = true; 14535 for (unsigned i = 0; i != NumElts; ++i) { 14536 if (!V->getOperand(i).isUndef()) { 14537 Base = V->getOperand(i); 14538 break; 14539 } 14540 } 14541 // Splat of <u, u, u, u>, return <u, u, u, u> 14542 if (!Base.getNode()) 14543 return N0; 14544 for (unsigned i = 0; i != NumElts; ++i) { 14545 if (V->getOperand(i) != Base) { 14546 AllSame = false; 14547 break; 14548 } 14549 } 14550 // Splat of <x, x, x, x>, return <x, x, x, x> 14551 if (AllSame) 14552 return N0; 14553 14554 // Canonicalize any other splat as a build_vector. 14555 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 14556 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 14557 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 14558 14559 // We may have jumped through bitcasts, so the type of the 14560 // BUILD_VECTOR may not match the type of the shuffle. 14561 if (V->getValueType(0) != VT) 14562 NewBV = DAG.getBitcast(VT, NewBV); 14563 return NewBV; 14564 } 14565 } 14566 14567 // There are various patterns used to build up a vector from smaller vectors, 14568 // subvectors, or elements. Scan chains of these and replace unused insertions 14569 // or components with undef. 14570 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 14571 return S; 14572 14573 // Match shuffles that can be converted to any_vector_extend_in_reg. 14574 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 14575 return V; 14576 14577 // Combine "truncate_vector_in_reg" style shuffles. 14578 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 14579 return V; 14580 14581 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 14582 Level < AfterLegalizeVectorOps && 14583 (N1.isUndef() || 14584 (N1.getOpcode() == ISD::CONCAT_VECTORS && 14585 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 14586 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 14587 return V; 14588 } 14589 14590 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14591 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14592 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14593 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 14594 return Res; 14595 14596 // If this shuffle only has a single input that is a bitcasted shuffle, 14597 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 14598 // back to their original types. 14599 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 14600 N1.isUndef() && Level < AfterLegalizeVectorOps && 14601 TLI.isTypeLegal(VT)) { 14602 14603 // Peek through the bitcast only if there is one user. 14604 SDValue BC0 = N0; 14605 while (BC0.getOpcode() == ISD::BITCAST) { 14606 if (!BC0.hasOneUse()) 14607 break; 14608 BC0 = BC0.getOperand(0); 14609 } 14610 14611 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 14612 if (Scale == 1) 14613 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 14614 14615 SmallVector<int, 8> NewMask; 14616 for (int M : Mask) 14617 for (int s = 0; s != Scale; ++s) 14618 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 14619 return NewMask; 14620 }; 14621 14622 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 14623 EVT SVT = VT.getScalarType(); 14624 EVT InnerVT = BC0->getValueType(0); 14625 EVT InnerSVT = InnerVT.getScalarType(); 14626 14627 // Determine which shuffle works with the smaller scalar type. 14628 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 14629 EVT ScaleSVT = ScaleVT.getScalarType(); 14630 14631 if (TLI.isTypeLegal(ScaleVT) && 14632 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 14633 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 14634 14635 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14636 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 14637 14638 // Scale the shuffle masks to the smaller scalar type. 14639 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 14640 SmallVector<int, 8> InnerMask = 14641 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 14642 SmallVector<int, 8> OuterMask = 14643 ScaleShuffleMask(SVN->getMask(), OuterScale); 14644 14645 // Merge the shuffle masks. 14646 SmallVector<int, 8> NewMask; 14647 for (int M : OuterMask) 14648 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 14649 14650 // Test for shuffle mask legality over both commutations. 14651 SDValue SV0 = BC0->getOperand(0); 14652 SDValue SV1 = BC0->getOperand(1); 14653 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14654 if (!LegalMask) { 14655 std::swap(SV0, SV1); 14656 ShuffleVectorSDNode::commuteMask(NewMask); 14657 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 14658 } 14659 14660 if (LegalMask) { 14661 SV0 = DAG.getBitcast(ScaleVT, SV0); 14662 SV1 = DAG.getBitcast(ScaleVT, SV1); 14663 return DAG.getBitcast( 14664 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 14665 } 14666 } 14667 } 14668 } 14669 14670 // Canonicalize shuffles according to rules: 14671 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 14672 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 14673 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 14674 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 14675 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 14676 TLI.isTypeLegal(VT)) { 14677 // The incoming shuffle must be of the same type as the result of the 14678 // current shuffle. 14679 assert(N1->getOperand(0).getValueType() == VT && 14680 "Shuffle types don't match"); 14681 14682 SDValue SV0 = N1->getOperand(0); 14683 SDValue SV1 = N1->getOperand(1); 14684 bool HasSameOp0 = N0 == SV0; 14685 bool IsSV1Undef = SV1.isUndef(); 14686 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 14687 // Commute the operands of this shuffle so that next rule 14688 // will trigger. 14689 return DAG.getCommutedVectorShuffle(*SVN); 14690 } 14691 14692 // Try to fold according to rules: 14693 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14694 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14695 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14696 // Don't try to fold shuffles with illegal type. 14697 // Only fold if this shuffle is the only user of the other shuffle. 14698 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 14699 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 14700 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 14701 14702 // Don't try to fold splats; they're likely to simplify somehow, or they 14703 // might be free. 14704 if (OtherSV->isSplat()) 14705 return SDValue(); 14706 14707 // The incoming shuffle must be of the same type as the result of the 14708 // current shuffle. 14709 assert(OtherSV->getOperand(0).getValueType() == VT && 14710 "Shuffle types don't match"); 14711 14712 SDValue SV0, SV1; 14713 SmallVector<int, 4> Mask; 14714 // Compute the combined shuffle mask for a shuffle with SV0 as the first 14715 // operand, and SV1 as the second operand. 14716 for (unsigned i = 0; i != NumElts; ++i) { 14717 int Idx = SVN->getMaskElt(i); 14718 if (Idx < 0) { 14719 // Propagate Undef. 14720 Mask.push_back(Idx); 14721 continue; 14722 } 14723 14724 SDValue CurrentVec; 14725 if (Idx < (int)NumElts) { 14726 // This shuffle index refers to the inner shuffle N0. Lookup the inner 14727 // shuffle mask to identify which vector is actually referenced. 14728 Idx = OtherSV->getMaskElt(Idx); 14729 if (Idx < 0) { 14730 // Propagate Undef. 14731 Mask.push_back(Idx); 14732 continue; 14733 } 14734 14735 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 14736 : OtherSV->getOperand(1); 14737 } else { 14738 // This shuffle index references an element within N1. 14739 CurrentVec = N1; 14740 } 14741 14742 // Simple case where 'CurrentVec' is UNDEF. 14743 if (CurrentVec.isUndef()) { 14744 Mask.push_back(-1); 14745 continue; 14746 } 14747 14748 // Canonicalize the shuffle index. We don't know yet if CurrentVec 14749 // will be the first or second operand of the combined shuffle. 14750 Idx = Idx % NumElts; 14751 if (!SV0.getNode() || SV0 == CurrentVec) { 14752 // Ok. CurrentVec is the left hand side. 14753 // Update the mask accordingly. 14754 SV0 = CurrentVec; 14755 Mask.push_back(Idx); 14756 continue; 14757 } 14758 14759 // Bail out if we cannot convert the shuffle pair into a single shuffle. 14760 if (SV1.getNode() && SV1 != CurrentVec) 14761 return SDValue(); 14762 14763 // Ok. CurrentVec is the right hand side. 14764 // Update the mask accordingly. 14765 SV1 = CurrentVec; 14766 Mask.push_back(Idx + NumElts); 14767 } 14768 14769 // Check if all indices in Mask are Undef. In case, propagate Undef. 14770 bool isUndefMask = true; 14771 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 14772 isUndefMask &= Mask[i] < 0; 14773 14774 if (isUndefMask) 14775 return DAG.getUNDEF(VT); 14776 14777 if (!SV0.getNode()) 14778 SV0 = DAG.getUNDEF(VT); 14779 if (!SV1.getNode()) 14780 SV1 = DAG.getUNDEF(VT); 14781 14782 // Avoid introducing shuffles with illegal mask. 14783 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 14784 ShuffleVectorSDNode::commuteMask(Mask); 14785 14786 if (!TLI.isShuffleMaskLegal(Mask, VT)) 14787 return SDValue(); 14788 14789 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 14790 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 14791 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 14792 std::swap(SV0, SV1); 14793 } 14794 14795 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 14796 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 14797 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 14798 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 14799 } 14800 14801 return SDValue(); 14802 } 14803 14804 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 14805 SDValue InVal = N->getOperand(0); 14806 EVT VT = N->getValueType(0); 14807 14808 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 14809 // with a VECTOR_SHUFFLE. 14810 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14811 SDValue InVec = InVal->getOperand(0); 14812 SDValue EltNo = InVal->getOperand(1); 14813 14814 // FIXME: We could support implicit truncation if the shuffle can be 14815 // scaled to a smaller vector scalar type. 14816 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 14817 if (C0 && VT == InVec.getValueType() && 14818 VT.getScalarType() == InVal.getValueType()) { 14819 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 14820 int Elt = C0->getZExtValue(); 14821 NewMask[0] = Elt; 14822 14823 if (TLI.isShuffleMaskLegal(NewMask, VT)) 14824 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 14825 NewMask); 14826 } 14827 } 14828 14829 return SDValue(); 14830 } 14831 14832 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 14833 EVT VT = N->getValueType(0); 14834 SDValue N0 = N->getOperand(0); 14835 SDValue N1 = N->getOperand(1); 14836 SDValue N2 = N->getOperand(2); 14837 14838 // If inserting an UNDEF, just return the original vector. 14839 if (N1.isUndef()) 14840 return N0; 14841 14842 // If this is an insert of an extracted vector into an undef vector, we can 14843 // just use the input to the extract. 14844 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 14845 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 14846 return N1.getOperand(0); 14847 14848 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 14849 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 14850 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 14851 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 14852 N0.getOperand(1).getValueType() == N1.getValueType() && 14853 N0.getOperand(2) == N2) 14854 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 14855 N1, N2); 14856 14857 if (!isa<ConstantSDNode>(N2)) 14858 return SDValue(); 14859 14860 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 14861 14862 // Canonicalize insert_subvector dag nodes. 14863 // Example: 14864 // (insert_subvector (insert_subvector A, Idx0), Idx1) 14865 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 14866 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 14867 N1.getValueType() == N0.getOperand(1).getValueType() && 14868 isa<ConstantSDNode>(N0.getOperand(2))) { 14869 unsigned OtherIdx = cast<ConstantSDNode>(N0.getOperand(2))->getZExtValue(); 14870 if (InsIdx < OtherIdx) { 14871 // Swap nodes. 14872 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 14873 N0.getOperand(0), N1, N2); 14874 AddToWorklist(NewOp.getNode()); 14875 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 14876 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 14877 } 14878 } 14879 14880 // If the input vector is a concatenation, and the insert replaces 14881 // one of the pieces, we can optimize into a single concat_vectors. 14882 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 14883 N0.getOperand(0).getValueType() == N1.getValueType()) { 14884 unsigned Factor = N1.getValueType().getVectorNumElements(); 14885 14886 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 14887 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 14888 14889 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14890 } 14891 14892 return SDValue(); 14893 } 14894 14895 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 14896 SDValue N0 = N->getOperand(0); 14897 14898 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 14899 if (N0->getOpcode() == ISD::FP16_TO_FP) 14900 return N0->getOperand(0); 14901 14902 return SDValue(); 14903 } 14904 14905 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 14906 SDValue N0 = N->getOperand(0); 14907 14908 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 14909 if (N0->getOpcode() == ISD::AND) { 14910 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 14911 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 14912 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 14913 N0.getOperand(0)); 14914 } 14915 } 14916 14917 return SDValue(); 14918 } 14919 14920 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 14921 /// with the destination vector and a zero vector. 14922 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 14923 /// vector_shuffle V, Zero, <0, 4, 2, 4> 14924 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 14925 EVT VT = N->getValueType(0); 14926 SDValue LHS = N->getOperand(0); 14927 SDValue RHS = N->getOperand(1); 14928 SDLoc DL(N); 14929 14930 // Make sure we're not running after operation legalization where it 14931 // may have custom lowered the vector shuffles. 14932 if (LegalOperations) 14933 return SDValue(); 14934 14935 if (N->getOpcode() != ISD::AND) 14936 return SDValue(); 14937 14938 if (RHS.getOpcode() == ISD::BITCAST) 14939 RHS = RHS.getOperand(0); 14940 14941 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 14942 return SDValue(); 14943 14944 EVT RVT = RHS.getValueType(); 14945 unsigned NumElts = RHS.getNumOperands(); 14946 14947 // Attempt to create a valid clear mask, splitting the mask into 14948 // sub elements and checking to see if each is 14949 // all zeros or all ones - suitable for shuffle masking. 14950 auto BuildClearMask = [&](int Split) { 14951 int NumSubElts = NumElts * Split; 14952 int NumSubBits = RVT.getScalarSizeInBits() / Split; 14953 14954 SmallVector<int, 8> Indices; 14955 for (int i = 0; i != NumSubElts; ++i) { 14956 int EltIdx = i / Split; 14957 int SubIdx = i % Split; 14958 SDValue Elt = RHS.getOperand(EltIdx); 14959 if (Elt.isUndef()) { 14960 Indices.push_back(-1); 14961 continue; 14962 } 14963 14964 APInt Bits; 14965 if (isa<ConstantSDNode>(Elt)) 14966 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 14967 else if (isa<ConstantFPSDNode>(Elt)) 14968 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 14969 else 14970 return SDValue(); 14971 14972 // Extract the sub element from the constant bit mask. 14973 if (DAG.getDataLayout().isBigEndian()) { 14974 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 14975 } else { 14976 Bits = Bits.lshr(SubIdx * NumSubBits); 14977 } 14978 14979 if (Split > 1) 14980 Bits = Bits.trunc(NumSubBits); 14981 14982 if (Bits.isAllOnesValue()) 14983 Indices.push_back(i); 14984 else if (Bits == 0) 14985 Indices.push_back(i + NumSubElts); 14986 else 14987 return SDValue(); 14988 } 14989 14990 // Let's see if the target supports this vector_shuffle. 14991 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 14992 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 14993 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 14994 return SDValue(); 14995 14996 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 14997 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 14998 DAG.getBitcast(ClearVT, LHS), 14999 Zero, Indices)); 15000 }; 15001 15002 // Determine maximum split level (byte level masking). 15003 int MaxSplit = 1; 15004 if (RVT.getScalarSizeInBits() % 8 == 0) 15005 MaxSplit = RVT.getScalarSizeInBits() / 8; 15006 15007 for (int Split = 1; Split <= MaxSplit; ++Split) 15008 if (RVT.getScalarSizeInBits() % Split == 0) 15009 if (SDValue S = BuildClearMask(Split)) 15010 return S; 15011 15012 return SDValue(); 15013 } 15014 15015 /// Visit a binary vector operation, like ADD. 15016 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 15017 assert(N->getValueType(0).isVector() && 15018 "SimplifyVBinOp only works on vectors!"); 15019 15020 SDValue LHS = N->getOperand(0); 15021 SDValue RHS = N->getOperand(1); 15022 SDValue Ops[] = {LHS, RHS}; 15023 15024 // See if we can constant fold the vector operation. 15025 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 15026 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 15027 return Fold; 15028 15029 // Try to convert a constant mask AND into a shuffle clear mask. 15030 if (SDValue Shuffle = XformToShuffleWithZero(N)) 15031 return Shuffle; 15032 15033 // Type legalization might introduce new shuffles in the DAG. 15034 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 15035 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 15036 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 15037 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 15038 LHS.getOperand(1).isUndef() && 15039 RHS.getOperand(1).isUndef()) { 15040 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 15041 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 15042 15043 if (SVN0->getMask().equals(SVN1->getMask())) { 15044 EVT VT = N->getValueType(0); 15045 SDValue UndefVector = LHS.getOperand(1); 15046 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 15047 LHS.getOperand(0), RHS.getOperand(0), 15048 N->getFlags()); 15049 AddUsersToWorklist(N); 15050 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 15051 SVN0->getMask()); 15052 } 15053 } 15054 15055 return SDValue(); 15056 } 15057 15058 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 15059 SDValue N2) { 15060 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 15061 15062 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 15063 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 15064 15065 // If we got a simplified select_cc node back from SimplifySelectCC, then 15066 // break it down into a new SETCC node, and a new SELECT node, and then return 15067 // the SELECT node, since we were called with a SELECT node. 15068 if (SCC.getNode()) { 15069 // Check to see if we got a select_cc back (to turn into setcc/select). 15070 // Otherwise, just return whatever node we got back, like fabs. 15071 if (SCC.getOpcode() == ISD::SELECT_CC) { 15072 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 15073 N0.getValueType(), 15074 SCC.getOperand(0), SCC.getOperand(1), 15075 SCC.getOperand(4)); 15076 AddToWorklist(SETCC.getNode()); 15077 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 15078 SCC.getOperand(2), SCC.getOperand(3)); 15079 } 15080 15081 return SCC; 15082 } 15083 return SDValue(); 15084 } 15085 15086 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 15087 /// being selected between, see if we can simplify the select. Callers of this 15088 /// should assume that TheSelect is deleted if this returns true. As such, they 15089 /// should return the appropriate thing (e.g. the node) back to the top-level of 15090 /// the DAG combiner loop to avoid it being looked at. 15091 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 15092 SDValue RHS) { 15093 15094 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15095 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 15096 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 15097 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 15098 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 15099 SDValue Sqrt = RHS; 15100 ISD::CondCode CC; 15101 SDValue CmpLHS; 15102 const ConstantFPSDNode *Zero = nullptr; 15103 15104 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 15105 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 15106 CmpLHS = TheSelect->getOperand(0); 15107 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 15108 } else { 15109 // SELECT or VSELECT 15110 SDValue Cmp = TheSelect->getOperand(0); 15111 if (Cmp.getOpcode() == ISD::SETCC) { 15112 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 15113 CmpLHS = Cmp.getOperand(0); 15114 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 15115 } 15116 } 15117 if (Zero && Zero->isZero() && 15118 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 15119 CC == ISD::SETULT || CC == ISD::SETLT)) { 15120 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15121 CombineTo(TheSelect, Sqrt); 15122 return true; 15123 } 15124 } 15125 } 15126 // Cannot simplify select with vector condition 15127 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 15128 15129 // If this is a select from two identical things, try to pull the operation 15130 // through the select. 15131 if (LHS.getOpcode() != RHS.getOpcode() || 15132 !LHS.hasOneUse() || !RHS.hasOneUse()) 15133 return false; 15134 15135 // If this is a load and the token chain is identical, replace the select 15136 // of two loads with a load through a select of the address to load from. 15137 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 15138 // constants have been dropped into the constant pool. 15139 if (LHS.getOpcode() == ISD::LOAD) { 15140 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 15141 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 15142 15143 // Token chains must be identical. 15144 if (LHS.getOperand(0) != RHS.getOperand(0) || 15145 // Do not let this transformation reduce the number of volatile loads. 15146 LLD->isVolatile() || RLD->isVolatile() || 15147 // FIXME: If either is a pre/post inc/dec load, 15148 // we'd need to split out the address adjustment. 15149 LLD->isIndexed() || RLD->isIndexed() || 15150 // If this is an EXTLOAD, the VT's must match. 15151 LLD->getMemoryVT() != RLD->getMemoryVT() || 15152 // If this is an EXTLOAD, the kind of extension must match. 15153 (LLD->getExtensionType() != RLD->getExtensionType() && 15154 // The only exception is if one of the extensions is anyext. 15155 LLD->getExtensionType() != ISD::EXTLOAD && 15156 RLD->getExtensionType() != ISD::EXTLOAD) || 15157 // FIXME: this discards src value information. This is 15158 // over-conservative. It would be beneficial to be able to remember 15159 // both potential memory locations. Since we are discarding 15160 // src value info, don't do the transformation if the memory 15161 // locations are not in the default address space. 15162 LLD->getPointerInfo().getAddrSpace() != 0 || 15163 RLD->getPointerInfo().getAddrSpace() != 0 || 15164 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 15165 LLD->getBasePtr().getValueType())) 15166 return false; 15167 15168 // Check that the select condition doesn't reach either load. If so, 15169 // folding this will induce a cycle into the DAG. If not, this is safe to 15170 // xform, so create a select of the addresses. 15171 SDValue Addr; 15172 if (TheSelect->getOpcode() == ISD::SELECT) { 15173 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 15174 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 15175 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 15176 return false; 15177 // The loads must not depend on one another. 15178 if (LLD->isPredecessorOf(RLD) || 15179 RLD->isPredecessorOf(LLD)) 15180 return false; 15181 Addr = DAG.getSelect(SDLoc(TheSelect), 15182 LLD->getBasePtr().getValueType(), 15183 TheSelect->getOperand(0), LLD->getBasePtr(), 15184 RLD->getBasePtr()); 15185 } else { // Otherwise SELECT_CC 15186 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 15187 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 15188 15189 if ((LLD->hasAnyUseOfValue(1) && 15190 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 15191 (RLD->hasAnyUseOfValue(1) && 15192 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 15193 return false; 15194 15195 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 15196 LLD->getBasePtr().getValueType(), 15197 TheSelect->getOperand(0), 15198 TheSelect->getOperand(1), 15199 LLD->getBasePtr(), RLD->getBasePtr(), 15200 TheSelect->getOperand(4)); 15201 } 15202 15203 SDValue Load; 15204 // It is safe to replace the two loads if they have different alignments, 15205 // but the new load must be the minimum (most restrictive) alignment of the 15206 // inputs. 15207 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 15208 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 15209 if (!RLD->isInvariant()) 15210 MMOFlags &= ~MachineMemOperand::MOInvariant; 15211 if (!RLD->isDereferenceable()) 15212 MMOFlags &= ~MachineMemOperand::MODereferenceable; 15213 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 15214 // FIXME: Discards pointer and AA info. 15215 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 15216 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 15217 MMOFlags); 15218 } else { 15219 // FIXME: Discards pointer and AA info. 15220 Load = DAG.getExtLoad( 15221 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 15222 : LLD->getExtensionType(), 15223 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 15224 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 15225 } 15226 15227 // Users of the select now use the result of the load. 15228 CombineTo(TheSelect, Load); 15229 15230 // Users of the old loads now use the new load's chain. We know the 15231 // old-load value is dead now. 15232 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 15233 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 15234 return true; 15235 } 15236 15237 return false; 15238 } 15239 15240 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 15241 /// bitwise 'and'. 15242 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 15243 SDValue N1, SDValue N2, SDValue N3, 15244 ISD::CondCode CC) { 15245 // If this is a select where the false operand is zero and the compare is a 15246 // check of the sign bit, see if we can perform the "gzip trick": 15247 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 15248 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 15249 EVT XType = N0.getValueType(); 15250 EVT AType = N2.getValueType(); 15251 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 15252 return SDValue(); 15253 15254 // If the comparison is testing for a positive value, we have to invert 15255 // the sign bit mask, so only do that transform if the target has a bitwise 15256 // 'and not' instruction (the invert is free). 15257 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 15258 // (X > -1) ? A : 0 15259 // (X > 0) ? X : 0 <-- This is canonical signed max. 15260 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 15261 return SDValue(); 15262 } else if (CC == ISD::SETLT) { 15263 // (X < 0) ? A : 0 15264 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 15265 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 15266 return SDValue(); 15267 } else { 15268 return SDValue(); 15269 } 15270 15271 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 15272 // constant. 15273 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 15274 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15275 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 15276 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 15277 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 15278 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 15279 AddToWorklist(Shift.getNode()); 15280 15281 if (XType.bitsGT(AType)) { 15282 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15283 AddToWorklist(Shift.getNode()); 15284 } 15285 15286 if (CC == ISD::SETGT) 15287 Shift = DAG.getNOT(DL, Shift, AType); 15288 15289 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15290 } 15291 15292 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 15293 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 15294 AddToWorklist(Shift.getNode()); 15295 15296 if (XType.bitsGT(AType)) { 15297 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15298 AddToWorklist(Shift.getNode()); 15299 } 15300 15301 if (CC == ISD::SETGT) 15302 Shift = DAG.getNOT(DL, Shift, AType); 15303 15304 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15305 } 15306 15307 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 15308 /// where 'cond' is the comparison specified by CC. 15309 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 15310 SDValue N2, SDValue N3, ISD::CondCode CC, 15311 bool NotExtCompare) { 15312 // (x ? y : y) -> y. 15313 if (N2 == N3) return N2; 15314 15315 EVT VT = N2.getValueType(); 15316 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 15317 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15318 15319 // Determine if the condition we're dealing with is constant 15320 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 15321 N0, N1, CC, DL, false); 15322 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 15323 15324 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 15325 // fold select_cc true, x, y -> x 15326 // fold select_cc false, x, y -> y 15327 return !SCCC->isNullValue() ? N2 : N3; 15328 } 15329 15330 // Check to see if we can simplify the select into an fabs node 15331 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 15332 // Allow either -0.0 or 0.0 15333 if (CFP->isZero()) { 15334 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 15335 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 15336 N0 == N2 && N3.getOpcode() == ISD::FNEG && 15337 N2 == N3.getOperand(0)) 15338 return DAG.getNode(ISD::FABS, DL, VT, N0); 15339 15340 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 15341 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 15342 N0 == N3 && N2.getOpcode() == ISD::FNEG && 15343 N2.getOperand(0) == N3) 15344 return DAG.getNode(ISD::FABS, DL, VT, N3); 15345 } 15346 } 15347 15348 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 15349 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 15350 // in it. This is a win when the constant is not otherwise available because 15351 // it replaces two constant pool loads with one. We only do this if the FP 15352 // type is known to be legal, because if it isn't, then we are before legalize 15353 // types an we want the other legalization to happen first (e.g. to avoid 15354 // messing with soft float) and if the ConstantFP is not legal, because if 15355 // it is legal, we may not need to store the FP constant in a constant pool. 15356 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 15357 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 15358 if (TLI.isTypeLegal(N2.getValueType()) && 15359 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 15360 TargetLowering::Legal && 15361 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 15362 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 15363 // If both constants have multiple uses, then we won't need to do an 15364 // extra load, they are likely around in registers for other users. 15365 (TV->hasOneUse() || FV->hasOneUse())) { 15366 Constant *Elts[] = { 15367 const_cast<ConstantFP*>(FV->getConstantFPValue()), 15368 const_cast<ConstantFP*>(TV->getConstantFPValue()) 15369 }; 15370 Type *FPTy = Elts[0]->getType(); 15371 const DataLayout &TD = DAG.getDataLayout(); 15372 15373 // Create a ConstantArray of the two constants. 15374 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 15375 SDValue CPIdx = 15376 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 15377 TD.getPrefTypeAlignment(FPTy)); 15378 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 15379 15380 // Get the offsets to the 0 and 1 element of the array so that we can 15381 // select between them. 15382 SDValue Zero = DAG.getIntPtrConstant(0, DL); 15383 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 15384 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 15385 15386 SDValue Cond = DAG.getSetCC(DL, 15387 getSetCCResultType(N0.getValueType()), 15388 N0, N1, CC); 15389 AddToWorklist(Cond.getNode()); 15390 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 15391 Cond, One, Zero); 15392 AddToWorklist(CstOffset.getNode()); 15393 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 15394 CstOffset); 15395 AddToWorklist(CPIdx.getNode()); 15396 return DAG.getLoad( 15397 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 15398 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 15399 Alignment); 15400 } 15401 } 15402 15403 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 15404 return V; 15405 15406 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 15407 // where y is has a single bit set. 15408 // A plaintext description would be, we can turn the SELECT_CC into an AND 15409 // when the condition can be materialized as an all-ones register. Any 15410 // single bit-test can be materialized as an all-ones register with 15411 // shift-left and shift-right-arith. 15412 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 15413 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 15414 SDValue AndLHS = N0->getOperand(0); 15415 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15416 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 15417 // Shift the tested bit over the sign bit. 15418 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 15419 SDValue ShlAmt = 15420 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 15421 getShiftAmountTy(AndLHS.getValueType())); 15422 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 15423 15424 // Now arithmetic right shift it all the way over, so the result is either 15425 // all-ones, or zero. 15426 SDValue ShrAmt = 15427 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 15428 getShiftAmountTy(Shl.getValueType())); 15429 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 15430 15431 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 15432 } 15433 } 15434 15435 // fold select C, 16, 0 -> shl C, 4 15436 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 15437 TLI.getBooleanContents(N0.getValueType()) == 15438 TargetLowering::ZeroOrOneBooleanContent) { 15439 15440 // If the caller doesn't want us to simplify this into a zext of a compare, 15441 // don't do it. 15442 if (NotExtCompare && N2C->isOne()) 15443 return SDValue(); 15444 15445 // Get a SetCC of the condition 15446 // NOTE: Don't create a SETCC if it's not legal on this target. 15447 if (!LegalOperations || 15448 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 15449 SDValue Temp, SCC; 15450 // cast from setcc result type to select result type 15451 if (LegalTypes) { 15452 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 15453 N0, N1, CC); 15454 if (N2.getValueType().bitsLT(SCC.getValueType())) 15455 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 15456 N2.getValueType()); 15457 else 15458 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15459 N2.getValueType(), SCC); 15460 } else { 15461 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 15462 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15463 N2.getValueType(), SCC); 15464 } 15465 15466 AddToWorklist(SCC.getNode()); 15467 AddToWorklist(Temp.getNode()); 15468 15469 if (N2C->isOne()) 15470 return Temp; 15471 15472 // shl setcc result by log2 n2c 15473 return DAG.getNode( 15474 ISD::SHL, DL, N2.getValueType(), Temp, 15475 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 15476 getShiftAmountTy(Temp.getValueType()))); 15477 } 15478 } 15479 15480 // Check to see if this is an integer abs. 15481 // select_cc setg[te] X, 0, X, -X -> 15482 // select_cc setgt X, -1, X, -X -> 15483 // select_cc setl[te] X, 0, -X, X -> 15484 // select_cc setlt X, 1, -X, X -> 15485 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 15486 if (N1C) { 15487 ConstantSDNode *SubC = nullptr; 15488 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 15489 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 15490 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 15491 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 15492 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 15493 (N1C->isOne() && CC == ISD::SETLT)) && 15494 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 15495 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 15496 15497 EVT XType = N0.getValueType(); 15498 if (SubC && SubC->isNullValue() && XType.isInteger()) { 15499 SDLoc DL(N0); 15500 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 15501 N0, 15502 DAG.getConstant(XType.getSizeInBits() - 1, DL, 15503 getShiftAmountTy(N0.getValueType()))); 15504 SDValue Add = DAG.getNode(ISD::ADD, DL, 15505 XType, N0, Shift); 15506 AddToWorklist(Shift.getNode()); 15507 AddToWorklist(Add.getNode()); 15508 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 15509 } 15510 } 15511 15512 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 15513 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 15514 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 15515 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 15516 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 15517 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 15518 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 15519 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 15520 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 15521 SDValue ValueOnZero = N2; 15522 SDValue Count = N3; 15523 // If the condition is NE instead of E, swap the operands. 15524 if (CC == ISD::SETNE) 15525 std::swap(ValueOnZero, Count); 15526 // Check if the value on zero is a constant equal to the bits in the type. 15527 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 15528 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 15529 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 15530 // legal, combine to just cttz. 15531 if ((Count.getOpcode() == ISD::CTTZ || 15532 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 15533 N0 == Count.getOperand(0) && 15534 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 15535 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 15536 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 15537 // legal, combine to just ctlz. 15538 if ((Count.getOpcode() == ISD::CTLZ || 15539 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 15540 N0 == Count.getOperand(0) && 15541 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 15542 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 15543 } 15544 } 15545 } 15546 15547 return SDValue(); 15548 } 15549 15550 /// This is a stub for TargetLowering::SimplifySetCC. 15551 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 15552 ISD::CondCode Cond, const SDLoc &DL, 15553 bool foldBooleans) { 15554 TargetLowering::DAGCombinerInfo 15555 DagCombineInfo(DAG, Level, false, this); 15556 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 15557 } 15558 15559 /// Given an ISD::SDIV node expressing a divide by constant, return 15560 /// a DAG expression to select that will generate the same value by multiplying 15561 /// by a magic number. 15562 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 15563 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 15564 // when optimising for minimum size, we don't want to expand a div to a mul 15565 // and a shift. 15566 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 15567 return SDValue(); 15568 15569 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15570 if (!C) 15571 return SDValue(); 15572 15573 // Avoid division by zero. 15574 if (C->isNullValue()) 15575 return SDValue(); 15576 15577 std::vector<SDNode*> Built; 15578 SDValue S = 15579 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 15580 15581 for (SDNode *N : Built) 15582 AddToWorklist(N); 15583 return S; 15584 } 15585 15586 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 15587 /// DAG expression that will generate the same value by right shifting. 15588 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 15589 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15590 if (!C) 15591 return SDValue(); 15592 15593 // Avoid division by zero. 15594 if (C->isNullValue()) 15595 return SDValue(); 15596 15597 std::vector<SDNode *> Built; 15598 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 15599 15600 for (SDNode *N : Built) 15601 AddToWorklist(N); 15602 return S; 15603 } 15604 15605 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 15606 /// expression that will generate the same value by multiplying by a magic 15607 /// number. 15608 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 15609 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 15610 // when optimising for minimum size, we don't want to expand a div to a mul 15611 // and a shift. 15612 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 15613 return SDValue(); 15614 15615 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15616 if (!C) 15617 return SDValue(); 15618 15619 // Avoid division by zero. 15620 if (C->isNullValue()) 15621 return SDValue(); 15622 15623 std::vector<SDNode*> Built; 15624 SDValue S = 15625 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 15626 15627 for (SDNode *N : Built) 15628 AddToWorklist(N); 15629 return S; 15630 } 15631 15632 /// Determines the LogBase2 value for a non-null input value using the 15633 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 15634 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 15635 EVT VT = V.getValueType(); 15636 unsigned EltBits = VT.getScalarSizeInBits(); 15637 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 15638 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 15639 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 15640 return LogBase2; 15641 } 15642 15643 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15644 /// For the reciprocal, we need to find the zero of the function: 15645 /// F(X) = A X - 1 [which has a zero at X = 1/A] 15646 /// => 15647 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 15648 /// does not require additional intermediate precision] 15649 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 15650 if (Level >= AfterLegalizeDAG) 15651 return SDValue(); 15652 15653 // TODO: Handle half and/or extended types? 15654 EVT VT = Op.getValueType(); 15655 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 15656 return SDValue(); 15657 15658 // If estimates are explicitly disabled for this function, we're done. 15659 MachineFunction &MF = DAG.getMachineFunction(); 15660 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 15661 if (Enabled == TLI.ReciprocalEstimate::Disabled) 15662 return SDValue(); 15663 15664 // Estimates may be explicitly enabled for this type with a custom number of 15665 // refinement steps. 15666 int Iterations = TLI.getDivRefinementSteps(VT, MF); 15667 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 15668 AddToWorklist(Est.getNode()); 15669 15670 if (Iterations) { 15671 EVT VT = Op.getValueType(); 15672 SDLoc DL(Op); 15673 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 15674 15675 // Newton iterations: Est = Est + Est (1 - Arg * Est) 15676 for (int i = 0; i < Iterations; ++i) { 15677 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 15678 AddToWorklist(NewEst.getNode()); 15679 15680 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 15681 AddToWorklist(NewEst.getNode()); 15682 15683 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 15684 AddToWorklist(NewEst.getNode()); 15685 15686 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 15687 AddToWorklist(Est.getNode()); 15688 } 15689 } 15690 return Est; 15691 } 15692 15693 return SDValue(); 15694 } 15695 15696 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15697 /// For the reciprocal sqrt, we need to find the zero of the function: 15698 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15699 /// => 15700 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 15701 /// As a result, we precompute A/2 prior to the iteration loop. 15702 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 15703 unsigned Iterations, 15704 SDNodeFlags *Flags, bool Reciprocal) { 15705 EVT VT = Arg.getValueType(); 15706 SDLoc DL(Arg); 15707 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 15708 15709 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 15710 // this entire sequence requires only one FP constant. 15711 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 15712 AddToWorklist(HalfArg.getNode()); 15713 15714 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 15715 AddToWorklist(HalfArg.getNode()); 15716 15717 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 15718 for (unsigned i = 0; i < Iterations; ++i) { 15719 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 15720 AddToWorklist(NewEst.getNode()); 15721 15722 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 15723 AddToWorklist(NewEst.getNode()); 15724 15725 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 15726 AddToWorklist(NewEst.getNode()); 15727 15728 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 15729 AddToWorklist(Est.getNode()); 15730 } 15731 15732 // If non-reciprocal square root is requested, multiply the result by Arg. 15733 if (!Reciprocal) { 15734 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 15735 AddToWorklist(Est.getNode()); 15736 } 15737 15738 return Est; 15739 } 15740 15741 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 15742 /// For the reciprocal sqrt, we need to find the zero of the function: 15743 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 15744 /// => 15745 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 15746 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 15747 unsigned Iterations, 15748 SDNodeFlags *Flags, bool Reciprocal) { 15749 EVT VT = Arg.getValueType(); 15750 SDLoc DL(Arg); 15751 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 15752 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 15753 15754 // This routine must enter the loop below to work correctly 15755 // when (Reciprocal == false). 15756 assert(Iterations > 0); 15757 15758 // Newton iterations for reciprocal square root: 15759 // E = (E * -0.5) * ((A * E) * E + -3.0) 15760 for (unsigned i = 0; i < Iterations; ++i) { 15761 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 15762 AddToWorklist(AE.getNode()); 15763 15764 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 15765 AddToWorklist(AEE.getNode()); 15766 15767 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 15768 AddToWorklist(RHS.getNode()); 15769 15770 // When calculating a square root at the last iteration build: 15771 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 15772 // (notice a common subexpression) 15773 SDValue LHS; 15774 if (Reciprocal || (i + 1) < Iterations) { 15775 // RSQRT: LHS = (E * -0.5) 15776 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 15777 } else { 15778 // SQRT: LHS = (A * E) * -0.5 15779 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 15780 } 15781 AddToWorklist(LHS.getNode()); 15782 15783 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 15784 AddToWorklist(Est.getNode()); 15785 } 15786 15787 return Est; 15788 } 15789 15790 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 15791 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 15792 /// Op can be zero. 15793 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 15794 bool Reciprocal) { 15795 if (Level >= AfterLegalizeDAG) 15796 return SDValue(); 15797 15798 // TODO: Handle half and/or extended types? 15799 EVT VT = Op.getValueType(); 15800 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 15801 return SDValue(); 15802 15803 // If estimates are explicitly disabled for this function, we're done. 15804 MachineFunction &MF = DAG.getMachineFunction(); 15805 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 15806 if (Enabled == TLI.ReciprocalEstimate::Disabled) 15807 return SDValue(); 15808 15809 // Estimates may be explicitly enabled for this type with a custom number of 15810 // refinement steps. 15811 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 15812 15813 bool UseOneConstNR = false; 15814 if (SDValue Est = 15815 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 15816 Reciprocal)) { 15817 AddToWorklist(Est.getNode()); 15818 15819 if (Iterations) { 15820 Est = UseOneConstNR 15821 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 15822 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 15823 15824 if (!Reciprocal) { 15825 // Unfortunately, Est is now NaN if the input was exactly 0.0. 15826 // Select out this case and force the answer to 0.0. 15827 EVT VT = Op.getValueType(); 15828 SDLoc DL(Op); 15829 15830 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 15831 EVT CCVT = getSetCCResultType(VT); 15832 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 15833 AddToWorklist(ZeroCmp.getNode()); 15834 15835 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 15836 ZeroCmp, FPZero, Est); 15837 AddToWorklist(Est.getNode()); 15838 } 15839 } 15840 return Est; 15841 } 15842 15843 return SDValue(); 15844 } 15845 15846 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15847 return buildSqrtEstimateImpl(Op, Flags, true); 15848 } 15849 15850 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 15851 return buildSqrtEstimateImpl(Op, Flags, false); 15852 } 15853 15854 /// Return true if base is a frame index, which is known not to alias with 15855 /// anything but itself. Provides base object and offset as results. 15856 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 15857 const GlobalValue *&GV, const void *&CV) { 15858 // Assume it is a primitive operation. 15859 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 15860 15861 // If it's an adding a simple constant then integrate the offset. 15862 if (Base.getOpcode() == ISD::ADD) { 15863 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 15864 Base = Base.getOperand(0); 15865 Offset += C->getSExtValue(); 15866 } 15867 } 15868 15869 // Return the underlying GlobalValue, and update the Offset. Return false 15870 // for GlobalAddressSDNode since the same GlobalAddress may be represented 15871 // by multiple nodes with different offsets. 15872 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 15873 GV = G->getGlobal(); 15874 Offset += G->getOffset(); 15875 return false; 15876 } 15877 15878 // Return the underlying Constant value, and update the Offset. Return false 15879 // for ConstantSDNodes since the same constant pool entry may be represented 15880 // by multiple nodes with different offsets. 15881 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 15882 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 15883 : (const void *)C->getConstVal(); 15884 Offset += C->getOffset(); 15885 return false; 15886 } 15887 // If it's any of the following then it can't alias with anything but itself. 15888 return isa<FrameIndexSDNode>(Base); 15889 } 15890 15891 /// Return true if there is any possibility that the two addresses overlap. 15892 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 15893 // If they are the same then they must be aliases. 15894 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 15895 15896 // If they are both volatile then they cannot be reordered. 15897 if (Op0->isVolatile() && Op1->isVolatile()) return true; 15898 15899 // If one operation reads from invariant memory, and the other may store, they 15900 // cannot alias. These should really be checking the equivalent of mayWrite, 15901 // but it only matters for memory nodes other than load /store. 15902 if (Op0->isInvariant() && Op1->writeMem()) 15903 return false; 15904 15905 if (Op1->isInvariant() && Op0->writeMem()) 15906 return false; 15907 15908 // Gather base node and offset information. 15909 SDValue Base1, Base2; 15910 int64_t Offset1, Offset2; 15911 const GlobalValue *GV1, *GV2; 15912 const void *CV1, *CV2; 15913 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 15914 Base1, Offset1, GV1, CV1); 15915 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 15916 Base2, Offset2, GV2, CV2); 15917 15918 // If they have a same base address then check to see if they overlap. 15919 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 15920 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15921 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15922 15923 // It is possible for different frame indices to alias each other, mostly 15924 // when tail call optimization reuses return address slots for arguments. 15925 // To catch this case, look up the actual index of frame indices to compute 15926 // the real alias relationship. 15927 if (isFrameIndex1 && isFrameIndex2) { 15928 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 15929 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 15930 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 15931 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 15932 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 15933 } 15934 15935 // Otherwise, if we know what the bases are, and they aren't identical, then 15936 // we know they cannot alias. 15937 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 15938 return false; 15939 15940 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 15941 // compared to the size and offset of the access, we may be able to prove they 15942 // do not alias. This check is conservative for now to catch cases created by 15943 // splitting vector types. 15944 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 15945 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 15946 (Op0->getMemoryVT().getSizeInBits() >> 3 == 15947 Op1->getMemoryVT().getSizeInBits() >> 3) && 15948 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 15949 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 15950 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 15951 15952 // There is no overlap between these relatively aligned accesses of similar 15953 // size, return no alias. 15954 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 15955 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 15956 return false; 15957 } 15958 15959 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 15960 ? CombinerGlobalAA 15961 : DAG.getSubtarget().useAA(); 15962 #ifndef NDEBUG 15963 if (CombinerAAOnlyFunc.getNumOccurrences() && 15964 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 15965 UseAA = false; 15966 #endif 15967 if (UseAA && 15968 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 15969 // Use alias analysis information. 15970 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 15971 Op1->getSrcValueOffset()); 15972 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 15973 Op0->getSrcValueOffset() - MinOffset; 15974 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 15975 Op1->getSrcValueOffset() - MinOffset; 15976 AliasResult AAResult = 15977 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 15978 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 15979 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 15980 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 15981 if (AAResult == NoAlias) 15982 return false; 15983 } 15984 15985 // Otherwise we have to assume they alias. 15986 return true; 15987 } 15988 15989 /// Walk up chain skipping non-aliasing memory nodes, 15990 /// looking for aliasing nodes and adding them to the Aliases vector. 15991 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 15992 SmallVectorImpl<SDValue> &Aliases) { 15993 SmallVector<SDValue, 8> Chains; // List of chains to visit. 15994 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 15995 15996 // Get alias information for node. 15997 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 15998 15999 // Starting off. 16000 Chains.push_back(OriginalChain); 16001 unsigned Depth = 0; 16002 16003 // Look at each chain and determine if it is an alias. If so, add it to the 16004 // aliases list. If not, then continue up the chain looking for the next 16005 // candidate. 16006 while (!Chains.empty()) { 16007 SDValue Chain = Chains.pop_back_val(); 16008 16009 // For TokenFactor nodes, look at each operand and only continue up the 16010 // chain until we reach the depth limit. 16011 // 16012 // FIXME: The depth check could be made to return the last non-aliasing 16013 // chain we found before we hit a tokenfactor rather than the original 16014 // chain. 16015 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 16016 Aliases.clear(); 16017 Aliases.push_back(OriginalChain); 16018 return; 16019 } 16020 16021 // Don't bother if we've been before. 16022 if (!Visited.insert(Chain.getNode()).second) 16023 continue; 16024 16025 switch (Chain.getOpcode()) { 16026 case ISD::EntryToken: 16027 // Entry token is ideal chain operand, but handled in FindBetterChain. 16028 break; 16029 16030 case ISD::LOAD: 16031 case ISD::STORE: { 16032 // Get alias information for Chain. 16033 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 16034 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 16035 16036 // If chain is alias then stop here. 16037 if (!(IsLoad && IsOpLoad) && 16038 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 16039 Aliases.push_back(Chain); 16040 } else { 16041 // Look further up the chain. 16042 Chains.push_back(Chain.getOperand(0)); 16043 ++Depth; 16044 } 16045 break; 16046 } 16047 16048 case ISD::TokenFactor: 16049 // We have to check each of the operands of the token factor for "small" 16050 // token factors, so we queue them up. Adding the operands to the queue 16051 // (stack) in reverse order maintains the original order and increases the 16052 // likelihood that getNode will find a matching token factor (CSE.) 16053 if (Chain.getNumOperands() > 16) { 16054 Aliases.push_back(Chain); 16055 break; 16056 } 16057 for (unsigned n = Chain.getNumOperands(); n;) 16058 Chains.push_back(Chain.getOperand(--n)); 16059 ++Depth; 16060 break; 16061 16062 case ISD::CopyFromReg: 16063 // Forward past CopyFromReg. 16064 Chains.push_back(Chain.getOperand(0)); 16065 ++Depth; 16066 break; 16067 16068 default: 16069 // For all other instructions we will just have to take what we can get. 16070 Aliases.push_back(Chain); 16071 break; 16072 } 16073 } 16074 } 16075 16076 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 16077 /// (aliasing node.) 16078 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 16079 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 16080 16081 // Accumulate all the aliases to this node. 16082 GatherAllAliases(N, OldChain, Aliases); 16083 16084 // If no operands then chain to entry token. 16085 if (Aliases.size() == 0) 16086 return DAG.getEntryNode(); 16087 16088 // If a single operand then chain to it. We don't need to revisit it. 16089 if (Aliases.size() == 1) 16090 return Aliases[0]; 16091 16092 // Construct a custom tailored token factor. 16093 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 16094 } 16095 16096 // This function tries to collect a bunch of potentially interesting 16097 // nodes to improve the chains of, all at once. This might seem 16098 // redundant, as this function gets called when visiting every store 16099 // node, so why not let the work be done on each store as it's visited? 16100 // 16101 // I believe this is mainly important because MergeConsecutiveStores 16102 // is unable to deal with merging stores of different sizes, so unless 16103 // we improve the chains of all the potential candidates up-front 16104 // before running MergeConsecutiveStores, it might only see some of 16105 // the nodes that will eventually be candidates, and then not be able 16106 // to go from a partially-merged state to the desired final 16107 // fully-merged state. 16108 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 16109 // This holds the base pointer, index, and the offset in bytes from the base 16110 // pointer. 16111 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 16112 16113 // We must have a base and an offset. 16114 if (!BasePtr.Base.getNode()) 16115 return false; 16116 16117 // Do not handle stores to undef base pointers. 16118 if (BasePtr.Base.isUndef()) 16119 return false; 16120 16121 SmallVector<StoreSDNode *, 8> ChainedStores; 16122 ChainedStores.push_back(St); 16123 16124 // Walk up the chain and look for nodes with offsets from the same 16125 // base pointer. Stop when reaching an instruction with a different kind 16126 // or instruction which has a different base pointer. 16127 StoreSDNode *Index = St; 16128 while (Index) { 16129 // If the chain has more than one use, then we can't reorder the mem ops. 16130 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 16131 break; 16132 16133 if (Index->isVolatile() || Index->isIndexed()) 16134 break; 16135 16136 // Find the base pointer and offset for this memory node. 16137 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 16138 16139 // Check that the base pointer is the same as the original one. 16140 if (!Ptr.equalBaseIndex(BasePtr)) 16141 break; 16142 16143 // Walk up the chain to find the next store node, ignoring any 16144 // intermediate loads. Any other kind of node will halt the loop. 16145 SDNode *NextInChain = Index->getChain().getNode(); 16146 while (true) { 16147 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 16148 // We found a store node. Use it for the next iteration. 16149 if (STn->isVolatile() || STn->isIndexed()) { 16150 Index = nullptr; 16151 break; 16152 } 16153 ChainedStores.push_back(STn); 16154 Index = STn; 16155 break; 16156 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 16157 NextInChain = Ldn->getChain().getNode(); 16158 continue; 16159 } else { 16160 Index = nullptr; 16161 break; 16162 } 16163 } // end while 16164 } 16165 16166 // At this point, ChainedStores lists all of the Store nodes 16167 // reachable by iterating up through chain nodes matching the above 16168 // conditions. For each such store identified, try to find an 16169 // earlier chain to attach the store to which won't violate the 16170 // required ordering. 16171 bool MadeChangeToSt = false; 16172 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 16173 16174 for (StoreSDNode *ChainedStore : ChainedStores) { 16175 SDValue Chain = ChainedStore->getChain(); 16176 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 16177 16178 if (Chain != BetterChain) { 16179 if (ChainedStore == St) 16180 MadeChangeToSt = true; 16181 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 16182 } 16183 } 16184 16185 // Do all replacements after finding the replacements to make to avoid making 16186 // the chains more complicated by introducing new TokenFactors. 16187 for (auto Replacement : BetterChains) 16188 replaceStoreChain(Replacement.first, Replacement.second); 16189 16190 return MadeChangeToSt; 16191 } 16192 16193 /// This is the entry point for the file. 16194 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 16195 CodeGenOpt::Level OptLevel) { 16196 /// This is the main entry point to this class. 16197 DAGCombiner(*this, AA, OptLevel).Run(Level); 16198 } 16199