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/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.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/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "dagcombine" 44 45 STATISTIC(NodesCombined , "Number of dag nodes combined"); 46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 50 STATISTIC(SlicedLoads, "Number of load sliced"); 51 52 namespace { 53 static cl::opt<bool> 54 CombinerAA("combiner-alias-analysis", cl::Hidden, 55 cl::desc("Enable DAG combiner alias-analysis heuristics")); 56 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 64> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis &AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 // Skip handle nodes as they can't usefully be combined and confuse the 135 // zero-use deletion strategy. 136 if (N->getOpcode() == ISD::HANDLENODE) 137 return; 138 139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 140 Worklist.push_back(N); 141 } 142 143 /// Remove all instances of N from the worklist. 144 void removeFromWorklist(SDNode *N) { 145 CombinedNodes.erase(N); 146 147 auto It = WorklistMap.find(N); 148 if (It == WorklistMap.end()) 149 return; // Not in the worklist. 150 151 // Null out the entry rather than erasing it to avoid a linear operation. 152 Worklist[It->second] = nullptr; 153 WorklistMap.erase(It); 154 } 155 156 void deleteAndRecombine(SDNode *N); 157 bool recursivelyDeleteUnusedNodes(SDNode *N); 158 159 /// Replaces all uses of the results of one DAG node with new values. 160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 161 bool AddTo = true); 162 163 /// Replaces all uses of the results of one DAG node with new values. 164 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 165 return CombineTo(N, &Res, 1, AddTo); 166 } 167 168 /// Replaces all uses of the results of one DAG node with new values. 169 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 170 bool AddTo = true) { 171 SDValue To[] = { Res0, Res1 }; 172 return CombineTo(N, To, 2, AddTo); 173 } 174 175 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 176 177 private: 178 179 /// Check the specified integer node value to see if it can be simplified or 180 /// if things it uses can be simplified by bit propagation. 181 /// If so, return true. 182 bool SimplifyDemandedBits(SDValue Op) { 183 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 184 APInt Demanded = APInt::getAllOnesValue(BitWidth); 185 return SimplifyDemandedBits(Op, Demanded); 186 } 187 188 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 189 190 bool CombineToPreIndexedLoadStore(SDNode *N); 191 bool CombineToPostIndexedLoadStore(SDNode *N); 192 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 193 bool SliceUpLoad(SDNode *N); 194 195 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 196 /// load. 197 /// 198 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 199 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 200 /// \param EltNo index of the vector element to load. 201 /// \param OriginalLoad load that EVE came from to be replaced. 202 /// \returns EVE on success SDValue() on failure. 203 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 204 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 205 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 206 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 207 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 208 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue PromoteIntBinOp(SDValue Op); 210 SDValue PromoteIntShiftOp(SDValue Op); 211 SDValue PromoteExtend(SDValue Op); 212 bool PromoteLoad(SDValue Op); 213 214 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 215 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 216 ISD::NodeType ExtType); 217 218 /// Call the node-specific routine that knows how to fold each 219 /// particular type of node. If that doesn't do anything, try the 220 /// target-specific DAG combines. 221 SDValue combine(SDNode *N); 222 223 // Visitation implementation - Implement dag node combining for different 224 // node types. The semantics are as follows: 225 // Return Value: 226 // SDValue.getNode() == 0 - No change was made 227 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 228 // otherwise - N should be replaced by the returned Operand. 229 // 230 SDValue visitTokenFactor(SDNode *N); 231 SDValue visitMERGE_VALUES(SDNode *N); 232 SDValue visitADD(SDNode *N); 233 SDValue visitSUB(SDNode *N); 234 SDValue visitADDC(SDNode *N); 235 SDValue visitSUBC(SDNode *N); 236 SDValue visitADDE(SDNode *N); 237 SDValue visitSUBE(SDNode *N); 238 SDValue visitMUL(SDNode *N); 239 SDValue useDivRem(SDNode *N); 240 SDValue visitSDIV(SDNode *N); 241 SDValue visitUDIV(SDNode *N); 242 SDValue visitREM(SDNode *N); 243 SDValue visitMULHU(SDNode *N); 244 SDValue visitMULHS(SDNode *N); 245 SDValue visitSMUL_LOHI(SDNode *N); 246 SDValue visitUMUL_LOHI(SDNode *N); 247 SDValue visitSMULO(SDNode *N); 248 SDValue visitUMULO(SDNode *N); 249 SDValue visitIMINMAX(SDNode *N); 250 SDValue visitAND(SDNode *N); 251 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 252 SDValue visitOR(SDNode *N); 253 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 254 SDValue visitXOR(SDNode *N); 255 SDValue SimplifyVBinOp(SDNode *N); 256 SDValue visitSHL(SDNode *N); 257 SDValue visitSRA(SDNode *N); 258 SDValue visitSRL(SDNode *N); 259 SDValue visitRotate(SDNode *N); 260 SDValue visitBSWAP(SDNode *N); 261 SDValue visitCTLZ(SDNode *N); 262 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 263 SDValue visitCTTZ(SDNode *N); 264 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 265 SDValue visitCTPOP(SDNode *N); 266 SDValue visitSELECT(SDNode *N); 267 SDValue visitVSELECT(SDNode *N); 268 SDValue visitSELECT_CC(SDNode *N); 269 SDValue visitSETCC(SDNode *N); 270 SDValue visitSETCCE(SDNode *N); 271 SDValue visitSIGN_EXTEND(SDNode *N); 272 SDValue visitZERO_EXTEND(SDNode *N); 273 SDValue visitANY_EXTEND(SDNode *N); 274 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 275 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 276 SDValue visitTRUNCATE(SDNode *N); 277 SDValue visitBITCAST(SDNode *N); 278 SDValue visitBUILD_PAIR(SDNode *N); 279 SDValue visitFADD(SDNode *N); 280 SDValue visitFSUB(SDNode *N); 281 SDValue visitFMUL(SDNode *N); 282 SDValue visitFMA(SDNode *N); 283 SDValue visitFDIV(SDNode *N); 284 SDValue visitFREM(SDNode *N); 285 SDValue visitFSQRT(SDNode *N); 286 SDValue visitFCOPYSIGN(SDNode *N); 287 SDValue visitSINT_TO_FP(SDNode *N); 288 SDValue visitUINT_TO_FP(SDNode *N); 289 SDValue visitFP_TO_SINT(SDNode *N); 290 SDValue visitFP_TO_UINT(SDNode *N); 291 SDValue visitFP_ROUND(SDNode *N); 292 SDValue visitFP_ROUND_INREG(SDNode *N); 293 SDValue visitFP_EXTEND(SDNode *N); 294 SDValue visitFNEG(SDNode *N); 295 SDValue visitFABS(SDNode *N); 296 SDValue visitFCEIL(SDNode *N); 297 SDValue visitFTRUNC(SDNode *N); 298 SDValue visitFFLOOR(SDNode *N); 299 SDValue visitFMINNUM(SDNode *N); 300 SDValue visitFMAXNUM(SDNode *N); 301 SDValue visitBRCOND(SDNode *N); 302 SDValue visitBR_CC(SDNode *N); 303 SDValue visitLOAD(SDNode *N); 304 305 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 306 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 307 308 SDValue visitSTORE(SDNode *N); 309 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 310 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 311 SDValue visitBUILD_VECTOR(SDNode *N); 312 SDValue visitCONCAT_VECTORS(SDNode *N); 313 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 314 SDValue visitVECTOR_SHUFFLE(SDNode *N); 315 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 316 SDValue visitINSERT_SUBVECTOR(SDNode *N); 317 SDValue visitMLOAD(SDNode *N); 318 SDValue visitMSTORE(SDNode *N); 319 SDValue visitMGATHER(SDNode *N); 320 SDValue visitMSCATTER(SDNode *N); 321 SDValue visitFP_TO_FP16(SDNode *N); 322 SDValue visitFP16_TO_FP(SDNode *N); 323 324 SDValue visitFADDForFMACombine(SDNode *N); 325 SDValue visitFSUBForFMACombine(SDNode *N); 326 SDValue visitFMULForFMACombine(SDNode *N); 327 328 SDValue XformToShuffleWithZero(SDNode *N); 329 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 330 331 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 332 333 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 334 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 335 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 336 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 337 SDValue N3, ISD::CondCode CC, 338 bool NotExtCompare = false); 339 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 340 SDLoc DL, bool foldBooleans = true); 341 342 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 343 SDValue &CC) const; 344 bool isOneUseSetCC(SDValue N) const; 345 346 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 347 unsigned HiOp); 348 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 349 SDValue CombineExtLoad(SDNode *N); 350 SDValue combineRepeatedFPDivisors(SDNode *N); 351 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 352 SDValue BuildSDIV(SDNode *N); 353 SDValue BuildSDIVPow2(SDNode *N); 354 SDValue BuildUDIV(SDNode *N); 355 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 356 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 357 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 358 SDNodeFlags *Flags); 359 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 360 SDNodeFlags *Flags); 361 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 362 bool DemandHighBits = true); 363 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 364 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 365 SDValue InnerPos, SDValue InnerNeg, 366 unsigned PosOpcode, unsigned NegOpcode, 367 SDLoc DL); 368 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 369 SDValue ReduceLoadWidth(SDNode *N); 370 SDValue ReduceLoadOpStoreWidth(SDNode *N); 371 SDValue TransformFPLoadStorePair(SDNode *N); 372 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 373 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 374 375 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 376 377 /// Walk up chain skipping non-aliasing memory nodes, 378 /// looking for aliasing nodes and adding them to the Aliases vector. 379 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 380 SmallVectorImpl<SDValue> &Aliases); 381 382 /// Return true if there is any possibility that the two addresses overlap. 383 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 384 385 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 386 /// chain (aliasing node.) 387 SDValue FindBetterChain(SDNode *N, SDValue Chain); 388 389 /// Do FindBetterChain for a store and any possibly adjacent stores on 390 /// consecutive chains. 391 bool findBetterNeighborChains(StoreSDNode *St); 392 393 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 394 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 395 396 /// Holds a pointer to an LSBaseSDNode as well as information on where it 397 /// is located in a sequence of memory operations connected by a chain. 398 struct MemOpLink { 399 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 400 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 401 // Ptr to the mem node. 402 LSBaseSDNode *MemNode; 403 // Offset from the base ptr. 404 int64_t OffsetFromBase; 405 // What is the sequence number of this mem node. 406 // Lowest mem operand in the DAG starts at zero. 407 unsigned SequenceNum; 408 }; 409 410 /// This is a helper function for visitMUL to check the profitability 411 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 412 /// MulNode is the original multiply, AddNode is (add x, c1), 413 /// and ConstNode is c2. 414 bool isMulAddWithConstProfitable(SDNode *MulNode, 415 SDValue &AddNode, 416 SDValue &ConstNode); 417 418 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 419 /// constant build_vector of the stored constant values in Stores. 420 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 421 SDLoc SL, 422 ArrayRef<MemOpLink> Stores, 423 SmallVectorImpl<SDValue> &Chains, 424 EVT Ty) const; 425 426 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 427 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 428 /// the type of the loaded value to be extended. LoadedVT returns the type 429 /// of the original loaded value. NarrowLoad returns whether the load would 430 /// need to be narrowed in order to match. 431 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 432 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 433 bool &NarrowLoad); 434 435 /// This is a helper function for MergeConsecutiveStores. When the source 436 /// elements of the consecutive stores are all constants or all extracted 437 /// vector elements, try to merge them into one larger store. 438 /// \return True if a merged store was created. 439 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 440 EVT MemVT, unsigned NumStores, 441 bool IsConstantSrc, bool UseVector); 442 443 /// This is a helper function for MergeConsecutiveStores. 444 /// Stores that may be merged are placed in StoreNodes. 445 /// Loads that may alias with those stores are placed in AliasLoadNodes. 446 void getStoreMergeAndAliasCandidates( 447 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 448 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 449 450 /// Merge consecutive store operations into a wide store. 451 /// This optimization uses wide integers or vectors when possible. 452 /// \return True if some memory operations were changed. 453 bool MergeConsecutiveStores(StoreSDNode *N); 454 455 /// \brief Try to transform a truncation where C is a constant: 456 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 457 /// 458 /// \p N needs to be a truncation and its first operand an AND. Other 459 /// requirements are checked by the function (e.g. that trunc is 460 /// single-use) and if missed an empty SDValue is returned. 461 SDValue distributeTruncateThroughAnd(SDNode *N); 462 463 public: 464 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 465 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 466 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 467 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 468 } 469 470 /// Runs the dag combiner on all nodes in the work list 471 void Run(CombineLevel AtLevel); 472 473 SelectionDAG &getDAG() const { return DAG; } 474 475 /// Returns a type large enough to hold any valid shift amount - before type 476 /// legalization these can be huge. 477 EVT getShiftAmountTy(EVT LHSTy) { 478 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 479 if (LHSTy.isVector()) 480 return LHSTy; 481 auto &DL = DAG.getDataLayout(); 482 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 483 : TLI.getPointerTy(DL); 484 } 485 486 /// This method returns true if we are running before type legalization or 487 /// if the specified VT is legal. 488 bool isTypeLegal(const EVT &VT) { 489 if (!LegalTypes) return true; 490 return TLI.isTypeLegal(VT); 491 } 492 493 /// Convenience wrapper around TargetLowering::getSetCCResultType 494 EVT getSetCCResultType(EVT VT) const { 495 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 496 } 497 }; 498 } 499 500 501 namespace { 502 /// This class is a DAGUpdateListener that removes any deleted 503 /// nodes from the worklist. 504 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 505 DAGCombiner &DC; 506 public: 507 explicit WorklistRemover(DAGCombiner &dc) 508 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 509 510 void NodeDeleted(SDNode *N, SDNode *E) override { 511 DC.removeFromWorklist(N); 512 } 513 }; 514 } 515 516 //===----------------------------------------------------------------------===// 517 // TargetLowering::DAGCombinerInfo implementation 518 //===----------------------------------------------------------------------===// 519 520 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 521 ((DAGCombiner*)DC)->AddToWorklist(N); 522 } 523 524 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 525 ((DAGCombiner*)DC)->removeFromWorklist(N); 526 } 527 528 SDValue TargetLowering::DAGCombinerInfo:: 529 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 530 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 531 } 532 533 SDValue TargetLowering::DAGCombinerInfo:: 534 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 535 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 536 } 537 538 539 SDValue TargetLowering::DAGCombinerInfo:: 540 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 541 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 542 } 543 544 void TargetLowering::DAGCombinerInfo:: 545 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 546 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 547 } 548 549 //===----------------------------------------------------------------------===// 550 // Helper Functions 551 //===----------------------------------------------------------------------===// 552 553 void DAGCombiner::deleteAndRecombine(SDNode *N) { 554 removeFromWorklist(N); 555 556 // If the operands of this node are only used by the node, they will now be 557 // dead. Make sure to re-visit them and recursively delete dead nodes. 558 for (const SDValue &Op : N->ops()) 559 // For an operand generating multiple values, one of the values may 560 // become dead allowing further simplification (e.g. split index 561 // arithmetic from an indexed load). 562 if (Op->hasOneUse() || Op->getNumValues() > 1) 563 AddToWorklist(Op.getNode()); 564 565 DAG.DeleteNode(N); 566 } 567 568 /// Return 1 if we can compute the negated form of the specified expression for 569 /// the same cost as the expression itself, or 2 if we can compute the negated 570 /// form more cheaply than the expression itself. 571 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 572 const TargetLowering &TLI, 573 const TargetOptions *Options, 574 unsigned Depth = 0) { 575 // fneg is removable even if it has multiple uses. 576 if (Op.getOpcode() == ISD::FNEG) return 2; 577 578 // Don't allow anything with multiple uses. 579 if (!Op.hasOneUse()) return 0; 580 581 // Don't recurse exponentially. 582 if (Depth > 6) return 0; 583 584 switch (Op.getOpcode()) { 585 default: return false; 586 case ISD::ConstantFP: 587 // Don't invert constant FP values after legalize. The negated constant 588 // isn't necessarily legal. 589 return LegalOperations ? 0 : 1; 590 case ISD::FADD: 591 // FIXME: determine better conditions for this xform. 592 if (!Options->UnsafeFPMath) return 0; 593 594 // After operation legalization, it might not be legal to create new FSUBs. 595 if (LegalOperations && 596 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 597 return 0; 598 599 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 600 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 601 Options, Depth + 1)) 602 return V; 603 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 604 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 605 Depth + 1); 606 case ISD::FSUB: 607 // We can't turn -(A-B) into B-A when we honor signed zeros. 608 if (!Options->UnsafeFPMath) return 0; 609 610 // fold (fneg (fsub A, B)) -> (fsub B, A) 611 return 1; 612 613 case ISD::FMUL: 614 case ISD::FDIV: 615 if (Options->HonorSignDependentRoundingFPMath()) return 0; 616 617 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 618 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 619 Options, Depth + 1)) 620 return V; 621 622 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 623 Depth + 1); 624 625 case ISD::FP_EXTEND: 626 case ISD::FP_ROUND: 627 case ISD::FSIN: 628 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 629 Depth + 1); 630 } 631 } 632 633 /// If isNegatibleForFree returns true, return the newly negated expression. 634 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 635 bool LegalOperations, unsigned Depth = 0) { 636 const TargetOptions &Options = DAG.getTarget().Options; 637 // fneg is removable even if it has multiple uses. 638 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 639 640 // Don't allow anything with multiple uses. 641 assert(Op.hasOneUse() && "Unknown reuse!"); 642 643 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 644 645 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 646 647 switch (Op.getOpcode()) { 648 default: llvm_unreachable("Unknown code"); 649 case ISD::ConstantFP: { 650 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 651 V.changeSign(); 652 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 653 } 654 case ISD::FADD: 655 // FIXME: determine better conditions for this xform. 656 assert(Options.UnsafeFPMath); 657 658 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 659 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 660 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 661 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 662 GetNegatedExpression(Op.getOperand(0), DAG, 663 LegalOperations, Depth+1), 664 Op.getOperand(1), Flags); 665 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 666 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 667 GetNegatedExpression(Op.getOperand(1), DAG, 668 LegalOperations, Depth+1), 669 Op.getOperand(0), Flags); 670 case ISD::FSUB: 671 // We can't turn -(A-B) into B-A when we honor signed zeros. 672 assert(Options.UnsafeFPMath); 673 674 // fold (fneg (fsub 0, B)) -> B 675 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 676 if (N0CFP->isZero()) 677 return Op.getOperand(1); 678 679 // fold (fneg (fsub A, B)) -> (fsub B, A) 680 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 681 Op.getOperand(1), Op.getOperand(0), Flags); 682 683 case ISD::FMUL: 684 case ISD::FDIV: 685 assert(!Options.HonorSignDependentRoundingFPMath()); 686 687 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 688 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 689 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 690 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 691 GetNegatedExpression(Op.getOperand(0), DAG, 692 LegalOperations, Depth+1), 693 Op.getOperand(1), Flags); 694 695 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 696 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 697 Op.getOperand(0), 698 GetNegatedExpression(Op.getOperand(1), DAG, 699 LegalOperations, Depth+1), Flags); 700 701 case ISD::FP_EXTEND: 702 case ISD::FSIN: 703 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 704 GetNegatedExpression(Op.getOperand(0), DAG, 705 LegalOperations, Depth+1)); 706 case ISD::FP_ROUND: 707 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 708 GetNegatedExpression(Op.getOperand(0), DAG, 709 LegalOperations, Depth+1), 710 Op.getOperand(1)); 711 } 712 } 713 714 // Return true if this node is a setcc, or is a select_cc 715 // that selects between the target values used for true and false, making it 716 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 717 // the appropriate nodes based on the type of node we are checking. This 718 // simplifies life a bit for the callers. 719 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 720 SDValue &CC) const { 721 if (N.getOpcode() == ISD::SETCC) { 722 LHS = N.getOperand(0); 723 RHS = N.getOperand(1); 724 CC = N.getOperand(2); 725 return true; 726 } 727 728 if (N.getOpcode() != ISD::SELECT_CC || 729 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 730 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 731 return false; 732 733 if (TLI.getBooleanContents(N.getValueType()) == 734 TargetLowering::UndefinedBooleanContent) 735 return false; 736 737 LHS = N.getOperand(0); 738 RHS = N.getOperand(1); 739 CC = N.getOperand(4); 740 return true; 741 } 742 743 /// Return true if this is a SetCC-equivalent operation with only one use. 744 /// If this is true, it allows the users to invert the operation for free when 745 /// it is profitable to do so. 746 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 747 SDValue N0, N1, N2; 748 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 749 return true; 750 return false; 751 } 752 753 /// Returns true if N is a BUILD_VECTOR node whose 754 /// elements are all the same constant or undefined. 755 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 756 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 757 if (!C) 758 return false; 759 760 APInt SplatUndef; 761 unsigned SplatBitSize; 762 bool HasAnyUndefs; 763 EVT EltVT = N->getValueType(0).getVectorElementType(); 764 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 765 HasAnyUndefs) && 766 EltVT.getSizeInBits() >= SplatBitSize); 767 } 768 769 // \brief Returns the SDNode if it is a constant float BuildVector 770 // or constant float. 771 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 772 if (isa<ConstantFPSDNode>(N)) 773 return N.getNode(); 774 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 775 return N.getNode(); 776 return nullptr; 777 } 778 779 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 780 // int. 781 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 782 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 783 return CN; 784 785 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 786 BitVector UndefElements; 787 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 788 789 // BuildVectors can truncate their operands. Ignore that case here. 790 // FIXME: We blindly ignore splats which include undef which is overly 791 // pessimistic. 792 if (CN && UndefElements.none() && 793 CN->getValueType(0) == N.getValueType().getScalarType()) 794 return CN; 795 } 796 797 return nullptr; 798 } 799 800 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 801 // float. 802 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 803 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 804 return CN; 805 806 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 807 BitVector UndefElements; 808 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 809 810 if (CN && UndefElements.none()) 811 return CN; 812 } 813 814 return nullptr; 815 } 816 817 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 818 SDValue N0, SDValue N1) { 819 EVT VT = N0.getValueType(); 820 if (N0.getOpcode() == Opc) { 821 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 822 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 823 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 824 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 825 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 826 return SDValue(); 827 } 828 if (N0.hasOneUse()) { 829 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 830 // use 831 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 832 if (!OpNode.getNode()) 833 return SDValue(); 834 AddToWorklist(OpNode.getNode()); 835 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 836 } 837 } 838 } 839 840 if (N1.getOpcode() == Opc) { 841 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 842 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 843 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 844 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 845 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 846 return SDValue(); 847 } 848 if (N1.hasOneUse()) { 849 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 850 // use 851 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 852 if (!OpNode.getNode()) 853 return SDValue(); 854 AddToWorklist(OpNode.getNode()); 855 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 856 } 857 } 858 } 859 860 return SDValue(); 861 } 862 863 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 864 bool AddTo) { 865 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 866 ++NodesCombined; 867 DEBUG(dbgs() << "\nReplacing.1 "; 868 N->dump(&DAG); 869 dbgs() << "\nWith: "; 870 To[0].getNode()->dump(&DAG); 871 dbgs() << " and " << NumTo-1 << " other values\n"); 872 for (unsigned i = 0, e = NumTo; i != e; ++i) 873 assert((!To[i].getNode() || 874 N->getValueType(i) == To[i].getValueType()) && 875 "Cannot combine value to value of different type!"); 876 877 WorklistRemover DeadNodes(*this); 878 DAG.ReplaceAllUsesWith(N, To); 879 if (AddTo) { 880 // Push the new nodes and any users onto the worklist 881 for (unsigned i = 0, e = NumTo; i != e; ++i) { 882 if (To[i].getNode()) { 883 AddToWorklist(To[i].getNode()); 884 AddUsersToWorklist(To[i].getNode()); 885 } 886 } 887 } 888 889 // Finally, if the node is now dead, remove it from the graph. The node 890 // may not be dead if the replacement process recursively simplified to 891 // something else needing this node. 892 if (N->use_empty()) 893 deleteAndRecombine(N); 894 return SDValue(N, 0); 895 } 896 897 void DAGCombiner:: 898 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 899 // Replace all uses. If any nodes become isomorphic to other nodes and 900 // are deleted, make sure to remove them from our worklist. 901 WorklistRemover DeadNodes(*this); 902 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 903 904 // Push the new node and any (possibly new) users onto the worklist. 905 AddToWorklist(TLO.New.getNode()); 906 AddUsersToWorklist(TLO.New.getNode()); 907 908 // Finally, if the node is now dead, remove it from the graph. The node 909 // may not be dead if the replacement process recursively simplified to 910 // something else needing this node. 911 if (TLO.Old.getNode()->use_empty()) 912 deleteAndRecombine(TLO.Old.getNode()); 913 } 914 915 /// Check the specified integer node value to see if it can be simplified or if 916 /// things it uses can be simplified by bit propagation. If so, return true. 917 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 918 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 919 APInt KnownZero, KnownOne; 920 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 921 return false; 922 923 // Revisit the node. 924 AddToWorklist(Op.getNode()); 925 926 // Replace the old value with the new one. 927 ++NodesCombined; 928 DEBUG(dbgs() << "\nReplacing.2 "; 929 TLO.Old.getNode()->dump(&DAG); 930 dbgs() << "\nWith: "; 931 TLO.New.getNode()->dump(&DAG); 932 dbgs() << '\n'); 933 934 CommitTargetLoweringOpt(TLO); 935 return true; 936 } 937 938 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 939 SDLoc dl(Load); 940 EVT VT = Load->getValueType(0); 941 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 942 943 DEBUG(dbgs() << "\nReplacing.9 "; 944 Load->dump(&DAG); 945 dbgs() << "\nWith: "; 946 Trunc.getNode()->dump(&DAG); 947 dbgs() << '\n'); 948 WorklistRemover DeadNodes(*this); 949 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 950 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 951 deleteAndRecombine(Load); 952 AddToWorklist(Trunc.getNode()); 953 } 954 955 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 956 Replace = false; 957 SDLoc dl(Op); 958 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 959 EVT MemVT = LD->getMemoryVT(); 960 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 961 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 962 : ISD::EXTLOAD) 963 : LD->getExtensionType(); 964 Replace = true; 965 return DAG.getExtLoad(ExtType, dl, PVT, 966 LD->getChain(), LD->getBasePtr(), 967 MemVT, LD->getMemOperand()); 968 } 969 970 unsigned Opc = Op.getOpcode(); 971 switch (Opc) { 972 default: break; 973 case ISD::AssertSext: 974 return DAG.getNode(ISD::AssertSext, dl, PVT, 975 SExtPromoteOperand(Op.getOperand(0), PVT), 976 Op.getOperand(1)); 977 case ISD::AssertZext: 978 return DAG.getNode(ISD::AssertZext, dl, PVT, 979 ZExtPromoteOperand(Op.getOperand(0), PVT), 980 Op.getOperand(1)); 981 case ISD::Constant: { 982 unsigned ExtOpc = 983 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 984 return DAG.getNode(ExtOpc, dl, PVT, Op); 985 } 986 } 987 988 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 989 return SDValue(); 990 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 991 } 992 993 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 994 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 995 return SDValue(); 996 EVT OldVT = Op.getValueType(); 997 SDLoc dl(Op); 998 bool Replace = false; 999 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1000 if (!NewOp.getNode()) 1001 return SDValue(); 1002 AddToWorklist(NewOp.getNode()); 1003 1004 if (Replace) 1005 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1006 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1007 DAG.getValueType(OldVT)); 1008 } 1009 1010 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1011 EVT OldVT = Op.getValueType(); 1012 SDLoc dl(Op); 1013 bool Replace = false; 1014 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1015 if (!NewOp.getNode()) 1016 return SDValue(); 1017 AddToWorklist(NewOp.getNode()); 1018 1019 if (Replace) 1020 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1021 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1022 } 1023 1024 /// Promote the specified integer binary operation if the target indicates it is 1025 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1026 /// i32 since i16 instructions are longer. 1027 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1028 if (!LegalOperations) 1029 return SDValue(); 1030 1031 EVT VT = Op.getValueType(); 1032 if (VT.isVector() || !VT.isInteger()) 1033 return SDValue(); 1034 1035 // If operation type is 'undesirable', e.g. i16 on x86, consider 1036 // promoting it. 1037 unsigned Opc = Op.getOpcode(); 1038 if (TLI.isTypeDesirableForOp(Opc, VT)) 1039 return SDValue(); 1040 1041 EVT PVT = VT; 1042 // Consult target whether it is a good idea to promote this operation and 1043 // what's the right type to promote it to. 1044 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1045 assert(PVT != VT && "Don't know what type to promote to!"); 1046 1047 bool Replace0 = false; 1048 SDValue N0 = Op.getOperand(0); 1049 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1050 if (!NN0.getNode()) 1051 return SDValue(); 1052 1053 bool Replace1 = false; 1054 SDValue N1 = Op.getOperand(1); 1055 SDValue NN1; 1056 if (N0 == N1) 1057 NN1 = NN0; 1058 else { 1059 NN1 = PromoteOperand(N1, PVT, Replace1); 1060 if (!NN1.getNode()) 1061 return SDValue(); 1062 } 1063 1064 AddToWorklist(NN0.getNode()); 1065 if (NN1.getNode()) 1066 AddToWorklist(NN1.getNode()); 1067 1068 if (Replace0) 1069 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1070 if (Replace1) 1071 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1072 1073 DEBUG(dbgs() << "\nPromoting "; 1074 Op.getNode()->dump(&DAG)); 1075 SDLoc dl(Op); 1076 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1077 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1078 } 1079 return SDValue(); 1080 } 1081 1082 /// Promote the specified integer shift operation if the target indicates it is 1083 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1084 /// i32 since i16 instructions are longer. 1085 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1086 if (!LegalOperations) 1087 return SDValue(); 1088 1089 EVT VT = Op.getValueType(); 1090 if (VT.isVector() || !VT.isInteger()) 1091 return SDValue(); 1092 1093 // If operation type is 'undesirable', e.g. i16 on x86, consider 1094 // promoting it. 1095 unsigned Opc = Op.getOpcode(); 1096 if (TLI.isTypeDesirableForOp(Opc, VT)) 1097 return SDValue(); 1098 1099 EVT PVT = VT; 1100 // Consult target whether it is a good idea to promote this operation and 1101 // what's the right type to promote it to. 1102 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1103 assert(PVT != VT && "Don't know what type to promote to!"); 1104 1105 bool Replace = false; 1106 SDValue N0 = Op.getOperand(0); 1107 if (Opc == ISD::SRA) 1108 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1109 else if (Opc == ISD::SRL) 1110 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1111 else 1112 N0 = PromoteOperand(N0, PVT, Replace); 1113 if (!N0.getNode()) 1114 return SDValue(); 1115 1116 AddToWorklist(N0.getNode()); 1117 if (Replace) 1118 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1119 1120 DEBUG(dbgs() << "\nPromoting "; 1121 Op.getNode()->dump(&DAG)); 1122 SDLoc dl(Op); 1123 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1124 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1125 } 1126 return SDValue(); 1127 } 1128 1129 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1130 if (!LegalOperations) 1131 return SDValue(); 1132 1133 EVT VT = Op.getValueType(); 1134 if (VT.isVector() || !VT.isInteger()) 1135 return SDValue(); 1136 1137 // If operation type is 'undesirable', e.g. i16 on x86, consider 1138 // promoting it. 1139 unsigned Opc = Op.getOpcode(); 1140 if (TLI.isTypeDesirableForOp(Opc, VT)) 1141 return SDValue(); 1142 1143 EVT PVT = VT; 1144 // Consult target whether it is a good idea to promote this operation and 1145 // what's the right type to promote it to. 1146 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1147 assert(PVT != VT && "Don't know what type to promote to!"); 1148 // fold (aext (aext x)) -> (aext x) 1149 // fold (aext (zext x)) -> (zext x) 1150 // fold (aext (sext x)) -> (sext x) 1151 DEBUG(dbgs() << "\nPromoting "; 1152 Op.getNode()->dump(&DAG)); 1153 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1154 } 1155 return SDValue(); 1156 } 1157 1158 bool DAGCombiner::PromoteLoad(SDValue Op) { 1159 if (!LegalOperations) 1160 return false; 1161 1162 EVT VT = Op.getValueType(); 1163 if (VT.isVector() || !VT.isInteger()) 1164 return false; 1165 1166 // If operation type is 'undesirable', e.g. i16 on x86, consider 1167 // promoting it. 1168 unsigned Opc = Op.getOpcode(); 1169 if (TLI.isTypeDesirableForOp(Opc, VT)) 1170 return false; 1171 1172 EVT PVT = VT; 1173 // Consult target whether it is a good idea to promote this operation and 1174 // what's the right type to promote it to. 1175 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1176 assert(PVT != VT && "Don't know what type to promote to!"); 1177 1178 SDLoc dl(Op); 1179 SDNode *N = Op.getNode(); 1180 LoadSDNode *LD = cast<LoadSDNode>(N); 1181 EVT MemVT = LD->getMemoryVT(); 1182 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1183 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1184 : ISD::EXTLOAD) 1185 : LD->getExtensionType(); 1186 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1187 LD->getChain(), LD->getBasePtr(), 1188 MemVT, LD->getMemOperand()); 1189 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1190 1191 DEBUG(dbgs() << "\nPromoting "; 1192 N->dump(&DAG); 1193 dbgs() << "\nTo: "; 1194 Result.getNode()->dump(&DAG); 1195 dbgs() << '\n'); 1196 WorklistRemover DeadNodes(*this); 1197 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1198 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1199 deleteAndRecombine(N); 1200 AddToWorklist(Result.getNode()); 1201 return true; 1202 } 1203 return false; 1204 } 1205 1206 /// \brief Recursively delete a node which has no uses and any operands for 1207 /// which it is the only use. 1208 /// 1209 /// Note that this both deletes the nodes and removes them from the worklist. 1210 /// It also adds any nodes who have had a user deleted to the worklist as they 1211 /// may now have only one use and subject to other combines. 1212 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1213 if (!N->use_empty()) 1214 return false; 1215 1216 SmallSetVector<SDNode *, 16> Nodes; 1217 Nodes.insert(N); 1218 do { 1219 N = Nodes.pop_back_val(); 1220 if (!N) 1221 continue; 1222 1223 if (N->use_empty()) { 1224 for (const SDValue &ChildN : N->op_values()) 1225 Nodes.insert(ChildN.getNode()); 1226 1227 removeFromWorklist(N); 1228 DAG.DeleteNode(N); 1229 } else { 1230 AddToWorklist(N); 1231 } 1232 } while (!Nodes.empty()); 1233 return true; 1234 } 1235 1236 //===----------------------------------------------------------------------===// 1237 // Main DAG Combiner implementation 1238 //===----------------------------------------------------------------------===// 1239 1240 void DAGCombiner::Run(CombineLevel AtLevel) { 1241 // set the instance variables, so that the various visit routines may use it. 1242 Level = AtLevel; 1243 LegalOperations = Level >= AfterLegalizeVectorOps; 1244 LegalTypes = Level >= AfterLegalizeTypes; 1245 1246 // Add all the dag nodes to the worklist. 1247 for (SDNode &Node : DAG.allnodes()) 1248 AddToWorklist(&Node); 1249 1250 // Create a dummy node (which is not added to allnodes), that adds a reference 1251 // to the root node, preventing it from being deleted, and tracking any 1252 // changes of the root. 1253 HandleSDNode Dummy(DAG.getRoot()); 1254 1255 // while the worklist isn't empty, find a node and 1256 // try and combine it. 1257 while (!WorklistMap.empty()) { 1258 SDNode *N; 1259 // The Worklist holds the SDNodes in order, but it may contain null entries. 1260 do { 1261 N = Worklist.pop_back_val(); 1262 } while (!N); 1263 1264 bool GoodWorklistEntry = WorklistMap.erase(N); 1265 (void)GoodWorklistEntry; 1266 assert(GoodWorklistEntry && 1267 "Found a worklist entry without a corresponding map entry!"); 1268 1269 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1270 // N is deleted from the DAG, since they too may now be dead or may have a 1271 // reduced number of uses, allowing other xforms. 1272 if (recursivelyDeleteUnusedNodes(N)) 1273 continue; 1274 1275 WorklistRemover DeadNodes(*this); 1276 1277 // If this combine is running after legalizing the DAG, re-legalize any 1278 // nodes pulled off the worklist. 1279 if (Level == AfterLegalizeDAG) { 1280 SmallSetVector<SDNode *, 16> UpdatedNodes; 1281 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1282 1283 for (SDNode *LN : UpdatedNodes) { 1284 AddToWorklist(LN); 1285 AddUsersToWorklist(LN); 1286 } 1287 if (!NIsValid) 1288 continue; 1289 } 1290 1291 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1292 1293 // Add any operands of the new node which have not yet been combined to the 1294 // worklist as well. Because the worklist uniques things already, this 1295 // won't repeatedly process the same operand. 1296 CombinedNodes.insert(N); 1297 for (const SDValue &ChildN : N->op_values()) 1298 if (!CombinedNodes.count(ChildN.getNode())) 1299 AddToWorklist(ChildN.getNode()); 1300 1301 SDValue RV = combine(N); 1302 1303 if (!RV.getNode()) 1304 continue; 1305 1306 ++NodesCombined; 1307 1308 // If we get back the same node we passed in, rather than a new node or 1309 // zero, we know that the node must have defined multiple values and 1310 // CombineTo was used. Since CombineTo takes care of the worklist 1311 // mechanics for us, we have no work to do in this case. 1312 if (RV.getNode() == N) 1313 continue; 1314 1315 assert(N->getOpcode() != ISD::DELETED_NODE && 1316 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1317 "Node was deleted but visit returned new node!"); 1318 1319 DEBUG(dbgs() << " ... into: "; 1320 RV.getNode()->dump(&DAG)); 1321 1322 // Transfer debug value. 1323 DAG.TransferDbgValues(SDValue(N, 0), RV); 1324 if (N->getNumValues() == RV.getNode()->getNumValues()) 1325 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1326 else { 1327 assert(N->getValueType(0) == RV.getValueType() && 1328 N->getNumValues() == 1 && "Type mismatch"); 1329 SDValue OpV = RV; 1330 DAG.ReplaceAllUsesWith(N, &OpV); 1331 } 1332 1333 // Push the new node and any users onto the worklist 1334 AddToWorklist(RV.getNode()); 1335 AddUsersToWorklist(RV.getNode()); 1336 1337 // Finally, if the node is now dead, remove it from the graph. The node 1338 // may not be dead if the replacement process recursively simplified to 1339 // something else needing this node. This will also take care of adding any 1340 // operands which have lost a user to the worklist. 1341 recursivelyDeleteUnusedNodes(N); 1342 } 1343 1344 // If the root changed (e.g. it was a dead load, update the root). 1345 DAG.setRoot(Dummy.getValue()); 1346 DAG.RemoveDeadNodes(); 1347 } 1348 1349 SDValue DAGCombiner::visit(SDNode *N) { 1350 switch (N->getOpcode()) { 1351 default: break; 1352 case ISD::TokenFactor: return visitTokenFactor(N); 1353 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1354 case ISD::ADD: return visitADD(N); 1355 case ISD::SUB: return visitSUB(N); 1356 case ISD::ADDC: return visitADDC(N); 1357 case ISD::SUBC: return visitSUBC(N); 1358 case ISD::ADDE: return visitADDE(N); 1359 case ISD::SUBE: return visitSUBE(N); 1360 case ISD::MUL: return visitMUL(N); 1361 case ISD::SDIV: return visitSDIV(N); 1362 case ISD::UDIV: return visitUDIV(N); 1363 case ISD::SREM: 1364 case ISD::UREM: return visitREM(N); 1365 case ISD::MULHU: return visitMULHU(N); 1366 case ISD::MULHS: return visitMULHS(N); 1367 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1368 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1369 case ISD::SMULO: return visitSMULO(N); 1370 case ISD::UMULO: return visitUMULO(N); 1371 case ISD::SMIN: 1372 case ISD::SMAX: 1373 case ISD::UMIN: 1374 case ISD::UMAX: return visitIMINMAX(N); 1375 case ISD::AND: return visitAND(N); 1376 case ISD::OR: return visitOR(N); 1377 case ISD::XOR: return visitXOR(N); 1378 case ISD::SHL: return visitSHL(N); 1379 case ISD::SRA: return visitSRA(N); 1380 case ISD::SRL: return visitSRL(N); 1381 case ISD::ROTR: 1382 case ISD::ROTL: return visitRotate(N); 1383 case ISD::BSWAP: return visitBSWAP(N); 1384 case ISD::CTLZ: return visitCTLZ(N); 1385 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1386 case ISD::CTTZ: return visitCTTZ(N); 1387 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1388 case ISD::CTPOP: return visitCTPOP(N); 1389 case ISD::SELECT: return visitSELECT(N); 1390 case ISD::VSELECT: return visitVSELECT(N); 1391 case ISD::SELECT_CC: return visitSELECT_CC(N); 1392 case ISD::SETCC: return visitSETCC(N); 1393 case ISD::SETCCE: return visitSETCCE(N); 1394 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1395 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1396 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1397 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1398 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1399 case ISD::TRUNCATE: return visitTRUNCATE(N); 1400 case ISD::BITCAST: return visitBITCAST(N); 1401 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1402 case ISD::FADD: return visitFADD(N); 1403 case ISD::FSUB: return visitFSUB(N); 1404 case ISD::FMUL: return visitFMUL(N); 1405 case ISD::FMA: return visitFMA(N); 1406 case ISD::FDIV: return visitFDIV(N); 1407 case ISD::FREM: return visitFREM(N); 1408 case ISD::FSQRT: return visitFSQRT(N); 1409 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1410 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1411 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1412 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1413 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1414 case ISD::FP_ROUND: return visitFP_ROUND(N); 1415 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1416 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1417 case ISD::FNEG: return visitFNEG(N); 1418 case ISD::FABS: return visitFABS(N); 1419 case ISD::FFLOOR: return visitFFLOOR(N); 1420 case ISD::FMINNUM: return visitFMINNUM(N); 1421 case ISD::FMAXNUM: return visitFMAXNUM(N); 1422 case ISD::FCEIL: return visitFCEIL(N); 1423 case ISD::FTRUNC: return visitFTRUNC(N); 1424 case ISD::BRCOND: return visitBRCOND(N); 1425 case ISD::BR_CC: return visitBR_CC(N); 1426 case ISD::LOAD: return visitLOAD(N); 1427 case ISD::STORE: return visitSTORE(N); 1428 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1429 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1430 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1431 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1432 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1433 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1434 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1435 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1436 case ISD::MGATHER: return visitMGATHER(N); 1437 case ISD::MLOAD: return visitMLOAD(N); 1438 case ISD::MSCATTER: return visitMSCATTER(N); 1439 case ISD::MSTORE: return visitMSTORE(N); 1440 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1441 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1442 } 1443 return SDValue(); 1444 } 1445 1446 SDValue DAGCombiner::combine(SDNode *N) { 1447 SDValue RV = visit(N); 1448 1449 // If nothing happened, try a target-specific DAG combine. 1450 if (!RV.getNode()) { 1451 assert(N->getOpcode() != ISD::DELETED_NODE && 1452 "Node was deleted but visit returned NULL!"); 1453 1454 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1455 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1456 1457 // Expose the DAG combiner to the target combiner impls. 1458 TargetLowering::DAGCombinerInfo 1459 DagCombineInfo(DAG, Level, false, this); 1460 1461 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1462 } 1463 } 1464 1465 // If nothing happened still, try promoting the operation. 1466 if (!RV.getNode()) { 1467 switch (N->getOpcode()) { 1468 default: break; 1469 case ISD::ADD: 1470 case ISD::SUB: 1471 case ISD::MUL: 1472 case ISD::AND: 1473 case ISD::OR: 1474 case ISD::XOR: 1475 RV = PromoteIntBinOp(SDValue(N, 0)); 1476 break; 1477 case ISD::SHL: 1478 case ISD::SRA: 1479 case ISD::SRL: 1480 RV = PromoteIntShiftOp(SDValue(N, 0)); 1481 break; 1482 case ISD::SIGN_EXTEND: 1483 case ISD::ZERO_EXTEND: 1484 case ISD::ANY_EXTEND: 1485 RV = PromoteExtend(SDValue(N, 0)); 1486 break; 1487 case ISD::LOAD: 1488 if (PromoteLoad(SDValue(N, 0))) 1489 RV = SDValue(N, 0); 1490 break; 1491 } 1492 } 1493 1494 // If N is a commutative binary node, try commuting it to enable more 1495 // sdisel CSE. 1496 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1497 N->getNumValues() == 1) { 1498 SDValue N0 = N->getOperand(0); 1499 SDValue N1 = N->getOperand(1); 1500 1501 // Constant operands are canonicalized to RHS. 1502 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1503 SDValue Ops[] = {N1, N0}; 1504 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1505 N->getFlags()); 1506 if (CSENode) 1507 return SDValue(CSENode, 0); 1508 } 1509 } 1510 1511 return RV; 1512 } 1513 1514 /// Given a node, return its input chain if it has one, otherwise return a null 1515 /// sd operand. 1516 static SDValue getInputChainForNode(SDNode *N) { 1517 if (unsigned NumOps = N->getNumOperands()) { 1518 if (N->getOperand(0).getValueType() == MVT::Other) 1519 return N->getOperand(0); 1520 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1521 return N->getOperand(NumOps-1); 1522 for (unsigned i = 1; i < NumOps-1; ++i) 1523 if (N->getOperand(i).getValueType() == MVT::Other) 1524 return N->getOperand(i); 1525 } 1526 return SDValue(); 1527 } 1528 1529 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1530 // If N has two operands, where one has an input chain equal to the other, 1531 // the 'other' chain is redundant. 1532 if (N->getNumOperands() == 2) { 1533 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1534 return N->getOperand(0); 1535 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1536 return N->getOperand(1); 1537 } 1538 1539 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1540 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1541 SmallPtrSet<SDNode*, 16> SeenOps; 1542 bool Changed = false; // If we should replace this token factor. 1543 1544 // Start out with this token factor. 1545 TFs.push_back(N); 1546 1547 // Iterate through token factors. The TFs grows when new token factors are 1548 // encountered. 1549 for (unsigned i = 0; i < TFs.size(); ++i) { 1550 SDNode *TF = TFs[i]; 1551 1552 // Check each of the operands. 1553 for (const SDValue &Op : TF->op_values()) { 1554 1555 switch (Op.getOpcode()) { 1556 case ISD::EntryToken: 1557 // Entry tokens don't need to be added to the list. They are 1558 // redundant. 1559 Changed = true; 1560 break; 1561 1562 case ISD::TokenFactor: 1563 if (Op.hasOneUse() && 1564 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1565 // Queue up for processing. 1566 TFs.push_back(Op.getNode()); 1567 // Clean up in case the token factor is removed. 1568 AddToWorklist(Op.getNode()); 1569 Changed = true; 1570 break; 1571 } 1572 // Fall thru 1573 1574 default: 1575 // Only add if it isn't already in the list. 1576 if (SeenOps.insert(Op.getNode()).second) 1577 Ops.push_back(Op); 1578 else 1579 Changed = true; 1580 break; 1581 } 1582 } 1583 } 1584 1585 SDValue Result; 1586 1587 // If we've changed things around then replace token factor. 1588 if (Changed) { 1589 if (Ops.empty()) { 1590 // The entry token is the only possible outcome. 1591 Result = DAG.getEntryNode(); 1592 } else { 1593 // New and improved token factor. 1594 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1595 } 1596 1597 // Add users to worklist if AA is enabled, since it may introduce 1598 // a lot of new chained token factors while removing memory deps. 1599 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1600 : DAG.getSubtarget().useAA(); 1601 return CombineTo(N, Result, UseAA /*add to worklist*/); 1602 } 1603 1604 return Result; 1605 } 1606 1607 /// MERGE_VALUES can always be eliminated. 1608 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1609 WorklistRemover DeadNodes(*this); 1610 // Replacing results may cause a different MERGE_VALUES to suddenly 1611 // be CSE'd with N, and carry its uses with it. Iterate until no 1612 // uses remain, to ensure that the node can be safely deleted. 1613 // First add the users of this node to the work list so that they 1614 // can be tried again once they have new operands. 1615 AddUsersToWorklist(N); 1616 do { 1617 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1618 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1619 } while (!N->use_empty()); 1620 deleteAndRecombine(N); 1621 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1622 } 1623 1624 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a 1625 /// ContantSDNode pointer else nullptr. 1626 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1627 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1628 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1629 } 1630 1631 SDValue DAGCombiner::visitADD(SDNode *N) { 1632 SDValue N0 = N->getOperand(0); 1633 SDValue N1 = N->getOperand(1); 1634 EVT VT = N0.getValueType(); 1635 1636 // fold vector ops 1637 if (VT.isVector()) { 1638 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1639 return FoldedVOp; 1640 1641 // fold (add x, 0) -> x, vector edition 1642 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1643 return N0; 1644 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1645 return N1; 1646 } 1647 1648 // fold (add x, undef) -> undef 1649 if (N0.getOpcode() == ISD::UNDEF) 1650 return N0; 1651 if (N1.getOpcode() == ISD::UNDEF) 1652 return N1; 1653 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1654 // canonicalize constant to RHS 1655 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1656 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1657 // fold (add c1, c2) -> c1+c2 1658 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1659 N0.getNode(), N1.getNode()); 1660 } 1661 // fold (add x, 0) -> x 1662 if (isNullConstant(N1)) 1663 return N0; 1664 // fold ((c1-A)+c2) -> (c1+c2)-A 1665 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1666 if (N0.getOpcode() == ISD::SUB) 1667 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1668 SDLoc DL(N); 1669 return DAG.getNode(ISD::SUB, DL, VT, 1670 DAG.getConstant(N1C->getAPIntValue()+ 1671 N0C->getAPIntValue(), DL, VT), 1672 N0.getOperand(1)); 1673 } 1674 } 1675 // reassociate add 1676 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1677 return RADD; 1678 // fold ((0-A) + B) -> B-A 1679 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1680 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1681 // fold (A + (0-B)) -> A-B 1682 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1683 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1684 // fold (A+(B-A)) -> B 1685 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1686 return N1.getOperand(0); 1687 // fold ((B-A)+A) -> B 1688 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1689 return N0.getOperand(0); 1690 // fold (A+(B-(A+C))) to (B-C) 1691 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1692 N0 == N1.getOperand(1).getOperand(0)) 1693 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1694 N1.getOperand(1).getOperand(1)); 1695 // fold (A+(B-(C+A))) to (B-C) 1696 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1697 N0 == N1.getOperand(1).getOperand(1)) 1698 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1699 N1.getOperand(1).getOperand(0)); 1700 // fold (A+((B-A)+or-C)) to (B+or-C) 1701 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1702 N1.getOperand(0).getOpcode() == ISD::SUB && 1703 N0 == N1.getOperand(0).getOperand(1)) 1704 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1705 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1706 1707 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1708 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1709 SDValue N00 = N0.getOperand(0); 1710 SDValue N01 = N0.getOperand(1); 1711 SDValue N10 = N1.getOperand(0); 1712 SDValue N11 = N1.getOperand(1); 1713 1714 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1715 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1716 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1717 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1718 } 1719 1720 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1721 return SDValue(N, 0); 1722 1723 // fold (a+b) -> (a|b) iff a and b share no bits. 1724 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1725 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1726 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1727 1728 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1729 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1730 isNullConstant(N1.getOperand(0).getOperand(0))) 1731 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1732 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1733 N1.getOperand(0).getOperand(1), 1734 N1.getOperand(1))); 1735 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1736 isNullConstant(N0.getOperand(0).getOperand(0))) 1737 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1738 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1739 N0.getOperand(0).getOperand(1), 1740 N0.getOperand(1))); 1741 1742 if (N1.getOpcode() == ISD::AND) { 1743 SDValue AndOp0 = N1.getOperand(0); 1744 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1745 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1746 1747 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1748 // and similar xforms where the inner op is either ~0 or 0. 1749 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1750 SDLoc DL(N); 1751 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1752 } 1753 } 1754 1755 // add (sext i1), X -> sub X, (zext i1) 1756 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1757 N0.getOperand(0).getValueType() == MVT::i1 && 1758 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1759 SDLoc DL(N); 1760 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1761 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1762 } 1763 1764 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1765 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1766 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1767 if (TN->getVT() == MVT::i1) { 1768 SDLoc DL(N); 1769 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1770 DAG.getConstant(1, DL, VT)); 1771 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1772 } 1773 } 1774 1775 return SDValue(); 1776 } 1777 1778 SDValue DAGCombiner::visitADDC(SDNode *N) { 1779 SDValue N0 = N->getOperand(0); 1780 SDValue N1 = N->getOperand(1); 1781 EVT VT = N0.getValueType(); 1782 1783 // If the flag result is dead, turn this into an ADD. 1784 if (!N->hasAnyUseOfValue(1)) 1785 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1786 DAG.getNode(ISD::CARRY_FALSE, 1787 SDLoc(N), MVT::Glue)); 1788 1789 // canonicalize constant to RHS. 1790 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1791 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1792 if (N0C && !N1C) 1793 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1794 1795 // fold (addc x, 0) -> x + no carry out 1796 if (isNullConstant(N1)) 1797 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1798 SDLoc(N), MVT::Glue)); 1799 1800 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1801 APInt LHSZero, LHSOne; 1802 APInt RHSZero, RHSOne; 1803 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1804 1805 if (LHSZero.getBoolValue()) { 1806 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1807 1808 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1809 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1810 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1811 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1812 DAG.getNode(ISD::CARRY_FALSE, 1813 SDLoc(N), MVT::Glue)); 1814 } 1815 1816 return SDValue(); 1817 } 1818 1819 SDValue DAGCombiner::visitADDE(SDNode *N) { 1820 SDValue N0 = N->getOperand(0); 1821 SDValue N1 = N->getOperand(1); 1822 SDValue CarryIn = N->getOperand(2); 1823 1824 // canonicalize constant to RHS 1825 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1827 if (N0C && !N1C) 1828 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1829 N1, N0, CarryIn); 1830 1831 // fold (adde x, y, false) -> (addc x, y) 1832 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1833 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1834 1835 return SDValue(); 1836 } 1837 1838 // Since it may not be valid to emit a fold to zero for vector initializers 1839 // check if we can before folding. 1840 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1841 SelectionDAG &DAG, 1842 bool LegalOperations, bool LegalTypes) { 1843 if (!VT.isVector()) 1844 return DAG.getConstant(0, DL, VT); 1845 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1846 return DAG.getConstant(0, DL, VT); 1847 return SDValue(); 1848 } 1849 1850 SDValue DAGCombiner::visitSUB(SDNode *N) { 1851 SDValue N0 = N->getOperand(0); 1852 SDValue N1 = N->getOperand(1); 1853 EVT VT = N0.getValueType(); 1854 1855 // fold vector ops 1856 if (VT.isVector()) { 1857 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1858 return FoldedVOp; 1859 1860 // fold (sub x, 0) -> x, vector edition 1861 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1862 return N0; 1863 } 1864 1865 // fold (sub x, x) -> 0 1866 // FIXME: Refactor this and xor and other similar operations together. 1867 if (N0 == N1) 1868 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1869 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1870 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1871 // fold (sub c1, c2) -> c1-c2 1872 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1873 N0.getNode(), N1.getNode()); 1874 } 1875 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1876 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1877 // fold (sub x, c) -> (add x, -c) 1878 if (N1C) { 1879 SDLoc DL(N); 1880 return DAG.getNode(ISD::ADD, DL, VT, N0, 1881 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1882 } 1883 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1884 if (isAllOnesConstant(N0)) 1885 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1886 // fold A-(A-B) -> B 1887 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1888 return N1.getOperand(1); 1889 // fold (A+B)-A -> B 1890 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1891 return N0.getOperand(1); 1892 // fold (A+B)-B -> A 1893 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1894 return N0.getOperand(0); 1895 // fold C2-(A+C1) -> (C2-C1)-A 1896 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1897 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1898 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1899 SDLoc DL(N); 1900 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1901 DL, VT); 1902 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1903 N1.getOperand(0)); 1904 } 1905 // fold ((A+(B+or-C))-B) -> A+or-C 1906 if (N0.getOpcode() == ISD::ADD && 1907 (N0.getOperand(1).getOpcode() == ISD::SUB || 1908 N0.getOperand(1).getOpcode() == ISD::ADD) && 1909 N0.getOperand(1).getOperand(0) == N1) 1910 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1911 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1912 // fold ((A+(C+B))-B) -> A+C 1913 if (N0.getOpcode() == ISD::ADD && 1914 N0.getOperand(1).getOpcode() == ISD::ADD && 1915 N0.getOperand(1).getOperand(1) == N1) 1916 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1917 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1918 // fold ((A-(B-C))-C) -> A-B 1919 if (N0.getOpcode() == ISD::SUB && 1920 N0.getOperand(1).getOpcode() == ISD::SUB && 1921 N0.getOperand(1).getOperand(1) == N1) 1922 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1923 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1924 1925 // If either operand of a sub is undef, the result is undef 1926 if (N0.getOpcode() == ISD::UNDEF) 1927 return N0; 1928 if (N1.getOpcode() == ISD::UNDEF) 1929 return N1; 1930 1931 // If the relocation model supports it, consider symbol offsets. 1932 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1933 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1934 // fold (sub Sym, c) -> Sym-c 1935 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1936 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1937 GA->getOffset() - 1938 (uint64_t)N1C->getSExtValue()); 1939 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1940 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1941 if (GA->getGlobal() == GB->getGlobal()) 1942 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1943 SDLoc(N), VT); 1944 } 1945 1946 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1947 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1948 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1949 if (TN->getVT() == MVT::i1) { 1950 SDLoc DL(N); 1951 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1952 DAG.getConstant(1, DL, VT)); 1953 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1954 } 1955 } 1956 1957 return SDValue(); 1958 } 1959 1960 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1961 SDValue N0 = N->getOperand(0); 1962 SDValue N1 = N->getOperand(1); 1963 EVT VT = N0.getValueType(); 1964 SDLoc DL(N); 1965 1966 // If the flag result is dead, turn this into an SUB. 1967 if (!N->hasAnyUseOfValue(1)) 1968 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1969 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1970 1971 // fold (subc x, x) -> 0 + no borrow 1972 if (N0 == N1) 1973 return CombineTo(N, DAG.getConstant(0, DL, VT), 1974 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1975 1976 // fold (subc x, 0) -> x + no borrow 1977 if (isNullConstant(N1)) 1978 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1979 1980 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1981 if (isAllOnesConstant(N0)) 1982 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1983 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1984 1985 return SDValue(); 1986 } 1987 1988 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1989 SDValue N0 = N->getOperand(0); 1990 SDValue N1 = N->getOperand(1); 1991 SDValue CarryIn = N->getOperand(2); 1992 1993 // fold (sube x, y, false) -> (subc x, y) 1994 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1995 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1996 1997 return SDValue(); 1998 } 1999 2000 SDValue DAGCombiner::visitMUL(SDNode *N) { 2001 SDValue N0 = N->getOperand(0); 2002 SDValue N1 = N->getOperand(1); 2003 EVT VT = N0.getValueType(); 2004 2005 // fold (mul x, undef) -> 0 2006 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2007 return DAG.getConstant(0, SDLoc(N), VT); 2008 2009 bool N0IsConst = false; 2010 bool N1IsConst = false; 2011 bool N1IsOpaqueConst = false; 2012 bool N0IsOpaqueConst = false; 2013 APInt ConstValue0, ConstValue1; 2014 // fold vector ops 2015 if (VT.isVector()) { 2016 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2017 return FoldedVOp; 2018 2019 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2020 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2021 } else { 2022 N0IsConst = isa<ConstantSDNode>(N0); 2023 if (N0IsConst) { 2024 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2025 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2026 } 2027 N1IsConst = isa<ConstantSDNode>(N1); 2028 if (N1IsConst) { 2029 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2030 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2031 } 2032 } 2033 2034 // fold (mul c1, c2) -> c1*c2 2035 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2036 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2037 N0.getNode(), N1.getNode()); 2038 2039 // canonicalize constant to RHS (vector doesn't have to splat) 2040 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2041 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2042 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2043 // fold (mul x, 0) -> 0 2044 if (N1IsConst && ConstValue1 == 0) 2045 return N1; 2046 // We require a splat of the entire scalar bit width for non-contiguous 2047 // bit patterns. 2048 bool IsFullSplat = 2049 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2050 // fold (mul x, 1) -> x 2051 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2052 return N0; 2053 // fold (mul x, -1) -> 0-x 2054 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2055 SDLoc DL(N); 2056 return DAG.getNode(ISD::SUB, DL, VT, 2057 DAG.getConstant(0, DL, VT), N0); 2058 } 2059 // fold (mul x, (1 << c)) -> x << c 2060 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2061 IsFullSplat) { 2062 SDLoc DL(N); 2063 return DAG.getNode(ISD::SHL, DL, VT, N0, 2064 DAG.getConstant(ConstValue1.logBase2(), DL, 2065 getShiftAmountTy(N0.getValueType()))); 2066 } 2067 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2068 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2069 IsFullSplat) { 2070 unsigned Log2Val = (-ConstValue1).logBase2(); 2071 SDLoc DL(N); 2072 // FIXME: If the input is something that is easily negated (e.g. a 2073 // single-use add), we should put the negate there. 2074 return DAG.getNode(ISD::SUB, DL, VT, 2075 DAG.getConstant(0, DL, VT), 2076 DAG.getNode(ISD::SHL, DL, VT, N0, 2077 DAG.getConstant(Log2Val, DL, 2078 getShiftAmountTy(N0.getValueType())))); 2079 } 2080 2081 APInt Val; 2082 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2083 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2084 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2085 isa<ConstantSDNode>(N0.getOperand(1)))) { 2086 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2087 N1, N0.getOperand(1)); 2088 AddToWorklist(C3.getNode()); 2089 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2090 N0.getOperand(0), C3); 2091 } 2092 2093 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2094 // use. 2095 { 2096 SDValue Sh(nullptr,0), Y(nullptr,0); 2097 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2098 if (N0.getOpcode() == ISD::SHL && 2099 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2100 isa<ConstantSDNode>(N0.getOperand(1))) && 2101 N0.getNode()->hasOneUse()) { 2102 Sh = N0; Y = N1; 2103 } else if (N1.getOpcode() == ISD::SHL && 2104 isa<ConstantSDNode>(N1.getOperand(1)) && 2105 N1.getNode()->hasOneUse()) { 2106 Sh = N1; Y = N0; 2107 } 2108 2109 if (Sh.getNode()) { 2110 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2111 Sh.getOperand(0), Y); 2112 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2113 Mul, Sh.getOperand(1)); 2114 } 2115 } 2116 2117 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2118 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2119 N0.getOpcode() == ISD::ADD && 2120 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2121 isMulAddWithConstProfitable(N, N0, N1)) 2122 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2123 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2124 N0.getOperand(0), N1), 2125 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2126 N0.getOperand(1), N1)); 2127 2128 // reassociate mul 2129 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2130 return RMUL; 2131 2132 return SDValue(); 2133 } 2134 2135 /// Return true if divmod libcall is available. 2136 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2137 const TargetLowering &TLI) { 2138 RTLIB::Libcall LC; 2139 switch (Node->getSimpleValueType(0).SimpleTy) { 2140 default: return false; // No libcall for vector types. 2141 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2142 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2143 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2144 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2145 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2146 } 2147 2148 return TLI.getLibcallName(LC) != nullptr; 2149 } 2150 2151 /// Issue divrem if both quotient and remainder are needed. 2152 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2153 if (Node->use_empty()) 2154 return SDValue(); // This is a dead node, leave it alone. 2155 2156 EVT VT = Node->getValueType(0); 2157 if (!TLI.isTypeLegal(VT)) 2158 return SDValue(); 2159 2160 unsigned Opcode = Node->getOpcode(); 2161 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2162 2163 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2164 // If DIVREM is going to get expanded into a libcall, 2165 // but there is no libcall available, then don't combine. 2166 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2167 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2168 return SDValue(); 2169 2170 // If div is legal, it's better to do the normal expansion 2171 unsigned OtherOpcode = 0; 2172 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2173 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2174 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2175 return SDValue(); 2176 } else { 2177 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2178 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2179 return SDValue(); 2180 } 2181 2182 SDValue Op0 = Node->getOperand(0); 2183 SDValue Op1 = Node->getOperand(1); 2184 SDValue combined; 2185 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2186 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2187 SDNode *User = *UI; 2188 if (User == Node || User->use_empty()) 2189 continue; 2190 // Convert the other matching node(s), too; 2191 // otherwise, the DIVREM may get target-legalized into something 2192 // target-specific that we won't be able to recognize. 2193 unsigned UserOpc = User->getOpcode(); 2194 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2195 User->getOperand(0) == Op0 && 2196 User->getOperand(1) == Op1) { 2197 if (!combined) { 2198 if (UserOpc == OtherOpcode) { 2199 SDVTList VTs = DAG.getVTList(VT, VT); 2200 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2201 } else if (UserOpc == DivRemOpc) { 2202 combined = SDValue(User, 0); 2203 } else { 2204 assert(UserOpc == Opcode); 2205 continue; 2206 } 2207 } 2208 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2209 CombineTo(User, combined); 2210 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2211 CombineTo(User, combined.getValue(1)); 2212 } 2213 } 2214 return combined; 2215 } 2216 2217 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2218 SDValue N0 = N->getOperand(0); 2219 SDValue N1 = N->getOperand(1); 2220 EVT VT = N->getValueType(0); 2221 2222 // fold vector ops 2223 if (VT.isVector()) 2224 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2225 return FoldedVOp; 2226 2227 SDLoc DL(N); 2228 2229 // fold (sdiv c1, c2) -> c1/c2 2230 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2231 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2232 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2233 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2234 // fold (sdiv X, 1) -> X 2235 if (N1C && N1C->isOne()) 2236 return N0; 2237 // fold (sdiv X, -1) -> 0-X 2238 if (N1C && N1C->isAllOnesValue()) 2239 return DAG.getNode(ISD::SUB, DL, VT, 2240 DAG.getConstant(0, DL, VT), N0); 2241 2242 // If we know the sign bits of both operands are zero, strength reduce to a 2243 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2244 if (!VT.isVector()) { 2245 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2246 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2247 } 2248 2249 // fold (sdiv X, pow2) -> simple ops after legalize 2250 // FIXME: We check for the exact bit here because the generic lowering gives 2251 // better results in that case. The target-specific lowering should learn how 2252 // to handle exact sdivs efficiently. 2253 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2254 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2255 (N1C->getAPIntValue().isPowerOf2() || 2256 (-N1C->getAPIntValue()).isPowerOf2())) { 2257 // Target-specific implementation of sdiv x, pow2. 2258 if (SDValue Res = BuildSDIVPow2(N)) 2259 return Res; 2260 2261 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2262 2263 // Splat the sign bit into the register 2264 SDValue SGN = 2265 DAG.getNode(ISD::SRA, DL, VT, N0, 2266 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2267 getShiftAmountTy(N0.getValueType()))); 2268 AddToWorklist(SGN.getNode()); 2269 2270 // Add (N0 < 0) ? abs2 - 1 : 0; 2271 SDValue SRL = 2272 DAG.getNode(ISD::SRL, DL, VT, SGN, 2273 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2274 getShiftAmountTy(SGN.getValueType()))); 2275 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2276 AddToWorklist(SRL.getNode()); 2277 AddToWorklist(ADD.getNode()); // Divide by pow2 2278 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2279 DAG.getConstant(lg2, DL, 2280 getShiftAmountTy(ADD.getValueType()))); 2281 2282 // If we're dividing by a positive value, we're done. Otherwise, we must 2283 // negate the result. 2284 if (N1C->getAPIntValue().isNonNegative()) 2285 return SRA; 2286 2287 AddToWorklist(SRA.getNode()); 2288 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2289 } 2290 2291 // If integer divide is expensive and we satisfy the requirements, emit an 2292 // alternate sequence. Targets may check function attributes for size/speed 2293 // trade-offs. 2294 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2295 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2296 if (SDValue Op = BuildSDIV(N)) 2297 return Op; 2298 2299 // sdiv, srem -> sdivrem 2300 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2301 // Otherwise, we break the simplification logic in visitREM(). 2302 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2303 if (SDValue DivRem = useDivRem(N)) 2304 return DivRem; 2305 2306 // undef / X -> 0 2307 if (N0.getOpcode() == ISD::UNDEF) 2308 return DAG.getConstant(0, DL, VT); 2309 // X / undef -> undef 2310 if (N1.getOpcode() == ISD::UNDEF) 2311 return N1; 2312 2313 return SDValue(); 2314 } 2315 2316 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2317 SDValue N0 = N->getOperand(0); 2318 SDValue N1 = N->getOperand(1); 2319 EVT VT = N->getValueType(0); 2320 2321 // fold vector ops 2322 if (VT.isVector()) 2323 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2324 return FoldedVOp; 2325 2326 SDLoc DL(N); 2327 2328 // fold (udiv c1, c2) -> c1/c2 2329 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2330 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2331 if (N0C && N1C) 2332 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2333 N0C, N1C)) 2334 return Folded; 2335 // fold (udiv x, (1 << c)) -> x >>u c 2336 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2337 return DAG.getNode(ISD::SRL, DL, VT, N0, 2338 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2339 getShiftAmountTy(N0.getValueType()))); 2340 2341 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2342 if (N1.getOpcode() == ISD::SHL) { 2343 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2344 if (SHC->getAPIntValue().isPowerOf2()) { 2345 EVT ADDVT = N1.getOperand(1).getValueType(); 2346 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2347 N1.getOperand(1), 2348 DAG.getConstant(SHC->getAPIntValue() 2349 .logBase2(), 2350 DL, ADDVT)); 2351 AddToWorklist(Add.getNode()); 2352 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2353 } 2354 } 2355 } 2356 2357 // fold (udiv x, c) -> alternate 2358 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2359 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2360 if (SDValue Op = BuildUDIV(N)) 2361 return Op; 2362 2363 // sdiv, srem -> sdivrem 2364 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2365 // Otherwise, we break the simplification logic in visitREM(). 2366 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2367 if (SDValue DivRem = useDivRem(N)) 2368 return DivRem; 2369 2370 // undef / X -> 0 2371 if (N0.getOpcode() == ISD::UNDEF) 2372 return DAG.getConstant(0, DL, VT); 2373 // X / undef -> undef 2374 if (N1.getOpcode() == ISD::UNDEF) 2375 return N1; 2376 2377 return SDValue(); 2378 } 2379 2380 // handles ISD::SREM and ISD::UREM 2381 SDValue DAGCombiner::visitREM(SDNode *N) { 2382 unsigned Opcode = N->getOpcode(); 2383 SDValue N0 = N->getOperand(0); 2384 SDValue N1 = N->getOperand(1); 2385 EVT VT = N->getValueType(0); 2386 bool isSigned = (Opcode == ISD::SREM); 2387 SDLoc DL(N); 2388 2389 // fold (rem c1, c2) -> c1%c2 2390 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2391 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2392 if (N0C && N1C) 2393 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2394 return Folded; 2395 2396 if (isSigned) { 2397 // If we know the sign bits of both operands are zero, strength reduce to a 2398 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2399 if (!VT.isVector()) { 2400 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2401 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2402 } 2403 } else { 2404 // fold (urem x, pow2) -> (and x, pow2-1) 2405 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2406 N1C->getAPIntValue().isPowerOf2()) { 2407 return DAG.getNode(ISD::AND, DL, VT, N0, 2408 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2409 } 2410 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2411 if (N1.getOpcode() == ISD::SHL) { 2412 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2413 if (SHC->getAPIntValue().isPowerOf2()) { 2414 SDValue Add = 2415 DAG.getNode(ISD::ADD, DL, VT, N1, 2416 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2417 VT)); 2418 AddToWorklist(Add.getNode()); 2419 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2420 } 2421 } 2422 } 2423 } 2424 2425 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2426 2427 // If X/C can be simplified by the division-by-constant logic, lower 2428 // X%C to the equivalent of X-X/C*C. 2429 // To avoid mangling nodes, this simplification requires that the combine() 2430 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2431 // against this by skipping the simplification if isIntDivCheap(). When 2432 // div is not cheap, combine will not return a DIVREM. Regardless, 2433 // checking cheapness here makes sense since the simplification results in 2434 // fatter code. 2435 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2436 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2437 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2438 AddToWorklist(Div.getNode()); 2439 SDValue OptimizedDiv = combine(Div.getNode()); 2440 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2441 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2442 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2443 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2444 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2445 AddToWorklist(Mul.getNode()); 2446 return Sub; 2447 } 2448 } 2449 2450 // sdiv, srem -> sdivrem 2451 if (SDValue DivRem = useDivRem(N)) 2452 return DivRem.getValue(1); 2453 2454 // undef % X -> 0 2455 if (N0.getOpcode() == ISD::UNDEF) 2456 return DAG.getConstant(0, DL, VT); 2457 // X % undef -> undef 2458 if (N1.getOpcode() == ISD::UNDEF) 2459 return N1; 2460 2461 return SDValue(); 2462 } 2463 2464 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2465 SDValue N0 = N->getOperand(0); 2466 SDValue N1 = N->getOperand(1); 2467 EVT VT = N->getValueType(0); 2468 SDLoc DL(N); 2469 2470 // fold (mulhs x, 0) -> 0 2471 if (isNullConstant(N1)) 2472 return N1; 2473 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2474 if (isOneConstant(N1)) { 2475 SDLoc DL(N); 2476 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2477 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2478 DL, 2479 getShiftAmountTy(N0.getValueType()))); 2480 } 2481 // fold (mulhs x, undef) -> 0 2482 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2483 return DAG.getConstant(0, SDLoc(N), VT); 2484 2485 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2486 // plus a shift. 2487 if (VT.isSimple() && !VT.isVector()) { 2488 MVT Simple = VT.getSimpleVT(); 2489 unsigned SimpleSize = Simple.getSizeInBits(); 2490 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2491 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2492 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2493 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2494 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2495 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2496 DAG.getConstant(SimpleSize, DL, 2497 getShiftAmountTy(N1.getValueType()))); 2498 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2499 } 2500 } 2501 2502 return SDValue(); 2503 } 2504 2505 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2506 SDValue N0 = N->getOperand(0); 2507 SDValue N1 = N->getOperand(1); 2508 EVT VT = N->getValueType(0); 2509 SDLoc DL(N); 2510 2511 // fold (mulhu x, 0) -> 0 2512 if (isNullConstant(N1)) 2513 return N1; 2514 // fold (mulhu x, 1) -> 0 2515 if (isOneConstant(N1)) 2516 return DAG.getConstant(0, DL, N0.getValueType()); 2517 // fold (mulhu x, undef) -> 0 2518 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2519 return DAG.getConstant(0, DL, VT); 2520 2521 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2522 // plus a shift. 2523 if (VT.isSimple() && !VT.isVector()) { 2524 MVT Simple = VT.getSimpleVT(); 2525 unsigned SimpleSize = Simple.getSizeInBits(); 2526 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2527 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2528 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2529 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2530 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2531 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2532 DAG.getConstant(SimpleSize, DL, 2533 getShiftAmountTy(N1.getValueType()))); 2534 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2535 } 2536 } 2537 2538 return SDValue(); 2539 } 2540 2541 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2542 /// give the opcodes for the two computations that are being performed. Return 2543 /// true if a simplification was made. 2544 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2545 unsigned HiOp) { 2546 // If the high half is not needed, just compute the low half. 2547 bool HiExists = N->hasAnyUseOfValue(1); 2548 if (!HiExists && 2549 (!LegalOperations || 2550 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2551 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2552 return CombineTo(N, Res, Res); 2553 } 2554 2555 // If the low half is not needed, just compute the high half. 2556 bool LoExists = N->hasAnyUseOfValue(0); 2557 if (!LoExists && 2558 (!LegalOperations || 2559 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2560 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2561 return CombineTo(N, Res, Res); 2562 } 2563 2564 // If both halves are used, return as it is. 2565 if (LoExists && HiExists) 2566 return SDValue(); 2567 2568 // If the two computed results can be simplified separately, separate them. 2569 if (LoExists) { 2570 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2571 AddToWorklist(Lo.getNode()); 2572 SDValue LoOpt = combine(Lo.getNode()); 2573 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2574 (!LegalOperations || 2575 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2576 return CombineTo(N, LoOpt, LoOpt); 2577 } 2578 2579 if (HiExists) { 2580 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2581 AddToWorklist(Hi.getNode()); 2582 SDValue HiOpt = combine(Hi.getNode()); 2583 if (HiOpt.getNode() && HiOpt != Hi && 2584 (!LegalOperations || 2585 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2586 return CombineTo(N, HiOpt, HiOpt); 2587 } 2588 2589 return SDValue(); 2590 } 2591 2592 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2593 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2594 return Res; 2595 2596 EVT VT = N->getValueType(0); 2597 SDLoc DL(N); 2598 2599 // If the type is twice as wide is legal, transform the mulhu to a wider 2600 // multiply plus a shift. 2601 if (VT.isSimple() && !VT.isVector()) { 2602 MVT Simple = VT.getSimpleVT(); 2603 unsigned SimpleSize = Simple.getSizeInBits(); 2604 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2605 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2606 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2607 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2608 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2609 // Compute the high part as N1. 2610 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2611 DAG.getConstant(SimpleSize, DL, 2612 getShiftAmountTy(Lo.getValueType()))); 2613 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2614 // Compute the low part as N0. 2615 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2616 return CombineTo(N, Lo, Hi); 2617 } 2618 } 2619 2620 return SDValue(); 2621 } 2622 2623 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2624 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2625 return Res; 2626 2627 EVT VT = N->getValueType(0); 2628 SDLoc DL(N); 2629 2630 // If the type is twice as wide is legal, transform the mulhu to a wider 2631 // multiply plus a shift. 2632 if (VT.isSimple() && !VT.isVector()) { 2633 MVT Simple = VT.getSimpleVT(); 2634 unsigned SimpleSize = Simple.getSizeInBits(); 2635 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2636 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2637 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2638 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2639 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2640 // Compute the high part as N1. 2641 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2642 DAG.getConstant(SimpleSize, DL, 2643 getShiftAmountTy(Lo.getValueType()))); 2644 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2645 // Compute the low part as N0. 2646 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2647 return CombineTo(N, Lo, Hi); 2648 } 2649 } 2650 2651 return SDValue(); 2652 } 2653 2654 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2655 // (smulo x, 2) -> (saddo x, x) 2656 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2657 if (C2->getAPIntValue() == 2) 2658 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2659 N->getOperand(0), N->getOperand(0)); 2660 2661 return SDValue(); 2662 } 2663 2664 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2665 // (umulo x, 2) -> (uaddo x, x) 2666 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2667 if (C2->getAPIntValue() == 2) 2668 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2669 N->getOperand(0), N->getOperand(0)); 2670 2671 return SDValue(); 2672 } 2673 2674 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2675 SDValue N0 = N->getOperand(0); 2676 SDValue N1 = N->getOperand(1); 2677 EVT VT = N0.getValueType(); 2678 2679 // fold vector ops 2680 if (VT.isVector()) 2681 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2682 return FoldedVOp; 2683 2684 // fold (add c1, c2) -> c1+c2 2685 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2686 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2687 if (N0C && N1C) 2688 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2689 2690 // canonicalize constant to RHS 2691 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2692 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2693 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2694 2695 return SDValue(); 2696 } 2697 2698 /// If this is a binary operator with two operands of the same opcode, try to 2699 /// simplify it. 2700 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2701 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2702 EVT VT = N0.getValueType(); 2703 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2704 2705 // Bail early if none of these transforms apply. 2706 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2707 2708 // For each of OP in AND/OR/XOR: 2709 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2710 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2711 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2712 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2713 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2714 // 2715 // do not sink logical op inside of a vector extend, since it may combine 2716 // into a vsetcc. 2717 EVT Op0VT = N0.getOperand(0).getValueType(); 2718 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2719 N0.getOpcode() == ISD::SIGN_EXTEND || 2720 N0.getOpcode() == ISD::BSWAP || 2721 // Avoid infinite looping with PromoteIntBinOp. 2722 (N0.getOpcode() == ISD::ANY_EXTEND && 2723 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2724 (N0.getOpcode() == ISD::TRUNCATE && 2725 (!TLI.isZExtFree(VT, Op0VT) || 2726 !TLI.isTruncateFree(Op0VT, VT)) && 2727 TLI.isTypeLegal(Op0VT))) && 2728 !VT.isVector() && 2729 Op0VT == N1.getOperand(0).getValueType() && 2730 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2731 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2732 N0.getOperand(0).getValueType(), 2733 N0.getOperand(0), N1.getOperand(0)); 2734 AddToWorklist(ORNode.getNode()); 2735 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2736 } 2737 2738 // For each of OP in SHL/SRL/SRA/AND... 2739 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2740 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2741 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2742 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2743 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2744 N0.getOperand(1) == N1.getOperand(1)) { 2745 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2746 N0.getOperand(0).getValueType(), 2747 N0.getOperand(0), N1.getOperand(0)); 2748 AddToWorklist(ORNode.getNode()); 2749 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2750 ORNode, N0.getOperand(1)); 2751 } 2752 2753 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2754 // Only perform this optimization after type legalization and before 2755 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2756 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2757 // we don't want to undo this promotion. 2758 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2759 // on scalars. 2760 if ((N0.getOpcode() == ISD::BITCAST || 2761 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2762 Level == AfterLegalizeTypes) { 2763 SDValue In0 = N0.getOperand(0); 2764 SDValue In1 = N1.getOperand(0); 2765 EVT In0Ty = In0.getValueType(); 2766 EVT In1Ty = In1.getValueType(); 2767 SDLoc DL(N); 2768 // If both incoming values are integers, and the original types are the 2769 // same. 2770 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2771 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2772 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2773 AddToWorklist(Op.getNode()); 2774 return BC; 2775 } 2776 } 2777 2778 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2779 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2780 // If both shuffles use the same mask, and both shuffle within a single 2781 // vector, then it is worthwhile to move the swizzle after the operation. 2782 // The type-legalizer generates this pattern when loading illegal 2783 // vector types from memory. In many cases this allows additional shuffle 2784 // optimizations. 2785 // There are other cases where moving the shuffle after the xor/and/or 2786 // is profitable even if shuffles don't perform a swizzle. 2787 // If both shuffles use the same mask, and both shuffles have the same first 2788 // or second operand, then it might still be profitable to move the shuffle 2789 // after the xor/and/or operation. 2790 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2791 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2792 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2793 2794 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2795 "Inputs to shuffles are not the same type"); 2796 2797 // Check that both shuffles use the same mask. The masks are known to be of 2798 // the same length because the result vector type is the same. 2799 // Check also that shuffles have only one use to avoid introducing extra 2800 // instructions. 2801 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2802 SVN0->getMask().equals(SVN1->getMask())) { 2803 SDValue ShOp = N0->getOperand(1); 2804 2805 // Don't try to fold this node if it requires introducing a 2806 // build vector of all zeros that might be illegal at this stage. 2807 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2808 if (!LegalTypes) 2809 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2810 else 2811 ShOp = SDValue(); 2812 } 2813 2814 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2815 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2816 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2817 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2818 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2819 N0->getOperand(0), N1->getOperand(0)); 2820 AddToWorklist(NewNode.getNode()); 2821 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2822 &SVN0->getMask()[0]); 2823 } 2824 2825 // Don't try to fold this node if it requires introducing a 2826 // build vector of all zeros that might be illegal at this stage. 2827 ShOp = N0->getOperand(0); 2828 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2829 if (!LegalTypes) 2830 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2831 else 2832 ShOp = SDValue(); 2833 } 2834 2835 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2836 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2837 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2838 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2839 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2840 N0->getOperand(1), N1->getOperand(1)); 2841 AddToWorklist(NewNode.getNode()); 2842 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2843 &SVN0->getMask()[0]); 2844 } 2845 } 2846 } 2847 2848 return SDValue(); 2849 } 2850 2851 /// This contains all DAGCombine rules which reduce two values combined by 2852 /// an And operation to a single value. This makes them reusable in the context 2853 /// of visitSELECT(). Rules involving constants are not included as 2854 /// visitSELECT() already handles those cases. 2855 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2856 SDNode *LocReference) { 2857 EVT VT = N1.getValueType(); 2858 2859 // fold (and x, undef) -> 0 2860 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2861 return DAG.getConstant(0, SDLoc(LocReference), VT); 2862 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2863 SDValue LL, LR, RL, RR, CC0, CC1; 2864 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2865 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2866 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2867 2868 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2869 LL.getValueType().isInteger()) { 2870 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2871 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2872 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2873 LR.getValueType(), LL, RL); 2874 AddToWorklist(ORNode.getNode()); 2875 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2876 } 2877 if (isAllOnesConstant(LR)) { 2878 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2879 if (Op1 == ISD::SETEQ) { 2880 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2881 LR.getValueType(), LL, RL); 2882 AddToWorklist(ANDNode.getNode()); 2883 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2884 } 2885 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2886 if (Op1 == ISD::SETGT) { 2887 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2888 LR.getValueType(), LL, RL); 2889 AddToWorklist(ORNode.getNode()); 2890 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2891 } 2892 } 2893 } 2894 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2895 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2896 Op0 == Op1 && LL.getValueType().isInteger() && 2897 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2898 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2899 SDLoc DL(N0); 2900 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2901 LL, DAG.getConstant(1, DL, 2902 LL.getValueType())); 2903 AddToWorklist(ADDNode.getNode()); 2904 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2905 DAG.getConstant(2, DL, LL.getValueType()), 2906 ISD::SETUGE); 2907 } 2908 // canonicalize equivalent to ll == rl 2909 if (LL == RR && LR == RL) { 2910 Op1 = ISD::getSetCCSwappedOperands(Op1); 2911 std::swap(RL, RR); 2912 } 2913 if (LL == RL && LR == RR) { 2914 bool isInteger = LL.getValueType().isInteger(); 2915 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2916 if (Result != ISD::SETCC_INVALID && 2917 (!LegalOperations || 2918 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2919 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2920 EVT CCVT = getSetCCResultType(LL.getValueType()); 2921 if (N0.getValueType() == CCVT || 2922 (!LegalOperations && N0.getValueType() == MVT::i1)) 2923 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2924 LL, LR, Result); 2925 } 2926 } 2927 } 2928 2929 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2930 VT.getSizeInBits() <= 64) { 2931 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2932 APInt ADDC = ADDI->getAPIntValue(); 2933 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2934 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2935 // immediate for an add, but it is legal if its top c2 bits are set, 2936 // transform the ADD so the immediate doesn't need to be materialized 2937 // in a register. 2938 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2939 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2940 SRLI->getZExtValue()); 2941 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2942 ADDC |= Mask; 2943 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2944 SDLoc DL(N0); 2945 SDValue NewAdd = 2946 DAG.getNode(ISD::ADD, DL, VT, 2947 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2948 CombineTo(N0.getNode(), NewAdd); 2949 // Return N so it doesn't get rechecked! 2950 return SDValue(LocReference, 0); 2951 } 2952 } 2953 } 2954 } 2955 } 2956 } 2957 2958 return SDValue(); 2959 } 2960 2961 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 2962 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 2963 bool &NarrowLoad) { 2964 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 2965 2966 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 2967 return false; 2968 2969 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2970 LoadedVT = LoadN->getMemoryVT(); 2971 2972 if (ExtVT == LoadedVT && 2973 (!LegalOperations || 2974 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 2975 // ZEXTLOAD will match without needing to change the size of the value being 2976 // loaded. 2977 NarrowLoad = false; 2978 return true; 2979 } 2980 2981 // Do not change the width of a volatile load. 2982 if (LoadN->isVolatile()) 2983 return false; 2984 2985 // Do not generate loads of non-round integer types since these can 2986 // be expensive (and would be wrong if the type is not byte sized). 2987 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 2988 return false; 2989 2990 if (LegalOperations && 2991 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 2992 return false; 2993 2994 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 2995 return false; 2996 2997 NarrowLoad = true; 2998 return true; 2999 } 3000 3001 SDValue DAGCombiner::visitAND(SDNode *N) { 3002 SDValue N0 = N->getOperand(0); 3003 SDValue N1 = N->getOperand(1); 3004 EVT VT = N1.getValueType(); 3005 3006 // fold vector ops 3007 if (VT.isVector()) { 3008 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3009 return FoldedVOp; 3010 3011 // fold (and x, 0) -> 0, vector edition 3012 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3013 // do not return N0, because undef node may exist in N0 3014 return DAG.getConstant( 3015 APInt::getNullValue( 3016 N0.getValueType().getScalarType().getSizeInBits()), 3017 SDLoc(N), N0.getValueType()); 3018 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3019 // do not return N1, because undef node may exist in N1 3020 return DAG.getConstant( 3021 APInt::getNullValue( 3022 N1.getValueType().getScalarType().getSizeInBits()), 3023 SDLoc(N), N1.getValueType()); 3024 3025 // fold (and x, -1) -> x, vector edition 3026 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3027 return N1; 3028 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3029 return N0; 3030 } 3031 3032 // fold (and c1, c2) -> c1&c2 3033 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3034 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3035 if (N0C && N1C && !N1C->isOpaque()) 3036 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3037 // canonicalize constant to RHS 3038 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3039 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3040 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3041 // fold (and x, -1) -> x 3042 if (isAllOnesConstant(N1)) 3043 return N0; 3044 // if (and x, c) is known to be zero, return 0 3045 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3046 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3047 APInt::getAllOnesValue(BitWidth))) 3048 return DAG.getConstant(0, SDLoc(N), VT); 3049 // reassociate and 3050 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3051 return RAND; 3052 // fold (and (or x, C), D) -> D if (C & D) == D 3053 if (N1C && N0.getOpcode() == ISD::OR) 3054 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3055 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3056 return N1; 3057 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3058 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3059 SDValue N0Op0 = N0.getOperand(0); 3060 APInt Mask = ~N1C->getAPIntValue(); 3061 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3062 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3063 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3064 N0.getValueType(), N0Op0); 3065 3066 // Replace uses of the AND with uses of the Zero extend node. 3067 CombineTo(N, Zext); 3068 3069 // We actually want to replace all uses of the any_extend with the 3070 // zero_extend, to avoid duplicating things. This will later cause this 3071 // AND to be folded. 3072 CombineTo(N0.getNode(), Zext); 3073 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3074 } 3075 } 3076 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3077 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3078 // already be zero by virtue of the width of the base type of the load. 3079 // 3080 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3081 // more cases. 3082 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3083 N0.getOperand(0).getOpcode() == ISD::LOAD) || 3084 N0.getOpcode() == ISD::LOAD) { 3085 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3086 N0 : N0.getOperand(0) ); 3087 3088 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3089 // This can be a pure constant or a vector splat, in which case we treat the 3090 // vector as a scalar and use the splat value. 3091 APInt Constant = APInt::getNullValue(1); 3092 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3093 Constant = C->getAPIntValue(); 3094 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3095 APInt SplatValue, SplatUndef; 3096 unsigned SplatBitSize; 3097 bool HasAnyUndefs; 3098 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3099 SplatBitSize, HasAnyUndefs); 3100 if (IsSplat) { 3101 // Undef bits can contribute to a possible optimisation if set, so 3102 // set them. 3103 SplatValue |= SplatUndef; 3104 3105 // The splat value may be something like "0x00FFFFFF", which means 0 for 3106 // the first vector value and FF for the rest, repeating. We need a mask 3107 // that will apply equally to all members of the vector, so AND all the 3108 // lanes of the constant together. 3109 EVT VT = Vector->getValueType(0); 3110 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3111 3112 // If the splat value has been compressed to a bitlength lower 3113 // than the size of the vector lane, we need to re-expand it to 3114 // the lane size. 3115 if (BitWidth > SplatBitSize) 3116 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3117 SplatBitSize < BitWidth; 3118 SplatBitSize = SplatBitSize * 2) 3119 SplatValue |= SplatValue.shl(SplatBitSize); 3120 3121 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3122 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3123 if (SplatBitSize % BitWidth == 0) { 3124 Constant = APInt::getAllOnesValue(BitWidth); 3125 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3126 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3127 } 3128 } 3129 } 3130 3131 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3132 // actually legal and isn't going to get expanded, else this is a false 3133 // optimisation. 3134 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3135 Load->getValueType(0), 3136 Load->getMemoryVT()); 3137 3138 // Resize the constant to the same size as the original memory access before 3139 // extension. If it is still the AllOnesValue then this AND is completely 3140 // unneeded. 3141 Constant = 3142 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3143 3144 bool B; 3145 switch (Load->getExtensionType()) { 3146 default: B = false; break; 3147 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3148 case ISD::ZEXTLOAD: 3149 case ISD::NON_EXTLOAD: B = true; break; 3150 } 3151 3152 if (B && Constant.isAllOnesValue()) { 3153 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3154 // preserve semantics once we get rid of the AND. 3155 SDValue NewLoad(Load, 0); 3156 if (Load->getExtensionType() == ISD::EXTLOAD) { 3157 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3158 Load->getValueType(0), SDLoc(Load), 3159 Load->getChain(), Load->getBasePtr(), 3160 Load->getOffset(), Load->getMemoryVT(), 3161 Load->getMemOperand()); 3162 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3163 if (Load->getNumValues() == 3) { 3164 // PRE/POST_INC loads have 3 values. 3165 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3166 NewLoad.getValue(2) }; 3167 CombineTo(Load, To, 3, true); 3168 } else { 3169 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3170 } 3171 } 3172 3173 // Fold the AND away, taking care not to fold to the old load node if we 3174 // replaced it. 3175 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3176 3177 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3178 } 3179 } 3180 3181 // fold (and (load x), 255) -> (zextload x, i8) 3182 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3183 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3184 if (N1C && (N0.getOpcode() == ISD::LOAD || 3185 (N0.getOpcode() == ISD::ANY_EXTEND && 3186 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3187 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3188 LoadSDNode *LN0 = HasAnyExt 3189 ? cast<LoadSDNode>(N0.getOperand(0)) 3190 : cast<LoadSDNode>(N0); 3191 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3192 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3193 auto NarrowLoad = false; 3194 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3195 EVT ExtVT, LoadedVT; 3196 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3197 NarrowLoad)) { 3198 if (!NarrowLoad) { 3199 SDValue NewLoad = 3200 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3201 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3202 LN0->getMemOperand()); 3203 AddToWorklist(N); 3204 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3205 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3206 } else { 3207 EVT PtrType = LN0->getOperand(1).getValueType(); 3208 3209 unsigned Alignment = LN0->getAlignment(); 3210 SDValue NewPtr = LN0->getBasePtr(); 3211 3212 // For big endian targets, we need to add an offset to the pointer 3213 // to load the correct bytes. For little endian systems, we merely 3214 // need to read fewer bytes from the same pointer. 3215 if (DAG.getDataLayout().isBigEndian()) { 3216 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3217 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3218 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3219 SDLoc DL(LN0); 3220 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3221 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3222 Alignment = MinAlign(Alignment, PtrOff); 3223 } 3224 3225 AddToWorklist(NewPtr.getNode()); 3226 3227 SDValue Load = 3228 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3229 LN0->getChain(), NewPtr, 3230 LN0->getPointerInfo(), 3231 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3232 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3233 AddToWorklist(N); 3234 CombineTo(LN0, Load, Load.getValue(1)); 3235 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3236 } 3237 } 3238 } 3239 } 3240 3241 if (SDValue Combined = visitANDLike(N0, N1, N)) 3242 return Combined; 3243 3244 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3245 if (N0.getOpcode() == N1.getOpcode()) 3246 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3247 return Tmp; 3248 3249 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3250 // fold (and (sra)) -> (and (srl)) when possible. 3251 if (!VT.isVector() && 3252 SimplifyDemandedBits(SDValue(N, 0))) 3253 return SDValue(N, 0); 3254 3255 // fold (zext_inreg (extload x)) -> (zextload x) 3256 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3257 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3258 EVT MemVT = LN0->getMemoryVT(); 3259 // If we zero all the possible extended bits, then we can turn this into 3260 // a zextload if we are running before legalize or the operation is legal. 3261 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3262 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3263 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3264 ((!LegalOperations && !LN0->isVolatile()) || 3265 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3266 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3267 LN0->getChain(), LN0->getBasePtr(), 3268 MemVT, LN0->getMemOperand()); 3269 AddToWorklist(N); 3270 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3271 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3272 } 3273 } 3274 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3275 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3276 N0.hasOneUse()) { 3277 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3278 EVT MemVT = LN0->getMemoryVT(); 3279 // If we zero all the possible extended bits, then we can turn this into 3280 // a zextload if we are running before legalize or the operation is legal. 3281 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3282 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3283 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3284 ((!LegalOperations && !LN0->isVolatile()) || 3285 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3286 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3287 LN0->getChain(), LN0->getBasePtr(), 3288 MemVT, LN0->getMemOperand()); 3289 AddToWorklist(N); 3290 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3291 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3292 } 3293 } 3294 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3295 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3296 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3297 N0.getOperand(1), false); 3298 if (BSwap.getNode()) 3299 return BSwap; 3300 } 3301 3302 return SDValue(); 3303 } 3304 3305 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3306 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3307 bool DemandHighBits) { 3308 if (!LegalOperations) 3309 return SDValue(); 3310 3311 EVT VT = N->getValueType(0); 3312 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3313 return SDValue(); 3314 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3315 return SDValue(); 3316 3317 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3318 bool LookPassAnd0 = false; 3319 bool LookPassAnd1 = false; 3320 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3321 std::swap(N0, N1); 3322 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3323 std::swap(N0, N1); 3324 if (N0.getOpcode() == ISD::AND) { 3325 if (!N0.getNode()->hasOneUse()) 3326 return SDValue(); 3327 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3328 if (!N01C || N01C->getZExtValue() != 0xFF00) 3329 return SDValue(); 3330 N0 = N0.getOperand(0); 3331 LookPassAnd0 = true; 3332 } 3333 3334 if (N1.getOpcode() == ISD::AND) { 3335 if (!N1.getNode()->hasOneUse()) 3336 return SDValue(); 3337 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3338 if (!N11C || N11C->getZExtValue() != 0xFF) 3339 return SDValue(); 3340 N1 = N1.getOperand(0); 3341 LookPassAnd1 = true; 3342 } 3343 3344 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3345 std::swap(N0, N1); 3346 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3347 return SDValue(); 3348 if (!N0.getNode()->hasOneUse() || 3349 !N1.getNode()->hasOneUse()) 3350 return SDValue(); 3351 3352 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3353 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3354 if (!N01C || !N11C) 3355 return SDValue(); 3356 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3357 return SDValue(); 3358 3359 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3360 SDValue N00 = N0->getOperand(0); 3361 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3362 if (!N00.getNode()->hasOneUse()) 3363 return SDValue(); 3364 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3365 if (!N001C || N001C->getZExtValue() != 0xFF) 3366 return SDValue(); 3367 N00 = N00.getOperand(0); 3368 LookPassAnd0 = true; 3369 } 3370 3371 SDValue N10 = N1->getOperand(0); 3372 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3373 if (!N10.getNode()->hasOneUse()) 3374 return SDValue(); 3375 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3376 if (!N101C || N101C->getZExtValue() != 0xFF00) 3377 return SDValue(); 3378 N10 = N10.getOperand(0); 3379 LookPassAnd1 = true; 3380 } 3381 3382 if (N00 != N10) 3383 return SDValue(); 3384 3385 // Make sure everything beyond the low halfword gets set to zero since the SRL 3386 // 16 will clear the top bits. 3387 unsigned OpSizeInBits = VT.getSizeInBits(); 3388 if (DemandHighBits && OpSizeInBits > 16) { 3389 // If the left-shift isn't masked out then the only way this is a bswap is 3390 // if all bits beyond the low 8 are 0. In that case the entire pattern 3391 // reduces to a left shift anyway: leave it for other parts of the combiner. 3392 if (!LookPassAnd0) 3393 return SDValue(); 3394 3395 // However, if the right shift isn't masked out then it might be because 3396 // it's not needed. See if we can spot that too. 3397 if (!LookPassAnd1 && 3398 !DAG.MaskedValueIsZero( 3399 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3400 return SDValue(); 3401 } 3402 3403 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3404 if (OpSizeInBits > 16) { 3405 SDLoc DL(N); 3406 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3407 DAG.getConstant(OpSizeInBits - 16, DL, 3408 getShiftAmountTy(VT))); 3409 } 3410 return Res; 3411 } 3412 3413 /// Return true if the specified node is an element that makes up a 32-bit 3414 /// packed halfword byteswap. 3415 /// ((x & 0x000000ff) << 8) | 3416 /// ((x & 0x0000ff00) >> 8) | 3417 /// ((x & 0x00ff0000) << 8) | 3418 /// ((x & 0xff000000) >> 8) 3419 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3420 if (!N.getNode()->hasOneUse()) 3421 return false; 3422 3423 unsigned Opc = N.getOpcode(); 3424 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3425 return false; 3426 3427 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3428 if (!N1C) 3429 return false; 3430 3431 unsigned Num; 3432 switch (N1C->getZExtValue()) { 3433 default: 3434 return false; 3435 case 0xFF: Num = 0; break; 3436 case 0xFF00: Num = 1; break; 3437 case 0xFF0000: Num = 2; break; 3438 case 0xFF000000: Num = 3; break; 3439 } 3440 3441 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3442 SDValue N0 = N.getOperand(0); 3443 if (Opc == ISD::AND) { 3444 if (Num == 0 || Num == 2) { 3445 // (x >> 8) & 0xff 3446 // (x >> 8) & 0xff0000 3447 if (N0.getOpcode() != ISD::SRL) 3448 return false; 3449 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3450 if (!C || C->getZExtValue() != 8) 3451 return false; 3452 } else { 3453 // (x << 8) & 0xff00 3454 // (x << 8) & 0xff000000 3455 if (N0.getOpcode() != ISD::SHL) 3456 return false; 3457 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3458 if (!C || C->getZExtValue() != 8) 3459 return false; 3460 } 3461 } else if (Opc == ISD::SHL) { 3462 // (x & 0xff) << 8 3463 // (x & 0xff0000) << 8 3464 if (Num != 0 && Num != 2) 3465 return false; 3466 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3467 if (!C || C->getZExtValue() != 8) 3468 return false; 3469 } else { // Opc == ISD::SRL 3470 // (x & 0xff00) >> 8 3471 // (x & 0xff000000) >> 8 3472 if (Num != 1 && Num != 3) 3473 return false; 3474 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3475 if (!C || C->getZExtValue() != 8) 3476 return false; 3477 } 3478 3479 if (Parts[Num]) 3480 return false; 3481 3482 Parts[Num] = N0.getOperand(0).getNode(); 3483 return true; 3484 } 3485 3486 /// Match a 32-bit packed halfword bswap. That is 3487 /// ((x & 0x000000ff) << 8) | 3488 /// ((x & 0x0000ff00) >> 8) | 3489 /// ((x & 0x00ff0000) << 8) | 3490 /// ((x & 0xff000000) >> 8) 3491 /// => (rotl (bswap x), 16) 3492 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3493 if (!LegalOperations) 3494 return SDValue(); 3495 3496 EVT VT = N->getValueType(0); 3497 if (VT != MVT::i32) 3498 return SDValue(); 3499 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3500 return SDValue(); 3501 3502 // Look for either 3503 // (or (or (and), (and)), (or (and), (and))) 3504 // (or (or (or (and), (and)), (and)), (and)) 3505 if (N0.getOpcode() != ISD::OR) 3506 return SDValue(); 3507 SDValue N00 = N0.getOperand(0); 3508 SDValue N01 = N0.getOperand(1); 3509 SDNode *Parts[4] = {}; 3510 3511 if (N1.getOpcode() == ISD::OR && 3512 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3513 // (or (or (and), (and)), (or (and), (and))) 3514 SDValue N000 = N00.getOperand(0); 3515 if (!isBSwapHWordElement(N000, Parts)) 3516 return SDValue(); 3517 3518 SDValue N001 = N00.getOperand(1); 3519 if (!isBSwapHWordElement(N001, Parts)) 3520 return SDValue(); 3521 SDValue N010 = N01.getOperand(0); 3522 if (!isBSwapHWordElement(N010, Parts)) 3523 return SDValue(); 3524 SDValue N011 = N01.getOperand(1); 3525 if (!isBSwapHWordElement(N011, Parts)) 3526 return SDValue(); 3527 } else { 3528 // (or (or (or (and), (and)), (and)), (and)) 3529 if (!isBSwapHWordElement(N1, Parts)) 3530 return SDValue(); 3531 if (!isBSwapHWordElement(N01, Parts)) 3532 return SDValue(); 3533 if (N00.getOpcode() != ISD::OR) 3534 return SDValue(); 3535 SDValue N000 = N00.getOperand(0); 3536 if (!isBSwapHWordElement(N000, Parts)) 3537 return SDValue(); 3538 SDValue N001 = N00.getOperand(1); 3539 if (!isBSwapHWordElement(N001, Parts)) 3540 return SDValue(); 3541 } 3542 3543 // Make sure the parts are all coming from the same node. 3544 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3545 return SDValue(); 3546 3547 SDLoc DL(N); 3548 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3549 SDValue(Parts[0], 0)); 3550 3551 // Result of the bswap should be rotated by 16. If it's not legal, then 3552 // do (x << 16) | (x >> 16). 3553 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3554 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3555 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3556 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3557 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3558 return DAG.getNode(ISD::OR, DL, VT, 3559 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3560 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3561 } 3562 3563 /// This contains all DAGCombine rules which reduce two values combined by 3564 /// an Or operation to a single value \see visitANDLike(). 3565 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3566 EVT VT = N1.getValueType(); 3567 // fold (or x, undef) -> -1 3568 if (!LegalOperations && 3569 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3570 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3571 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3572 SDLoc(LocReference), VT); 3573 } 3574 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3575 SDValue LL, LR, RL, RR, CC0, CC1; 3576 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3577 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3578 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3579 3580 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3581 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3582 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3583 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3584 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3585 LR.getValueType(), LL, RL); 3586 AddToWorklist(ORNode.getNode()); 3587 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3588 } 3589 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3590 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3591 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3592 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3593 LR.getValueType(), LL, RL); 3594 AddToWorklist(ANDNode.getNode()); 3595 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3596 } 3597 } 3598 // canonicalize equivalent to ll == rl 3599 if (LL == RR && LR == RL) { 3600 Op1 = ISD::getSetCCSwappedOperands(Op1); 3601 std::swap(RL, RR); 3602 } 3603 if (LL == RL && LR == RR) { 3604 bool isInteger = LL.getValueType().isInteger(); 3605 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3606 if (Result != ISD::SETCC_INVALID && 3607 (!LegalOperations || 3608 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3609 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3610 EVT CCVT = getSetCCResultType(LL.getValueType()); 3611 if (N0.getValueType() == CCVT || 3612 (!LegalOperations && N0.getValueType() == MVT::i1)) 3613 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3614 LL, LR, Result); 3615 } 3616 } 3617 } 3618 3619 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3620 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3621 // Don't increase # computations. 3622 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3623 // We can only do this xform if we know that bits from X that are set in C2 3624 // but not in C1 are already zero. Likewise for Y. 3625 if (const ConstantSDNode *N0O1C = 3626 getAsNonOpaqueConstant(N0.getOperand(1))) { 3627 if (const ConstantSDNode *N1O1C = 3628 getAsNonOpaqueConstant(N1.getOperand(1))) { 3629 // We can only do this xform if we know that bits from X that are set in 3630 // C2 but not in C1 are already zero. Likewise for Y. 3631 const APInt &LHSMask = N0O1C->getAPIntValue(); 3632 const APInt &RHSMask = N1O1C->getAPIntValue(); 3633 3634 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3635 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3636 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3637 N0.getOperand(0), N1.getOperand(0)); 3638 SDLoc DL(LocReference); 3639 return DAG.getNode(ISD::AND, DL, VT, X, 3640 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3641 } 3642 } 3643 } 3644 } 3645 3646 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3647 if (N0.getOpcode() == ISD::AND && 3648 N1.getOpcode() == ISD::AND && 3649 N0.getOperand(0) == N1.getOperand(0) && 3650 // Don't increase # computations. 3651 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3652 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3653 N0.getOperand(1), N1.getOperand(1)); 3654 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3655 } 3656 3657 return SDValue(); 3658 } 3659 3660 SDValue DAGCombiner::visitOR(SDNode *N) { 3661 SDValue N0 = N->getOperand(0); 3662 SDValue N1 = N->getOperand(1); 3663 EVT VT = N1.getValueType(); 3664 3665 // fold vector ops 3666 if (VT.isVector()) { 3667 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3668 return FoldedVOp; 3669 3670 // fold (or x, 0) -> x, vector edition 3671 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3672 return N1; 3673 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3674 return N0; 3675 3676 // fold (or x, -1) -> -1, vector edition 3677 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3678 // do not return N0, because undef node may exist in N0 3679 return DAG.getConstant( 3680 APInt::getAllOnesValue( 3681 N0.getValueType().getScalarType().getSizeInBits()), 3682 SDLoc(N), N0.getValueType()); 3683 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3684 // do not return N1, because undef node may exist in N1 3685 return DAG.getConstant( 3686 APInt::getAllOnesValue( 3687 N1.getValueType().getScalarType().getSizeInBits()), 3688 SDLoc(N), N1.getValueType()); 3689 3690 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3691 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3692 // Do this only if the resulting shuffle is legal. 3693 if (isa<ShuffleVectorSDNode>(N0) && 3694 isa<ShuffleVectorSDNode>(N1) && 3695 // Avoid folding a node with illegal type. 3696 TLI.isTypeLegal(VT) && 3697 N0->getOperand(1) == N1->getOperand(1) && 3698 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3699 bool CanFold = true; 3700 unsigned NumElts = VT.getVectorNumElements(); 3701 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3702 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3703 // We construct two shuffle masks: 3704 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3705 // and N1 as the second operand. 3706 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3707 // and N0 as the second operand. 3708 // We do this because OR is commutable and therefore there might be 3709 // two ways to fold this node into a shuffle. 3710 SmallVector<int,4> Mask1; 3711 SmallVector<int,4> Mask2; 3712 3713 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3714 int M0 = SV0->getMaskElt(i); 3715 int M1 = SV1->getMaskElt(i); 3716 3717 // Both shuffle indexes are undef. Propagate Undef. 3718 if (M0 < 0 && M1 < 0) { 3719 Mask1.push_back(M0); 3720 Mask2.push_back(M0); 3721 continue; 3722 } 3723 3724 if (M0 < 0 || M1 < 0 || 3725 (M0 < (int)NumElts && M1 < (int)NumElts) || 3726 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3727 CanFold = false; 3728 break; 3729 } 3730 3731 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3732 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3733 } 3734 3735 if (CanFold) { 3736 // Fold this sequence only if the resulting shuffle is 'legal'. 3737 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3738 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3739 N1->getOperand(0), &Mask1[0]); 3740 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3741 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3742 N0->getOperand(0), &Mask2[0]); 3743 } 3744 } 3745 } 3746 3747 // fold (or c1, c2) -> c1|c2 3748 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3749 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3750 if (N0C && N1C && !N1C->isOpaque()) 3751 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3752 // canonicalize constant to RHS 3753 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3754 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3755 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3756 // fold (or x, 0) -> x 3757 if (isNullConstant(N1)) 3758 return N0; 3759 // fold (or x, -1) -> -1 3760 if (isAllOnesConstant(N1)) 3761 return N1; 3762 // fold (or x, c) -> c iff (x & ~c) == 0 3763 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3764 return N1; 3765 3766 if (SDValue Combined = visitORLike(N0, N1, N)) 3767 return Combined; 3768 3769 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3770 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3771 return BSwap; 3772 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3773 return BSwap; 3774 3775 // reassociate or 3776 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3777 return ROR; 3778 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3779 // iff (c1 & c2) == 0. 3780 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3781 isa<ConstantSDNode>(N0.getOperand(1))) { 3782 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3783 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3784 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3785 N1C, C1)) 3786 return DAG.getNode( 3787 ISD::AND, SDLoc(N), VT, 3788 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3789 return SDValue(); 3790 } 3791 } 3792 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3793 if (N0.getOpcode() == N1.getOpcode()) 3794 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3795 return Tmp; 3796 3797 // See if this is some rotate idiom. 3798 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3799 return SDValue(Rot, 0); 3800 3801 // Simplify the operands using demanded-bits information. 3802 if (!VT.isVector() && 3803 SimplifyDemandedBits(SDValue(N, 0))) 3804 return SDValue(N, 0); 3805 3806 return SDValue(); 3807 } 3808 3809 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3810 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3811 if (Op.getOpcode() == ISD::AND) { 3812 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3813 Mask = Op.getOperand(1); 3814 Op = Op.getOperand(0); 3815 } else { 3816 return false; 3817 } 3818 } 3819 3820 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3821 Shift = Op; 3822 return true; 3823 } 3824 3825 return false; 3826 } 3827 3828 // Return true if we can prove that, whenever Neg and Pos are both in the 3829 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3830 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3831 // 3832 // (or (shift1 X, Neg), (shift2 X, Pos)) 3833 // 3834 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3835 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3836 // to consider shift amounts with defined behavior. 3837 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3838 // If EltSize is a power of 2 then: 3839 // 3840 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3841 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3842 // 3843 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3844 // for the stronger condition: 3845 // 3846 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3847 // 3848 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3849 // we can just replace Neg with Neg' for the rest of the function. 3850 // 3851 // In other cases we check for the even stronger condition: 3852 // 3853 // Neg == EltSize - Pos [B] 3854 // 3855 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3856 // behavior if Pos == 0 (and consequently Neg == EltSize). 3857 // 3858 // We could actually use [A] whenever EltSize is a power of 2, but the 3859 // only extra cases that it would match are those uninteresting ones 3860 // where Neg and Pos are never in range at the same time. E.g. for 3861 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3862 // as well as (sub 32, Pos), but: 3863 // 3864 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3865 // 3866 // always invokes undefined behavior for 32-bit X. 3867 // 3868 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3869 unsigned MaskLoBits = 0; 3870 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3871 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3872 if (NegC->getAPIntValue() == EltSize - 1) { 3873 Neg = Neg.getOperand(0); 3874 MaskLoBits = Log2_64(EltSize); 3875 } 3876 } 3877 } 3878 3879 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3880 if (Neg.getOpcode() != ISD::SUB) 3881 return false; 3882 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3883 if (!NegC) 3884 return false; 3885 SDValue NegOp1 = Neg.getOperand(1); 3886 3887 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3888 // Pos'. The truncation is redundant for the purpose of the equality. 3889 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3890 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3891 if (PosC->getAPIntValue() == EltSize - 1) 3892 Pos = Pos.getOperand(0); 3893 3894 // The condition we need is now: 3895 // 3896 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3897 // 3898 // If NegOp1 == Pos then we need: 3899 // 3900 // EltSize & Mask == NegC & Mask 3901 // 3902 // (because "x & Mask" is a truncation and distributes through subtraction). 3903 APInt Width; 3904 if (Pos == NegOp1) 3905 Width = NegC->getAPIntValue(); 3906 3907 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3908 // Then the condition we want to prove becomes: 3909 // 3910 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3911 // 3912 // which, again because "x & Mask" is a truncation, becomes: 3913 // 3914 // NegC & Mask == (EltSize - PosC) & Mask 3915 // EltSize & Mask == (NegC + PosC) & Mask 3916 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3917 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3918 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3919 else 3920 return false; 3921 } else 3922 return false; 3923 3924 // Now we just need to check that EltSize & Mask == Width & Mask. 3925 if (MaskLoBits) 3926 // EltSize & Mask is 0 since Mask is EltSize - 1. 3927 return Width.getLoBits(MaskLoBits) == 0; 3928 return Width == EltSize; 3929 } 3930 3931 // A subroutine of MatchRotate used once we have found an OR of two opposite 3932 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3933 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3934 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3935 // Neg with outer conversions stripped away. 3936 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3937 SDValue Neg, SDValue InnerPos, 3938 SDValue InnerNeg, unsigned PosOpcode, 3939 unsigned NegOpcode, SDLoc DL) { 3940 // fold (or (shl x, (*ext y)), 3941 // (srl x, (*ext (sub 32, y)))) -> 3942 // (rotl x, y) or (rotr x, (sub 32, y)) 3943 // 3944 // fold (or (shl x, (*ext (sub 32, y))), 3945 // (srl x, (*ext y))) -> 3946 // (rotr x, y) or (rotl x, (sub 32, y)) 3947 EVT VT = Shifted.getValueType(); 3948 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 3949 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3950 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3951 HasPos ? Pos : Neg).getNode(); 3952 } 3953 3954 return nullptr; 3955 } 3956 3957 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3958 // idioms for rotate, and if the target supports rotation instructions, generate 3959 // a rot[lr]. 3960 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3961 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3962 EVT VT = LHS.getValueType(); 3963 if (!TLI.isTypeLegal(VT)) return nullptr; 3964 3965 // The target must have at least one rotate flavor. 3966 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3967 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3968 if (!HasROTL && !HasROTR) return nullptr; 3969 3970 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3971 SDValue LHSShift; // The shift. 3972 SDValue LHSMask; // AND value if any. 3973 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3974 return nullptr; // Not part of a rotate. 3975 3976 SDValue RHSShift; // The shift. 3977 SDValue RHSMask; // AND value if any. 3978 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3979 return nullptr; // Not part of a rotate. 3980 3981 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3982 return nullptr; // Not shifting the same value. 3983 3984 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3985 return nullptr; // Shifts must disagree. 3986 3987 // Canonicalize shl to left side in a shl/srl pair. 3988 if (RHSShift.getOpcode() == ISD::SHL) { 3989 std::swap(LHS, RHS); 3990 std::swap(LHSShift, RHSShift); 3991 std::swap(LHSMask, RHSMask); 3992 } 3993 3994 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 3995 SDValue LHSShiftArg = LHSShift.getOperand(0); 3996 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3997 SDValue RHSShiftArg = RHSShift.getOperand(0); 3998 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3999 4000 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4001 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4002 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4003 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4004 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4005 if ((LShVal + RShVal) != EltSizeInBits) 4006 return nullptr; 4007 4008 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4009 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4010 4011 // If there is an AND of either shifted operand, apply it to the result. 4012 if (LHSMask.getNode() || RHSMask.getNode()) { 4013 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4014 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4015 4016 if (LHSMask.getNode()) { 4017 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4018 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4019 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4020 DAG.getConstant(RHSBits, DL, VT))); 4021 } 4022 if (RHSMask.getNode()) { 4023 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4024 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4025 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4026 DAG.getConstant(LHSBits, DL, VT))); 4027 } 4028 4029 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4030 } 4031 4032 return Rot.getNode(); 4033 } 4034 4035 // If there is a mask here, and we have a variable shift, we can't be sure 4036 // that we're masking out the right stuff. 4037 if (LHSMask.getNode() || RHSMask.getNode()) 4038 return nullptr; 4039 4040 // If the shift amount is sign/zext/any-extended just peel it off. 4041 SDValue LExtOp0 = LHSShiftAmt; 4042 SDValue RExtOp0 = RHSShiftAmt; 4043 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4044 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4045 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4046 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4047 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4048 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4049 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4050 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4051 LExtOp0 = LHSShiftAmt.getOperand(0); 4052 RExtOp0 = RHSShiftAmt.getOperand(0); 4053 } 4054 4055 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4056 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4057 if (TryL) 4058 return TryL; 4059 4060 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4061 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4062 if (TryR) 4063 return TryR; 4064 4065 return nullptr; 4066 } 4067 4068 SDValue DAGCombiner::visitXOR(SDNode *N) { 4069 SDValue N0 = N->getOperand(0); 4070 SDValue N1 = N->getOperand(1); 4071 EVT VT = N0.getValueType(); 4072 4073 // fold vector ops 4074 if (VT.isVector()) { 4075 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4076 return FoldedVOp; 4077 4078 // fold (xor x, 0) -> x, vector edition 4079 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4080 return N1; 4081 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4082 return N0; 4083 } 4084 4085 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4086 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 4087 return DAG.getConstant(0, SDLoc(N), VT); 4088 // fold (xor x, undef) -> undef 4089 if (N0.getOpcode() == ISD::UNDEF) 4090 return N0; 4091 if (N1.getOpcode() == ISD::UNDEF) 4092 return N1; 4093 // fold (xor c1, c2) -> c1^c2 4094 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4095 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4096 if (N0C && N1C) 4097 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4098 // canonicalize constant to RHS 4099 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4100 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4101 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4102 // fold (xor x, 0) -> x 4103 if (isNullConstant(N1)) 4104 return N0; 4105 // reassociate xor 4106 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4107 return RXOR; 4108 4109 // fold !(x cc y) -> (x !cc y) 4110 SDValue LHS, RHS, CC; 4111 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4112 bool isInt = LHS.getValueType().isInteger(); 4113 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4114 isInt); 4115 4116 if (!LegalOperations || 4117 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4118 switch (N0.getOpcode()) { 4119 default: 4120 llvm_unreachable("Unhandled SetCC Equivalent!"); 4121 case ISD::SETCC: 4122 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4123 case ISD::SELECT_CC: 4124 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4125 N0.getOperand(3), NotCC); 4126 } 4127 } 4128 } 4129 4130 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4131 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4132 N0.getNode()->hasOneUse() && 4133 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4134 SDValue V = N0.getOperand(0); 4135 SDLoc DL(N0); 4136 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4137 DAG.getConstant(1, DL, V.getValueType())); 4138 AddToWorklist(V.getNode()); 4139 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4140 } 4141 4142 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4143 if (isOneConstant(N1) && VT == MVT::i1 && 4144 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4145 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4146 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4147 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4148 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4149 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4150 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4151 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4152 } 4153 } 4154 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4155 if (isAllOnesConstant(N1) && 4156 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4157 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4158 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4159 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4160 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4161 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4162 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4163 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4164 } 4165 } 4166 // fold (xor (and x, y), y) -> (and (not x), y) 4167 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4168 N0->getOperand(1) == N1) { 4169 SDValue X = N0->getOperand(0); 4170 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4171 AddToWorklist(NotX.getNode()); 4172 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4173 } 4174 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4175 if (N1C && N0.getOpcode() == ISD::XOR) { 4176 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4177 SDLoc DL(N); 4178 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4179 DAG.getConstant(N1C->getAPIntValue() ^ 4180 N00C->getAPIntValue(), DL, VT)); 4181 } 4182 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4183 SDLoc DL(N); 4184 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4185 DAG.getConstant(N1C->getAPIntValue() ^ 4186 N01C->getAPIntValue(), DL, VT)); 4187 } 4188 } 4189 // fold (xor x, x) -> 0 4190 if (N0 == N1) 4191 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4192 4193 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4194 // Here is a concrete example of this equivalence: 4195 // i16 x == 14 4196 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4197 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4198 // 4199 // => 4200 // 4201 // i16 ~1 == 0b1111111111111110 4202 // i16 rol(~1, 14) == 0b1011111111111111 4203 // 4204 // Some additional tips to help conceptualize this transform: 4205 // - Try to see the operation as placing a single zero in a value of all ones. 4206 // - There exists no value for x which would allow the result to contain zero. 4207 // - Values of x larger than the bitwidth are undefined and do not require a 4208 // consistent result. 4209 // - Pushing the zero left requires shifting one bits in from the right. 4210 // A rotate left of ~1 is a nice way of achieving the desired result. 4211 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4212 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4213 SDLoc DL(N); 4214 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4215 N0.getOperand(1)); 4216 } 4217 4218 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4219 if (N0.getOpcode() == N1.getOpcode()) 4220 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4221 return Tmp; 4222 4223 // Simplify the expression using non-local knowledge. 4224 if (!VT.isVector() && 4225 SimplifyDemandedBits(SDValue(N, 0))) 4226 return SDValue(N, 0); 4227 4228 return SDValue(); 4229 } 4230 4231 /// Handle transforms common to the three shifts, when the shift amount is a 4232 /// constant. 4233 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4234 SDNode *LHS = N->getOperand(0).getNode(); 4235 if (!LHS->hasOneUse()) return SDValue(); 4236 4237 // We want to pull some binops through shifts, so that we have (and (shift)) 4238 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4239 // thing happens with address calculations, so it's important to canonicalize 4240 // it. 4241 bool HighBitSet = false; // Can we transform this if the high bit is set? 4242 4243 switch (LHS->getOpcode()) { 4244 default: return SDValue(); 4245 case ISD::OR: 4246 case ISD::XOR: 4247 HighBitSet = false; // We can only transform sra if the high bit is clear. 4248 break; 4249 case ISD::AND: 4250 HighBitSet = true; // We can only transform sra if the high bit is set. 4251 break; 4252 case ISD::ADD: 4253 if (N->getOpcode() != ISD::SHL) 4254 return SDValue(); // only shl(add) not sr[al](add). 4255 HighBitSet = false; // We can only transform sra if the high bit is clear. 4256 break; 4257 } 4258 4259 // We require the RHS of the binop to be a constant and not opaque as well. 4260 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4261 if (!BinOpCst) return SDValue(); 4262 4263 // FIXME: disable this unless the input to the binop is a shift by a constant. 4264 // If it is not a shift, it pessimizes some common cases like: 4265 // 4266 // void foo(int *X, int i) { X[i & 1235] = 1; } 4267 // int bar(int *X, int i) { return X[i & 255]; } 4268 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4269 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4270 BinOpLHSVal->getOpcode() != ISD::SRA && 4271 BinOpLHSVal->getOpcode() != ISD::SRL) || 4272 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4273 return SDValue(); 4274 4275 EVT VT = N->getValueType(0); 4276 4277 // If this is a signed shift right, and the high bit is modified by the 4278 // logical operation, do not perform the transformation. The highBitSet 4279 // boolean indicates the value of the high bit of the constant which would 4280 // cause it to be modified for this operation. 4281 if (N->getOpcode() == ISD::SRA) { 4282 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4283 if (BinOpRHSSignSet != HighBitSet) 4284 return SDValue(); 4285 } 4286 4287 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4288 return SDValue(); 4289 4290 // Fold the constants, shifting the binop RHS by the shift amount. 4291 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4292 N->getValueType(0), 4293 LHS->getOperand(1), N->getOperand(1)); 4294 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4295 4296 // Create the new shift. 4297 SDValue NewShift = DAG.getNode(N->getOpcode(), 4298 SDLoc(LHS->getOperand(0)), 4299 VT, LHS->getOperand(0), N->getOperand(1)); 4300 4301 // Create the new binop. 4302 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4303 } 4304 4305 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4306 assert(N->getOpcode() == ISD::TRUNCATE); 4307 assert(N->getOperand(0).getOpcode() == ISD::AND); 4308 4309 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4310 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4311 SDValue N01 = N->getOperand(0).getOperand(1); 4312 4313 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4314 if (!N01C->isOpaque()) { 4315 EVT TruncVT = N->getValueType(0); 4316 SDValue N00 = N->getOperand(0).getOperand(0); 4317 APInt TruncC = N01C->getAPIntValue(); 4318 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4319 SDLoc DL(N); 4320 4321 return DAG.getNode(ISD::AND, DL, TruncVT, 4322 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4323 DAG.getConstant(TruncC, DL, TruncVT)); 4324 } 4325 } 4326 } 4327 4328 return SDValue(); 4329 } 4330 4331 SDValue DAGCombiner::visitRotate(SDNode *N) { 4332 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4333 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4334 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4335 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4336 if (NewOp1.getNode()) 4337 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4338 N->getOperand(0), NewOp1); 4339 } 4340 return SDValue(); 4341 } 4342 4343 SDValue DAGCombiner::visitSHL(SDNode *N) { 4344 SDValue N0 = N->getOperand(0); 4345 SDValue N1 = N->getOperand(1); 4346 EVT VT = N0.getValueType(); 4347 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4348 4349 // fold vector ops 4350 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4351 if (VT.isVector()) { 4352 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4353 return FoldedVOp; 4354 4355 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4356 // If setcc produces all-one true value then: 4357 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4358 if (N1CV && N1CV->isConstant()) { 4359 if (N0.getOpcode() == ISD::AND) { 4360 SDValue N00 = N0->getOperand(0); 4361 SDValue N01 = N0->getOperand(1); 4362 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4363 4364 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4365 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4366 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4367 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4368 N01CV, N1CV)) 4369 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4370 } 4371 } else { 4372 N1C = isConstOrConstSplat(N1); 4373 } 4374 } 4375 } 4376 4377 // fold (shl c1, c2) -> c1<<c2 4378 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4379 if (N0C && N1C && !N1C->isOpaque()) 4380 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4381 // fold (shl 0, x) -> 0 4382 if (isNullConstant(N0)) 4383 return N0; 4384 // fold (shl x, c >= size(x)) -> undef 4385 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4386 return DAG.getUNDEF(VT); 4387 // fold (shl x, 0) -> x 4388 if (N1C && N1C->isNullValue()) 4389 return N0; 4390 // fold (shl undef, x) -> 0 4391 if (N0.getOpcode() == ISD::UNDEF) 4392 return DAG.getConstant(0, SDLoc(N), VT); 4393 // if (shl x, c) is known to be zero, return 0 4394 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4395 APInt::getAllOnesValue(OpSizeInBits))) 4396 return DAG.getConstant(0, SDLoc(N), VT); 4397 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4398 if (N1.getOpcode() == ISD::TRUNCATE && 4399 N1.getOperand(0).getOpcode() == ISD::AND) { 4400 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4401 if (NewOp1.getNode()) 4402 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4403 } 4404 4405 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4406 return SDValue(N, 0); 4407 4408 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4409 if (N1C && N0.getOpcode() == ISD::SHL) { 4410 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4411 uint64_t c1 = N0C1->getZExtValue(); 4412 uint64_t c2 = N1C->getZExtValue(); 4413 SDLoc DL(N); 4414 if (c1 + c2 >= OpSizeInBits) 4415 return DAG.getConstant(0, DL, VT); 4416 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4417 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4418 } 4419 } 4420 4421 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4422 // For this to be valid, the second form must not preserve any of the bits 4423 // that are shifted out by the inner shift in the first form. This means 4424 // the outer shift size must be >= the number of bits added by the ext. 4425 // As a corollary, we don't care what kind of ext it is. 4426 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4427 N0.getOpcode() == ISD::ANY_EXTEND || 4428 N0.getOpcode() == ISD::SIGN_EXTEND) && 4429 N0.getOperand(0).getOpcode() == ISD::SHL) { 4430 SDValue N0Op0 = N0.getOperand(0); 4431 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4432 uint64_t c1 = N0Op0C1->getZExtValue(); 4433 uint64_t c2 = N1C->getZExtValue(); 4434 EVT InnerShiftVT = N0Op0.getValueType(); 4435 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4436 if (c2 >= OpSizeInBits - InnerShiftSize) { 4437 SDLoc DL(N0); 4438 if (c1 + c2 >= OpSizeInBits) 4439 return DAG.getConstant(0, DL, VT); 4440 return DAG.getNode(ISD::SHL, DL, VT, 4441 DAG.getNode(N0.getOpcode(), DL, VT, 4442 N0Op0->getOperand(0)), 4443 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4444 } 4445 } 4446 } 4447 4448 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4449 // Only fold this if the inner zext has no other uses to avoid increasing 4450 // the total number of instructions. 4451 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4452 N0.getOperand(0).getOpcode() == ISD::SRL) { 4453 SDValue N0Op0 = N0.getOperand(0); 4454 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4455 uint64_t c1 = N0Op0C1->getZExtValue(); 4456 if (c1 < VT.getScalarSizeInBits()) { 4457 uint64_t c2 = N1C->getZExtValue(); 4458 if (c1 == c2) { 4459 SDValue NewOp0 = N0.getOperand(0); 4460 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4461 SDLoc DL(N); 4462 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4463 NewOp0, 4464 DAG.getConstant(c2, DL, CountVT)); 4465 AddToWorklist(NewSHL.getNode()); 4466 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4467 } 4468 } 4469 } 4470 } 4471 4472 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4473 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4474 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4475 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4476 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4477 uint64_t C1 = N0C1->getZExtValue(); 4478 uint64_t C2 = N1C->getZExtValue(); 4479 SDLoc DL(N); 4480 if (C1 <= C2) 4481 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4482 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4483 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4484 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4485 } 4486 } 4487 4488 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4489 // (and (srl x, (sub c1, c2), MASK) 4490 // Only fold this if the inner shift has no other uses -- if it does, folding 4491 // this will increase the total number of instructions. 4492 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4493 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4494 uint64_t c1 = N0C1->getZExtValue(); 4495 if (c1 < OpSizeInBits) { 4496 uint64_t c2 = N1C->getZExtValue(); 4497 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4498 SDValue Shift; 4499 if (c2 > c1) { 4500 Mask = Mask.shl(c2 - c1); 4501 SDLoc DL(N); 4502 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4503 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4504 } else { 4505 Mask = Mask.lshr(c1 - c2); 4506 SDLoc DL(N); 4507 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4508 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4509 } 4510 SDLoc DL(N0); 4511 return DAG.getNode(ISD::AND, DL, VT, Shift, 4512 DAG.getConstant(Mask, DL, VT)); 4513 } 4514 } 4515 } 4516 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4517 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4518 unsigned BitSize = VT.getScalarSizeInBits(); 4519 SDLoc DL(N); 4520 SDValue HiBitsMask = 4521 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4522 BitSize - N1C->getZExtValue()), 4523 DL, VT); 4524 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4525 HiBitsMask); 4526 } 4527 4528 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4529 // Variant of version done on multiply, except mul by a power of 2 is turned 4530 // into a shift. 4531 APInt Val; 4532 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4533 (isa<ConstantSDNode>(N0.getOperand(1)) || 4534 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4535 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4536 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4537 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4538 } 4539 4540 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4541 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4542 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4543 if (SDValue Folded = 4544 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4545 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4546 } 4547 } 4548 4549 if (N1C && !N1C->isOpaque()) 4550 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4551 return NewSHL; 4552 4553 return SDValue(); 4554 } 4555 4556 SDValue DAGCombiner::visitSRA(SDNode *N) { 4557 SDValue N0 = N->getOperand(0); 4558 SDValue N1 = N->getOperand(1); 4559 EVT VT = N0.getValueType(); 4560 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4561 4562 // fold vector ops 4563 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4564 if (VT.isVector()) { 4565 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4566 return FoldedVOp; 4567 4568 N1C = isConstOrConstSplat(N1); 4569 } 4570 4571 // fold (sra c1, c2) -> (sra c1, c2) 4572 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4573 if (N0C && N1C && !N1C->isOpaque()) 4574 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4575 // fold (sra 0, x) -> 0 4576 if (isNullConstant(N0)) 4577 return N0; 4578 // fold (sra -1, x) -> -1 4579 if (isAllOnesConstant(N0)) 4580 return N0; 4581 // fold (sra x, (setge c, size(x))) -> undef 4582 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4583 return DAG.getUNDEF(VT); 4584 // fold (sra x, 0) -> x 4585 if (N1C && N1C->isNullValue()) 4586 return N0; 4587 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4588 // sext_inreg. 4589 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4590 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4591 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4592 if (VT.isVector()) 4593 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4594 ExtVT, VT.getVectorNumElements()); 4595 if ((!LegalOperations || 4596 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4597 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4598 N0.getOperand(0), DAG.getValueType(ExtVT)); 4599 } 4600 4601 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4602 if (N1C && N0.getOpcode() == ISD::SRA) { 4603 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4604 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4605 if (Sum >= OpSizeInBits) 4606 Sum = OpSizeInBits - 1; 4607 SDLoc DL(N); 4608 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4609 DAG.getConstant(Sum, DL, N1.getValueType())); 4610 } 4611 } 4612 4613 // fold (sra (shl X, m), (sub result_size, n)) 4614 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4615 // result_size - n != m. 4616 // If truncate is free for the target sext(shl) is likely to result in better 4617 // code. 4618 if (N0.getOpcode() == ISD::SHL && N1C) { 4619 // Get the two constanst of the shifts, CN0 = m, CN = n. 4620 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4621 if (N01C) { 4622 LLVMContext &Ctx = *DAG.getContext(); 4623 // Determine what the truncate's result bitsize and type would be. 4624 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4625 4626 if (VT.isVector()) 4627 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4628 4629 // Determine the residual right-shift amount. 4630 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4631 4632 // If the shift is not a no-op (in which case this should be just a sign 4633 // extend already), the truncated to type is legal, sign_extend is legal 4634 // on that type, and the truncate to that type is both legal and free, 4635 // perform the transform. 4636 if ((ShiftAmt > 0) && 4637 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4638 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4639 TLI.isTruncateFree(VT, TruncVT)) { 4640 4641 SDLoc DL(N); 4642 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4643 getShiftAmountTy(N0.getOperand(0).getValueType())); 4644 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4645 N0.getOperand(0), Amt); 4646 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4647 Shift); 4648 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4649 N->getValueType(0), Trunc); 4650 } 4651 } 4652 } 4653 4654 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4655 if (N1.getOpcode() == ISD::TRUNCATE && 4656 N1.getOperand(0).getOpcode() == ISD::AND) { 4657 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4658 if (NewOp1.getNode()) 4659 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4660 } 4661 4662 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4663 // if c1 is equal to the number of bits the trunc removes 4664 if (N0.getOpcode() == ISD::TRUNCATE && 4665 (N0.getOperand(0).getOpcode() == ISD::SRL || 4666 N0.getOperand(0).getOpcode() == ISD::SRA) && 4667 N0.getOperand(0).hasOneUse() && 4668 N0.getOperand(0).getOperand(1).hasOneUse() && 4669 N1C) { 4670 SDValue N0Op0 = N0.getOperand(0); 4671 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4672 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4673 EVT LargeVT = N0Op0.getValueType(); 4674 4675 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4676 SDLoc DL(N); 4677 SDValue Amt = 4678 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4679 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4680 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4681 N0Op0.getOperand(0), Amt); 4682 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4683 } 4684 } 4685 } 4686 4687 // Simplify, based on bits shifted out of the LHS. 4688 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4689 return SDValue(N, 0); 4690 4691 4692 // If the sign bit is known to be zero, switch this to a SRL. 4693 if (DAG.SignBitIsZero(N0)) 4694 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4695 4696 if (N1C && !N1C->isOpaque()) 4697 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4698 return NewSRA; 4699 4700 return SDValue(); 4701 } 4702 4703 SDValue DAGCombiner::visitSRL(SDNode *N) { 4704 SDValue N0 = N->getOperand(0); 4705 SDValue N1 = N->getOperand(1); 4706 EVT VT = N0.getValueType(); 4707 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4708 4709 // fold vector ops 4710 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4711 if (VT.isVector()) { 4712 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4713 return FoldedVOp; 4714 4715 N1C = isConstOrConstSplat(N1); 4716 } 4717 4718 // fold (srl c1, c2) -> c1 >>u c2 4719 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4720 if (N0C && N1C && !N1C->isOpaque()) 4721 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4722 // fold (srl 0, x) -> 0 4723 if (isNullConstant(N0)) 4724 return N0; 4725 // fold (srl x, c >= size(x)) -> undef 4726 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4727 return DAG.getUNDEF(VT); 4728 // fold (srl x, 0) -> x 4729 if (N1C && N1C->isNullValue()) 4730 return N0; 4731 // if (srl x, c) is known to be zero, return 0 4732 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4733 APInt::getAllOnesValue(OpSizeInBits))) 4734 return DAG.getConstant(0, SDLoc(N), VT); 4735 4736 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4737 if (N1C && N0.getOpcode() == ISD::SRL) { 4738 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4739 uint64_t c1 = N01C->getZExtValue(); 4740 uint64_t c2 = N1C->getZExtValue(); 4741 SDLoc DL(N); 4742 if (c1 + c2 >= OpSizeInBits) 4743 return DAG.getConstant(0, DL, VT); 4744 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4745 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4746 } 4747 } 4748 4749 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4750 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4751 N0.getOperand(0).getOpcode() == ISD::SRL && 4752 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4753 uint64_t c1 = 4754 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4755 uint64_t c2 = N1C->getZExtValue(); 4756 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4757 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4758 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4759 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4760 if (c1 + OpSizeInBits == InnerShiftSize) { 4761 SDLoc DL(N0); 4762 if (c1 + c2 >= InnerShiftSize) 4763 return DAG.getConstant(0, DL, VT); 4764 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4765 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4766 N0.getOperand(0)->getOperand(0), 4767 DAG.getConstant(c1 + c2, DL, 4768 ShiftCountVT))); 4769 } 4770 } 4771 4772 // fold (srl (shl x, c), c) -> (and x, cst2) 4773 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4774 unsigned BitSize = N0.getScalarValueSizeInBits(); 4775 if (BitSize <= 64) { 4776 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4777 SDLoc DL(N); 4778 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4779 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4780 } 4781 } 4782 4783 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4784 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4785 // Shifting in all undef bits? 4786 EVT SmallVT = N0.getOperand(0).getValueType(); 4787 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4788 if (N1C->getZExtValue() >= BitSize) 4789 return DAG.getUNDEF(VT); 4790 4791 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4792 uint64_t ShiftAmt = N1C->getZExtValue(); 4793 SDLoc DL0(N0); 4794 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4795 N0.getOperand(0), 4796 DAG.getConstant(ShiftAmt, DL0, 4797 getShiftAmountTy(SmallVT))); 4798 AddToWorklist(SmallShift.getNode()); 4799 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4800 SDLoc DL(N); 4801 return DAG.getNode(ISD::AND, DL, VT, 4802 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4803 DAG.getConstant(Mask, DL, VT)); 4804 } 4805 } 4806 4807 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4808 // bit, which is unmodified by sra. 4809 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4810 if (N0.getOpcode() == ISD::SRA) 4811 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4812 } 4813 4814 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4815 if (N1C && N0.getOpcode() == ISD::CTLZ && 4816 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4817 APInt KnownZero, KnownOne; 4818 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4819 4820 // If any of the input bits are KnownOne, then the input couldn't be all 4821 // zeros, thus the result of the srl will always be zero. 4822 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4823 4824 // If all of the bits input the to ctlz node are known to be zero, then 4825 // the result of the ctlz is "32" and the result of the shift is one. 4826 APInt UnknownBits = ~KnownZero; 4827 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4828 4829 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4830 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4831 // Okay, we know that only that the single bit specified by UnknownBits 4832 // could be set on input to the CTLZ node. If this bit is set, the SRL 4833 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4834 // to an SRL/XOR pair, which is likely to simplify more. 4835 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4836 SDValue Op = N0.getOperand(0); 4837 4838 if (ShAmt) { 4839 SDLoc DL(N0); 4840 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4841 DAG.getConstant(ShAmt, DL, 4842 getShiftAmountTy(Op.getValueType()))); 4843 AddToWorklist(Op.getNode()); 4844 } 4845 4846 SDLoc DL(N); 4847 return DAG.getNode(ISD::XOR, DL, VT, 4848 Op, DAG.getConstant(1, DL, VT)); 4849 } 4850 } 4851 4852 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4853 if (N1.getOpcode() == ISD::TRUNCATE && 4854 N1.getOperand(0).getOpcode() == ISD::AND) { 4855 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4856 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4857 } 4858 4859 // fold operands of srl based on knowledge that the low bits are not 4860 // demanded. 4861 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4862 return SDValue(N, 0); 4863 4864 if (N1C && !N1C->isOpaque()) 4865 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4866 return NewSRL; 4867 4868 // Attempt to convert a srl of a load into a narrower zero-extending load. 4869 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4870 return NarrowLoad; 4871 4872 // Here is a common situation. We want to optimize: 4873 // 4874 // %a = ... 4875 // %b = and i32 %a, 2 4876 // %c = srl i32 %b, 1 4877 // brcond i32 %c ... 4878 // 4879 // into 4880 // 4881 // %a = ... 4882 // %b = and %a, 2 4883 // %c = setcc eq %b, 0 4884 // brcond %c ... 4885 // 4886 // However when after the source operand of SRL is optimized into AND, the SRL 4887 // itself may not be optimized further. Look for it and add the BRCOND into 4888 // the worklist. 4889 if (N->hasOneUse()) { 4890 SDNode *Use = *N->use_begin(); 4891 if (Use->getOpcode() == ISD::BRCOND) 4892 AddToWorklist(Use); 4893 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4894 // Also look pass the truncate. 4895 Use = *Use->use_begin(); 4896 if (Use->getOpcode() == ISD::BRCOND) 4897 AddToWorklist(Use); 4898 } 4899 } 4900 4901 return SDValue(); 4902 } 4903 4904 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4905 SDValue N0 = N->getOperand(0); 4906 EVT VT = N->getValueType(0); 4907 4908 // fold (bswap c1) -> c2 4909 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4910 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4911 // fold (bswap (bswap x)) -> x 4912 if (N0.getOpcode() == ISD::BSWAP) 4913 return N0->getOperand(0); 4914 return SDValue(); 4915 } 4916 4917 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4918 SDValue N0 = N->getOperand(0); 4919 EVT VT = N->getValueType(0); 4920 4921 // fold (ctlz c1) -> c2 4922 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4923 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4924 return SDValue(); 4925 } 4926 4927 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4928 SDValue N0 = N->getOperand(0); 4929 EVT VT = N->getValueType(0); 4930 4931 // fold (ctlz_zero_undef c1) -> c2 4932 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4933 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4934 return SDValue(); 4935 } 4936 4937 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4938 SDValue N0 = N->getOperand(0); 4939 EVT VT = N->getValueType(0); 4940 4941 // fold (cttz c1) -> c2 4942 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4943 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4944 return SDValue(); 4945 } 4946 4947 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4948 SDValue N0 = N->getOperand(0); 4949 EVT VT = N->getValueType(0); 4950 4951 // fold (cttz_zero_undef c1) -> c2 4952 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4953 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4954 return SDValue(); 4955 } 4956 4957 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4958 SDValue N0 = N->getOperand(0); 4959 EVT VT = N->getValueType(0); 4960 4961 // fold (ctpop c1) -> c2 4962 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4963 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4964 return SDValue(); 4965 } 4966 4967 4968 /// \brief Generate Min/Max node 4969 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4970 SDValue True, SDValue False, 4971 ISD::CondCode CC, const TargetLowering &TLI, 4972 SelectionDAG &DAG) { 4973 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4974 return SDValue(); 4975 4976 switch (CC) { 4977 case ISD::SETOLT: 4978 case ISD::SETOLE: 4979 case ISD::SETLT: 4980 case ISD::SETLE: 4981 case ISD::SETULT: 4982 case ISD::SETULE: { 4983 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4984 if (TLI.isOperationLegal(Opcode, VT)) 4985 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4986 return SDValue(); 4987 } 4988 case ISD::SETOGT: 4989 case ISD::SETOGE: 4990 case ISD::SETGT: 4991 case ISD::SETGE: 4992 case ISD::SETUGT: 4993 case ISD::SETUGE: { 4994 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4995 if (TLI.isOperationLegal(Opcode, VT)) 4996 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4997 return SDValue(); 4998 } 4999 default: 5000 return SDValue(); 5001 } 5002 } 5003 5004 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5005 SDValue N0 = N->getOperand(0); 5006 SDValue N1 = N->getOperand(1); 5007 SDValue N2 = N->getOperand(2); 5008 EVT VT = N->getValueType(0); 5009 EVT VT0 = N0.getValueType(); 5010 5011 // fold (select C, X, X) -> X 5012 if (N1 == N2) 5013 return N1; 5014 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5015 // fold (select true, X, Y) -> X 5016 // fold (select false, X, Y) -> Y 5017 return !N0C->isNullValue() ? N1 : N2; 5018 } 5019 // fold (select C, 1, X) -> (or C, X) 5020 if (VT == MVT::i1 && isOneConstant(N1)) 5021 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5022 // fold (select C, 0, 1) -> (xor C, 1) 5023 // We can't do this reliably if integer based booleans have different contents 5024 // to floating point based booleans. This is because we can't tell whether we 5025 // have an integer-based boolean or a floating-point-based boolean unless we 5026 // can find the SETCC that produced it and inspect its operands. This is 5027 // fairly easy if C is the SETCC node, but it can potentially be 5028 // undiscoverable (or not reasonably discoverable). For example, it could be 5029 // in another basic block or it could require searching a complicated 5030 // expression. 5031 if (VT.isInteger() && 5032 (VT0 == MVT::i1 || (VT0.isInteger() && 5033 TLI.getBooleanContents(false, false) == 5034 TLI.getBooleanContents(false, true) && 5035 TLI.getBooleanContents(false, false) == 5036 TargetLowering::ZeroOrOneBooleanContent)) && 5037 isNullConstant(N1) && isOneConstant(N2)) { 5038 SDValue XORNode; 5039 if (VT == VT0) { 5040 SDLoc DL(N); 5041 return DAG.getNode(ISD::XOR, DL, VT0, 5042 N0, DAG.getConstant(1, DL, VT0)); 5043 } 5044 SDLoc DL0(N0); 5045 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5046 N0, DAG.getConstant(1, DL0, VT0)); 5047 AddToWorklist(XORNode.getNode()); 5048 if (VT.bitsGT(VT0)) 5049 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5051 } 5052 // fold (select C, 0, X) -> (and (not C), X) 5053 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5054 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5055 AddToWorklist(NOTNode.getNode()); 5056 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5057 } 5058 // fold (select C, X, 1) -> (or (not C), X) 5059 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5060 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5061 AddToWorklist(NOTNode.getNode()); 5062 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5063 } 5064 // fold (select C, X, 0) -> (and C, X) 5065 if (VT == MVT::i1 && isNullConstant(N2)) 5066 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5067 // fold (select X, X, Y) -> (or X, Y) 5068 // fold (select X, 1, Y) -> (or X, Y) 5069 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5070 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5071 // fold (select X, Y, X) -> (and X, Y) 5072 // fold (select X, Y, 0) -> (and X, Y) 5073 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5074 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5075 5076 // If we can fold this based on the true/false value, do so. 5077 if (SimplifySelectOps(N, N1, N2)) 5078 return SDValue(N, 0); // Don't revisit N. 5079 5080 if (VT0 == MVT::i1) { 5081 // The code in this block deals with the following 2 equivalences: 5082 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5083 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5084 // The target can specify its prefered form with the 5085 // shouldNormalizeToSelectSequence() callback. However we always transform 5086 // to the right anyway if we find the inner select exists in the DAG anyway 5087 // and we always transform to the left side if we know that we can further 5088 // optimize the combination of the conditions. 5089 bool normalizeToSequence 5090 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5091 // select (and Cond0, Cond1), X, Y 5092 // -> select Cond0, (select Cond1, X, Y), Y 5093 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5094 SDValue Cond0 = N0->getOperand(0); 5095 SDValue Cond1 = N0->getOperand(1); 5096 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5097 N1.getValueType(), Cond1, N1, N2); 5098 if (normalizeToSequence || !InnerSelect.use_empty()) 5099 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5100 InnerSelect, N2); 5101 } 5102 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5103 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5104 SDValue Cond0 = N0->getOperand(0); 5105 SDValue Cond1 = N0->getOperand(1); 5106 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5107 N1.getValueType(), Cond1, N1, N2); 5108 if (normalizeToSequence || !InnerSelect.use_empty()) 5109 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5110 InnerSelect); 5111 } 5112 5113 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5114 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5115 SDValue N1_0 = N1->getOperand(0); 5116 SDValue N1_1 = N1->getOperand(1); 5117 SDValue N1_2 = N1->getOperand(2); 5118 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5119 // Create the actual and node if we can generate good code for it. 5120 if (!normalizeToSequence) { 5121 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5122 N0, N1_0); 5123 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5124 N1_1, N2); 5125 } 5126 // Otherwise see if we can optimize the "and" to a better pattern. 5127 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5128 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5129 N1_1, N2); 5130 } 5131 } 5132 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5133 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5134 SDValue N2_0 = N2->getOperand(0); 5135 SDValue N2_1 = N2->getOperand(1); 5136 SDValue N2_2 = N2->getOperand(2); 5137 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5138 // Create the actual or node if we can generate good code for it. 5139 if (!normalizeToSequence) { 5140 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5141 N0, N2_0); 5142 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5143 N1, N2_2); 5144 } 5145 // Otherwise see if we can optimize to a better pattern. 5146 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5147 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5148 N1, N2_2); 5149 } 5150 } 5151 } 5152 5153 // fold selects based on a setcc into other things, such as min/max/abs 5154 if (N0.getOpcode() == ISD::SETCC) { 5155 // select x, y (fcmp lt x, y) -> fminnum x, y 5156 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5157 // 5158 // This is OK if we don't care about what happens if either operand is a 5159 // NaN. 5160 // 5161 5162 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5163 // no signed zeros as well as no nans. 5164 const TargetOptions &Options = DAG.getTarget().Options; 5165 if (Options.UnsafeFPMath && 5166 VT.isFloatingPoint() && N0.hasOneUse() && 5167 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5168 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5169 5170 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5171 N0.getOperand(1), N1, N2, CC, 5172 TLI, DAG)) 5173 return FMinMax; 5174 } 5175 5176 if ((!LegalOperations && 5177 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5178 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5179 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5180 N0.getOperand(0), N0.getOperand(1), 5181 N1, N2, N0.getOperand(2)); 5182 return SimplifySelect(SDLoc(N), N0, N1, N2); 5183 } 5184 5185 return SDValue(); 5186 } 5187 5188 static 5189 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5190 SDLoc DL(N); 5191 EVT LoVT, HiVT; 5192 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5193 5194 // Split the inputs. 5195 SDValue Lo, Hi, LL, LH, RL, RH; 5196 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5197 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5198 5199 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5200 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5201 5202 return std::make_pair(Lo, Hi); 5203 } 5204 5205 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5206 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5207 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5208 SDLoc dl(N); 5209 SDValue Cond = N->getOperand(0); 5210 SDValue LHS = N->getOperand(1); 5211 SDValue RHS = N->getOperand(2); 5212 EVT VT = N->getValueType(0); 5213 int NumElems = VT.getVectorNumElements(); 5214 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5215 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5216 Cond.getOpcode() == ISD::BUILD_VECTOR); 5217 5218 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5219 // binary ones here. 5220 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5221 return SDValue(); 5222 5223 // We're sure we have an even number of elements due to the 5224 // concat_vectors we have as arguments to vselect. 5225 // Skip BV elements until we find one that's not an UNDEF 5226 // After we find an UNDEF element, keep looping until we get to half the 5227 // length of the BV and see if all the non-undef nodes are the same. 5228 ConstantSDNode *BottomHalf = nullptr; 5229 for (int i = 0; i < NumElems / 2; ++i) { 5230 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5231 continue; 5232 5233 if (BottomHalf == nullptr) 5234 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5235 else if (Cond->getOperand(i).getNode() != BottomHalf) 5236 return SDValue(); 5237 } 5238 5239 // Do the same for the second half of the BuildVector 5240 ConstantSDNode *TopHalf = nullptr; 5241 for (int i = NumElems / 2; i < NumElems; ++i) { 5242 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5243 continue; 5244 5245 if (TopHalf == nullptr) 5246 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5247 else if (Cond->getOperand(i).getNode() != TopHalf) 5248 return SDValue(); 5249 } 5250 5251 assert(TopHalf && BottomHalf && 5252 "One half of the selector was all UNDEFs and the other was all the " 5253 "same value. This should have been addressed before this function."); 5254 return DAG.getNode( 5255 ISD::CONCAT_VECTORS, dl, VT, 5256 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5257 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5258 } 5259 5260 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5261 5262 if (Level >= AfterLegalizeTypes) 5263 return SDValue(); 5264 5265 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5266 SDValue Mask = MSC->getMask(); 5267 SDValue Data = MSC->getValue(); 5268 SDLoc DL(N); 5269 5270 // If the MSCATTER data type requires splitting and the mask is provided by a 5271 // SETCC, then split both nodes and its operands before legalization. This 5272 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5273 // and enables future optimizations (e.g. min/max pattern matching on X86). 5274 if (Mask.getOpcode() != ISD::SETCC) 5275 return SDValue(); 5276 5277 // Check if any splitting is required. 5278 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5279 TargetLowering::TypeSplitVector) 5280 return SDValue(); 5281 SDValue MaskLo, MaskHi, Lo, Hi; 5282 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5283 5284 EVT LoVT, HiVT; 5285 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5286 5287 SDValue Chain = MSC->getChain(); 5288 5289 EVT MemoryVT = MSC->getMemoryVT(); 5290 unsigned Alignment = MSC->getOriginalAlignment(); 5291 5292 EVT LoMemVT, HiMemVT; 5293 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5294 5295 SDValue DataLo, DataHi; 5296 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5297 5298 SDValue BasePtr = MSC->getBasePtr(); 5299 SDValue IndexLo, IndexHi; 5300 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5301 5302 MachineMemOperand *MMO = DAG.getMachineFunction(). 5303 getMachineMemOperand(MSC->getPointerInfo(), 5304 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5305 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5306 5307 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5308 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5309 DL, OpsLo, MMO); 5310 5311 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5312 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5313 DL, OpsHi, MMO); 5314 5315 AddToWorklist(Lo.getNode()); 5316 AddToWorklist(Hi.getNode()); 5317 5318 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5319 } 5320 5321 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5322 5323 if (Level >= AfterLegalizeTypes) 5324 return SDValue(); 5325 5326 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5327 SDValue Mask = MST->getMask(); 5328 SDValue Data = MST->getValue(); 5329 SDLoc DL(N); 5330 5331 // If the MSTORE data type requires splitting and the mask is provided by a 5332 // SETCC, then split both nodes and its operands before legalization. This 5333 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5334 // and enables future optimizations (e.g. min/max pattern matching on X86). 5335 if (Mask.getOpcode() == ISD::SETCC) { 5336 5337 // Check if any splitting is required. 5338 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5339 TargetLowering::TypeSplitVector) 5340 return SDValue(); 5341 5342 SDValue MaskLo, MaskHi, Lo, Hi; 5343 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5344 5345 EVT LoVT, HiVT; 5346 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5347 5348 SDValue Chain = MST->getChain(); 5349 SDValue Ptr = MST->getBasePtr(); 5350 5351 EVT MemoryVT = MST->getMemoryVT(); 5352 unsigned Alignment = MST->getOriginalAlignment(); 5353 5354 // if Alignment is equal to the vector size, 5355 // take the half of it for the second part 5356 unsigned SecondHalfAlignment = 5357 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5358 Alignment/2 : Alignment; 5359 5360 EVT LoMemVT, HiMemVT; 5361 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5362 5363 SDValue DataLo, DataHi; 5364 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5365 5366 MachineMemOperand *MMO = DAG.getMachineFunction(). 5367 getMachineMemOperand(MST->getPointerInfo(), 5368 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5369 Alignment, MST->getAAInfo(), MST->getRanges()); 5370 5371 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5372 MST->isTruncatingStore()); 5373 5374 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5375 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5376 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5377 5378 MMO = DAG.getMachineFunction(). 5379 getMachineMemOperand(MST->getPointerInfo(), 5380 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5381 SecondHalfAlignment, MST->getAAInfo(), 5382 MST->getRanges()); 5383 5384 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5385 MST->isTruncatingStore()); 5386 5387 AddToWorklist(Lo.getNode()); 5388 AddToWorklist(Hi.getNode()); 5389 5390 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5391 } 5392 return SDValue(); 5393 } 5394 5395 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5396 5397 if (Level >= AfterLegalizeTypes) 5398 return SDValue(); 5399 5400 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5401 SDValue Mask = MGT->getMask(); 5402 SDLoc DL(N); 5403 5404 // If the MGATHER result requires splitting and the mask is provided by a 5405 // SETCC, then split both nodes and its operands before legalization. This 5406 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5407 // and enables future optimizations (e.g. min/max pattern matching on X86). 5408 5409 if (Mask.getOpcode() != ISD::SETCC) 5410 return SDValue(); 5411 5412 EVT VT = N->getValueType(0); 5413 5414 // Check if any splitting is required. 5415 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5416 TargetLowering::TypeSplitVector) 5417 return SDValue(); 5418 5419 SDValue MaskLo, MaskHi, Lo, Hi; 5420 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5421 5422 SDValue Src0 = MGT->getValue(); 5423 SDValue Src0Lo, Src0Hi; 5424 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5425 5426 EVT LoVT, HiVT; 5427 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5428 5429 SDValue Chain = MGT->getChain(); 5430 EVT MemoryVT = MGT->getMemoryVT(); 5431 unsigned Alignment = MGT->getOriginalAlignment(); 5432 5433 EVT LoMemVT, HiMemVT; 5434 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5435 5436 SDValue BasePtr = MGT->getBasePtr(); 5437 SDValue Index = MGT->getIndex(); 5438 SDValue IndexLo, IndexHi; 5439 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5440 5441 MachineMemOperand *MMO = DAG.getMachineFunction(). 5442 getMachineMemOperand(MGT->getPointerInfo(), 5443 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5444 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5445 5446 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5447 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5448 MMO); 5449 5450 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5451 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5452 MMO); 5453 5454 AddToWorklist(Lo.getNode()); 5455 AddToWorklist(Hi.getNode()); 5456 5457 // Build a factor node to remember that this load is independent of the 5458 // other one. 5459 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5460 Hi.getValue(1)); 5461 5462 // Legalized the chain result - switch anything that used the old chain to 5463 // use the new one. 5464 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5465 5466 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5467 5468 SDValue RetOps[] = { GatherRes, Chain }; 5469 return DAG.getMergeValues(RetOps, DL); 5470 } 5471 5472 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5473 5474 if (Level >= AfterLegalizeTypes) 5475 return SDValue(); 5476 5477 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5478 SDValue Mask = MLD->getMask(); 5479 SDLoc DL(N); 5480 5481 // If the MLOAD result requires splitting and the mask is provided by a 5482 // SETCC, then split both nodes and its operands before legalization. This 5483 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5484 // and enables future optimizations (e.g. min/max pattern matching on X86). 5485 5486 if (Mask.getOpcode() == ISD::SETCC) { 5487 EVT VT = N->getValueType(0); 5488 5489 // Check if any splitting is required. 5490 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5491 TargetLowering::TypeSplitVector) 5492 return SDValue(); 5493 5494 SDValue MaskLo, MaskHi, Lo, Hi; 5495 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5496 5497 SDValue Src0 = MLD->getSrc0(); 5498 SDValue Src0Lo, Src0Hi; 5499 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5500 5501 EVT LoVT, HiVT; 5502 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5503 5504 SDValue Chain = MLD->getChain(); 5505 SDValue Ptr = MLD->getBasePtr(); 5506 EVT MemoryVT = MLD->getMemoryVT(); 5507 unsigned Alignment = MLD->getOriginalAlignment(); 5508 5509 // if Alignment is equal to the vector size, 5510 // take the half of it for the second part 5511 unsigned SecondHalfAlignment = 5512 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5513 Alignment/2 : Alignment; 5514 5515 EVT LoMemVT, HiMemVT; 5516 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5517 5518 MachineMemOperand *MMO = DAG.getMachineFunction(). 5519 getMachineMemOperand(MLD->getPointerInfo(), 5520 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5521 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5522 5523 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5524 ISD::NON_EXTLOAD); 5525 5526 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5527 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5528 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5529 5530 MMO = DAG.getMachineFunction(). 5531 getMachineMemOperand(MLD->getPointerInfo(), 5532 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5533 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5534 5535 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5536 ISD::NON_EXTLOAD); 5537 5538 AddToWorklist(Lo.getNode()); 5539 AddToWorklist(Hi.getNode()); 5540 5541 // Build a factor node to remember that this load is independent of the 5542 // other one. 5543 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5544 Hi.getValue(1)); 5545 5546 // Legalized the chain result - switch anything that used the old chain to 5547 // use the new one. 5548 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5549 5550 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5551 5552 SDValue RetOps[] = { LoadRes, Chain }; 5553 return DAG.getMergeValues(RetOps, DL); 5554 } 5555 return SDValue(); 5556 } 5557 5558 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5559 SDValue N0 = N->getOperand(0); 5560 SDValue N1 = N->getOperand(1); 5561 SDValue N2 = N->getOperand(2); 5562 SDLoc DL(N); 5563 5564 // Canonicalize integer abs. 5565 // vselect (setg[te] X, 0), X, -X -> 5566 // vselect (setgt X, -1), X, -X -> 5567 // vselect (setl[te] X, 0), -X, X -> 5568 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5569 if (N0.getOpcode() == ISD::SETCC) { 5570 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5571 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5572 bool isAbs = false; 5573 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5574 5575 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5576 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5577 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5578 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5579 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5580 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5581 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5582 5583 if (isAbs) { 5584 EVT VT = LHS.getValueType(); 5585 SDValue Shift = DAG.getNode( 5586 ISD::SRA, DL, VT, LHS, 5587 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5588 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5589 AddToWorklist(Shift.getNode()); 5590 AddToWorklist(Add.getNode()); 5591 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5592 } 5593 } 5594 5595 if (SimplifySelectOps(N, N1, N2)) 5596 return SDValue(N, 0); // Don't revisit N. 5597 5598 // If the VSELECT result requires splitting and the mask is provided by a 5599 // SETCC, then split both nodes and its operands before legalization. This 5600 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5601 // and enables future optimizations (e.g. min/max pattern matching on X86). 5602 if (N0.getOpcode() == ISD::SETCC) { 5603 EVT VT = N->getValueType(0); 5604 5605 // Check if any splitting is required. 5606 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5607 TargetLowering::TypeSplitVector) 5608 return SDValue(); 5609 5610 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5611 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5612 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5613 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5614 5615 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5616 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5617 5618 // Add the new VSELECT nodes to the work list in case they need to be split 5619 // again. 5620 AddToWorklist(Lo.getNode()); 5621 AddToWorklist(Hi.getNode()); 5622 5623 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5624 } 5625 5626 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5627 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5628 return N1; 5629 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5630 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5631 return N2; 5632 5633 // The ConvertSelectToConcatVector function is assuming both the above 5634 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5635 // and addressed. 5636 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5637 N2.getOpcode() == ISD::CONCAT_VECTORS && 5638 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5639 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5640 return CV; 5641 } 5642 5643 return SDValue(); 5644 } 5645 5646 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5647 SDValue N0 = N->getOperand(0); 5648 SDValue N1 = N->getOperand(1); 5649 SDValue N2 = N->getOperand(2); 5650 SDValue N3 = N->getOperand(3); 5651 SDValue N4 = N->getOperand(4); 5652 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5653 5654 // fold select_cc lhs, rhs, x, x, cc -> x 5655 if (N2 == N3) 5656 return N2; 5657 5658 // Determine if the condition we're dealing with is constant 5659 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5660 N0, N1, CC, SDLoc(N), false); 5661 if (SCC.getNode()) { 5662 AddToWorklist(SCC.getNode()); 5663 5664 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5665 if (!SCCC->isNullValue()) 5666 return N2; // cond always true -> true val 5667 else 5668 return N3; // cond always false -> false val 5669 } else if (SCC->getOpcode() == ISD::UNDEF) { 5670 // When the condition is UNDEF, just return the first operand. This is 5671 // coherent the DAG creation, no setcc node is created in this case 5672 return N2; 5673 } else if (SCC.getOpcode() == ISD::SETCC) { 5674 // Fold to a simpler select_cc 5675 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5676 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5677 SCC.getOperand(2)); 5678 } 5679 } 5680 5681 // If we can fold this based on the true/false value, do so. 5682 if (SimplifySelectOps(N, N2, N3)) 5683 return SDValue(N, 0); // Don't revisit N. 5684 5685 // fold select_cc into other things, such as min/max/abs 5686 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5687 } 5688 5689 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5690 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5691 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5692 SDLoc(N)); 5693 } 5694 5695 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5696 SDValue LHS = N->getOperand(0); 5697 SDValue RHS = N->getOperand(1); 5698 SDValue Carry = N->getOperand(2); 5699 SDValue Cond = N->getOperand(3); 5700 5701 // If Carry is false, fold to a regular SETCC. 5702 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5703 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5704 5705 return SDValue(); 5706 } 5707 5708 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5709 /// a build_vector of constants. 5710 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5711 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5712 /// Vector extends are not folded if operations are legal; this is to 5713 /// avoid introducing illegal build_vector dag nodes. 5714 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5715 SelectionDAG &DAG, bool LegalTypes, 5716 bool LegalOperations) { 5717 unsigned Opcode = N->getOpcode(); 5718 SDValue N0 = N->getOperand(0); 5719 EVT VT = N->getValueType(0); 5720 5721 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5722 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5723 && "Expected EXTEND dag node in input!"); 5724 5725 // fold (sext c1) -> c1 5726 // fold (zext c1) -> c1 5727 // fold (aext c1) -> c1 5728 if (isa<ConstantSDNode>(N0)) 5729 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5730 5731 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5732 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5733 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5734 EVT SVT = VT.getScalarType(); 5735 if (!(VT.isVector() && 5736 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5737 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5738 return nullptr; 5739 5740 // We can fold this node into a build_vector. 5741 unsigned VTBits = SVT.getSizeInBits(); 5742 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5743 SmallVector<SDValue, 8> Elts; 5744 unsigned NumElts = VT.getVectorNumElements(); 5745 SDLoc DL(N); 5746 5747 for (unsigned i=0; i != NumElts; ++i) { 5748 SDValue Op = N0->getOperand(i); 5749 if (Op->getOpcode() == ISD::UNDEF) { 5750 Elts.push_back(DAG.getUNDEF(SVT)); 5751 continue; 5752 } 5753 5754 SDLoc DL(Op); 5755 // Get the constant value and if needed trunc it to the size of the type. 5756 // Nodes like build_vector might have constants wider than the scalar type. 5757 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5758 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5759 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5760 else 5761 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5762 } 5763 5764 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5765 } 5766 5767 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5768 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5769 // transformation. Returns true if extension are possible and the above 5770 // mentioned transformation is profitable. 5771 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5772 unsigned ExtOpc, 5773 SmallVectorImpl<SDNode *> &ExtendNodes, 5774 const TargetLowering &TLI) { 5775 bool HasCopyToRegUses = false; 5776 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5777 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5778 UE = N0.getNode()->use_end(); 5779 UI != UE; ++UI) { 5780 SDNode *User = *UI; 5781 if (User == N) 5782 continue; 5783 if (UI.getUse().getResNo() != N0.getResNo()) 5784 continue; 5785 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5786 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5787 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5788 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5789 // Sign bits will be lost after a zext. 5790 return false; 5791 bool Add = false; 5792 for (unsigned i = 0; i != 2; ++i) { 5793 SDValue UseOp = User->getOperand(i); 5794 if (UseOp == N0) 5795 continue; 5796 if (!isa<ConstantSDNode>(UseOp)) 5797 return false; 5798 Add = true; 5799 } 5800 if (Add) 5801 ExtendNodes.push_back(User); 5802 continue; 5803 } 5804 // If truncates aren't free and there are users we can't 5805 // extend, it isn't worthwhile. 5806 if (!isTruncFree) 5807 return false; 5808 // Remember if this value is live-out. 5809 if (User->getOpcode() == ISD::CopyToReg) 5810 HasCopyToRegUses = true; 5811 } 5812 5813 if (HasCopyToRegUses) { 5814 bool BothLiveOut = false; 5815 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5816 UI != UE; ++UI) { 5817 SDUse &Use = UI.getUse(); 5818 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5819 BothLiveOut = true; 5820 break; 5821 } 5822 } 5823 if (BothLiveOut) 5824 // Both unextended and extended values are live out. There had better be 5825 // a good reason for the transformation. 5826 return ExtendNodes.size(); 5827 } 5828 return true; 5829 } 5830 5831 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5832 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5833 ISD::NodeType ExtType) { 5834 // Extend SetCC uses if necessary. 5835 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5836 SDNode *SetCC = SetCCs[i]; 5837 SmallVector<SDValue, 4> Ops; 5838 5839 for (unsigned j = 0; j != 2; ++j) { 5840 SDValue SOp = SetCC->getOperand(j); 5841 if (SOp == Trunc) 5842 Ops.push_back(ExtLoad); 5843 else 5844 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5845 } 5846 5847 Ops.push_back(SetCC->getOperand(2)); 5848 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5849 } 5850 } 5851 5852 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5853 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5854 SDValue N0 = N->getOperand(0); 5855 EVT DstVT = N->getValueType(0); 5856 EVT SrcVT = N0.getValueType(); 5857 5858 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5859 N->getOpcode() == ISD::ZERO_EXTEND) && 5860 "Unexpected node type (not an extend)!"); 5861 5862 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5863 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5864 // (v8i32 (sext (v8i16 (load x)))) 5865 // into: 5866 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5867 // (v4i32 (sextload (x + 16))))) 5868 // Where uses of the original load, i.e.: 5869 // (v8i16 (load x)) 5870 // are replaced with: 5871 // (v8i16 (truncate 5872 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5873 // (v4i32 (sextload (x + 16))))))) 5874 // 5875 // This combine is only applicable to illegal, but splittable, vectors. 5876 // All legal types, and illegal non-vector types, are handled elsewhere. 5877 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5878 // 5879 if (N0->getOpcode() != ISD::LOAD) 5880 return SDValue(); 5881 5882 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5883 5884 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5885 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5886 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5887 return SDValue(); 5888 5889 SmallVector<SDNode *, 4> SetCCs; 5890 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5891 return SDValue(); 5892 5893 ISD::LoadExtType ExtType = 5894 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5895 5896 // Try to split the vector types to get down to legal types. 5897 EVT SplitSrcVT = SrcVT; 5898 EVT SplitDstVT = DstVT; 5899 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5900 SplitSrcVT.getVectorNumElements() > 1) { 5901 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5902 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5903 } 5904 5905 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5906 return SDValue(); 5907 5908 SDLoc DL(N); 5909 const unsigned NumSplits = 5910 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5911 const unsigned Stride = SplitSrcVT.getStoreSize(); 5912 SmallVector<SDValue, 4> Loads; 5913 SmallVector<SDValue, 4> Chains; 5914 5915 SDValue BasePtr = LN0->getBasePtr(); 5916 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5917 const unsigned Offset = Idx * Stride; 5918 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5919 5920 SDValue SplitLoad = DAG.getExtLoad( 5921 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5922 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5923 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5924 Align, LN0->getAAInfo()); 5925 5926 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5927 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5928 5929 Loads.push_back(SplitLoad.getValue(0)); 5930 Chains.push_back(SplitLoad.getValue(1)); 5931 } 5932 5933 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5934 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5935 5936 CombineTo(N, NewValue); 5937 5938 // Replace uses of the original load (before extension) 5939 // with a truncate of the concatenated sextloaded vectors. 5940 SDValue Trunc = 5941 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5942 CombineTo(N0.getNode(), Trunc, NewChain); 5943 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5944 (ISD::NodeType)N->getOpcode()); 5945 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5946 } 5947 5948 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5949 SDValue N0 = N->getOperand(0); 5950 EVT VT = N->getValueType(0); 5951 5952 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5953 LegalOperations)) 5954 return SDValue(Res, 0); 5955 5956 // fold (sext (sext x)) -> (sext x) 5957 // fold (sext (aext x)) -> (sext x) 5958 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5959 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5960 N0.getOperand(0)); 5961 5962 if (N0.getOpcode() == ISD::TRUNCATE) { 5963 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5964 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5965 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5966 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5967 if (NarrowLoad.getNode() != N0.getNode()) { 5968 CombineTo(N0.getNode(), NarrowLoad); 5969 // CombineTo deleted the truncate, if needed, but not what's under it. 5970 AddToWorklist(oye); 5971 } 5972 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5973 } 5974 5975 // See if the value being truncated is already sign extended. If so, just 5976 // eliminate the trunc/sext pair. 5977 SDValue Op = N0.getOperand(0); 5978 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5979 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5980 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5981 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5982 5983 if (OpBits == DestBits) { 5984 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5985 // bits, it is already ready. 5986 if (NumSignBits > DestBits-MidBits) 5987 return Op; 5988 } else if (OpBits < DestBits) { 5989 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5990 // bits, just sext from i32. 5991 if (NumSignBits > OpBits-MidBits) 5992 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5993 } else { 5994 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5995 // bits, just truncate to i32. 5996 if (NumSignBits > OpBits-MidBits) 5997 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5998 } 5999 6000 // fold (sext (truncate x)) -> (sextinreg x). 6001 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6002 N0.getValueType())) { 6003 if (OpBits < DestBits) 6004 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6005 else if (OpBits > DestBits) 6006 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6007 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6008 DAG.getValueType(N0.getValueType())); 6009 } 6010 } 6011 6012 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6013 // Only generate vector extloads when 1) they're legal, and 2) they are 6014 // deemed desirable by the target. 6015 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6016 ((!LegalOperations && !VT.isVector() && 6017 !cast<LoadSDNode>(N0)->isVolatile()) || 6018 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6019 bool DoXform = true; 6020 SmallVector<SDNode*, 4> SetCCs; 6021 if (!N0.hasOneUse()) 6022 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6023 if (VT.isVector()) 6024 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6025 if (DoXform) { 6026 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6027 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6028 LN0->getChain(), 6029 LN0->getBasePtr(), N0.getValueType(), 6030 LN0->getMemOperand()); 6031 CombineTo(N, ExtLoad); 6032 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6033 N0.getValueType(), ExtLoad); 6034 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6035 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6036 ISD::SIGN_EXTEND); 6037 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6038 } 6039 } 6040 6041 // fold (sext (load x)) to multiple smaller sextloads. 6042 // Only on illegal but splittable vectors. 6043 if (SDValue ExtLoad = CombineExtLoad(N)) 6044 return ExtLoad; 6045 6046 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6047 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6048 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6049 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6050 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6051 EVT MemVT = LN0->getMemoryVT(); 6052 if ((!LegalOperations && !LN0->isVolatile()) || 6053 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6054 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6055 LN0->getChain(), 6056 LN0->getBasePtr(), MemVT, 6057 LN0->getMemOperand()); 6058 CombineTo(N, ExtLoad); 6059 CombineTo(N0.getNode(), 6060 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6061 N0.getValueType(), ExtLoad), 6062 ExtLoad.getValue(1)); 6063 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6064 } 6065 } 6066 6067 // fold (sext (and/or/xor (load x), cst)) -> 6068 // (and/or/xor (sextload x), (sext cst)) 6069 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6070 N0.getOpcode() == ISD::XOR) && 6071 isa<LoadSDNode>(N0.getOperand(0)) && 6072 N0.getOperand(1).getOpcode() == ISD::Constant && 6073 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6074 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6075 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6076 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6077 bool DoXform = true; 6078 SmallVector<SDNode*, 4> SetCCs; 6079 if (!N0.hasOneUse()) 6080 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6081 SetCCs, TLI); 6082 if (DoXform) { 6083 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6084 LN0->getChain(), LN0->getBasePtr(), 6085 LN0->getMemoryVT(), 6086 LN0->getMemOperand()); 6087 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6088 Mask = Mask.sext(VT.getSizeInBits()); 6089 SDLoc DL(N); 6090 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6091 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6092 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6093 SDLoc(N0.getOperand(0)), 6094 N0.getOperand(0).getValueType(), ExtLoad); 6095 CombineTo(N, And); 6096 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6097 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6098 ISD::SIGN_EXTEND); 6099 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6100 } 6101 } 6102 } 6103 6104 if (N0.getOpcode() == ISD::SETCC) { 6105 EVT N0VT = N0.getOperand(0).getValueType(); 6106 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6107 // Only do this before legalize for now. 6108 if (VT.isVector() && !LegalOperations && 6109 TLI.getBooleanContents(N0VT) == 6110 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6111 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6112 // of the same size as the compared operands. Only optimize sext(setcc()) 6113 // if this is the case. 6114 EVT SVT = getSetCCResultType(N0VT); 6115 6116 // We know that the # elements of the results is the same as the 6117 // # elements of the compare (and the # elements of the compare result 6118 // for that matter). Check to see that they are the same size. If so, 6119 // we know that the element size of the sext'd result matches the 6120 // element size of the compare operands. 6121 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6122 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6123 N0.getOperand(1), 6124 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6125 6126 // If the desired elements are smaller or larger than the source 6127 // elements we can use a matching integer vector type and then 6128 // truncate/sign extend 6129 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6130 if (SVT == MatchingVectorType) { 6131 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6132 N0.getOperand(0), N0.getOperand(1), 6133 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6134 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6135 } 6136 } 6137 6138 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6139 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6140 SDLoc DL(N); 6141 SDValue NegOne = 6142 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6143 SDValue SCC = 6144 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6145 NegOne, DAG.getConstant(0, DL, VT), 6146 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6147 if (SCC.getNode()) return SCC; 6148 6149 if (!VT.isVector()) { 6150 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6151 if (!LegalOperations || 6152 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6153 SDLoc DL(N); 6154 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6155 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6156 N0.getOperand(0), N0.getOperand(1), CC); 6157 return DAG.getSelect(DL, VT, SetCC, 6158 NegOne, DAG.getConstant(0, DL, VT)); 6159 } 6160 } 6161 } 6162 6163 // fold (sext x) -> (zext x) if the sign bit is known zero. 6164 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6165 DAG.SignBitIsZero(N0)) 6166 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6167 6168 return SDValue(); 6169 } 6170 6171 // isTruncateOf - If N is a truncate of some other value, return true, record 6172 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6173 // This function computes KnownZero to avoid a duplicated call to 6174 // computeKnownBits in the caller. 6175 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6176 APInt &KnownZero) { 6177 APInt KnownOne; 6178 if (N->getOpcode() == ISD::TRUNCATE) { 6179 Op = N->getOperand(0); 6180 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6181 return true; 6182 } 6183 6184 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6185 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6186 return false; 6187 6188 SDValue Op0 = N->getOperand(0); 6189 SDValue Op1 = N->getOperand(1); 6190 assert(Op0.getValueType() == Op1.getValueType()); 6191 6192 if (isNullConstant(Op0)) 6193 Op = Op1; 6194 else if (isNullConstant(Op1)) 6195 Op = Op0; 6196 else 6197 return false; 6198 6199 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6200 6201 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6202 return false; 6203 6204 return true; 6205 } 6206 6207 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6208 SDValue N0 = N->getOperand(0); 6209 EVT VT = N->getValueType(0); 6210 6211 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6212 LegalOperations)) 6213 return SDValue(Res, 0); 6214 6215 // fold (zext (zext x)) -> (zext x) 6216 // fold (zext (aext x)) -> (zext x) 6217 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6218 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6219 N0.getOperand(0)); 6220 6221 // fold (zext (truncate x)) -> (zext x) or 6222 // (zext (truncate x)) -> (truncate x) 6223 // This is valid when the truncated bits of x are already zero. 6224 // FIXME: We should extend this to work for vectors too. 6225 SDValue Op; 6226 APInt KnownZero; 6227 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6228 APInt TruncatedBits = 6229 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6230 APInt(Op.getValueSizeInBits(), 0) : 6231 APInt::getBitsSet(Op.getValueSizeInBits(), 6232 N0.getValueSizeInBits(), 6233 std::min(Op.getValueSizeInBits(), 6234 VT.getSizeInBits())); 6235 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6236 if (VT.bitsGT(Op.getValueType())) 6237 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6238 if (VT.bitsLT(Op.getValueType())) 6239 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6240 6241 return Op; 6242 } 6243 } 6244 6245 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6246 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6247 if (N0.getOpcode() == ISD::TRUNCATE) { 6248 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6249 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6250 if (NarrowLoad.getNode() != N0.getNode()) { 6251 CombineTo(N0.getNode(), NarrowLoad); 6252 // CombineTo deleted the truncate, if needed, but not what's under it. 6253 AddToWorklist(oye); 6254 } 6255 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6256 } 6257 } 6258 6259 // fold (zext (truncate x)) -> (and x, mask) 6260 if (N0.getOpcode() == ISD::TRUNCATE) { 6261 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6262 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6263 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6264 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6265 if (NarrowLoad.getNode() != N0.getNode()) { 6266 CombineTo(N0.getNode(), NarrowLoad); 6267 // CombineTo deleted the truncate, if needed, but not what's under it. 6268 AddToWorklist(oye); 6269 } 6270 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6271 } 6272 6273 EVT SrcVT = N0.getOperand(0).getValueType(); 6274 EVT MinVT = N0.getValueType(); 6275 6276 // Try to mask before the extension to avoid having to generate a larger mask, 6277 // possibly over several sub-vectors. 6278 if (SrcVT.bitsLT(VT)) { 6279 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6280 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6281 SDValue Op = N0.getOperand(0); 6282 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6283 AddToWorklist(Op.getNode()); 6284 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6285 } 6286 } 6287 6288 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6289 SDValue Op = N0.getOperand(0); 6290 if (SrcVT.bitsLT(VT)) { 6291 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6292 AddToWorklist(Op.getNode()); 6293 } else if (SrcVT.bitsGT(VT)) { 6294 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6295 AddToWorklist(Op.getNode()); 6296 } 6297 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6298 } 6299 } 6300 6301 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6302 // if either of the casts is not free. 6303 if (N0.getOpcode() == ISD::AND && 6304 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6305 N0.getOperand(1).getOpcode() == ISD::Constant && 6306 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6307 N0.getValueType()) || 6308 !TLI.isZExtFree(N0.getValueType(), VT))) { 6309 SDValue X = N0.getOperand(0).getOperand(0); 6310 if (X.getValueType().bitsLT(VT)) { 6311 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6312 } else if (X.getValueType().bitsGT(VT)) { 6313 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6314 } 6315 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6316 Mask = Mask.zext(VT.getSizeInBits()); 6317 SDLoc DL(N); 6318 return DAG.getNode(ISD::AND, DL, VT, 6319 X, DAG.getConstant(Mask, DL, VT)); 6320 } 6321 6322 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6323 // Only generate vector extloads when 1) they're legal, and 2) they are 6324 // deemed desirable by the target. 6325 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6326 ((!LegalOperations && !VT.isVector() && 6327 !cast<LoadSDNode>(N0)->isVolatile()) || 6328 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6329 bool DoXform = true; 6330 SmallVector<SDNode*, 4> SetCCs; 6331 if (!N0.hasOneUse()) 6332 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6333 if (VT.isVector()) 6334 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6335 if (DoXform) { 6336 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6337 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6338 LN0->getChain(), 6339 LN0->getBasePtr(), N0.getValueType(), 6340 LN0->getMemOperand()); 6341 CombineTo(N, ExtLoad); 6342 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6343 N0.getValueType(), ExtLoad); 6344 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6345 6346 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6347 ISD::ZERO_EXTEND); 6348 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6349 } 6350 } 6351 6352 // fold (zext (load x)) to multiple smaller zextloads. 6353 // Only on illegal but splittable vectors. 6354 if (SDValue ExtLoad = CombineExtLoad(N)) 6355 return ExtLoad; 6356 6357 // fold (zext (and/or/xor (load x), cst)) -> 6358 // (and/or/xor (zextload x), (zext cst)) 6359 // Unless (and (load x) cst) will match as a zextload already and has 6360 // additional users. 6361 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6362 N0.getOpcode() == ISD::XOR) && 6363 isa<LoadSDNode>(N0.getOperand(0)) && 6364 N0.getOperand(1).getOpcode() == ISD::Constant && 6365 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6366 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6367 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6368 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6369 bool DoXform = true; 6370 SmallVector<SDNode*, 4> SetCCs; 6371 if (!N0.hasOneUse()) { 6372 if (N0.getOpcode() == ISD::AND) { 6373 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6374 auto NarrowLoad = false; 6375 EVT LoadResultTy = AndC->getValueType(0); 6376 EVT ExtVT, LoadedVT; 6377 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6378 NarrowLoad)) 6379 DoXform = false; 6380 } 6381 if (DoXform) 6382 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6383 ISD::ZERO_EXTEND, SetCCs, TLI); 6384 } 6385 if (DoXform) { 6386 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6387 LN0->getChain(), LN0->getBasePtr(), 6388 LN0->getMemoryVT(), 6389 LN0->getMemOperand()); 6390 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6391 Mask = Mask.zext(VT.getSizeInBits()); 6392 SDLoc DL(N); 6393 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6394 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6395 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6396 SDLoc(N0.getOperand(0)), 6397 N0.getOperand(0).getValueType(), ExtLoad); 6398 CombineTo(N, And); 6399 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6400 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6401 ISD::ZERO_EXTEND); 6402 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6403 } 6404 } 6405 } 6406 6407 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6408 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6409 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6410 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6411 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6412 EVT MemVT = LN0->getMemoryVT(); 6413 if ((!LegalOperations && !LN0->isVolatile()) || 6414 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6415 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6416 LN0->getChain(), 6417 LN0->getBasePtr(), MemVT, 6418 LN0->getMemOperand()); 6419 CombineTo(N, ExtLoad); 6420 CombineTo(N0.getNode(), 6421 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6422 ExtLoad), 6423 ExtLoad.getValue(1)); 6424 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6425 } 6426 } 6427 6428 if (N0.getOpcode() == ISD::SETCC) { 6429 if (!LegalOperations && VT.isVector() && 6430 N0.getValueType().getVectorElementType() == MVT::i1) { 6431 EVT N0VT = N0.getOperand(0).getValueType(); 6432 if (getSetCCResultType(N0VT) == N0.getValueType()) 6433 return SDValue(); 6434 6435 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6436 // Only do this before legalize for now. 6437 EVT EltVT = VT.getVectorElementType(); 6438 SDLoc DL(N); 6439 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6440 DAG.getConstant(1, DL, EltVT)); 6441 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6442 // We know that the # elements of the results is the same as the 6443 // # elements of the compare (and the # elements of the compare result 6444 // for that matter). Check to see that they are the same size. If so, 6445 // we know that the element size of the sext'd result matches the 6446 // element size of the compare operands. 6447 return DAG.getNode(ISD::AND, DL, VT, 6448 DAG.getSetCC(DL, VT, N0.getOperand(0), 6449 N0.getOperand(1), 6450 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6451 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6452 OneOps)); 6453 6454 // If the desired elements are smaller or larger than the source 6455 // elements we can use a matching integer vector type and then 6456 // truncate/sign extend 6457 EVT MatchingElementType = 6458 EVT::getIntegerVT(*DAG.getContext(), 6459 N0VT.getScalarType().getSizeInBits()); 6460 EVT MatchingVectorType = 6461 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6462 N0VT.getVectorNumElements()); 6463 SDValue VsetCC = 6464 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6465 N0.getOperand(1), 6466 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6467 return DAG.getNode(ISD::AND, DL, VT, 6468 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6469 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6470 } 6471 6472 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6473 SDLoc DL(N); 6474 SDValue SCC = 6475 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6476 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6477 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6478 if (SCC.getNode()) return SCC; 6479 } 6480 6481 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6482 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6483 isa<ConstantSDNode>(N0.getOperand(1)) && 6484 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6485 N0.hasOneUse()) { 6486 SDValue ShAmt = N0.getOperand(1); 6487 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6488 if (N0.getOpcode() == ISD::SHL) { 6489 SDValue InnerZExt = N0.getOperand(0); 6490 // If the original shl may be shifting out bits, do not perform this 6491 // transformation. 6492 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6493 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6494 if (ShAmtVal > KnownZeroBits) 6495 return SDValue(); 6496 } 6497 6498 SDLoc DL(N); 6499 6500 // Ensure that the shift amount is wide enough for the shifted value. 6501 if (VT.getSizeInBits() >= 256) 6502 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6503 6504 return DAG.getNode(N0.getOpcode(), DL, VT, 6505 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6506 ShAmt); 6507 } 6508 6509 return SDValue(); 6510 } 6511 6512 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6513 SDValue N0 = N->getOperand(0); 6514 EVT VT = N->getValueType(0); 6515 6516 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6517 LegalOperations)) 6518 return SDValue(Res, 0); 6519 6520 // fold (aext (aext x)) -> (aext x) 6521 // fold (aext (zext x)) -> (zext x) 6522 // fold (aext (sext x)) -> (sext x) 6523 if (N0.getOpcode() == ISD::ANY_EXTEND || 6524 N0.getOpcode() == ISD::ZERO_EXTEND || 6525 N0.getOpcode() == ISD::SIGN_EXTEND) 6526 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6527 6528 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6529 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6530 if (N0.getOpcode() == ISD::TRUNCATE) { 6531 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6532 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6533 if (NarrowLoad.getNode() != N0.getNode()) { 6534 CombineTo(N0.getNode(), NarrowLoad); 6535 // CombineTo deleted the truncate, if needed, but not what's under it. 6536 AddToWorklist(oye); 6537 } 6538 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6539 } 6540 } 6541 6542 // fold (aext (truncate x)) 6543 if (N0.getOpcode() == ISD::TRUNCATE) { 6544 SDValue TruncOp = N0.getOperand(0); 6545 if (TruncOp.getValueType() == VT) 6546 return TruncOp; // x iff x size == zext size. 6547 if (TruncOp.getValueType().bitsGT(VT)) 6548 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6549 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6550 } 6551 6552 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6553 // if the trunc is not free. 6554 if (N0.getOpcode() == ISD::AND && 6555 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6556 N0.getOperand(1).getOpcode() == ISD::Constant && 6557 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6558 N0.getValueType())) { 6559 SDValue X = N0.getOperand(0).getOperand(0); 6560 if (X.getValueType().bitsLT(VT)) { 6561 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6562 } else if (X.getValueType().bitsGT(VT)) { 6563 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6564 } 6565 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6566 Mask = Mask.zext(VT.getSizeInBits()); 6567 SDLoc DL(N); 6568 return DAG.getNode(ISD::AND, DL, VT, 6569 X, DAG.getConstant(Mask, DL, VT)); 6570 } 6571 6572 // fold (aext (load x)) -> (aext (truncate (extload x))) 6573 // None of the supported targets knows how to perform load and any_ext 6574 // on vectors in one instruction. We only perform this transformation on 6575 // scalars. 6576 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6577 ISD::isUNINDEXEDLoad(N0.getNode()) && 6578 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6579 bool DoXform = true; 6580 SmallVector<SDNode*, 4> SetCCs; 6581 if (!N0.hasOneUse()) 6582 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6583 if (DoXform) { 6584 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6585 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6586 LN0->getChain(), 6587 LN0->getBasePtr(), N0.getValueType(), 6588 LN0->getMemOperand()); 6589 CombineTo(N, ExtLoad); 6590 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6591 N0.getValueType(), ExtLoad); 6592 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6593 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6594 ISD::ANY_EXTEND); 6595 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6596 } 6597 } 6598 6599 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6600 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6601 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6602 if (N0.getOpcode() == ISD::LOAD && 6603 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6604 N0.hasOneUse()) { 6605 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6606 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6607 EVT MemVT = LN0->getMemoryVT(); 6608 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6609 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6610 VT, LN0->getChain(), LN0->getBasePtr(), 6611 MemVT, LN0->getMemOperand()); 6612 CombineTo(N, ExtLoad); 6613 CombineTo(N0.getNode(), 6614 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6615 N0.getValueType(), ExtLoad), 6616 ExtLoad.getValue(1)); 6617 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6618 } 6619 } 6620 6621 if (N0.getOpcode() == ISD::SETCC) { 6622 // For vectors: 6623 // aext(setcc) -> vsetcc 6624 // aext(setcc) -> truncate(vsetcc) 6625 // aext(setcc) -> aext(vsetcc) 6626 // Only do this before legalize for now. 6627 if (VT.isVector() && !LegalOperations) { 6628 EVT N0VT = N0.getOperand(0).getValueType(); 6629 // We know that the # elements of the results is the same as the 6630 // # elements of the compare (and the # elements of the compare result 6631 // for that matter). Check to see that they are the same size. If so, 6632 // we know that the element size of the sext'd result matches the 6633 // element size of the compare operands. 6634 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6635 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6636 N0.getOperand(1), 6637 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6638 // If the desired elements are smaller or larger than the source 6639 // elements we can use a matching integer vector type and then 6640 // truncate/any extend 6641 else { 6642 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6643 SDValue VsetCC = 6644 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6645 N0.getOperand(1), 6646 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6647 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6648 } 6649 } 6650 6651 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6652 SDLoc DL(N); 6653 SDValue SCC = 6654 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6655 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6656 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6657 if (SCC.getNode()) 6658 return SCC; 6659 } 6660 6661 return SDValue(); 6662 } 6663 6664 /// See if the specified operand can be simplified with the knowledge that only 6665 /// the bits specified by Mask are used. If so, return the simpler operand, 6666 /// otherwise return a null SDValue. 6667 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6668 switch (V.getOpcode()) { 6669 default: break; 6670 case ISD::Constant: { 6671 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6672 assert(CV && "Const value should be ConstSDNode."); 6673 const APInt &CVal = CV->getAPIntValue(); 6674 APInt NewVal = CVal & Mask; 6675 if (NewVal != CVal) 6676 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6677 break; 6678 } 6679 case ISD::OR: 6680 case ISD::XOR: 6681 // If the LHS or RHS don't contribute bits to the or, drop them. 6682 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6683 return V.getOperand(1); 6684 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6685 return V.getOperand(0); 6686 break; 6687 case ISD::SRL: 6688 // Only look at single-use SRLs. 6689 if (!V.getNode()->hasOneUse()) 6690 break; 6691 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6692 // See if we can recursively simplify the LHS. 6693 unsigned Amt = RHSC->getZExtValue(); 6694 6695 // Watch out for shift count overflow though. 6696 if (Amt >= Mask.getBitWidth()) break; 6697 APInt NewMask = Mask << Amt; 6698 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6699 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6700 SimplifyLHS, V.getOperand(1)); 6701 } 6702 } 6703 return SDValue(); 6704 } 6705 6706 /// If the result of a wider load is shifted to right of N bits and then 6707 /// truncated to a narrower type and where N is a multiple of number of bits of 6708 /// the narrower type, transform it to a narrower load from address + N / num of 6709 /// bits of new type. If the result is to be extended, also fold the extension 6710 /// to form a extending load. 6711 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6712 unsigned Opc = N->getOpcode(); 6713 6714 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6715 SDValue N0 = N->getOperand(0); 6716 EVT VT = N->getValueType(0); 6717 EVT ExtVT = VT; 6718 6719 // This transformation isn't valid for vector loads. 6720 if (VT.isVector()) 6721 return SDValue(); 6722 6723 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6724 // extended to VT. 6725 if (Opc == ISD::SIGN_EXTEND_INREG) { 6726 ExtType = ISD::SEXTLOAD; 6727 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6728 } else if (Opc == ISD::SRL) { 6729 // Another special-case: SRL is basically zero-extending a narrower value. 6730 ExtType = ISD::ZEXTLOAD; 6731 N0 = SDValue(N, 0); 6732 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6733 if (!N01) return SDValue(); 6734 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6735 VT.getSizeInBits() - N01->getZExtValue()); 6736 } 6737 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6738 return SDValue(); 6739 6740 unsigned EVTBits = ExtVT.getSizeInBits(); 6741 6742 // Do not generate loads of non-round integer types since these can 6743 // be expensive (and would be wrong if the type is not byte sized). 6744 if (!ExtVT.isRound()) 6745 return SDValue(); 6746 6747 unsigned ShAmt = 0; 6748 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6749 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6750 ShAmt = N01->getZExtValue(); 6751 // Is the shift amount a multiple of size of VT? 6752 if ((ShAmt & (EVTBits-1)) == 0) { 6753 N0 = N0.getOperand(0); 6754 // Is the load width a multiple of size of VT? 6755 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6756 return SDValue(); 6757 } 6758 6759 // At this point, we must have a load or else we can't do the transform. 6760 if (!isa<LoadSDNode>(N0)) return SDValue(); 6761 6762 // Because a SRL must be assumed to *need* to zero-extend the high bits 6763 // (as opposed to anyext the high bits), we can't combine the zextload 6764 // lowering of SRL and an sextload. 6765 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6766 return SDValue(); 6767 6768 // If the shift amount is larger than the input type then we're not 6769 // accessing any of the loaded bytes. If the load was a zextload/extload 6770 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6771 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6772 return SDValue(); 6773 } 6774 } 6775 6776 // If the load is shifted left (and the result isn't shifted back right), 6777 // we can fold the truncate through the shift. 6778 unsigned ShLeftAmt = 0; 6779 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6780 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6781 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6782 ShLeftAmt = N01->getZExtValue(); 6783 N0 = N0.getOperand(0); 6784 } 6785 } 6786 6787 // If we haven't found a load, we can't narrow it. Don't transform one with 6788 // multiple uses, this would require adding a new load. 6789 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6790 return SDValue(); 6791 6792 // Don't change the width of a volatile load. 6793 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6794 if (LN0->isVolatile()) 6795 return SDValue(); 6796 6797 // Verify that we are actually reducing a load width here. 6798 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6799 return SDValue(); 6800 6801 // For the transform to be legal, the load must produce only two values 6802 // (the value loaded and the chain). Don't transform a pre-increment 6803 // load, for example, which produces an extra value. Otherwise the 6804 // transformation is not equivalent, and the downstream logic to replace 6805 // uses gets things wrong. 6806 if (LN0->getNumValues() > 2) 6807 return SDValue(); 6808 6809 // If the load that we're shrinking is an extload and we're not just 6810 // discarding the extension we can't simply shrink the load. Bail. 6811 // TODO: It would be possible to merge the extensions in some cases. 6812 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6813 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6814 return SDValue(); 6815 6816 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6817 return SDValue(); 6818 6819 EVT PtrType = N0.getOperand(1).getValueType(); 6820 6821 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6822 // It's not possible to generate a constant of extended or untyped type. 6823 return SDValue(); 6824 6825 // For big endian targets, we need to adjust the offset to the pointer to 6826 // load the correct bytes. 6827 if (DAG.getDataLayout().isBigEndian()) { 6828 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6829 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6830 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6831 } 6832 6833 uint64_t PtrOff = ShAmt / 8; 6834 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6835 SDLoc DL(LN0); 6836 // The original load itself didn't wrap, so an offset within it doesn't. 6837 SDNodeFlags Flags; 6838 Flags.setNoUnsignedWrap(true); 6839 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6840 PtrType, LN0->getBasePtr(), 6841 DAG.getConstant(PtrOff, DL, PtrType), 6842 &Flags); 6843 AddToWorklist(NewPtr.getNode()); 6844 6845 SDValue Load; 6846 if (ExtType == ISD::NON_EXTLOAD) 6847 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6848 LN0->getPointerInfo().getWithOffset(PtrOff), 6849 LN0->isVolatile(), LN0->isNonTemporal(), 6850 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6851 else 6852 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6853 LN0->getPointerInfo().getWithOffset(PtrOff), 6854 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6855 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6856 6857 // Replace the old load's chain with the new load's chain. 6858 WorklistRemover DeadNodes(*this); 6859 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6860 6861 // Shift the result left, if we've swallowed a left shift. 6862 SDValue Result = Load; 6863 if (ShLeftAmt != 0) { 6864 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6865 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6866 ShImmTy = VT; 6867 // If the shift amount is as large as the result size (but, presumably, 6868 // no larger than the source) then the useful bits of the result are 6869 // zero; we can't simply return the shortened shift, because the result 6870 // of that operation is undefined. 6871 SDLoc DL(N0); 6872 if (ShLeftAmt >= VT.getSizeInBits()) 6873 Result = DAG.getConstant(0, DL, VT); 6874 else 6875 Result = DAG.getNode(ISD::SHL, DL, VT, 6876 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6877 } 6878 6879 // Return the new loaded value. 6880 return Result; 6881 } 6882 6883 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6884 SDValue N0 = N->getOperand(0); 6885 SDValue N1 = N->getOperand(1); 6886 EVT VT = N->getValueType(0); 6887 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6888 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6889 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6890 6891 if (N0.isUndef()) 6892 return DAG.getUNDEF(VT); 6893 6894 // fold (sext_in_reg c1) -> c1 6895 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6896 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6897 6898 // If the input is already sign extended, just drop the extension. 6899 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6900 return N0; 6901 6902 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6903 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6904 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6905 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6906 N0.getOperand(0), N1); 6907 6908 // fold (sext_in_reg (sext x)) -> (sext x) 6909 // fold (sext_in_reg (aext x)) -> (sext x) 6910 // if x is small enough. 6911 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6912 SDValue N00 = N0.getOperand(0); 6913 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6914 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6915 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6916 } 6917 6918 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6919 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6920 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6921 6922 // fold operands of sext_in_reg based on knowledge that the top bits are not 6923 // demanded. 6924 if (SimplifyDemandedBits(SDValue(N, 0))) 6925 return SDValue(N, 0); 6926 6927 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6928 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6929 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6930 return NarrowLoad; 6931 6932 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6933 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6934 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6935 if (N0.getOpcode() == ISD::SRL) { 6936 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6937 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6938 // We can turn this into an SRA iff the input to the SRL is already sign 6939 // extended enough. 6940 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6941 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6942 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6943 N0.getOperand(0), N0.getOperand(1)); 6944 } 6945 } 6946 6947 // fold (sext_inreg (extload x)) -> (sextload x) 6948 if (ISD::isEXTLoad(N0.getNode()) && 6949 ISD::isUNINDEXEDLoad(N0.getNode()) && 6950 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6951 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6952 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6953 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6954 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6955 LN0->getChain(), 6956 LN0->getBasePtr(), EVT, 6957 LN0->getMemOperand()); 6958 CombineTo(N, ExtLoad); 6959 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6960 AddToWorklist(ExtLoad.getNode()); 6961 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6962 } 6963 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6964 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6965 N0.hasOneUse() && 6966 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6967 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6968 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6969 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6970 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6971 LN0->getChain(), 6972 LN0->getBasePtr(), EVT, 6973 LN0->getMemOperand()); 6974 CombineTo(N, ExtLoad); 6975 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6976 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6977 } 6978 6979 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6980 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6981 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6982 N0.getOperand(1), false); 6983 if (BSwap.getNode()) 6984 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6985 BSwap, N1); 6986 } 6987 6988 return SDValue(); 6989 } 6990 6991 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 6992 SDValue N0 = N->getOperand(0); 6993 EVT VT = N->getValueType(0); 6994 6995 if (N0.getOpcode() == ISD::UNDEF) 6996 return DAG.getUNDEF(VT); 6997 6998 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6999 LegalOperations)) 7000 return SDValue(Res, 0); 7001 7002 return SDValue(); 7003 } 7004 7005 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7006 SDValue N0 = N->getOperand(0); 7007 EVT VT = N->getValueType(0); 7008 bool isLE = DAG.getDataLayout().isLittleEndian(); 7009 7010 // noop truncate 7011 if (N0.getValueType() == N->getValueType(0)) 7012 return N0; 7013 // fold (truncate c1) -> c1 7014 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7015 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7016 // fold (truncate (truncate x)) -> (truncate x) 7017 if (N0.getOpcode() == ISD::TRUNCATE) 7018 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7019 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7020 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7021 N0.getOpcode() == ISD::SIGN_EXTEND || 7022 N0.getOpcode() == ISD::ANY_EXTEND) { 7023 // if the source is smaller than the dest, we still need an extend. 7024 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7025 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7026 // if the source is larger than the dest, than we just need the truncate. 7027 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7028 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7029 // if the source and dest are the same type, we can drop both the extend 7030 // and the truncate. 7031 return N0.getOperand(0); 7032 } 7033 7034 // Fold extract-and-trunc into a narrow extract. For example: 7035 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7036 // i32 y = TRUNCATE(i64 x) 7037 // -- becomes -- 7038 // v16i8 b = BITCAST (v2i64 val) 7039 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7040 // 7041 // Note: We only run this optimization after type legalization (which often 7042 // creates this pattern) and before operation legalization after which 7043 // we need to be more careful about the vector instructions that we generate. 7044 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7045 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7046 7047 EVT VecTy = N0.getOperand(0).getValueType(); 7048 EVT ExTy = N0.getValueType(); 7049 EVT TrTy = N->getValueType(0); 7050 7051 unsigned NumElem = VecTy.getVectorNumElements(); 7052 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7053 7054 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7055 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7056 7057 SDValue EltNo = N0->getOperand(1); 7058 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7059 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7060 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7061 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7062 7063 SDLoc DL(N); 7064 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7065 DAG.getBitcast(NVT, N0.getOperand(0)), 7066 DAG.getConstant(Index, DL, IndexTy)); 7067 } 7068 } 7069 7070 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7071 if (N0.getOpcode() == ISD::SELECT) { 7072 EVT SrcVT = N0.getValueType(); 7073 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7074 TLI.isTruncateFree(SrcVT, VT)) { 7075 SDLoc SL(N0); 7076 SDValue Cond = N0.getOperand(0); 7077 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7078 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7079 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7080 } 7081 } 7082 7083 // Fold a series of buildvector, bitcast, and truncate if possible. 7084 // For example fold 7085 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7086 // (2xi32 (buildvector x, y)). 7087 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7088 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7089 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7090 N0.getOperand(0).hasOneUse()) { 7091 7092 SDValue BuildVect = N0.getOperand(0); 7093 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7094 EVT TruncVecEltTy = VT.getVectorElementType(); 7095 7096 // Check that the element types match. 7097 if (BuildVectEltTy == TruncVecEltTy) { 7098 // Now we only need to compute the offset of the truncated elements. 7099 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7100 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7101 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7102 7103 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7104 "Invalid number of elements"); 7105 7106 SmallVector<SDValue, 8> Opnds; 7107 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7108 Opnds.push_back(BuildVect.getOperand(i)); 7109 7110 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 7111 } 7112 } 7113 7114 // See if we can simplify the input to this truncate through knowledge that 7115 // only the low bits are being used. 7116 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7117 // Currently we only perform this optimization on scalars because vectors 7118 // may have different active low bits. 7119 if (!VT.isVector()) { 7120 SDValue Shorter = 7121 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7122 VT.getSizeInBits())); 7123 if (Shorter.getNode()) 7124 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7125 } 7126 // fold (truncate (load x)) -> (smaller load x) 7127 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7128 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7129 if (SDValue Reduced = ReduceLoadWidth(N)) 7130 return Reduced; 7131 7132 // Handle the case where the load remains an extending load even 7133 // after truncation. 7134 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7135 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7136 if (!LN0->isVolatile() && 7137 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7138 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7139 VT, LN0->getChain(), LN0->getBasePtr(), 7140 LN0->getMemoryVT(), 7141 LN0->getMemOperand()); 7142 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7143 return NewLoad; 7144 } 7145 } 7146 } 7147 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7148 // where ... are all 'undef'. 7149 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7150 SmallVector<EVT, 8> VTs; 7151 SDValue V; 7152 unsigned Idx = 0; 7153 unsigned NumDefs = 0; 7154 7155 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7156 SDValue X = N0.getOperand(i); 7157 if (X.getOpcode() != ISD::UNDEF) { 7158 V = X; 7159 Idx = i; 7160 NumDefs++; 7161 } 7162 // Stop if more than one members are non-undef. 7163 if (NumDefs > 1) 7164 break; 7165 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7166 VT.getVectorElementType(), 7167 X.getValueType().getVectorNumElements())); 7168 } 7169 7170 if (NumDefs == 0) 7171 return DAG.getUNDEF(VT); 7172 7173 if (NumDefs == 1) { 7174 assert(V.getNode() && "The single defined operand is empty!"); 7175 SmallVector<SDValue, 8> Opnds; 7176 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7177 if (i != Idx) { 7178 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7179 continue; 7180 } 7181 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7182 AddToWorklist(NV.getNode()); 7183 Opnds.push_back(NV); 7184 } 7185 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7186 } 7187 } 7188 7189 // Simplify the operands using demanded-bits information. 7190 if (!VT.isVector() && 7191 SimplifyDemandedBits(SDValue(N, 0))) 7192 return SDValue(N, 0); 7193 7194 return SDValue(); 7195 } 7196 7197 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7198 SDValue Elt = N->getOperand(i); 7199 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7200 return Elt.getNode(); 7201 return Elt.getOperand(Elt.getResNo()).getNode(); 7202 } 7203 7204 /// build_pair (load, load) -> load 7205 /// if load locations are consecutive. 7206 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7207 assert(N->getOpcode() == ISD::BUILD_PAIR); 7208 7209 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7210 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7211 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7212 LD1->getAddressSpace() != LD2->getAddressSpace()) 7213 return SDValue(); 7214 EVT LD1VT = LD1->getValueType(0); 7215 7216 if (ISD::isNON_EXTLoad(LD2) && 7217 LD2->hasOneUse() && 7218 // If both are volatile this would reduce the number of volatile loads. 7219 // If one is volatile it might be ok, but play conservative and bail out. 7220 !LD1->isVolatile() && 7221 !LD2->isVolatile() && 7222 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7223 unsigned Align = LD1->getAlignment(); 7224 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7225 VT.getTypeForEVT(*DAG.getContext())); 7226 7227 if (NewAlign <= Align && 7228 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7229 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7230 LD1->getBasePtr(), LD1->getPointerInfo(), 7231 false, false, false, Align); 7232 } 7233 7234 return SDValue(); 7235 } 7236 7237 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7238 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7239 // and Lo parts; on big-endian machines it doesn't. 7240 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7241 } 7242 7243 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7244 SDValue N0 = N->getOperand(0); 7245 EVT VT = N->getValueType(0); 7246 7247 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7248 // Only do this before legalize, since afterward the target may be depending 7249 // on the bitconvert. 7250 // First check to see if this is all constant. 7251 if (!LegalTypes && 7252 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7253 VT.isVector()) { 7254 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7255 7256 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7257 assert(!DestEltVT.isVector() && 7258 "Element type of vector ValueType must not be vector!"); 7259 if (isSimple) 7260 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7261 } 7262 7263 // If the input is a constant, let getNode fold it. 7264 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7265 // If we can't allow illegal operations, we need to check that this is just 7266 // a fp -> int or int -> conversion and that the resulting operation will 7267 // be legal. 7268 if (!LegalOperations || 7269 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7270 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7271 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7272 TLI.isOperationLegal(ISD::Constant, VT))) 7273 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7274 } 7275 7276 // (conv (conv x, t1), t2) -> (conv x, t2) 7277 if (N0.getOpcode() == ISD::BITCAST) 7278 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7279 N0.getOperand(0)); 7280 7281 // fold (conv (load x)) -> (load (conv*)x) 7282 // If the resultant load doesn't need a higher alignment than the original! 7283 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7284 // Do not change the width of a volatile load. 7285 !cast<LoadSDNode>(N0)->isVolatile() && 7286 // Do not remove the cast if the types differ in endian layout. 7287 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7288 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7289 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7290 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7291 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7292 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7293 VT.getTypeForEVT(*DAG.getContext())); 7294 unsigned OrigAlign = LN0->getAlignment(); 7295 7296 if (Align <= OrigAlign) { 7297 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7298 LN0->getBasePtr(), LN0->getPointerInfo(), 7299 LN0->isVolatile(), LN0->isNonTemporal(), 7300 LN0->isInvariant(), OrigAlign, 7301 LN0->getAAInfo()); 7302 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7303 return Load; 7304 } 7305 } 7306 7307 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7308 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7309 // 7310 // For ppc_fp128: 7311 // fold (bitcast (fneg x)) -> 7312 // flipbit = signbit 7313 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7314 // 7315 // fold (bitcast (fabs x)) -> 7316 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7317 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7318 // This often reduces constant pool loads. 7319 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7320 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7321 N0.getNode()->hasOneUse() && VT.isInteger() && 7322 !VT.isVector() && !N0.getValueType().isVector()) { 7323 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7324 N0.getOperand(0)); 7325 AddToWorklist(NewConv.getNode()); 7326 7327 SDLoc DL(N); 7328 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7329 assert(VT.getSizeInBits() == 128); 7330 SDValue SignBit = DAG.getConstant( 7331 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7332 SDValue FlipBit; 7333 if (N0.getOpcode() == ISD::FNEG) { 7334 FlipBit = SignBit; 7335 AddToWorklist(FlipBit.getNode()); 7336 } else { 7337 assert(N0.getOpcode() == ISD::FABS); 7338 SDValue Hi = 7339 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7340 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7341 SDLoc(NewConv))); 7342 AddToWorklist(Hi.getNode()); 7343 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7344 AddToWorklist(FlipBit.getNode()); 7345 } 7346 SDValue FlipBits = 7347 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7348 AddToWorklist(FlipBits.getNode()); 7349 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7350 } 7351 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7352 if (N0.getOpcode() == ISD::FNEG) 7353 return DAG.getNode(ISD::XOR, DL, VT, 7354 NewConv, DAG.getConstant(SignBit, DL, VT)); 7355 assert(N0.getOpcode() == ISD::FABS); 7356 return DAG.getNode(ISD::AND, DL, VT, 7357 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7358 } 7359 7360 // fold (bitconvert (fcopysign cst, x)) -> 7361 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7362 // Note that we don't handle (copysign x, cst) because this can always be 7363 // folded to an fneg or fabs. 7364 // 7365 // For ppc_fp128: 7366 // fold (bitcast (fcopysign cst, x)) -> 7367 // flipbit = (and (extract_element 7368 // (xor (bitcast cst), (bitcast x)), 0), 7369 // signbit) 7370 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7371 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7372 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7373 VT.isInteger() && !VT.isVector()) { 7374 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7375 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7376 if (isTypeLegal(IntXVT)) { 7377 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7378 IntXVT, N0.getOperand(1)); 7379 AddToWorklist(X.getNode()); 7380 7381 // If X has a different width than the result/lhs, sext it or truncate it. 7382 unsigned VTWidth = VT.getSizeInBits(); 7383 if (OrigXWidth < VTWidth) { 7384 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7385 AddToWorklist(X.getNode()); 7386 } else if (OrigXWidth > VTWidth) { 7387 // To get the sign bit in the right place, we have to shift it right 7388 // before truncating. 7389 SDLoc DL(X); 7390 X = DAG.getNode(ISD::SRL, DL, 7391 X.getValueType(), X, 7392 DAG.getConstant(OrigXWidth-VTWidth, DL, 7393 X.getValueType())); 7394 AddToWorklist(X.getNode()); 7395 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7396 AddToWorklist(X.getNode()); 7397 } 7398 7399 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7400 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7401 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(0)), VT, 7402 N0.getOperand(0)); 7403 AddToWorklist(Cst.getNode()); 7404 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(1)), VT, 7405 N0.getOperand(1)); 7406 AddToWorklist(X.getNode()); 7407 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7408 AddToWorklist(XorResult.getNode()); 7409 SDValue XorResult64 = DAG.getNode( 7410 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7411 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7412 SDLoc(XorResult))); 7413 AddToWorklist(XorResult64.getNode()); 7414 SDValue FlipBit = 7415 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7416 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7417 AddToWorklist(FlipBit.getNode()); 7418 SDValue FlipBits = 7419 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7420 AddToWorklist(FlipBits.getNode()); 7421 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7422 } 7423 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7424 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7425 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7426 AddToWorklist(X.getNode()); 7427 7428 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7429 VT, N0.getOperand(0)); 7430 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7431 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7432 AddToWorklist(Cst.getNode()); 7433 7434 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7435 } 7436 } 7437 7438 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7439 if (N0.getOpcode() == ISD::BUILD_PAIR) 7440 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7441 return CombineLD; 7442 7443 // Remove double bitcasts from shuffles - this is often a legacy of 7444 // XformToShuffleWithZero being used to combine bitmaskings (of 7445 // float vectors bitcast to integer vectors) into shuffles. 7446 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7447 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7448 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7449 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7450 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7451 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7452 7453 // If operands are a bitcast, peek through if it casts the original VT. 7454 // If operands are a constant, just bitcast back to original VT. 7455 auto PeekThroughBitcast = [&](SDValue Op) { 7456 if (Op.getOpcode() == ISD::BITCAST && 7457 Op.getOperand(0).getValueType() == VT) 7458 return SDValue(Op.getOperand(0)); 7459 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7460 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7461 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7462 return SDValue(); 7463 }; 7464 7465 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7466 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7467 if (!(SV0 && SV1)) 7468 return SDValue(); 7469 7470 int MaskScale = 7471 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7472 SmallVector<int, 8> NewMask; 7473 for (int M : SVN->getMask()) 7474 for (int i = 0; i != MaskScale; ++i) 7475 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7476 7477 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7478 if (!LegalMask) { 7479 std::swap(SV0, SV1); 7480 ShuffleVectorSDNode::commuteMask(NewMask); 7481 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7482 } 7483 7484 if (LegalMask) 7485 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7486 } 7487 7488 return SDValue(); 7489 } 7490 7491 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7492 EVT VT = N->getValueType(0); 7493 return CombineConsecutiveLoads(N, VT); 7494 } 7495 7496 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7497 /// operands. DstEltVT indicates the destination element value type. 7498 SDValue DAGCombiner:: 7499 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7500 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7501 7502 // If this is already the right type, we're done. 7503 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7504 7505 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7506 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7507 7508 // If this is a conversion of N elements of one type to N elements of another 7509 // type, convert each element. This handles FP<->INT cases. 7510 if (SrcBitSize == DstBitSize) { 7511 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7512 BV->getValueType(0).getVectorNumElements()); 7513 7514 // Due to the FP element handling below calling this routine recursively, 7515 // we can end up with a scalar-to-vector node here. 7516 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7517 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7518 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7519 DstEltVT, BV->getOperand(0))); 7520 7521 SmallVector<SDValue, 8> Ops; 7522 for (SDValue Op : BV->op_values()) { 7523 // If the vector element type is not legal, the BUILD_VECTOR operands 7524 // are promoted and implicitly truncated. Make that explicit here. 7525 if (Op.getValueType() != SrcEltVT) 7526 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7527 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7528 DstEltVT, Op)); 7529 AddToWorklist(Ops.back().getNode()); 7530 } 7531 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7532 } 7533 7534 // Otherwise, we're growing or shrinking the elements. To avoid having to 7535 // handle annoying details of growing/shrinking FP values, we convert them to 7536 // int first. 7537 if (SrcEltVT.isFloatingPoint()) { 7538 // Convert the input float vector to a int vector where the elements are the 7539 // same sizes. 7540 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7541 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7542 SrcEltVT = IntVT; 7543 } 7544 7545 // Now we know the input is an integer vector. If the output is a FP type, 7546 // convert to integer first, then to FP of the right size. 7547 if (DstEltVT.isFloatingPoint()) { 7548 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7549 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7550 7551 // Next, convert to FP elements of the same size. 7552 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7553 } 7554 7555 SDLoc DL(BV); 7556 7557 // Okay, we know the src/dst types are both integers of differing types. 7558 // Handling growing first. 7559 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7560 if (SrcBitSize < DstBitSize) { 7561 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7562 7563 SmallVector<SDValue, 8> Ops; 7564 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7565 i += NumInputsPerOutput) { 7566 bool isLE = DAG.getDataLayout().isLittleEndian(); 7567 APInt NewBits = APInt(DstBitSize, 0); 7568 bool EltIsUndef = true; 7569 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7570 // Shift the previously computed bits over. 7571 NewBits <<= SrcBitSize; 7572 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7573 if (Op.getOpcode() == ISD::UNDEF) continue; 7574 EltIsUndef = false; 7575 7576 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7577 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7578 } 7579 7580 if (EltIsUndef) 7581 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7582 else 7583 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7584 } 7585 7586 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7587 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7588 } 7589 7590 // Finally, this must be the case where we are shrinking elements: each input 7591 // turns into multiple outputs. 7592 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7593 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7594 NumOutputsPerInput*BV->getNumOperands()); 7595 SmallVector<SDValue, 8> Ops; 7596 7597 for (const SDValue &Op : BV->op_values()) { 7598 if (Op.getOpcode() == ISD::UNDEF) { 7599 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7600 continue; 7601 } 7602 7603 APInt OpVal = cast<ConstantSDNode>(Op)-> 7604 getAPIntValue().zextOrTrunc(SrcBitSize); 7605 7606 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7607 APInt ThisVal = OpVal.trunc(DstBitSize); 7608 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7609 OpVal = OpVal.lshr(DstBitSize); 7610 } 7611 7612 // For big endian targets, swap the order of the pieces of each element. 7613 if (DAG.getDataLayout().isBigEndian()) 7614 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7615 } 7616 7617 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7618 } 7619 7620 /// Try to perform FMA combining on a given FADD node. 7621 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7622 SDValue N0 = N->getOperand(0); 7623 SDValue N1 = N->getOperand(1); 7624 EVT VT = N->getValueType(0); 7625 SDLoc SL(N); 7626 7627 const TargetOptions &Options = DAG.getTarget().Options; 7628 bool AllowFusion = 7629 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7630 7631 // Floating-point multiply-add with intermediate rounding. 7632 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7633 7634 // Floating-point multiply-add without intermediate rounding. 7635 bool HasFMA = 7636 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7637 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7638 7639 // No valid opcode, do not combine. 7640 if (!HasFMAD && !HasFMA) 7641 return SDValue(); 7642 7643 // Always prefer FMAD to FMA for precision. 7644 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7645 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7646 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7647 7648 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7649 // prefer to fold the multiply with fewer uses. 7650 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7651 N1.getOpcode() == ISD::FMUL) { 7652 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7653 std::swap(N0, N1); 7654 } 7655 7656 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7657 if (N0.getOpcode() == ISD::FMUL && 7658 (Aggressive || N0->hasOneUse())) { 7659 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7660 N0.getOperand(0), N0.getOperand(1), N1); 7661 } 7662 7663 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7664 // Note: Commutes FADD operands. 7665 if (N1.getOpcode() == ISD::FMUL && 7666 (Aggressive || N1->hasOneUse())) { 7667 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7668 N1.getOperand(0), N1.getOperand(1), N0); 7669 } 7670 7671 // Look through FP_EXTEND nodes to do more combining. 7672 if (AllowFusion && LookThroughFPExt) { 7673 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7674 if (N0.getOpcode() == ISD::FP_EXTEND) { 7675 SDValue N00 = N0.getOperand(0); 7676 if (N00.getOpcode() == ISD::FMUL) 7677 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7678 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7679 N00.getOperand(0)), 7680 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7681 N00.getOperand(1)), N1); 7682 } 7683 7684 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7685 // Note: Commutes FADD operands. 7686 if (N1.getOpcode() == ISD::FP_EXTEND) { 7687 SDValue N10 = N1.getOperand(0); 7688 if (N10.getOpcode() == ISD::FMUL) 7689 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7690 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7691 N10.getOperand(0)), 7692 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7693 N10.getOperand(1)), N0); 7694 } 7695 } 7696 7697 // More folding opportunities when target permits. 7698 if ((AllowFusion || HasFMAD) && Aggressive) { 7699 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7700 if (N0.getOpcode() == PreferredFusedOpcode && 7701 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7702 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7703 N0.getOperand(0), N0.getOperand(1), 7704 DAG.getNode(PreferredFusedOpcode, SL, VT, 7705 N0.getOperand(2).getOperand(0), 7706 N0.getOperand(2).getOperand(1), 7707 N1)); 7708 } 7709 7710 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7711 if (N1->getOpcode() == PreferredFusedOpcode && 7712 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7713 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7714 N1.getOperand(0), N1.getOperand(1), 7715 DAG.getNode(PreferredFusedOpcode, SL, VT, 7716 N1.getOperand(2).getOperand(0), 7717 N1.getOperand(2).getOperand(1), 7718 N0)); 7719 } 7720 7721 if (AllowFusion && LookThroughFPExt) { 7722 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7723 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7724 auto FoldFAddFMAFPExtFMul = [&] ( 7725 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7726 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7727 DAG.getNode(PreferredFusedOpcode, SL, VT, 7728 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7729 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7730 Z)); 7731 }; 7732 if (N0.getOpcode() == PreferredFusedOpcode) { 7733 SDValue N02 = N0.getOperand(2); 7734 if (N02.getOpcode() == ISD::FP_EXTEND) { 7735 SDValue N020 = N02.getOperand(0); 7736 if (N020.getOpcode() == ISD::FMUL) 7737 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7738 N020.getOperand(0), N020.getOperand(1), 7739 N1); 7740 } 7741 } 7742 7743 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7744 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7745 // FIXME: This turns two single-precision and one double-precision 7746 // operation into two double-precision operations, which might not be 7747 // interesting for all targets, especially GPUs. 7748 auto FoldFAddFPExtFMAFMul = [&] ( 7749 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7750 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7751 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7752 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7753 DAG.getNode(PreferredFusedOpcode, SL, VT, 7754 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7755 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7756 Z)); 7757 }; 7758 if (N0.getOpcode() == ISD::FP_EXTEND) { 7759 SDValue N00 = N0.getOperand(0); 7760 if (N00.getOpcode() == PreferredFusedOpcode) { 7761 SDValue N002 = N00.getOperand(2); 7762 if (N002.getOpcode() == ISD::FMUL) 7763 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7764 N002.getOperand(0), N002.getOperand(1), 7765 N1); 7766 } 7767 } 7768 7769 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7770 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7771 if (N1.getOpcode() == PreferredFusedOpcode) { 7772 SDValue N12 = N1.getOperand(2); 7773 if (N12.getOpcode() == ISD::FP_EXTEND) { 7774 SDValue N120 = N12.getOperand(0); 7775 if (N120.getOpcode() == ISD::FMUL) 7776 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7777 N120.getOperand(0), N120.getOperand(1), 7778 N0); 7779 } 7780 } 7781 7782 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7783 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7784 // FIXME: This turns two single-precision and one double-precision 7785 // operation into two double-precision operations, which might not be 7786 // interesting for all targets, especially GPUs. 7787 if (N1.getOpcode() == ISD::FP_EXTEND) { 7788 SDValue N10 = N1.getOperand(0); 7789 if (N10.getOpcode() == PreferredFusedOpcode) { 7790 SDValue N102 = N10.getOperand(2); 7791 if (N102.getOpcode() == ISD::FMUL) 7792 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7793 N102.getOperand(0), N102.getOperand(1), 7794 N0); 7795 } 7796 } 7797 } 7798 } 7799 7800 return SDValue(); 7801 } 7802 7803 /// Try to perform FMA combining on a given FSUB node. 7804 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7805 SDValue N0 = N->getOperand(0); 7806 SDValue N1 = N->getOperand(1); 7807 EVT VT = N->getValueType(0); 7808 SDLoc SL(N); 7809 7810 const TargetOptions &Options = DAG.getTarget().Options; 7811 bool AllowFusion = 7812 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7813 7814 // Floating-point multiply-add with intermediate rounding. 7815 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7816 7817 // Floating-point multiply-add without intermediate rounding. 7818 bool HasFMA = 7819 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7820 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7821 7822 // No valid opcode, do not combine. 7823 if (!HasFMAD && !HasFMA) 7824 return SDValue(); 7825 7826 // Always prefer FMAD to FMA for precision. 7827 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7828 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7829 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7830 7831 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7832 if (N0.getOpcode() == ISD::FMUL && 7833 (Aggressive || N0->hasOneUse())) { 7834 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7835 N0.getOperand(0), N0.getOperand(1), 7836 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7837 } 7838 7839 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7840 // Note: Commutes FSUB operands. 7841 if (N1.getOpcode() == ISD::FMUL && 7842 (Aggressive || N1->hasOneUse())) 7843 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7844 DAG.getNode(ISD::FNEG, SL, VT, 7845 N1.getOperand(0)), 7846 N1.getOperand(1), N0); 7847 7848 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7849 if (N0.getOpcode() == ISD::FNEG && 7850 N0.getOperand(0).getOpcode() == ISD::FMUL && 7851 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7852 SDValue N00 = N0.getOperand(0).getOperand(0); 7853 SDValue N01 = N0.getOperand(0).getOperand(1); 7854 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7855 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7856 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7857 } 7858 7859 // Look through FP_EXTEND nodes to do more combining. 7860 if (AllowFusion && LookThroughFPExt) { 7861 // fold (fsub (fpext (fmul x, y)), z) 7862 // -> (fma (fpext x), (fpext y), (fneg z)) 7863 if (N0.getOpcode() == ISD::FP_EXTEND) { 7864 SDValue N00 = N0.getOperand(0); 7865 if (N00.getOpcode() == ISD::FMUL) 7866 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7867 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7868 N00.getOperand(0)), 7869 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7870 N00.getOperand(1)), 7871 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7872 } 7873 7874 // fold (fsub x, (fpext (fmul y, z))) 7875 // -> (fma (fneg (fpext y)), (fpext z), x) 7876 // Note: Commutes FSUB operands. 7877 if (N1.getOpcode() == ISD::FP_EXTEND) { 7878 SDValue N10 = N1.getOperand(0); 7879 if (N10.getOpcode() == ISD::FMUL) 7880 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7881 DAG.getNode(ISD::FNEG, SL, VT, 7882 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7883 N10.getOperand(0))), 7884 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7885 N10.getOperand(1)), 7886 N0); 7887 } 7888 7889 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7890 // -> (fneg (fma (fpext x), (fpext y), z)) 7891 // Note: This could be removed with appropriate canonicalization of the 7892 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7893 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7894 // from implementing the canonicalization in visitFSUB. 7895 if (N0.getOpcode() == ISD::FP_EXTEND) { 7896 SDValue N00 = N0.getOperand(0); 7897 if (N00.getOpcode() == ISD::FNEG) { 7898 SDValue N000 = N00.getOperand(0); 7899 if (N000.getOpcode() == ISD::FMUL) { 7900 return DAG.getNode(ISD::FNEG, SL, VT, 7901 DAG.getNode(PreferredFusedOpcode, SL, VT, 7902 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7903 N000.getOperand(0)), 7904 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7905 N000.getOperand(1)), 7906 N1)); 7907 } 7908 } 7909 } 7910 7911 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7912 // -> (fneg (fma (fpext x)), (fpext y), z) 7913 // Note: This could be removed with appropriate canonicalization of the 7914 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7915 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7916 // from implementing the canonicalization in visitFSUB. 7917 if (N0.getOpcode() == ISD::FNEG) { 7918 SDValue N00 = N0.getOperand(0); 7919 if (N00.getOpcode() == ISD::FP_EXTEND) { 7920 SDValue N000 = N00.getOperand(0); 7921 if (N000.getOpcode() == ISD::FMUL) { 7922 return DAG.getNode(ISD::FNEG, SL, VT, 7923 DAG.getNode(PreferredFusedOpcode, SL, VT, 7924 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7925 N000.getOperand(0)), 7926 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7927 N000.getOperand(1)), 7928 N1)); 7929 } 7930 } 7931 } 7932 7933 } 7934 7935 // More folding opportunities when target permits. 7936 if ((AllowFusion || HasFMAD) && Aggressive) { 7937 // fold (fsub (fma x, y, (fmul u, v)), z) 7938 // -> (fma x, y (fma u, v, (fneg z))) 7939 if (N0.getOpcode() == PreferredFusedOpcode && 7940 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7941 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7942 N0.getOperand(0), N0.getOperand(1), 7943 DAG.getNode(PreferredFusedOpcode, SL, VT, 7944 N0.getOperand(2).getOperand(0), 7945 N0.getOperand(2).getOperand(1), 7946 DAG.getNode(ISD::FNEG, SL, VT, 7947 N1))); 7948 } 7949 7950 // fold (fsub x, (fma y, z, (fmul u, v))) 7951 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7952 if (N1.getOpcode() == PreferredFusedOpcode && 7953 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7954 SDValue N20 = N1.getOperand(2).getOperand(0); 7955 SDValue N21 = N1.getOperand(2).getOperand(1); 7956 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7957 DAG.getNode(ISD::FNEG, SL, VT, 7958 N1.getOperand(0)), 7959 N1.getOperand(1), 7960 DAG.getNode(PreferredFusedOpcode, SL, VT, 7961 DAG.getNode(ISD::FNEG, SL, VT, N20), 7962 7963 N21, N0)); 7964 } 7965 7966 if (AllowFusion && LookThroughFPExt) { 7967 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7968 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7969 if (N0.getOpcode() == PreferredFusedOpcode) { 7970 SDValue N02 = N0.getOperand(2); 7971 if (N02.getOpcode() == ISD::FP_EXTEND) { 7972 SDValue N020 = N02.getOperand(0); 7973 if (N020.getOpcode() == ISD::FMUL) 7974 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7975 N0.getOperand(0), N0.getOperand(1), 7976 DAG.getNode(PreferredFusedOpcode, SL, VT, 7977 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7978 N020.getOperand(0)), 7979 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7980 N020.getOperand(1)), 7981 DAG.getNode(ISD::FNEG, SL, VT, 7982 N1))); 7983 } 7984 } 7985 7986 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7987 // -> (fma (fpext x), (fpext y), 7988 // (fma (fpext u), (fpext v), (fneg z))) 7989 // FIXME: This turns two single-precision and one double-precision 7990 // operation into two double-precision operations, which might not be 7991 // interesting for all targets, especially GPUs. 7992 if (N0.getOpcode() == ISD::FP_EXTEND) { 7993 SDValue N00 = N0.getOperand(0); 7994 if (N00.getOpcode() == PreferredFusedOpcode) { 7995 SDValue N002 = N00.getOperand(2); 7996 if (N002.getOpcode() == ISD::FMUL) 7997 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7998 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7999 N00.getOperand(0)), 8000 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8001 N00.getOperand(1)), 8002 DAG.getNode(PreferredFusedOpcode, SL, VT, 8003 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8004 N002.getOperand(0)), 8005 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8006 N002.getOperand(1)), 8007 DAG.getNode(ISD::FNEG, SL, VT, 8008 N1))); 8009 } 8010 } 8011 8012 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8013 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8014 if (N1.getOpcode() == PreferredFusedOpcode && 8015 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8016 SDValue N120 = N1.getOperand(2).getOperand(0); 8017 if (N120.getOpcode() == ISD::FMUL) { 8018 SDValue N1200 = N120.getOperand(0); 8019 SDValue N1201 = N120.getOperand(1); 8020 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8021 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8022 N1.getOperand(1), 8023 DAG.getNode(PreferredFusedOpcode, SL, VT, 8024 DAG.getNode(ISD::FNEG, SL, VT, 8025 DAG.getNode(ISD::FP_EXTEND, SL, 8026 VT, N1200)), 8027 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8028 N1201), 8029 N0)); 8030 } 8031 } 8032 8033 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8034 // -> (fma (fneg (fpext y)), (fpext z), 8035 // (fma (fneg (fpext u)), (fpext v), x)) 8036 // FIXME: This turns two single-precision and one double-precision 8037 // operation into two double-precision operations, which might not be 8038 // interesting for all targets, especially GPUs. 8039 if (N1.getOpcode() == ISD::FP_EXTEND && 8040 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8041 SDValue N100 = N1.getOperand(0).getOperand(0); 8042 SDValue N101 = N1.getOperand(0).getOperand(1); 8043 SDValue N102 = N1.getOperand(0).getOperand(2); 8044 if (N102.getOpcode() == ISD::FMUL) { 8045 SDValue N1020 = N102.getOperand(0); 8046 SDValue N1021 = N102.getOperand(1); 8047 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8048 DAG.getNode(ISD::FNEG, SL, VT, 8049 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8050 N100)), 8051 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8052 DAG.getNode(PreferredFusedOpcode, SL, VT, 8053 DAG.getNode(ISD::FNEG, SL, VT, 8054 DAG.getNode(ISD::FP_EXTEND, SL, 8055 VT, N1020)), 8056 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8057 N1021), 8058 N0)); 8059 } 8060 } 8061 } 8062 } 8063 8064 return SDValue(); 8065 } 8066 8067 /// Try to perform FMA combining on a given FMUL node. 8068 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8069 SDValue N0 = N->getOperand(0); 8070 SDValue N1 = N->getOperand(1); 8071 EVT VT = N->getValueType(0); 8072 SDLoc SL(N); 8073 8074 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8075 8076 const TargetOptions &Options = DAG.getTarget().Options; 8077 bool AllowFusion = 8078 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8079 8080 // Floating-point multiply-add with intermediate rounding. 8081 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8082 8083 // Floating-point multiply-add without intermediate rounding. 8084 bool HasFMA = 8085 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8086 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8087 8088 // No valid opcode, do not combine. 8089 if (!HasFMAD && !HasFMA) 8090 return SDValue(); 8091 8092 // Always prefer FMAD to FMA for precision. 8093 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8094 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8095 8096 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8097 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8098 auto FuseFADD = [&](SDValue X, SDValue Y) { 8099 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8100 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8101 if (XC1 && XC1->isExactlyValue(+1.0)) 8102 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8103 if (XC1 && XC1->isExactlyValue(-1.0)) 8104 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8105 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8106 } 8107 return SDValue(); 8108 }; 8109 8110 if (SDValue FMA = FuseFADD(N0, N1)) 8111 return FMA; 8112 if (SDValue FMA = FuseFADD(N1, N0)) 8113 return FMA; 8114 8115 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8116 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8117 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8118 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8119 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8120 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8121 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8122 if (XC0 && XC0->isExactlyValue(+1.0)) 8123 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8124 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8125 Y); 8126 if (XC0 && XC0->isExactlyValue(-1.0)) 8127 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8128 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8129 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8130 8131 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8132 if (XC1 && XC1->isExactlyValue(+1.0)) 8133 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8134 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8135 if (XC1 && XC1->isExactlyValue(-1.0)) 8136 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8137 } 8138 return SDValue(); 8139 }; 8140 8141 if (SDValue FMA = FuseFSUB(N0, N1)) 8142 return FMA; 8143 if (SDValue FMA = FuseFSUB(N1, N0)) 8144 return FMA; 8145 8146 return SDValue(); 8147 } 8148 8149 SDValue DAGCombiner::visitFADD(SDNode *N) { 8150 SDValue N0 = N->getOperand(0); 8151 SDValue N1 = N->getOperand(1); 8152 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8153 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8154 EVT VT = N->getValueType(0); 8155 SDLoc DL(N); 8156 const TargetOptions &Options = DAG.getTarget().Options; 8157 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8158 8159 // fold vector ops 8160 if (VT.isVector()) 8161 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8162 return FoldedVOp; 8163 8164 // fold (fadd c1, c2) -> c1 + c2 8165 if (N0CFP && N1CFP) 8166 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8167 8168 // canonicalize constant to RHS 8169 if (N0CFP && !N1CFP) 8170 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8171 8172 // fold (fadd A, (fneg B)) -> (fsub A, B) 8173 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8174 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8175 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8176 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8177 8178 // fold (fadd (fneg A), B) -> (fsub B, A) 8179 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8180 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8181 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8182 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8183 8184 // If 'unsafe math' is enabled, fold lots of things. 8185 if (Options.UnsafeFPMath) { 8186 // No FP constant should be created after legalization as Instruction 8187 // Selection pass has a hard time dealing with FP constants. 8188 bool AllowNewConst = (Level < AfterLegalizeDAG); 8189 8190 // fold (fadd A, 0) -> A 8191 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8192 if (N1C->isZero()) 8193 return N0; 8194 8195 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8196 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8197 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8198 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8199 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8200 Flags), 8201 Flags); 8202 8203 // If allowed, fold (fadd (fneg x), x) -> 0.0 8204 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8205 return DAG.getConstantFP(0.0, DL, VT); 8206 8207 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8208 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8209 return DAG.getConstantFP(0.0, DL, VT); 8210 8211 // We can fold chains of FADD's of the same value into multiplications. 8212 // This transform is not safe in general because we are reducing the number 8213 // of rounding steps. 8214 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8215 if (N0.getOpcode() == ISD::FMUL) { 8216 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8217 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8218 8219 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8220 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8221 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8222 DAG.getConstantFP(1.0, DL, VT), Flags); 8223 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8224 } 8225 8226 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8227 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8228 N1.getOperand(0) == N1.getOperand(1) && 8229 N0.getOperand(0) == N1.getOperand(0)) { 8230 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8231 DAG.getConstantFP(2.0, DL, VT), Flags); 8232 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8233 } 8234 } 8235 8236 if (N1.getOpcode() == ISD::FMUL) { 8237 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8238 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8239 8240 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8241 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8242 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8243 DAG.getConstantFP(1.0, DL, VT), Flags); 8244 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8245 } 8246 8247 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8248 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8249 N0.getOperand(0) == N0.getOperand(1) && 8250 N1.getOperand(0) == N0.getOperand(0)) { 8251 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8252 DAG.getConstantFP(2.0, DL, VT), Flags); 8253 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8254 } 8255 } 8256 8257 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8258 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8259 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8260 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8261 (N0.getOperand(0) == N1)) { 8262 return DAG.getNode(ISD::FMUL, DL, VT, 8263 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8264 } 8265 } 8266 8267 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8268 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8269 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8270 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8271 N1.getOperand(0) == N0) { 8272 return DAG.getNode(ISD::FMUL, DL, VT, 8273 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8274 } 8275 } 8276 8277 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8278 if (AllowNewConst && 8279 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8280 N0.getOperand(0) == N0.getOperand(1) && 8281 N1.getOperand(0) == N1.getOperand(1) && 8282 N0.getOperand(0) == N1.getOperand(0)) { 8283 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8284 DAG.getConstantFP(4.0, DL, VT), Flags); 8285 } 8286 } 8287 } // enable-unsafe-fp-math 8288 8289 // FADD -> FMA combines: 8290 if (SDValue Fused = visitFADDForFMACombine(N)) { 8291 AddToWorklist(Fused.getNode()); 8292 return Fused; 8293 } 8294 8295 return SDValue(); 8296 } 8297 8298 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8299 SDValue N0 = N->getOperand(0); 8300 SDValue N1 = N->getOperand(1); 8301 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8302 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8303 EVT VT = N->getValueType(0); 8304 SDLoc dl(N); 8305 const TargetOptions &Options = DAG.getTarget().Options; 8306 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8307 8308 // fold vector ops 8309 if (VT.isVector()) 8310 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8311 return FoldedVOp; 8312 8313 // fold (fsub c1, c2) -> c1-c2 8314 if (N0CFP && N1CFP) 8315 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8316 8317 // fold (fsub A, (fneg B)) -> (fadd A, B) 8318 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8319 return DAG.getNode(ISD::FADD, dl, VT, N0, 8320 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8321 8322 // If 'unsafe math' is enabled, fold lots of things. 8323 if (Options.UnsafeFPMath) { 8324 // (fsub A, 0) -> A 8325 if (N1CFP && N1CFP->isZero()) 8326 return N0; 8327 8328 // (fsub 0, B) -> -B 8329 if (N0CFP && N0CFP->isZero()) { 8330 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8331 return GetNegatedExpression(N1, DAG, LegalOperations); 8332 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8333 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8334 } 8335 8336 // (fsub x, x) -> 0.0 8337 if (N0 == N1) 8338 return DAG.getConstantFP(0.0f, dl, VT); 8339 8340 // (fsub x, (fadd x, y)) -> (fneg y) 8341 // (fsub x, (fadd y, x)) -> (fneg y) 8342 if (N1.getOpcode() == ISD::FADD) { 8343 SDValue N10 = N1->getOperand(0); 8344 SDValue N11 = N1->getOperand(1); 8345 8346 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8347 return GetNegatedExpression(N11, DAG, LegalOperations); 8348 8349 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8350 return GetNegatedExpression(N10, DAG, LegalOperations); 8351 } 8352 } 8353 8354 // FSUB -> FMA combines: 8355 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8356 AddToWorklist(Fused.getNode()); 8357 return Fused; 8358 } 8359 8360 return SDValue(); 8361 } 8362 8363 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8364 SDValue N0 = N->getOperand(0); 8365 SDValue N1 = N->getOperand(1); 8366 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8367 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8368 EVT VT = N->getValueType(0); 8369 SDLoc DL(N); 8370 const TargetOptions &Options = DAG.getTarget().Options; 8371 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8372 8373 // fold vector ops 8374 if (VT.isVector()) { 8375 // This just handles C1 * C2 for vectors. Other vector folds are below. 8376 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8377 return FoldedVOp; 8378 } 8379 8380 // fold (fmul c1, c2) -> c1*c2 8381 if (N0CFP && N1CFP) 8382 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8383 8384 // canonicalize constant to RHS 8385 if (isConstantFPBuildVectorOrConstantFP(N0) && 8386 !isConstantFPBuildVectorOrConstantFP(N1)) 8387 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8388 8389 // fold (fmul A, 1.0) -> A 8390 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8391 return N0; 8392 8393 if (Options.UnsafeFPMath) { 8394 // fold (fmul A, 0) -> 0 8395 if (N1CFP && N1CFP->isZero()) 8396 return N1; 8397 8398 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8399 if (N0.getOpcode() == ISD::FMUL) { 8400 // Fold scalars or any vector constants (not just splats). 8401 // This fold is done in general by InstCombine, but extra fmul insts 8402 // may have been generated during lowering. 8403 SDValue N00 = N0.getOperand(0); 8404 SDValue N01 = N0.getOperand(1); 8405 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8406 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8407 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8408 8409 // Check 1: Make sure that the first operand of the inner multiply is NOT 8410 // a constant. Otherwise, we may induce infinite looping. 8411 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8412 // Check 2: Make sure that the second operand of the inner multiply and 8413 // the second operand of the outer multiply are constants. 8414 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8415 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8416 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8417 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8418 } 8419 } 8420 } 8421 8422 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8423 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8424 // during an early run of DAGCombiner can prevent folding with fmuls 8425 // inserted during lowering. 8426 if (N0.getOpcode() == ISD::FADD && 8427 (N0.getOperand(0) == N0.getOperand(1)) && 8428 N0.hasOneUse()) { 8429 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8430 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8431 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8432 } 8433 } 8434 8435 // fold (fmul X, 2.0) -> (fadd X, X) 8436 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8437 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8438 8439 // fold (fmul X, -1.0) -> (fneg X) 8440 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8441 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8442 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8443 8444 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8445 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8446 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8447 // Both can be negated for free, check to see if at least one is cheaper 8448 // negated. 8449 if (LHSNeg == 2 || RHSNeg == 2) 8450 return DAG.getNode(ISD::FMUL, DL, VT, 8451 GetNegatedExpression(N0, DAG, LegalOperations), 8452 GetNegatedExpression(N1, DAG, LegalOperations), 8453 Flags); 8454 } 8455 } 8456 8457 // FMUL -> FMA combines: 8458 if (SDValue Fused = visitFMULForFMACombine(N)) { 8459 AddToWorklist(Fused.getNode()); 8460 return Fused; 8461 } 8462 8463 return SDValue(); 8464 } 8465 8466 SDValue DAGCombiner::visitFMA(SDNode *N) { 8467 SDValue N0 = N->getOperand(0); 8468 SDValue N1 = N->getOperand(1); 8469 SDValue N2 = N->getOperand(2); 8470 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8471 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8472 EVT VT = N->getValueType(0); 8473 SDLoc dl(N); 8474 const TargetOptions &Options = DAG.getTarget().Options; 8475 8476 // Constant fold FMA. 8477 if (isa<ConstantFPSDNode>(N0) && 8478 isa<ConstantFPSDNode>(N1) && 8479 isa<ConstantFPSDNode>(N2)) { 8480 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8481 } 8482 8483 if (Options.UnsafeFPMath) { 8484 if (N0CFP && N0CFP->isZero()) 8485 return N2; 8486 if (N1CFP && N1CFP->isZero()) 8487 return N2; 8488 } 8489 // TODO: The FMA node should have flags that propagate to these nodes. 8490 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8491 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8492 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8493 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8494 8495 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8496 if (isConstantFPBuildVectorOrConstantFP(N0) && 8497 !isConstantFPBuildVectorOrConstantFP(N1)) 8498 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8499 8500 // TODO: FMA nodes should have flags that propagate to the created nodes. 8501 // For now, create a Flags object for use with all unsafe math transforms. 8502 SDNodeFlags Flags; 8503 Flags.setUnsafeAlgebra(true); 8504 8505 if (Options.UnsafeFPMath) { 8506 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8507 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8508 isConstantFPBuildVectorOrConstantFP(N1) && 8509 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8510 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8511 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8512 &Flags), &Flags); 8513 } 8514 8515 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8516 if (N0.getOpcode() == ISD::FMUL && 8517 isConstantFPBuildVectorOrConstantFP(N1) && 8518 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8519 return DAG.getNode(ISD::FMA, dl, VT, 8520 N0.getOperand(0), 8521 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8522 &Flags), 8523 N2); 8524 } 8525 } 8526 8527 // (fma x, 1, y) -> (fadd x, y) 8528 // (fma x, -1, y) -> (fadd (fneg x), y) 8529 if (N1CFP) { 8530 if (N1CFP->isExactlyValue(1.0)) 8531 // TODO: The FMA node should have flags that propagate to this node. 8532 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8533 8534 if (N1CFP->isExactlyValue(-1.0) && 8535 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8536 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8537 AddToWorklist(RHSNeg.getNode()); 8538 // TODO: The FMA node should have flags that propagate to this node. 8539 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8540 } 8541 } 8542 8543 if (Options.UnsafeFPMath) { 8544 // (fma x, c, x) -> (fmul x, (c+1)) 8545 if (N1CFP && N0 == N2) { 8546 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8547 DAG.getNode(ISD::FADD, dl, VT, 8548 N1, DAG.getConstantFP(1.0, dl, VT), 8549 &Flags), &Flags); 8550 } 8551 8552 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8553 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8554 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8555 DAG.getNode(ISD::FADD, dl, VT, 8556 N1, DAG.getConstantFP(-1.0, dl, VT), 8557 &Flags), &Flags); 8558 } 8559 } 8560 8561 return SDValue(); 8562 } 8563 8564 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8565 // reciprocal. 8566 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8567 // Notice that this is not always beneficial. One reason is different target 8568 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8569 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8570 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8571 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8572 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8573 const SDNodeFlags *Flags = N->getFlags(); 8574 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8575 return SDValue(); 8576 8577 // Skip if current node is a reciprocal. 8578 SDValue N0 = N->getOperand(0); 8579 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8580 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8581 return SDValue(); 8582 8583 // Exit early if the target does not want this transform or if there can't 8584 // possibly be enough uses of the divisor to make the transform worthwhile. 8585 SDValue N1 = N->getOperand(1); 8586 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8587 if (!MinUses || N1->use_size() < MinUses) 8588 return SDValue(); 8589 8590 // Find all FDIV users of the same divisor. 8591 // Use a set because duplicates may be present in the user list. 8592 SetVector<SDNode *> Users; 8593 for (auto *U : N1->uses()) { 8594 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8595 // This division is eligible for optimization only if global unsafe math 8596 // is enabled or if this division allows reciprocal formation. 8597 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8598 Users.insert(U); 8599 } 8600 } 8601 8602 // Now that we have the actual number of divisor uses, make sure it meets 8603 // the minimum threshold specified by the target. 8604 if (Users.size() < MinUses) 8605 return SDValue(); 8606 8607 EVT VT = N->getValueType(0); 8608 SDLoc DL(N); 8609 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8610 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8611 8612 // Dividend / Divisor -> Dividend * Reciprocal 8613 for (auto *U : Users) { 8614 SDValue Dividend = U->getOperand(0); 8615 if (Dividend != FPOne) { 8616 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8617 Reciprocal, Flags); 8618 CombineTo(U, NewNode); 8619 } else if (U != Reciprocal.getNode()) { 8620 // In the absence of fast-math-flags, this user node is always the 8621 // same node as Reciprocal, but with FMF they may be different nodes. 8622 CombineTo(U, Reciprocal); 8623 } 8624 } 8625 return SDValue(N, 0); // N was replaced. 8626 } 8627 8628 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8629 SDValue N0 = N->getOperand(0); 8630 SDValue N1 = N->getOperand(1); 8631 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8632 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8633 EVT VT = N->getValueType(0); 8634 SDLoc DL(N); 8635 const TargetOptions &Options = DAG.getTarget().Options; 8636 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8637 8638 // fold vector ops 8639 if (VT.isVector()) 8640 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8641 return FoldedVOp; 8642 8643 // fold (fdiv c1, c2) -> c1/c2 8644 if (N0CFP && N1CFP) 8645 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8646 8647 if (Options.UnsafeFPMath) { 8648 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8649 if (N1CFP) { 8650 // Compute the reciprocal 1.0 / c2. 8651 APFloat N1APF = N1CFP->getValueAPF(); 8652 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8653 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8654 // Only do the transform if the reciprocal is a legal fp immediate that 8655 // isn't too nasty (eg NaN, denormal, ...). 8656 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8657 (!LegalOperations || 8658 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8659 // backend)... we should handle this gracefully after Legalize. 8660 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8661 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8662 TLI.isFPImmLegal(Recip, VT))) 8663 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8664 DAG.getConstantFP(Recip, DL, VT), Flags); 8665 } 8666 8667 // If this FDIV is part of a reciprocal square root, it may be folded 8668 // into a target-specific square root estimate instruction. 8669 if (N1.getOpcode() == ISD::FSQRT) { 8670 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8671 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8672 } 8673 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8674 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8675 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8676 Flags)) { 8677 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8678 AddToWorklist(RV.getNode()); 8679 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8680 } 8681 } else if (N1.getOpcode() == ISD::FP_ROUND && 8682 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8683 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8684 Flags)) { 8685 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8686 AddToWorklist(RV.getNode()); 8687 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8688 } 8689 } else if (N1.getOpcode() == ISD::FMUL) { 8690 // Look through an FMUL. Even though this won't remove the FDIV directly, 8691 // it's still worthwhile to get rid of the FSQRT if possible. 8692 SDValue SqrtOp; 8693 SDValue OtherOp; 8694 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8695 SqrtOp = N1.getOperand(0); 8696 OtherOp = N1.getOperand(1); 8697 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8698 SqrtOp = N1.getOperand(1); 8699 OtherOp = N1.getOperand(0); 8700 } 8701 if (SqrtOp.getNode()) { 8702 // We found a FSQRT, so try to make this fold: 8703 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8704 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8705 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8706 AddToWorklist(RV.getNode()); 8707 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8708 } 8709 } 8710 } 8711 8712 // Fold into a reciprocal estimate and multiply instead of a real divide. 8713 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8714 AddToWorklist(RV.getNode()); 8715 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8716 } 8717 } 8718 8719 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8720 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8721 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8722 // Both can be negated for free, check to see if at least one is cheaper 8723 // negated. 8724 if (LHSNeg == 2 || RHSNeg == 2) 8725 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8726 GetNegatedExpression(N0, DAG, LegalOperations), 8727 GetNegatedExpression(N1, DAG, LegalOperations), 8728 Flags); 8729 } 8730 } 8731 8732 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8733 return CombineRepeatedDivisors; 8734 8735 return SDValue(); 8736 } 8737 8738 SDValue DAGCombiner::visitFREM(SDNode *N) { 8739 SDValue N0 = N->getOperand(0); 8740 SDValue N1 = N->getOperand(1); 8741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8743 EVT VT = N->getValueType(0); 8744 8745 // fold (frem c1, c2) -> fmod(c1,c2) 8746 if (N0CFP && N1CFP) 8747 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8748 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8749 8750 return SDValue(); 8751 } 8752 8753 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8754 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8755 return SDValue(); 8756 8757 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8758 // For now, create a Flags object for use with all unsafe math transforms. 8759 SDNodeFlags Flags; 8760 Flags.setUnsafeAlgebra(true); 8761 8762 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8763 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8764 if (!RV) 8765 return SDValue(); 8766 8767 EVT VT = RV.getValueType(); 8768 SDLoc DL(N); 8769 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8770 AddToWorklist(RV.getNode()); 8771 8772 // Unfortunately, RV is now NaN if the input was exactly 0. 8773 // Select out this case and force the answer to 0. 8774 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8775 EVT CCVT = getSetCCResultType(VT); 8776 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8777 AddToWorklist(ZeroCmp.getNode()); 8778 AddToWorklist(RV.getNode()); 8779 8780 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8781 ZeroCmp, Zero, RV); 8782 } 8783 8784 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8785 /// copysign(x, fp_round(y)) -> copysign(x, y) 8786 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8787 SDValue N1 = N->getOperand(1); 8788 if ((N1.getOpcode() == ISD::FP_EXTEND || 8789 N1.getOpcode() == ISD::FP_ROUND)) { 8790 // Do not optimize out type conversion of f128 type yet. 8791 // For some targets like x86_64, configuration is changed to keep one f128 8792 // value in one SSE register, but instruction selection cannot handle 8793 // FCOPYSIGN on SSE registers yet. 8794 EVT N1VT = N1->getValueType(0); 8795 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8796 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8797 } 8798 return false; 8799 } 8800 8801 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8802 SDValue N0 = N->getOperand(0); 8803 SDValue N1 = N->getOperand(1); 8804 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8805 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8806 EVT VT = N->getValueType(0); 8807 8808 if (N0CFP && N1CFP) // Constant fold 8809 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8810 8811 if (N1CFP) { 8812 const APFloat& V = N1CFP->getValueAPF(); 8813 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8814 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8815 if (!V.isNegative()) { 8816 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8817 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8818 } else { 8819 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8820 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8821 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8822 } 8823 } 8824 8825 // copysign(fabs(x), y) -> copysign(x, y) 8826 // copysign(fneg(x), y) -> copysign(x, y) 8827 // copysign(copysign(x,z), y) -> copysign(x, y) 8828 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8829 N0.getOpcode() == ISD::FCOPYSIGN) 8830 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8831 N0.getOperand(0), N1); 8832 8833 // copysign(x, abs(y)) -> abs(x) 8834 if (N1.getOpcode() == ISD::FABS) 8835 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8836 8837 // copysign(x, copysign(y,z)) -> copysign(x, z) 8838 if (N1.getOpcode() == ISD::FCOPYSIGN) 8839 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8840 N0, N1.getOperand(1)); 8841 8842 // copysign(x, fp_extend(y)) -> copysign(x, y) 8843 // copysign(x, fp_round(y)) -> copysign(x, y) 8844 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 8845 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8846 N0, N1.getOperand(0)); 8847 8848 return SDValue(); 8849 } 8850 8851 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8852 SDValue N0 = N->getOperand(0); 8853 EVT VT = N->getValueType(0); 8854 EVT OpVT = N0.getValueType(); 8855 8856 // fold (sint_to_fp c1) -> c1fp 8857 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8858 // ...but only if the target supports immediate floating-point values 8859 (!LegalOperations || 8860 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8861 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8862 8863 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8864 // but UINT_TO_FP is legal on this target, try to convert. 8865 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8866 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8867 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8868 if (DAG.SignBitIsZero(N0)) 8869 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8870 } 8871 8872 // The next optimizations are desirable only if SELECT_CC can be lowered. 8873 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8874 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8875 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8876 !VT.isVector() && 8877 (!LegalOperations || 8878 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8879 SDLoc DL(N); 8880 SDValue Ops[] = 8881 { N0.getOperand(0), N0.getOperand(1), 8882 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8883 N0.getOperand(2) }; 8884 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8885 } 8886 8887 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8888 // (select_cc x, y, 1.0, 0.0,, cc) 8889 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8890 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8891 (!LegalOperations || 8892 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8893 SDLoc DL(N); 8894 SDValue Ops[] = 8895 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8896 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8897 N0.getOperand(0).getOperand(2) }; 8898 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8899 } 8900 } 8901 8902 return SDValue(); 8903 } 8904 8905 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8906 SDValue N0 = N->getOperand(0); 8907 EVT VT = N->getValueType(0); 8908 EVT OpVT = N0.getValueType(); 8909 8910 // fold (uint_to_fp c1) -> c1fp 8911 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8912 // ...but only if the target supports immediate floating-point values 8913 (!LegalOperations || 8914 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8915 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8916 8917 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8918 // but SINT_TO_FP is legal on this target, try to convert. 8919 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8920 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8921 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8922 if (DAG.SignBitIsZero(N0)) 8923 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8924 } 8925 8926 // The next optimizations are desirable only if SELECT_CC can be lowered. 8927 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8928 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8929 8930 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8931 (!LegalOperations || 8932 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8933 SDLoc DL(N); 8934 SDValue Ops[] = 8935 { N0.getOperand(0), N0.getOperand(1), 8936 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8937 N0.getOperand(2) }; 8938 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8939 } 8940 } 8941 8942 return SDValue(); 8943 } 8944 8945 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8946 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8947 SDValue N0 = N->getOperand(0); 8948 EVT VT = N->getValueType(0); 8949 8950 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8951 return SDValue(); 8952 8953 SDValue Src = N0.getOperand(0); 8954 EVT SrcVT = Src.getValueType(); 8955 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8956 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8957 8958 // We can safely assume the conversion won't overflow the output range, 8959 // because (for example) (uint8_t)18293.f is undefined behavior. 8960 8961 // Since we can assume the conversion won't overflow, our decision as to 8962 // whether the input will fit in the float should depend on the minimum 8963 // of the input range and output range. 8964 8965 // This means this is also safe for a signed input and unsigned output, since 8966 // a negative input would lead to undefined behavior. 8967 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8968 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8969 unsigned ActualSize = std::min(InputSize, OutputSize); 8970 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8971 8972 // We can only fold away the float conversion if the input range can be 8973 // represented exactly in the float range. 8974 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8975 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8976 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8977 : ISD::ZERO_EXTEND; 8978 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8979 } 8980 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8981 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8982 if (SrcVT == VT) 8983 return Src; 8984 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8985 } 8986 return SDValue(); 8987 } 8988 8989 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8990 SDValue N0 = N->getOperand(0); 8991 EVT VT = N->getValueType(0); 8992 8993 // fold (fp_to_sint c1fp) -> c1 8994 if (isConstantFPBuildVectorOrConstantFP(N0)) 8995 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8996 8997 return FoldIntToFPToInt(N, DAG); 8998 } 8999 9000 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9001 SDValue N0 = N->getOperand(0); 9002 EVT VT = N->getValueType(0); 9003 9004 // fold (fp_to_uint c1fp) -> c1 9005 if (isConstantFPBuildVectorOrConstantFP(N0)) 9006 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9007 9008 return FoldIntToFPToInt(N, DAG); 9009 } 9010 9011 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9012 SDValue N0 = N->getOperand(0); 9013 SDValue N1 = N->getOperand(1); 9014 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9015 EVT VT = N->getValueType(0); 9016 9017 // fold (fp_round c1fp) -> c1fp 9018 if (N0CFP) 9019 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9020 9021 // fold (fp_round (fp_extend x)) -> x 9022 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9023 return N0.getOperand(0); 9024 9025 // fold (fp_round (fp_round x)) -> (fp_round x) 9026 if (N0.getOpcode() == ISD::FP_ROUND) { 9027 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9028 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9029 // If the first fp_round isn't a value preserving truncation, it might 9030 // introduce a tie in the second fp_round, that wouldn't occur in the 9031 // single-step fp_round we want to fold to. 9032 // In other words, double rounding isn't the same as rounding. 9033 // Also, this is a value preserving truncation iff both fp_round's are. 9034 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9035 SDLoc DL(N); 9036 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9037 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9038 } 9039 } 9040 9041 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9042 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9043 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9044 N0.getOperand(0), N1); 9045 AddToWorklist(Tmp.getNode()); 9046 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9047 Tmp, N0.getOperand(1)); 9048 } 9049 9050 return SDValue(); 9051 } 9052 9053 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9054 SDValue N0 = N->getOperand(0); 9055 EVT VT = N->getValueType(0); 9056 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9057 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9058 9059 // fold (fp_round_inreg c1fp) -> c1fp 9060 if (N0CFP && isTypeLegal(EVT)) { 9061 SDLoc DL(N); 9062 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9063 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9064 } 9065 9066 return SDValue(); 9067 } 9068 9069 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9070 SDValue N0 = N->getOperand(0); 9071 EVT VT = N->getValueType(0); 9072 9073 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9074 if (N->hasOneUse() && 9075 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9076 return SDValue(); 9077 9078 // fold (fp_extend c1fp) -> c1fp 9079 if (isConstantFPBuildVectorOrConstantFP(N0)) 9080 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9081 9082 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9083 if (N0.getOpcode() == ISD::FP16_TO_FP && 9084 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9085 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9086 9087 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9088 // value of X. 9089 if (N0.getOpcode() == ISD::FP_ROUND 9090 && N0.getNode()->getConstantOperandVal(1) == 1) { 9091 SDValue In = N0.getOperand(0); 9092 if (In.getValueType() == VT) return In; 9093 if (VT.bitsLT(In.getValueType())) 9094 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9095 In, N0.getOperand(1)); 9096 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9097 } 9098 9099 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9100 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9101 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9102 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9103 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9104 LN0->getChain(), 9105 LN0->getBasePtr(), N0.getValueType(), 9106 LN0->getMemOperand()); 9107 CombineTo(N, ExtLoad); 9108 CombineTo(N0.getNode(), 9109 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9110 N0.getValueType(), ExtLoad, 9111 DAG.getIntPtrConstant(1, SDLoc(N0))), 9112 ExtLoad.getValue(1)); 9113 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9114 } 9115 9116 return SDValue(); 9117 } 9118 9119 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9120 SDValue N0 = N->getOperand(0); 9121 EVT VT = N->getValueType(0); 9122 9123 // fold (fceil c1) -> fceil(c1) 9124 if (isConstantFPBuildVectorOrConstantFP(N0)) 9125 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9126 9127 return SDValue(); 9128 } 9129 9130 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9131 SDValue N0 = N->getOperand(0); 9132 EVT VT = N->getValueType(0); 9133 9134 // fold (ftrunc c1) -> ftrunc(c1) 9135 if (isConstantFPBuildVectorOrConstantFP(N0)) 9136 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9137 9138 return SDValue(); 9139 } 9140 9141 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9142 SDValue N0 = N->getOperand(0); 9143 EVT VT = N->getValueType(0); 9144 9145 // fold (ffloor c1) -> ffloor(c1) 9146 if (isConstantFPBuildVectorOrConstantFP(N0)) 9147 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9148 9149 return SDValue(); 9150 } 9151 9152 // FIXME: FNEG and FABS have a lot in common; refactor. 9153 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9154 SDValue N0 = N->getOperand(0); 9155 EVT VT = N->getValueType(0); 9156 9157 // Constant fold FNEG. 9158 if (isConstantFPBuildVectorOrConstantFP(N0)) 9159 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9160 9161 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9162 &DAG.getTarget().Options)) 9163 return GetNegatedExpression(N0, DAG, LegalOperations); 9164 9165 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9166 // constant pool values. 9167 if (!TLI.isFNegFree(VT) && 9168 N0.getOpcode() == ISD::BITCAST && 9169 N0.getNode()->hasOneUse()) { 9170 SDValue Int = N0.getOperand(0); 9171 EVT IntVT = Int.getValueType(); 9172 if (IntVT.isInteger() && !IntVT.isVector()) { 9173 APInt SignMask; 9174 if (N0.getValueType().isVector()) { 9175 // For a vector, get a mask such as 0x80... per scalar element 9176 // and splat it. 9177 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9178 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9179 } else { 9180 // For a scalar, just generate 0x80... 9181 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9182 } 9183 SDLoc DL0(N0); 9184 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9185 DAG.getConstant(SignMask, DL0, IntVT)); 9186 AddToWorklist(Int.getNode()); 9187 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9188 } 9189 } 9190 9191 // (fneg (fmul c, x)) -> (fmul -c, x) 9192 if (N0.getOpcode() == ISD::FMUL && 9193 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9194 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9195 if (CFP1) { 9196 APFloat CVal = CFP1->getValueAPF(); 9197 CVal.changeSign(); 9198 if (Level >= AfterLegalizeDAG && 9199 (TLI.isFPImmLegal(CVal, VT) || 9200 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9201 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9202 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9203 N0.getOperand(1)), 9204 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9205 } 9206 } 9207 9208 return SDValue(); 9209 } 9210 9211 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9212 SDValue N0 = N->getOperand(0); 9213 SDValue N1 = N->getOperand(1); 9214 EVT VT = N->getValueType(0); 9215 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9216 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9217 9218 if (N0CFP && N1CFP) { 9219 const APFloat &C0 = N0CFP->getValueAPF(); 9220 const APFloat &C1 = N1CFP->getValueAPF(); 9221 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9222 } 9223 9224 // Canonicalize to constant on RHS. 9225 if (isConstantFPBuildVectorOrConstantFP(N0) && 9226 !isConstantFPBuildVectorOrConstantFP(N1)) 9227 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9228 9229 return SDValue(); 9230 } 9231 9232 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9233 SDValue N0 = N->getOperand(0); 9234 SDValue N1 = N->getOperand(1); 9235 EVT VT = N->getValueType(0); 9236 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9237 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9238 9239 if (N0CFP && N1CFP) { 9240 const APFloat &C0 = N0CFP->getValueAPF(); 9241 const APFloat &C1 = N1CFP->getValueAPF(); 9242 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9243 } 9244 9245 // Canonicalize to constant on RHS. 9246 if (isConstantFPBuildVectorOrConstantFP(N0) && 9247 !isConstantFPBuildVectorOrConstantFP(N1)) 9248 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9249 9250 return SDValue(); 9251 } 9252 9253 SDValue DAGCombiner::visitFABS(SDNode *N) { 9254 SDValue N0 = N->getOperand(0); 9255 EVT VT = N->getValueType(0); 9256 9257 // fold (fabs c1) -> fabs(c1) 9258 if (isConstantFPBuildVectorOrConstantFP(N0)) 9259 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9260 9261 // fold (fabs (fabs x)) -> (fabs x) 9262 if (N0.getOpcode() == ISD::FABS) 9263 return N->getOperand(0); 9264 9265 // fold (fabs (fneg x)) -> (fabs x) 9266 // fold (fabs (fcopysign x, y)) -> (fabs x) 9267 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9268 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9269 9270 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9271 // constant pool values. 9272 if (!TLI.isFAbsFree(VT) && 9273 N0.getOpcode() == ISD::BITCAST && 9274 N0.getNode()->hasOneUse()) { 9275 SDValue Int = N0.getOperand(0); 9276 EVT IntVT = Int.getValueType(); 9277 if (IntVT.isInteger() && !IntVT.isVector()) { 9278 APInt SignMask; 9279 if (N0.getValueType().isVector()) { 9280 // For a vector, get a mask such as 0x7f... per scalar element 9281 // and splat it. 9282 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9283 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9284 } else { 9285 // For a scalar, just generate 0x7f... 9286 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9287 } 9288 SDLoc DL(N0); 9289 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9290 DAG.getConstant(SignMask, DL, IntVT)); 9291 AddToWorklist(Int.getNode()); 9292 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9293 } 9294 } 9295 9296 return SDValue(); 9297 } 9298 9299 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9300 SDValue Chain = N->getOperand(0); 9301 SDValue N1 = N->getOperand(1); 9302 SDValue N2 = N->getOperand(2); 9303 9304 // If N is a constant we could fold this into a fallthrough or unconditional 9305 // branch. However that doesn't happen very often in normal code, because 9306 // Instcombine/SimplifyCFG should have handled the available opportunities. 9307 // If we did this folding here, it would be necessary to update the 9308 // MachineBasicBlock CFG, which is awkward. 9309 9310 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9311 // on the target. 9312 if (N1.getOpcode() == ISD::SETCC && 9313 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9314 N1.getOperand(0).getValueType())) { 9315 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9316 Chain, N1.getOperand(2), 9317 N1.getOperand(0), N1.getOperand(1), N2); 9318 } 9319 9320 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9321 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9322 (N1.getOperand(0).hasOneUse() && 9323 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9324 SDNode *Trunc = nullptr; 9325 if (N1.getOpcode() == ISD::TRUNCATE) { 9326 // Look pass the truncate. 9327 Trunc = N1.getNode(); 9328 N1 = N1.getOperand(0); 9329 } 9330 9331 // Match this pattern so that we can generate simpler code: 9332 // 9333 // %a = ... 9334 // %b = and i32 %a, 2 9335 // %c = srl i32 %b, 1 9336 // brcond i32 %c ... 9337 // 9338 // into 9339 // 9340 // %a = ... 9341 // %b = and i32 %a, 2 9342 // %c = setcc eq %b, 0 9343 // brcond %c ... 9344 // 9345 // This applies only when the AND constant value has one bit set and the 9346 // SRL constant is equal to the log2 of the AND constant. The back-end is 9347 // smart enough to convert the result into a TEST/JMP sequence. 9348 SDValue Op0 = N1.getOperand(0); 9349 SDValue Op1 = N1.getOperand(1); 9350 9351 if (Op0.getOpcode() == ISD::AND && 9352 Op1.getOpcode() == ISD::Constant) { 9353 SDValue AndOp1 = Op0.getOperand(1); 9354 9355 if (AndOp1.getOpcode() == ISD::Constant) { 9356 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9357 9358 if (AndConst.isPowerOf2() && 9359 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9360 SDLoc DL(N); 9361 SDValue SetCC = 9362 DAG.getSetCC(DL, 9363 getSetCCResultType(Op0.getValueType()), 9364 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9365 ISD::SETNE); 9366 9367 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9368 MVT::Other, Chain, SetCC, N2); 9369 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9370 // will convert it back to (X & C1) >> C2. 9371 CombineTo(N, NewBRCond, false); 9372 // Truncate is dead. 9373 if (Trunc) 9374 deleteAndRecombine(Trunc); 9375 // Replace the uses of SRL with SETCC 9376 WorklistRemover DeadNodes(*this); 9377 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9378 deleteAndRecombine(N1.getNode()); 9379 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9380 } 9381 } 9382 } 9383 9384 if (Trunc) 9385 // Restore N1 if the above transformation doesn't match. 9386 N1 = N->getOperand(1); 9387 } 9388 9389 // Transform br(xor(x, y)) -> br(x != y) 9390 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9391 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9392 SDNode *TheXor = N1.getNode(); 9393 SDValue Op0 = TheXor->getOperand(0); 9394 SDValue Op1 = TheXor->getOperand(1); 9395 if (Op0.getOpcode() == Op1.getOpcode()) { 9396 // Avoid missing important xor optimizations. 9397 if (SDValue Tmp = visitXOR(TheXor)) { 9398 if (Tmp.getNode() != TheXor) { 9399 DEBUG(dbgs() << "\nReplacing.8 "; 9400 TheXor->dump(&DAG); 9401 dbgs() << "\nWith: "; 9402 Tmp.getNode()->dump(&DAG); 9403 dbgs() << '\n'); 9404 WorklistRemover DeadNodes(*this); 9405 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9406 deleteAndRecombine(TheXor); 9407 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9408 MVT::Other, Chain, Tmp, N2); 9409 } 9410 9411 // visitXOR has changed XOR's operands or replaced the XOR completely, 9412 // bail out. 9413 return SDValue(N, 0); 9414 } 9415 } 9416 9417 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9418 bool Equal = false; 9419 if (isOneConstant(Op0) && Op0.hasOneUse() && 9420 Op0.getOpcode() == ISD::XOR) { 9421 TheXor = Op0.getNode(); 9422 Equal = true; 9423 } 9424 9425 EVT SetCCVT = N1.getValueType(); 9426 if (LegalTypes) 9427 SetCCVT = getSetCCResultType(SetCCVT); 9428 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9429 SetCCVT, 9430 Op0, Op1, 9431 Equal ? ISD::SETEQ : ISD::SETNE); 9432 // Replace the uses of XOR with SETCC 9433 WorklistRemover DeadNodes(*this); 9434 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9435 deleteAndRecombine(N1.getNode()); 9436 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9437 MVT::Other, Chain, SetCC, N2); 9438 } 9439 } 9440 9441 return SDValue(); 9442 } 9443 9444 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9445 // 9446 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9447 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9448 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9449 9450 // If N is a constant we could fold this into a fallthrough or unconditional 9451 // branch. However that doesn't happen very often in normal code, because 9452 // Instcombine/SimplifyCFG should have handled the available opportunities. 9453 // If we did this folding here, it would be necessary to update the 9454 // MachineBasicBlock CFG, which is awkward. 9455 9456 // Use SimplifySetCC to simplify SETCC's. 9457 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9458 CondLHS, CondRHS, CC->get(), SDLoc(N), 9459 false); 9460 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9461 9462 // fold to a simpler setcc 9463 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9464 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9465 N->getOperand(0), Simp.getOperand(2), 9466 Simp.getOperand(0), Simp.getOperand(1), 9467 N->getOperand(4)); 9468 9469 return SDValue(); 9470 } 9471 9472 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9473 /// and that N may be folded in the load / store addressing mode. 9474 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9475 SelectionDAG &DAG, 9476 const TargetLowering &TLI) { 9477 EVT VT; 9478 unsigned AS; 9479 9480 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9481 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9482 return false; 9483 VT = LD->getMemoryVT(); 9484 AS = LD->getAddressSpace(); 9485 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9486 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9487 return false; 9488 VT = ST->getMemoryVT(); 9489 AS = ST->getAddressSpace(); 9490 } else 9491 return false; 9492 9493 TargetLowering::AddrMode AM; 9494 if (N->getOpcode() == ISD::ADD) { 9495 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9496 if (Offset) 9497 // [reg +/- imm] 9498 AM.BaseOffs = Offset->getSExtValue(); 9499 else 9500 // [reg +/- reg] 9501 AM.Scale = 1; 9502 } else if (N->getOpcode() == ISD::SUB) { 9503 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9504 if (Offset) 9505 // [reg +/- imm] 9506 AM.BaseOffs = -Offset->getSExtValue(); 9507 else 9508 // [reg +/- reg] 9509 AM.Scale = 1; 9510 } else 9511 return false; 9512 9513 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9514 VT.getTypeForEVT(*DAG.getContext()), AS); 9515 } 9516 9517 /// Try turning a load/store into a pre-indexed load/store when the base 9518 /// pointer is an add or subtract and it has other uses besides the load/store. 9519 /// After the transformation, the new indexed load/store has effectively folded 9520 /// the add/subtract in and all of its other uses are redirected to the 9521 /// new load/store. 9522 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9523 if (Level < AfterLegalizeDAG) 9524 return false; 9525 9526 bool isLoad = true; 9527 SDValue Ptr; 9528 EVT VT; 9529 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9530 if (LD->isIndexed()) 9531 return false; 9532 VT = LD->getMemoryVT(); 9533 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9534 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9535 return false; 9536 Ptr = LD->getBasePtr(); 9537 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9538 if (ST->isIndexed()) 9539 return false; 9540 VT = ST->getMemoryVT(); 9541 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9542 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9543 return false; 9544 Ptr = ST->getBasePtr(); 9545 isLoad = false; 9546 } else { 9547 return false; 9548 } 9549 9550 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9551 // out. There is no reason to make this a preinc/predec. 9552 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9553 Ptr.getNode()->hasOneUse()) 9554 return false; 9555 9556 // Ask the target to do addressing mode selection. 9557 SDValue BasePtr; 9558 SDValue Offset; 9559 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9560 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9561 return false; 9562 9563 // Backends without true r+i pre-indexed forms may need to pass a 9564 // constant base with a variable offset so that constant coercion 9565 // will work with the patterns in canonical form. 9566 bool Swapped = false; 9567 if (isa<ConstantSDNode>(BasePtr)) { 9568 std::swap(BasePtr, Offset); 9569 Swapped = true; 9570 } 9571 9572 // Don't create a indexed load / store with zero offset. 9573 if (isNullConstant(Offset)) 9574 return false; 9575 9576 // Try turning it into a pre-indexed load / store except when: 9577 // 1) The new base ptr is a frame index. 9578 // 2) If N is a store and the new base ptr is either the same as or is a 9579 // predecessor of the value being stored. 9580 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9581 // that would create a cycle. 9582 // 4) All uses are load / store ops that use it as old base ptr. 9583 9584 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9585 // (plus the implicit offset) to a register to preinc anyway. 9586 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9587 return false; 9588 9589 // Check #2. 9590 if (!isLoad) { 9591 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9592 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9593 return false; 9594 } 9595 9596 // If the offset is a constant, there may be other adds of constants that 9597 // can be folded with this one. We should do this to avoid having to keep 9598 // a copy of the original base pointer. 9599 SmallVector<SDNode *, 16> OtherUses; 9600 if (isa<ConstantSDNode>(Offset)) 9601 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9602 UE = BasePtr.getNode()->use_end(); 9603 UI != UE; ++UI) { 9604 SDUse &Use = UI.getUse(); 9605 // Skip the use that is Ptr and uses of other results from BasePtr's 9606 // node (important for nodes that return multiple results). 9607 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9608 continue; 9609 9610 if (Use.getUser()->isPredecessorOf(N)) 9611 continue; 9612 9613 if (Use.getUser()->getOpcode() != ISD::ADD && 9614 Use.getUser()->getOpcode() != ISD::SUB) { 9615 OtherUses.clear(); 9616 break; 9617 } 9618 9619 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9620 if (!isa<ConstantSDNode>(Op1)) { 9621 OtherUses.clear(); 9622 break; 9623 } 9624 9625 // FIXME: In some cases, we can be smarter about this. 9626 if (Op1.getValueType() != Offset.getValueType()) { 9627 OtherUses.clear(); 9628 break; 9629 } 9630 9631 OtherUses.push_back(Use.getUser()); 9632 } 9633 9634 if (Swapped) 9635 std::swap(BasePtr, Offset); 9636 9637 // Now check for #3 and #4. 9638 bool RealUse = false; 9639 9640 // Caches for hasPredecessorHelper 9641 SmallPtrSet<const SDNode *, 32> Visited; 9642 SmallVector<const SDNode *, 16> Worklist; 9643 9644 for (SDNode *Use : Ptr.getNode()->uses()) { 9645 if (Use == N) 9646 continue; 9647 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9648 return false; 9649 9650 // If Ptr may be folded in addressing mode of other use, then it's 9651 // not profitable to do this transformation. 9652 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9653 RealUse = true; 9654 } 9655 9656 if (!RealUse) 9657 return false; 9658 9659 SDValue Result; 9660 if (isLoad) 9661 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9662 BasePtr, Offset, AM); 9663 else 9664 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9665 BasePtr, Offset, AM); 9666 ++PreIndexedNodes; 9667 ++NodesCombined; 9668 DEBUG(dbgs() << "\nReplacing.4 "; 9669 N->dump(&DAG); 9670 dbgs() << "\nWith: "; 9671 Result.getNode()->dump(&DAG); 9672 dbgs() << '\n'); 9673 WorklistRemover DeadNodes(*this); 9674 if (isLoad) { 9675 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9676 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9677 } else { 9678 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9679 } 9680 9681 // Finally, since the node is now dead, remove it from the graph. 9682 deleteAndRecombine(N); 9683 9684 if (Swapped) 9685 std::swap(BasePtr, Offset); 9686 9687 // Replace other uses of BasePtr that can be updated to use Ptr 9688 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9689 unsigned OffsetIdx = 1; 9690 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9691 OffsetIdx = 0; 9692 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9693 BasePtr.getNode() && "Expected BasePtr operand"); 9694 9695 // We need to replace ptr0 in the following expression: 9696 // x0 * offset0 + y0 * ptr0 = t0 9697 // knowing that 9698 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9699 // 9700 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9701 // indexed load/store and the expresion that needs to be re-written. 9702 // 9703 // Therefore, we have: 9704 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9705 9706 ConstantSDNode *CN = 9707 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9708 int X0, X1, Y0, Y1; 9709 APInt Offset0 = CN->getAPIntValue(); 9710 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9711 9712 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9713 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9714 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9715 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9716 9717 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9718 9719 APInt CNV = Offset0; 9720 if (X0 < 0) CNV = -CNV; 9721 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9722 else CNV = CNV - Offset1; 9723 9724 SDLoc DL(OtherUses[i]); 9725 9726 // We can now generate the new expression. 9727 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9728 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9729 9730 SDValue NewUse = DAG.getNode(Opcode, 9731 DL, 9732 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9733 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9734 deleteAndRecombine(OtherUses[i]); 9735 } 9736 9737 // Replace the uses of Ptr with uses of the updated base value. 9738 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9739 deleteAndRecombine(Ptr.getNode()); 9740 9741 return true; 9742 } 9743 9744 /// Try to combine a load/store with a add/sub of the base pointer node into a 9745 /// post-indexed load/store. The transformation folded the add/subtract into the 9746 /// new indexed load/store effectively and all of its uses are redirected to the 9747 /// new load/store. 9748 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9749 if (Level < AfterLegalizeDAG) 9750 return false; 9751 9752 bool isLoad = true; 9753 SDValue Ptr; 9754 EVT VT; 9755 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9756 if (LD->isIndexed()) 9757 return false; 9758 VT = LD->getMemoryVT(); 9759 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9760 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9761 return false; 9762 Ptr = LD->getBasePtr(); 9763 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9764 if (ST->isIndexed()) 9765 return false; 9766 VT = ST->getMemoryVT(); 9767 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9768 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9769 return false; 9770 Ptr = ST->getBasePtr(); 9771 isLoad = false; 9772 } else { 9773 return false; 9774 } 9775 9776 if (Ptr.getNode()->hasOneUse()) 9777 return false; 9778 9779 for (SDNode *Op : Ptr.getNode()->uses()) { 9780 if (Op == N || 9781 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9782 continue; 9783 9784 SDValue BasePtr; 9785 SDValue Offset; 9786 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9787 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9788 // Don't create a indexed load / store with zero offset. 9789 if (isNullConstant(Offset)) 9790 continue; 9791 9792 // Try turning it into a post-indexed load / store except when 9793 // 1) All uses are load / store ops that use it as base ptr (and 9794 // it may be folded as addressing mmode). 9795 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9796 // nor a successor of N. Otherwise, if Op is folded that would 9797 // create a cycle. 9798 9799 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9800 continue; 9801 9802 // Check for #1. 9803 bool TryNext = false; 9804 for (SDNode *Use : BasePtr.getNode()->uses()) { 9805 if (Use == Ptr.getNode()) 9806 continue; 9807 9808 // If all the uses are load / store addresses, then don't do the 9809 // transformation. 9810 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9811 bool RealUse = false; 9812 for (SDNode *UseUse : Use->uses()) { 9813 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9814 RealUse = true; 9815 } 9816 9817 if (!RealUse) { 9818 TryNext = true; 9819 break; 9820 } 9821 } 9822 } 9823 9824 if (TryNext) 9825 continue; 9826 9827 // Check for #2 9828 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9829 SDValue Result = isLoad 9830 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9831 BasePtr, Offset, AM) 9832 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9833 BasePtr, Offset, AM); 9834 ++PostIndexedNodes; 9835 ++NodesCombined; 9836 DEBUG(dbgs() << "\nReplacing.5 "; 9837 N->dump(&DAG); 9838 dbgs() << "\nWith: "; 9839 Result.getNode()->dump(&DAG); 9840 dbgs() << '\n'); 9841 WorklistRemover DeadNodes(*this); 9842 if (isLoad) { 9843 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9844 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9845 } else { 9846 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9847 } 9848 9849 // Finally, since the node is now dead, remove it from the graph. 9850 deleteAndRecombine(N); 9851 9852 // Replace the uses of Use with uses of the updated base value. 9853 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9854 Result.getValue(isLoad ? 1 : 0)); 9855 deleteAndRecombine(Op); 9856 return true; 9857 } 9858 } 9859 } 9860 9861 return false; 9862 } 9863 9864 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9865 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9866 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9867 assert(AM != ISD::UNINDEXED); 9868 SDValue BP = LD->getOperand(1); 9869 SDValue Inc = LD->getOperand(2); 9870 9871 // Some backends use TargetConstants for load offsets, but don't expect 9872 // TargetConstants in general ADD nodes. We can convert these constants into 9873 // regular Constants (if the constant is not opaque). 9874 assert((Inc.getOpcode() != ISD::TargetConstant || 9875 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9876 "Cannot split out indexing using opaque target constants"); 9877 if (Inc.getOpcode() == ISD::TargetConstant) { 9878 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9879 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9880 ConstInc->getValueType(0)); 9881 } 9882 9883 unsigned Opc = 9884 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9885 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9886 } 9887 9888 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9889 LoadSDNode *LD = cast<LoadSDNode>(N); 9890 SDValue Chain = LD->getChain(); 9891 SDValue Ptr = LD->getBasePtr(); 9892 9893 // If load is not volatile and there are no uses of the loaded value (and 9894 // the updated indexed value in case of indexed loads), change uses of the 9895 // chain value into uses of the chain input (i.e. delete the dead load). 9896 if (!LD->isVolatile()) { 9897 if (N->getValueType(1) == MVT::Other) { 9898 // Unindexed loads. 9899 if (!N->hasAnyUseOfValue(0)) { 9900 // It's not safe to use the two value CombineTo variant here. e.g. 9901 // v1, chain2 = load chain1, loc 9902 // v2, chain3 = load chain2, loc 9903 // v3 = add v2, c 9904 // Now we replace use of chain2 with chain1. This makes the second load 9905 // isomorphic to the one we are deleting, and thus makes this load live. 9906 DEBUG(dbgs() << "\nReplacing.6 "; 9907 N->dump(&DAG); 9908 dbgs() << "\nWith chain: "; 9909 Chain.getNode()->dump(&DAG); 9910 dbgs() << "\n"); 9911 WorklistRemover DeadNodes(*this); 9912 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9913 9914 if (N->use_empty()) 9915 deleteAndRecombine(N); 9916 9917 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9918 } 9919 } else { 9920 // Indexed loads. 9921 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9922 9923 // If this load has an opaque TargetConstant offset, then we cannot split 9924 // the indexing into an add/sub directly (that TargetConstant may not be 9925 // valid for a different type of node, and we cannot convert an opaque 9926 // target constant into a regular constant). 9927 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9928 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9929 9930 if (!N->hasAnyUseOfValue(0) && 9931 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9932 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9933 SDValue Index; 9934 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9935 Index = SplitIndexingFromLoad(LD); 9936 // Try to fold the base pointer arithmetic into subsequent loads and 9937 // stores. 9938 AddUsersToWorklist(N); 9939 } else 9940 Index = DAG.getUNDEF(N->getValueType(1)); 9941 DEBUG(dbgs() << "\nReplacing.7 "; 9942 N->dump(&DAG); 9943 dbgs() << "\nWith: "; 9944 Undef.getNode()->dump(&DAG); 9945 dbgs() << " and 2 other values\n"); 9946 WorklistRemover DeadNodes(*this); 9947 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9948 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9949 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9950 deleteAndRecombine(N); 9951 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9952 } 9953 } 9954 } 9955 9956 // If this load is directly stored, replace the load value with the stored 9957 // value. 9958 // TODO: Handle store large -> read small portion. 9959 // TODO: Handle TRUNCSTORE/LOADEXT 9960 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9961 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9962 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9963 if (PrevST->getBasePtr() == Ptr && 9964 PrevST->getValue().getValueType() == N->getValueType(0)) 9965 return CombineTo(N, Chain.getOperand(1), Chain); 9966 } 9967 } 9968 9969 // Try to infer better alignment information than the load already has. 9970 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9971 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9972 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9973 SDValue NewLoad = 9974 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9975 LD->getValueType(0), 9976 Chain, Ptr, LD->getPointerInfo(), 9977 LD->getMemoryVT(), 9978 LD->isVolatile(), LD->isNonTemporal(), 9979 LD->isInvariant(), Align, LD->getAAInfo()); 9980 if (NewLoad.getNode() != N) 9981 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9982 } 9983 } 9984 } 9985 9986 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9987 : DAG.getSubtarget().useAA(); 9988 #ifndef NDEBUG 9989 if (CombinerAAOnlyFunc.getNumOccurrences() && 9990 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9991 UseAA = false; 9992 #endif 9993 if (UseAA && LD->isUnindexed()) { 9994 // Walk up chain skipping non-aliasing memory nodes. 9995 SDValue BetterChain = FindBetterChain(N, Chain); 9996 9997 // If there is a better chain. 9998 if (Chain != BetterChain) { 9999 SDValue ReplLoad; 10000 10001 // Replace the chain to void dependency. 10002 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10003 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10004 BetterChain, Ptr, LD->getMemOperand()); 10005 } else { 10006 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10007 LD->getValueType(0), 10008 BetterChain, Ptr, LD->getMemoryVT(), 10009 LD->getMemOperand()); 10010 } 10011 10012 // Create token factor to keep old chain connected. 10013 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10014 MVT::Other, Chain, ReplLoad.getValue(1)); 10015 10016 // Make sure the new and old chains are cleaned up. 10017 AddToWorklist(Token.getNode()); 10018 10019 // Replace uses with load result and token factor. Don't add users 10020 // to work list. 10021 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10022 } 10023 } 10024 10025 // Try transforming N to an indexed load. 10026 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10027 return SDValue(N, 0); 10028 10029 // Try to slice up N to more direct loads if the slices are mapped to 10030 // different register banks or pairing can take place. 10031 if (SliceUpLoad(N)) 10032 return SDValue(N, 0); 10033 10034 return SDValue(); 10035 } 10036 10037 namespace { 10038 /// \brief Helper structure used to slice a load in smaller loads. 10039 /// Basically a slice is obtained from the following sequence: 10040 /// Origin = load Ty1, Base 10041 /// Shift = srl Ty1 Origin, CstTy Amount 10042 /// Inst = trunc Shift to Ty2 10043 /// 10044 /// Then, it will be rewriten into: 10045 /// Slice = load SliceTy, Base + SliceOffset 10046 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10047 /// 10048 /// SliceTy is deduced from the number of bits that are actually used to 10049 /// build Inst. 10050 struct LoadedSlice { 10051 /// \brief Helper structure used to compute the cost of a slice. 10052 struct Cost { 10053 /// Are we optimizing for code size. 10054 bool ForCodeSize; 10055 /// Various cost. 10056 unsigned Loads; 10057 unsigned Truncates; 10058 unsigned CrossRegisterBanksCopies; 10059 unsigned ZExts; 10060 unsigned Shift; 10061 10062 Cost(bool ForCodeSize = false) 10063 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10064 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10065 10066 /// \brief Get the cost of one isolated slice. 10067 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10068 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10069 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10070 EVT TruncType = LS.Inst->getValueType(0); 10071 EVT LoadedType = LS.getLoadedType(); 10072 if (TruncType != LoadedType && 10073 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10074 ZExts = 1; 10075 } 10076 10077 /// \brief Account for slicing gain in the current cost. 10078 /// Slicing provide a few gains like removing a shift or a 10079 /// truncate. This method allows to grow the cost of the original 10080 /// load with the gain from this slice. 10081 void addSliceGain(const LoadedSlice &LS) { 10082 // Each slice saves a truncate. 10083 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10084 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10085 LS.Inst->getValueType(0))) 10086 ++Truncates; 10087 // If there is a shift amount, this slice gets rid of it. 10088 if (LS.Shift) 10089 ++Shift; 10090 // If this slice can merge a cross register bank copy, account for it. 10091 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10092 ++CrossRegisterBanksCopies; 10093 } 10094 10095 Cost &operator+=(const Cost &RHS) { 10096 Loads += RHS.Loads; 10097 Truncates += RHS.Truncates; 10098 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10099 ZExts += RHS.ZExts; 10100 Shift += RHS.Shift; 10101 return *this; 10102 } 10103 10104 bool operator==(const Cost &RHS) const { 10105 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10106 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10107 ZExts == RHS.ZExts && Shift == RHS.Shift; 10108 } 10109 10110 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10111 10112 bool operator<(const Cost &RHS) const { 10113 // Assume cross register banks copies are as expensive as loads. 10114 // FIXME: Do we want some more target hooks? 10115 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10116 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10117 // Unless we are optimizing for code size, consider the 10118 // expensive operation first. 10119 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10120 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10121 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10122 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10123 } 10124 10125 bool operator>(const Cost &RHS) const { return RHS < *this; } 10126 10127 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10128 10129 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10130 }; 10131 // The last instruction that represent the slice. This should be a 10132 // truncate instruction. 10133 SDNode *Inst; 10134 // The original load instruction. 10135 LoadSDNode *Origin; 10136 // The right shift amount in bits from the original load. 10137 unsigned Shift; 10138 // The DAG from which Origin came from. 10139 // This is used to get some contextual information about legal types, etc. 10140 SelectionDAG *DAG; 10141 10142 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10143 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10144 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10145 10146 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10147 /// \return Result is \p BitWidth and has used bits set to 1 and 10148 /// not used bits set to 0. 10149 APInt getUsedBits() const { 10150 // Reproduce the trunc(lshr) sequence: 10151 // - Start from the truncated value. 10152 // - Zero extend to the desired bit width. 10153 // - Shift left. 10154 assert(Origin && "No original load to compare against."); 10155 unsigned BitWidth = Origin->getValueSizeInBits(0); 10156 assert(Inst && "This slice is not bound to an instruction"); 10157 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10158 "Extracted slice is bigger than the whole type!"); 10159 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10160 UsedBits.setAllBits(); 10161 UsedBits = UsedBits.zext(BitWidth); 10162 UsedBits <<= Shift; 10163 return UsedBits; 10164 } 10165 10166 /// \brief Get the size of the slice to be loaded in bytes. 10167 unsigned getLoadedSize() const { 10168 unsigned SliceSize = getUsedBits().countPopulation(); 10169 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10170 return SliceSize / 8; 10171 } 10172 10173 /// \brief Get the type that will be loaded for this slice. 10174 /// Note: This may not be the final type for the slice. 10175 EVT getLoadedType() const { 10176 assert(DAG && "Missing context"); 10177 LLVMContext &Ctxt = *DAG->getContext(); 10178 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10179 } 10180 10181 /// \brief Get the alignment of the load used for this slice. 10182 unsigned getAlignment() const { 10183 unsigned Alignment = Origin->getAlignment(); 10184 unsigned Offset = getOffsetFromBase(); 10185 if (Offset != 0) 10186 Alignment = MinAlign(Alignment, Alignment + Offset); 10187 return Alignment; 10188 } 10189 10190 /// \brief Check if this slice can be rewritten with legal operations. 10191 bool isLegal() const { 10192 // An invalid slice is not legal. 10193 if (!Origin || !Inst || !DAG) 10194 return false; 10195 10196 // Offsets are for indexed load only, we do not handle that. 10197 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 10198 return false; 10199 10200 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10201 10202 // Check that the type is legal. 10203 EVT SliceType = getLoadedType(); 10204 if (!TLI.isTypeLegal(SliceType)) 10205 return false; 10206 10207 // Check that the load is legal for this type. 10208 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10209 return false; 10210 10211 // Check that the offset can be computed. 10212 // 1. Check its type. 10213 EVT PtrType = Origin->getBasePtr().getValueType(); 10214 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10215 return false; 10216 10217 // 2. Check that it fits in the immediate. 10218 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10219 return false; 10220 10221 // 3. Check that the computation is legal. 10222 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10223 return false; 10224 10225 // Check that the zext is legal if it needs one. 10226 EVT TruncateType = Inst->getValueType(0); 10227 if (TruncateType != SliceType && 10228 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10229 return false; 10230 10231 return true; 10232 } 10233 10234 /// \brief Get the offset in bytes of this slice in the original chunk of 10235 /// bits. 10236 /// \pre DAG != nullptr. 10237 uint64_t getOffsetFromBase() const { 10238 assert(DAG && "Missing context."); 10239 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10240 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10241 uint64_t Offset = Shift / 8; 10242 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10243 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10244 "The size of the original loaded type is not a multiple of a" 10245 " byte."); 10246 // If Offset is bigger than TySizeInBytes, it means we are loading all 10247 // zeros. This should have been optimized before in the process. 10248 assert(TySizeInBytes > Offset && 10249 "Invalid shift amount for given loaded size"); 10250 if (IsBigEndian) 10251 Offset = TySizeInBytes - Offset - getLoadedSize(); 10252 return Offset; 10253 } 10254 10255 /// \brief Generate the sequence of instructions to load the slice 10256 /// represented by this object and redirect the uses of this slice to 10257 /// this new sequence of instructions. 10258 /// \pre this->Inst && this->Origin are valid Instructions and this 10259 /// object passed the legal check: LoadedSlice::isLegal returned true. 10260 /// \return The last instruction of the sequence used to load the slice. 10261 SDValue loadSlice() const { 10262 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10263 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10264 SDValue BaseAddr = OldBaseAddr; 10265 // Get the offset in that chunk of bytes w.r.t. the endianess. 10266 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10267 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10268 if (Offset) { 10269 // BaseAddr = BaseAddr + Offset. 10270 EVT ArithType = BaseAddr.getValueType(); 10271 SDLoc DL(Origin); 10272 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10273 DAG->getConstant(Offset, DL, ArithType)); 10274 } 10275 10276 // Create the type of the loaded slice according to its size. 10277 EVT SliceType = getLoadedType(); 10278 10279 // Create the load for the slice. 10280 SDValue LastInst = DAG->getLoad( 10281 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10282 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10283 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10284 // If the final type is not the same as the loaded type, this means that 10285 // we have to pad with zero. Create a zero extend for that. 10286 EVT FinalType = Inst->getValueType(0); 10287 if (SliceType != FinalType) 10288 LastInst = 10289 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10290 return LastInst; 10291 } 10292 10293 /// \brief Check if this slice can be merged with an expensive cross register 10294 /// bank copy. E.g., 10295 /// i = load i32 10296 /// f = bitcast i32 i to float 10297 bool canMergeExpensiveCrossRegisterBankCopy() const { 10298 if (!Inst || !Inst->hasOneUse()) 10299 return false; 10300 SDNode *Use = *Inst->use_begin(); 10301 if (Use->getOpcode() != ISD::BITCAST) 10302 return false; 10303 assert(DAG && "Missing context"); 10304 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10305 EVT ResVT = Use->getValueType(0); 10306 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10307 const TargetRegisterClass *ArgRC = 10308 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10309 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10310 return false; 10311 10312 // At this point, we know that we perform a cross-register-bank copy. 10313 // Check if it is expensive. 10314 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10315 // Assume bitcasts are cheap, unless both register classes do not 10316 // explicitly share a common sub class. 10317 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10318 return false; 10319 10320 // Check if it will be merged with the load. 10321 // 1. Check the alignment constraint. 10322 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10323 ResVT.getTypeForEVT(*DAG->getContext())); 10324 10325 if (RequiredAlignment > getAlignment()) 10326 return false; 10327 10328 // 2. Check that the load is a legal operation for that type. 10329 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10330 return false; 10331 10332 // 3. Check that we do not have a zext in the way. 10333 if (Inst->getValueType(0) != getLoadedType()) 10334 return false; 10335 10336 return true; 10337 } 10338 }; 10339 } 10340 10341 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10342 /// \p UsedBits looks like 0..0 1..1 0..0. 10343 static bool areUsedBitsDense(const APInt &UsedBits) { 10344 // If all the bits are one, this is dense! 10345 if (UsedBits.isAllOnesValue()) 10346 return true; 10347 10348 // Get rid of the unused bits on the right. 10349 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10350 // Get rid of the unused bits on the left. 10351 if (NarrowedUsedBits.countLeadingZeros()) 10352 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10353 // Check that the chunk of bits is completely used. 10354 return NarrowedUsedBits.isAllOnesValue(); 10355 } 10356 10357 /// \brief Check whether or not \p First and \p Second are next to each other 10358 /// in memory. This means that there is no hole between the bits loaded 10359 /// by \p First and the bits loaded by \p Second. 10360 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10361 const LoadedSlice &Second) { 10362 assert(First.Origin == Second.Origin && First.Origin && 10363 "Unable to match different memory origins."); 10364 APInt UsedBits = First.getUsedBits(); 10365 assert((UsedBits & Second.getUsedBits()) == 0 && 10366 "Slices are not supposed to overlap."); 10367 UsedBits |= Second.getUsedBits(); 10368 return areUsedBitsDense(UsedBits); 10369 } 10370 10371 /// \brief Adjust the \p GlobalLSCost according to the target 10372 /// paring capabilities and the layout of the slices. 10373 /// \pre \p GlobalLSCost should account for at least as many loads as 10374 /// there is in the slices in \p LoadedSlices. 10375 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10376 LoadedSlice::Cost &GlobalLSCost) { 10377 unsigned NumberOfSlices = LoadedSlices.size(); 10378 // If there is less than 2 elements, no pairing is possible. 10379 if (NumberOfSlices < 2) 10380 return; 10381 10382 // Sort the slices so that elements that are likely to be next to each 10383 // other in memory are next to each other in the list. 10384 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10385 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10386 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10387 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10388 }); 10389 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10390 // First (resp. Second) is the first (resp. Second) potentially candidate 10391 // to be placed in a paired load. 10392 const LoadedSlice *First = nullptr; 10393 const LoadedSlice *Second = nullptr; 10394 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10395 // Set the beginning of the pair. 10396 First = Second) { 10397 10398 Second = &LoadedSlices[CurrSlice]; 10399 10400 // If First is NULL, it means we start a new pair. 10401 // Get to the next slice. 10402 if (!First) 10403 continue; 10404 10405 EVT LoadedType = First->getLoadedType(); 10406 10407 // If the types of the slices are different, we cannot pair them. 10408 if (LoadedType != Second->getLoadedType()) 10409 continue; 10410 10411 // Check if the target supplies paired loads for this type. 10412 unsigned RequiredAlignment = 0; 10413 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10414 // move to the next pair, this type is hopeless. 10415 Second = nullptr; 10416 continue; 10417 } 10418 // Check if we meet the alignment requirement. 10419 if (RequiredAlignment > First->getAlignment()) 10420 continue; 10421 10422 // Check that both loads are next to each other in memory. 10423 if (!areSlicesNextToEachOther(*First, *Second)) 10424 continue; 10425 10426 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10427 --GlobalLSCost.Loads; 10428 // Move to the next pair. 10429 Second = nullptr; 10430 } 10431 } 10432 10433 /// \brief Check the profitability of all involved LoadedSlice. 10434 /// Currently, it is considered profitable if there is exactly two 10435 /// involved slices (1) which are (2) next to each other in memory, and 10436 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10437 /// 10438 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10439 /// the elements themselves. 10440 /// 10441 /// FIXME: When the cost model will be mature enough, we can relax 10442 /// constraints (1) and (2). 10443 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10444 const APInt &UsedBits, bool ForCodeSize) { 10445 unsigned NumberOfSlices = LoadedSlices.size(); 10446 if (StressLoadSlicing) 10447 return NumberOfSlices > 1; 10448 10449 // Check (1). 10450 if (NumberOfSlices != 2) 10451 return false; 10452 10453 // Check (2). 10454 if (!areUsedBitsDense(UsedBits)) 10455 return false; 10456 10457 // Check (3). 10458 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10459 // The original code has one big load. 10460 OrigCost.Loads = 1; 10461 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10462 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10463 // Accumulate the cost of all the slices. 10464 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10465 GlobalSlicingCost += SliceCost; 10466 10467 // Account as cost in the original configuration the gain obtained 10468 // with the current slices. 10469 OrigCost.addSliceGain(LS); 10470 } 10471 10472 // If the target supports paired load, adjust the cost accordingly. 10473 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10474 return OrigCost > GlobalSlicingCost; 10475 } 10476 10477 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10478 /// operations, split it in the various pieces being extracted. 10479 /// 10480 /// This sort of thing is introduced by SROA. 10481 /// This slicing takes care not to insert overlapping loads. 10482 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10483 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10484 if (Level < AfterLegalizeDAG) 10485 return false; 10486 10487 LoadSDNode *LD = cast<LoadSDNode>(N); 10488 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10489 !LD->getValueType(0).isInteger()) 10490 return false; 10491 10492 // Keep track of already used bits to detect overlapping values. 10493 // In that case, we will just abort the transformation. 10494 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10495 10496 SmallVector<LoadedSlice, 4> LoadedSlices; 10497 10498 // Check if this load is used as several smaller chunks of bits. 10499 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10500 // of computation for each trunc. 10501 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10502 UI != UIEnd; ++UI) { 10503 // Skip the uses of the chain. 10504 if (UI.getUse().getResNo() != 0) 10505 continue; 10506 10507 SDNode *User = *UI; 10508 unsigned Shift = 0; 10509 10510 // Check if this is a trunc(lshr). 10511 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10512 isa<ConstantSDNode>(User->getOperand(1))) { 10513 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10514 User = *User->use_begin(); 10515 } 10516 10517 // At this point, User is a Truncate, iff we encountered, trunc or 10518 // trunc(lshr). 10519 if (User->getOpcode() != ISD::TRUNCATE) 10520 return false; 10521 10522 // The width of the type must be a power of 2 and greater than 8-bits. 10523 // Otherwise the load cannot be represented in LLVM IR. 10524 // Moreover, if we shifted with a non-8-bits multiple, the slice 10525 // will be across several bytes. We do not support that. 10526 unsigned Width = User->getValueSizeInBits(0); 10527 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10528 return 0; 10529 10530 // Build the slice for this chain of computations. 10531 LoadedSlice LS(User, LD, Shift, &DAG); 10532 APInt CurrentUsedBits = LS.getUsedBits(); 10533 10534 // Check if this slice overlaps with another. 10535 if ((CurrentUsedBits & UsedBits) != 0) 10536 return false; 10537 // Update the bits used globally. 10538 UsedBits |= CurrentUsedBits; 10539 10540 // Check if the new slice would be legal. 10541 if (!LS.isLegal()) 10542 return false; 10543 10544 // Record the slice. 10545 LoadedSlices.push_back(LS); 10546 } 10547 10548 // Abort slicing if it does not seem to be profitable. 10549 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10550 return false; 10551 10552 ++SlicedLoads; 10553 10554 // Rewrite each chain to use an independent load. 10555 // By construction, each chain can be represented by a unique load. 10556 10557 // Prepare the argument for the new token factor for all the slices. 10558 SmallVector<SDValue, 8> ArgChains; 10559 for (SmallVectorImpl<LoadedSlice>::const_iterator 10560 LSIt = LoadedSlices.begin(), 10561 LSItEnd = LoadedSlices.end(); 10562 LSIt != LSItEnd; ++LSIt) { 10563 SDValue SliceInst = LSIt->loadSlice(); 10564 CombineTo(LSIt->Inst, SliceInst, true); 10565 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10566 SliceInst = SliceInst.getOperand(0); 10567 assert(SliceInst->getOpcode() == ISD::LOAD && 10568 "It takes more than a zext to get to the loaded slice!!"); 10569 ArgChains.push_back(SliceInst.getValue(1)); 10570 } 10571 10572 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10573 ArgChains); 10574 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10575 return true; 10576 } 10577 10578 /// Check to see if V is (and load (ptr), imm), where the load is having 10579 /// specific bytes cleared out. If so, return the byte size being masked out 10580 /// and the shift amount. 10581 static std::pair<unsigned, unsigned> 10582 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10583 std::pair<unsigned, unsigned> Result(0, 0); 10584 10585 // Check for the structure we're looking for. 10586 if (V->getOpcode() != ISD::AND || 10587 !isa<ConstantSDNode>(V->getOperand(1)) || 10588 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10589 return Result; 10590 10591 // Check the chain and pointer. 10592 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10593 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10594 10595 // The store should be chained directly to the load or be an operand of a 10596 // tokenfactor. 10597 if (LD == Chain.getNode()) 10598 ; // ok. 10599 else if (Chain->getOpcode() != ISD::TokenFactor) 10600 return Result; // Fail. 10601 else { 10602 bool isOk = false; 10603 for (const SDValue &ChainOp : Chain->op_values()) 10604 if (ChainOp.getNode() == LD) { 10605 isOk = true; 10606 break; 10607 } 10608 if (!isOk) return Result; 10609 } 10610 10611 // This only handles simple types. 10612 if (V.getValueType() != MVT::i16 && 10613 V.getValueType() != MVT::i32 && 10614 V.getValueType() != MVT::i64) 10615 return Result; 10616 10617 // Check the constant mask. Invert it so that the bits being masked out are 10618 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10619 // follow the sign bit for uniformity. 10620 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10621 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10622 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10623 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10624 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10625 if (NotMaskLZ == 64) return Result; // All zero mask. 10626 10627 // See if we have a continuous run of bits. If so, we have 0*1+0* 10628 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10629 return Result; 10630 10631 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10632 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10633 NotMaskLZ -= 64-V.getValueSizeInBits(); 10634 10635 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10636 switch (MaskedBytes) { 10637 case 1: 10638 case 2: 10639 case 4: break; 10640 default: return Result; // All one mask, or 5-byte mask. 10641 } 10642 10643 // Verify that the first bit starts at a multiple of mask so that the access 10644 // is aligned the same as the access width. 10645 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10646 10647 Result.first = MaskedBytes; 10648 Result.second = NotMaskTZ/8; 10649 return Result; 10650 } 10651 10652 10653 /// Check to see if IVal is something that provides a value as specified by 10654 /// MaskInfo. If so, replace the specified store with a narrower store of 10655 /// truncated IVal. 10656 static SDNode * 10657 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10658 SDValue IVal, StoreSDNode *St, 10659 DAGCombiner *DC) { 10660 unsigned NumBytes = MaskInfo.first; 10661 unsigned ByteShift = MaskInfo.second; 10662 SelectionDAG &DAG = DC->getDAG(); 10663 10664 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10665 // that uses this. If not, this is not a replacement. 10666 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10667 ByteShift*8, (ByteShift+NumBytes)*8); 10668 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10669 10670 // Check that it is legal on the target to do this. It is legal if the new 10671 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10672 // legalization. 10673 MVT VT = MVT::getIntegerVT(NumBytes*8); 10674 if (!DC->isTypeLegal(VT)) 10675 return nullptr; 10676 10677 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10678 // shifted by ByteShift and truncated down to NumBytes. 10679 if (ByteShift) { 10680 SDLoc DL(IVal); 10681 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10682 DAG.getConstant(ByteShift*8, DL, 10683 DC->getShiftAmountTy(IVal.getValueType()))); 10684 } 10685 10686 // Figure out the offset for the store and the alignment of the access. 10687 unsigned StOffset; 10688 unsigned NewAlign = St->getAlignment(); 10689 10690 if (DAG.getDataLayout().isLittleEndian()) 10691 StOffset = ByteShift; 10692 else 10693 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10694 10695 SDValue Ptr = St->getBasePtr(); 10696 if (StOffset) { 10697 SDLoc DL(IVal); 10698 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10699 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10700 NewAlign = MinAlign(NewAlign, StOffset); 10701 } 10702 10703 // Truncate down to the new size. 10704 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10705 10706 ++OpsNarrowed; 10707 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10708 St->getPointerInfo().getWithOffset(StOffset), 10709 false, false, NewAlign).getNode(); 10710 } 10711 10712 10713 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10714 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10715 /// narrowing the load and store if it would end up being a win for performance 10716 /// or code size. 10717 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10718 StoreSDNode *ST = cast<StoreSDNode>(N); 10719 if (ST->isVolatile()) 10720 return SDValue(); 10721 10722 SDValue Chain = ST->getChain(); 10723 SDValue Value = ST->getValue(); 10724 SDValue Ptr = ST->getBasePtr(); 10725 EVT VT = Value.getValueType(); 10726 10727 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10728 return SDValue(); 10729 10730 unsigned Opc = Value.getOpcode(); 10731 10732 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10733 // is a byte mask indicating a consecutive number of bytes, check to see if 10734 // Y is known to provide just those bytes. If so, we try to replace the 10735 // load + replace + store sequence with a single (narrower) store, which makes 10736 // the load dead. 10737 if (Opc == ISD::OR) { 10738 std::pair<unsigned, unsigned> MaskedLoad; 10739 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10740 if (MaskedLoad.first) 10741 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10742 Value.getOperand(1), ST,this)) 10743 return SDValue(NewST, 0); 10744 10745 // Or is commutative, so try swapping X and Y. 10746 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10747 if (MaskedLoad.first) 10748 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10749 Value.getOperand(0), ST,this)) 10750 return SDValue(NewST, 0); 10751 } 10752 10753 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10754 Value.getOperand(1).getOpcode() != ISD::Constant) 10755 return SDValue(); 10756 10757 SDValue N0 = Value.getOperand(0); 10758 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10759 Chain == SDValue(N0.getNode(), 1)) { 10760 LoadSDNode *LD = cast<LoadSDNode>(N0); 10761 if (LD->getBasePtr() != Ptr || 10762 LD->getPointerInfo().getAddrSpace() != 10763 ST->getPointerInfo().getAddrSpace()) 10764 return SDValue(); 10765 10766 // Find the type to narrow it the load / op / store to. 10767 SDValue N1 = Value.getOperand(1); 10768 unsigned BitWidth = N1.getValueSizeInBits(); 10769 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10770 if (Opc == ISD::AND) 10771 Imm ^= APInt::getAllOnesValue(BitWidth); 10772 if (Imm == 0 || Imm.isAllOnesValue()) 10773 return SDValue(); 10774 unsigned ShAmt = Imm.countTrailingZeros(); 10775 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10776 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10777 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10778 // The narrowing should be profitable, the load/store operation should be 10779 // legal (or custom) and the store size should be equal to the NewVT width. 10780 while (NewBW < BitWidth && 10781 (NewVT.getStoreSizeInBits() != NewBW || 10782 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10783 !TLI.isNarrowingProfitable(VT, NewVT))) { 10784 NewBW = NextPowerOf2(NewBW); 10785 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10786 } 10787 if (NewBW >= BitWidth) 10788 return SDValue(); 10789 10790 // If the lsb changed does not start at the type bitwidth boundary, 10791 // start at the previous one. 10792 if (ShAmt % NewBW) 10793 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10794 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10795 std::min(BitWidth, ShAmt + NewBW)); 10796 if ((Imm & Mask) == Imm) { 10797 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10798 if (Opc == ISD::AND) 10799 NewImm ^= APInt::getAllOnesValue(NewBW); 10800 uint64_t PtrOff = ShAmt / 8; 10801 // For big endian targets, we need to adjust the offset to the pointer to 10802 // load the correct bytes. 10803 if (DAG.getDataLayout().isBigEndian()) 10804 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10805 10806 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10807 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10808 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10809 return SDValue(); 10810 10811 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10812 Ptr.getValueType(), Ptr, 10813 DAG.getConstant(PtrOff, SDLoc(LD), 10814 Ptr.getValueType())); 10815 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10816 LD->getChain(), NewPtr, 10817 LD->getPointerInfo().getWithOffset(PtrOff), 10818 LD->isVolatile(), LD->isNonTemporal(), 10819 LD->isInvariant(), NewAlign, 10820 LD->getAAInfo()); 10821 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10822 DAG.getConstant(NewImm, SDLoc(Value), 10823 NewVT)); 10824 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10825 NewVal, NewPtr, 10826 ST->getPointerInfo().getWithOffset(PtrOff), 10827 false, false, NewAlign); 10828 10829 AddToWorklist(NewPtr.getNode()); 10830 AddToWorklist(NewLD.getNode()); 10831 AddToWorklist(NewVal.getNode()); 10832 WorklistRemover DeadNodes(*this); 10833 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10834 ++OpsNarrowed; 10835 return NewST; 10836 } 10837 } 10838 10839 return SDValue(); 10840 } 10841 10842 /// For a given floating point load / store pair, if the load value isn't used 10843 /// by any other operations, then consider transforming the pair to integer 10844 /// load / store operations if the target deems the transformation profitable. 10845 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10846 StoreSDNode *ST = cast<StoreSDNode>(N); 10847 SDValue Chain = ST->getChain(); 10848 SDValue Value = ST->getValue(); 10849 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10850 Value.hasOneUse() && 10851 Chain == SDValue(Value.getNode(), 1)) { 10852 LoadSDNode *LD = cast<LoadSDNode>(Value); 10853 EVT VT = LD->getMemoryVT(); 10854 if (!VT.isFloatingPoint() || 10855 VT != ST->getMemoryVT() || 10856 LD->isNonTemporal() || 10857 ST->isNonTemporal() || 10858 LD->getPointerInfo().getAddrSpace() != 0 || 10859 ST->getPointerInfo().getAddrSpace() != 0) 10860 return SDValue(); 10861 10862 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10863 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10864 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10865 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10866 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10867 return SDValue(); 10868 10869 unsigned LDAlign = LD->getAlignment(); 10870 unsigned STAlign = ST->getAlignment(); 10871 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10872 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10873 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10874 return SDValue(); 10875 10876 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10877 LD->getChain(), LD->getBasePtr(), 10878 LD->getPointerInfo(), 10879 false, false, false, LDAlign); 10880 10881 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10882 NewLD, ST->getBasePtr(), 10883 ST->getPointerInfo(), 10884 false, false, STAlign); 10885 10886 AddToWorklist(NewLD.getNode()); 10887 AddToWorklist(NewST.getNode()); 10888 WorklistRemover DeadNodes(*this); 10889 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10890 ++LdStFP2Int; 10891 return NewST; 10892 } 10893 10894 return SDValue(); 10895 } 10896 10897 namespace { 10898 /// Helper struct to parse and store a memory address as base + index + offset. 10899 /// We ignore sign extensions when it is safe to do so. 10900 /// The following two expressions are not equivalent. To differentiate we need 10901 /// to store whether there was a sign extension involved in the index 10902 /// computation. 10903 /// (load (i64 add (i64 copyfromreg %c) 10904 /// (i64 signextend (add (i8 load %index) 10905 /// (i8 1)))) 10906 /// vs 10907 /// 10908 /// (load (i64 add (i64 copyfromreg %c) 10909 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10910 /// (i32 1))))) 10911 struct BaseIndexOffset { 10912 SDValue Base; 10913 SDValue Index; 10914 int64_t Offset; 10915 bool IsIndexSignExt; 10916 10917 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10918 10919 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10920 bool IsIndexSignExt) : 10921 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10922 10923 bool equalBaseIndex(const BaseIndexOffset &Other) { 10924 return Other.Base == Base && Other.Index == Index && 10925 Other.IsIndexSignExt == IsIndexSignExt; 10926 } 10927 10928 /// Parses tree in Ptr for base, index, offset addresses. 10929 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 10930 bool IsIndexSignExt = false; 10931 10932 // Split up a folded GlobalAddress+Offset into its component parts. 10933 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 10934 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 10935 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 10936 SDLoc(GA), 10937 GA->getValueType(0), 10938 /*Offset=*/0, 10939 /*isTargetGA=*/false, 10940 GA->getTargetFlags()), 10941 SDValue(), 10942 GA->getOffset(), 10943 IsIndexSignExt); 10944 } 10945 10946 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10947 // instruction, then it could be just the BASE or everything else we don't 10948 // know how to handle. Just use Ptr as BASE and give up. 10949 if (Ptr->getOpcode() != ISD::ADD) 10950 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10951 10952 // We know that we have at least an ADD instruction. Try to pattern match 10953 // the simple case of BASE + OFFSET. 10954 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10955 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10956 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10957 IsIndexSignExt); 10958 } 10959 10960 // Inside a loop the current BASE pointer is calculated using an ADD and a 10961 // MUL instruction. In this case Ptr is the actual BASE pointer. 10962 // (i64 add (i64 %array_ptr) 10963 // (i64 mul (i64 %induction_var) 10964 // (i64 %element_size))) 10965 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10966 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10967 10968 // Look at Base + Index + Offset cases. 10969 SDValue Base = Ptr->getOperand(0); 10970 SDValue IndexOffset = Ptr->getOperand(1); 10971 10972 // Skip signextends. 10973 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10974 IndexOffset = IndexOffset->getOperand(0); 10975 IsIndexSignExt = true; 10976 } 10977 10978 // Either the case of Base + Index (no offset) or something else. 10979 if (IndexOffset->getOpcode() != ISD::ADD) 10980 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10981 10982 // Now we have the case of Base + Index + offset. 10983 SDValue Index = IndexOffset->getOperand(0); 10984 SDValue Offset = IndexOffset->getOperand(1); 10985 10986 if (!isa<ConstantSDNode>(Offset)) 10987 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10988 10989 // Ignore signextends. 10990 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10991 Index = Index->getOperand(0); 10992 IsIndexSignExt = true; 10993 } else IsIndexSignExt = false; 10994 10995 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10996 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10997 } 10998 }; 10999 } // namespace 11000 11001 // This is a helper function for visitMUL to check the profitability 11002 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11003 // MulNode is the original multiply, AddNode is (add x, c1), 11004 // and ConstNode is c2. 11005 // 11006 // If the (add x, c1) has multiple uses, we could increase 11007 // the number of adds if we make this transformation. 11008 // It would only be worth doing this if we can remove a 11009 // multiply in the process. Check for that here. 11010 // To illustrate: 11011 // (A + c1) * c3 11012 // (A + c2) * c3 11013 // We're checking for cases where we have common "c3 * A" expressions. 11014 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11015 SDValue &AddNode, 11016 SDValue &ConstNode) { 11017 APInt Val; 11018 11019 // If the add only has one use, this would be OK to do. 11020 if (AddNode.getNode()->hasOneUse()) 11021 return true; 11022 11023 // Walk all the users of the constant with which we're multiplying. 11024 for (SDNode *Use : ConstNode->uses()) { 11025 11026 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11027 continue; 11028 11029 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11030 SDNode *OtherOp; 11031 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11032 11033 // OtherOp is what we're multiplying against the constant. 11034 if (Use->getOperand(0) == ConstNode) 11035 OtherOp = Use->getOperand(1).getNode(); 11036 else 11037 OtherOp = Use->getOperand(0).getNode(); 11038 11039 // Check to see if multiply is with the same operand of our "add". 11040 // 11041 // ConstNode = CONST 11042 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11043 // ... 11044 // AddNode = (A + c1) <-- MulVar is A. 11045 // = AddNode * ConstNode <-- current visiting instruction. 11046 // 11047 // If we make this transformation, we will have a common 11048 // multiply (ConstNode * A) that we can save. 11049 if (OtherOp == MulVar) 11050 return true; 11051 11052 // Now check to see if a future expansion will give us a common 11053 // multiply. 11054 // 11055 // ConstNode = CONST 11056 // AddNode = (A + c1) 11057 // ... = AddNode * ConstNode <-- current visiting instruction. 11058 // ... 11059 // OtherOp = (A + c2) 11060 // Use = OtherOp * ConstNode <-- visiting Use. 11061 // 11062 // If we make this transformation, we will have a common 11063 // multiply (CONST * A) after we also do the same transformation 11064 // to the "t2" instruction. 11065 if (OtherOp->getOpcode() == ISD::ADD && 11066 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11067 OtherOp->getOperand(0).getNode() == MulVar) 11068 return true; 11069 } 11070 } 11071 11072 // Didn't find a case where this would be profitable. 11073 return false; 11074 } 11075 11076 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 11077 SDLoc SL, 11078 ArrayRef<MemOpLink> Stores, 11079 SmallVectorImpl<SDValue> &Chains, 11080 EVT Ty) const { 11081 SmallVector<SDValue, 8> BuildVector; 11082 11083 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11084 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11085 Chains.push_back(St->getChain()); 11086 BuildVector.push_back(St->getValue()); 11087 } 11088 11089 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 11090 } 11091 11092 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11093 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11094 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11095 // Make sure we have something to merge. 11096 if (NumStores < 2) 11097 return false; 11098 11099 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11100 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11101 unsigned LatestNodeUsed = 0; 11102 11103 for (unsigned i=0; i < NumStores; ++i) { 11104 // Find a chain for the new wide-store operand. Notice that some 11105 // of the store nodes that we found may not be selected for inclusion 11106 // in the wide store. The chain we use needs to be the chain of the 11107 // latest store node which is *used* and replaced by the wide store. 11108 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11109 LatestNodeUsed = i; 11110 } 11111 11112 SmallVector<SDValue, 8> Chains; 11113 11114 // The latest Node in the DAG. 11115 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11116 SDLoc DL(StoreNodes[0].MemNode); 11117 11118 SDValue StoredVal; 11119 if (UseVector) { 11120 bool IsVec = MemVT.isVector(); 11121 unsigned Elts = NumStores; 11122 if (IsVec) { 11123 // When merging vector stores, get the total number of elements. 11124 Elts *= MemVT.getVectorNumElements(); 11125 } 11126 // Get the type for the merged vector store. 11127 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11128 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11129 11130 if (IsConstantSrc) { 11131 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11132 } else { 11133 SmallVector<SDValue, 8> Ops; 11134 for (unsigned i = 0; i < NumStores; ++i) { 11135 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11136 SDValue Val = St->getValue(); 11137 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11138 if (Val.getValueType() != MemVT) 11139 return false; 11140 Ops.push_back(Val); 11141 Chains.push_back(St->getChain()); 11142 } 11143 11144 // Build the extracted vector elements back into a vector. 11145 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11146 DL, Ty, Ops); } 11147 } else { 11148 // We should always use a vector store when merging extracted vector 11149 // elements, so this path implies a store of constants. 11150 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11151 11152 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11153 APInt StoreInt(SizeInBits, 0); 11154 11155 // Construct a single integer constant which is made of the smaller 11156 // constant inputs. 11157 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11158 for (unsigned i = 0; i < NumStores; ++i) { 11159 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11160 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11161 Chains.push_back(St->getChain()); 11162 11163 SDValue Val = St->getValue(); 11164 StoreInt <<= ElementSizeBytes * 8; 11165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11166 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11167 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11168 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11169 } else { 11170 llvm_unreachable("Invalid constant element type"); 11171 } 11172 } 11173 11174 // Create the new Load and Store operations. 11175 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11176 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11177 } 11178 11179 assert(!Chains.empty()); 11180 11181 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11182 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11183 FirstInChain->getBasePtr(), 11184 FirstInChain->getPointerInfo(), 11185 false, false, 11186 FirstInChain->getAlignment()); 11187 11188 // Replace the last store with the new store 11189 CombineTo(LatestOp, NewStore); 11190 // Erase all other stores. 11191 for (unsigned i = 0; i < NumStores; ++i) { 11192 if (StoreNodes[i].MemNode == LatestOp) 11193 continue; 11194 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11195 // ReplaceAllUsesWith will replace all uses that existed when it was 11196 // called, but graph optimizations may cause new ones to appear. For 11197 // example, the case in pr14333 looks like 11198 // 11199 // St's chain -> St -> another store -> X 11200 // 11201 // And the only difference from St to the other store is the chain. 11202 // When we change it's chain to be St's chain they become identical, 11203 // get CSEed and the net result is that X is now a use of St. 11204 // Since we know that St is redundant, just iterate. 11205 while (!St->use_empty()) 11206 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11207 deleteAndRecombine(St); 11208 } 11209 11210 return true; 11211 } 11212 11213 void DAGCombiner::getStoreMergeAndAliasCandidates( 11214 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11215 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11216 // This holds the base pointer, index, and the offset in bytes from the base 11217 // pointer. 11218 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11219 11220 // We must have a base and an offset. 11221 if (!BasePtr.Base.getNode()) 11222 return; 11223 11224 // Do not handle stores to undef base pointers. 11225 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 11226 return; 11227 11228 // Walk up the chain and look for nodes with offsets from the same 11229 // base pointer. Stop when reaching an instruction with a different kind 11230 // or instruction which has a different base pointer. 11231 EVT MemVT = St->getMemoryVT(); 11232 unsigned Seq = 0; 11233 StoreSDNode *Index = St; 11234 11235 11236 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11237 : DAG.getSubtarget().useAA(); 11238 11239 if (UseAA) { 11240 // Look at other users of the same chain. Stores on the same chain do not 11241 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11242 // to be on the same chain, so don't bother looking at adjacent chains. 11243 11244 SDValue Chain = St->getChain(); 11245 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11246 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11247 if (I.getOperandNo() != 0) 11248 continue; 11249 11250 if (OtherST->isVolatile() || OtherST->isIndexed()) 11251 continue; 11252 11253 if (OtherST->getMemoryVT() != MemVT) 11254 continue; 11255 11256 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11257 11258 if (Ptr.equalBaseIndex(BasePtr)) 11259 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11260 } 11261 } 11262 11263 return; 11264 } 11265 11266 while (Index) { 11267 // If the chain has more than one use, then we can't reorder the mem ops. 11268 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11269 break; 11270 11271 // Find the base pointer and offset for this memory node. 11272 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11273 11274 // Check that the base pointer is the same as the original one. 11275 if (!Ptr.equalBaseIndex(BasePtr)) 11276 break; 11277 11278 // The memory operands must not be volatile. 11279 if (Index->isVolatile() || Index->isIndexed()) 11280 break; 11281 11282 // No truncation. 11283 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 11284 if (St->isTruncatingStore()) 11285 break; 11286 11287 // The stored memory type must be the same. 11288 if (Index->getMemoryVT() != MemVT) 11289 break; 11290 11291 // We do not allow under-aligned stores in order to prevent 11292 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11293 // be irrelevant here; what MATTERS is that we not move memory 11294 // operations that potentially overlap past each-other. 11295 if (Index->getAlignment() < MemVT.getStoreSize()) 11296 break; 11297 11298 // We found a potential memory operand to merge. 11299 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11300 11301 // Find the next memory operand in the chain. If the next operand in the 11302 // chain is a store then move up and continue the scan with the next 11303 // memory operand. If the next operand is a load save it and use alias 11304 // information to check if it interferes with anything. 11305 SDNode *NextInChain = Index->getChain().getNode(); 11306 while (1) { 11307 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11308 // We found a store node. Use it for the next iteration. 11309 Index = STn; 11310 break; 11311 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11312 if (Ldn->isVolatile()) { 11313 Index = nullptr; 11314 break; 11315 } 11316 11317 // Save the load node for later. Continue the scan. 11318 AliasLoadNodes.push_back(Ldn); 11319 NextInChain = Ldn->getChain().getNode(); 11320 continue; 11321 } else { 11322 Index = nullptr; 11323 break; 11324 } 11325 } 11326 } 11327 } 11328 11329 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11330 if (OptLevel == CodeGenOpt::None) 11331 return false; 11332 11333 EVT MemVT = St->getMemoryVT(); 11334 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11335 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11336 Attribute::NoImplicitFloat); 11337 11338 // This function cannot currently deal with non-byte-sized memory sizes. 11339 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11340 return false; 11341 11342 if (!MemVT.isSimple()) 11343 return false; 11344 11345 // Perform an early exit check. Do not bother looking at stored values that 11346 // are not constants, loads, or extracted vector elements. 11347 SDValue StoredVal = St->getValue(); 11348 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11349 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11350 isa<ConstantFPSDNode>(StoredVal); 11351 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11352 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11353 11354 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11355 return false; 11356 11357 // Don't merge vectors into wider vectors if the source data comes from loads. 11358 // TODO: This restriction can be lifted by using logic similar to the 11359 // ExtractVecSrc case. 11360 if (MemVT.isVector() && IsLoadSrc) 11361 return false; 11362 11363 // Only look at ends of store sequences. 11364 SDValue Chain = SDValue(St, 0); 11365 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11366 return false; 11367 11368 // Save the LoadSDNodes that we find in the chain. 11369 // We need to make sure that these nodes do not interfere with 11370 // any of the store nodes. 11371 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11372 11373 // Save the StoreSDNodes that we find in the chain. 11374 SmallVector<MemOpLink, 8> StoreNodes; 11375 11376 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11377 11378 // Check if there is anything to merge. 11379 if (StoreNodes.size() < 2) 11380 return false; 11381 11382 // Sort the memory operands according to their distance from the 11383 // base pointer. As a secondary criteria: make sure stores coming 11384 // later in the code come first in the list. This is important for 11385 // the non-UseAA case, because we're merging stores into the FINAL 11386 // store along a chain which potentially contains aliasing stores. 11387 // Thus, if there are multiple stores to the same address, the last 11388 // one can be considered for merging but not the others. 11389 std::sort(StoreNodes.begin(), StoreNodes.end(), 11390 [](MemOpLink LHS, MemOpLink RHS) { 11391 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11392 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11393 LHS.SequenceNum < RHS.SequenceNum); 11394 }); 11395 11396 // Scan the memory operations on the chain and find the first non-consecutive 11397 // store memory address. 11398 unsigned LastConsecutiveStore = 0; 11399 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11400 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11401 11402 // Check that the addresses are consecutive starting from the second 11403 // element in the list of stores. 11404 if (i > 0) { 11405 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11406 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11407 break; 11408 } 11409 11410 // Check if this store interferes with any of the loads that we found. 11411 // If we find a load that alias with this store. Stop the sequence. 11412 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(), 11413 [&](LSBaseSDNode* Ldn) { 11414 return isAlias(Ldn, StoreNodes[i].MemNode); 11415 })) 11416 break; 11417 11418 // Mark this node as useful. 11419 LastConsecutiveStore = i; 11420 } 11421 11422 // The node with the lowest store address. 11423 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11424 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11425 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11426 LLVMContext &Context = *DAG.getContext(); 11427 const DataLayout &DL = DAG.getDataLayout(); 11428 11429 // Store the constants into memory as one consecutive store. 11430 if (IsConstantSrc) { 11431 unsigned LastLegalType = 0; 11432 unsigned LastLegalVectorType = 0; 11433 bool NonZero = false; 11434 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11435 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11436 SDValue StoredVal = St->getValue(); 11437 11438 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11439 NonZero |= !C->isNullValue(); 11440 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11441 NonZero |= !C->getConstantFPValue()->isNullValue(); 11442 } else { 11443 // Non-constant. 11444 break; 11445 } 11446 11447 // Find a legal type for the constant store. 11448 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11449 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11450 bool IsFast; 11451 if (TLI.isTypeLegal(StoreTy) && 11452 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11453 FirstStoreAlign, &IsFast) && IsFast) { 11454 LastLegalType = i+1; 11455 // Or check whether a truncstore is legal. 11456 } else if (TLI.getTypeAction(Context, StoreTy) == 11457 TargetLowering::TypePromoteInteger) { 11458 EVT LegalizedStoredValueTy = 11459 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11460 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11461 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11462 FirstStoreAS, FirstStoreAlign, &IsFast) && 11463 IsFast) { 11464 LastLegalType = i + 1; 11465 } 11466 } 11467 11468 // We only use vectors if the constant is known to be zero or the target 11469 // allows it and the function is not marked with the noimplicitfloat 11470 // attribute. 11471 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11472 FirstStoreAS)) && 11473 !NoVectors) { 11474 // Find a legal type for the vector store. 11475 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11476 if (TLI.isTypeLegal(Ty) && 11477 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11478 FirstStoreAlign, &IsFast) && IsFast) 11479 LastLegalVectorType = i + 1; 11480 } 11481 } 11482 11483 // Check if we found a legal integer type to store. 11484 if (LastLegalType == 0 && LastLegalVectorType == 0) 11485 return false; 11486 11487 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11488 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11489 11490 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11491 true, UseVector); 11492 } 11493 11494 // When extracting multiple vector elements, try to store them 11495 // in one vector store rather than a sequence of scalar stores. 11496 if (IsExtractVecSrc) { 11497 unsigned NumStoresToMerge = 0; 11498 bool IsVec = MemVT.isVector(); 11499 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11500 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11501 unsigned StoreValOpcode = St->getValue().getOpcode(); 11502 // This restriction could be loosened. 11503 // Bail out if any stored values are not elements extracted from a vector. 11504 // It should be possible to handle mixed sources, but load sources need 11505 // more careful handling (see the block of code below that handles 11506 // consecutive loads). 11507 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11508 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11509 return false; 11510 11511 // Find a legal type for the vector store. 11512 unsigned Elts = i + 1; 11513 if (IsVec) { 11514 // When merging vector stores, get the total number of elements. 11515 Elts *= MemVT.getVectorNumElements(); 11516 } 11517 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11518 bool IsFast; 11519 if (TLI.isTypeLegal(Ty) && 11520 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11521 FirstStoreAlign, &IsFast) && IsFast) 11522 NumStoresToMerge = i + 1; 11523 } 11524 11525 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11526 false, true); 11527 } 11528 11529 // Below we handle the case of multiple consecutive stores that 11530 // come from multiple consecutive loads. We merge them into a single 11531 // wide load and a single wide store. 11532 11533 // Look for load nodes which are used by the stored values. 11534 SmallVector<MemOpLink, 8> LoadNodes; 11535 11536 // Find acceptable loads. Loads need to have the same chain (token factor), 11537 // must not be zext, volatile, indexed, and they must be consecutive. 11538 BaseIndexOffset LdBasePtr; 11539 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11540 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11541 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11542 if (!Ld) break; 11543 11544 // Loads must only have one use. 11545 if (!Ld->hasNUsesOfValue(1, 0)) 11546 break; 11547 11548 // The memory operands must not be volatile. 11549 if (Ld->isVolatile() || Ld->isIndexed()) 11550 break; 11551 11552 // We do not accept ext loads. 11553 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11554 break; 11555 11556 // The stored memory type must be the same. 11557 if (Ld->getMemoryVT() != MemVT) 11558 break; 11559 11560 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11561 // If this is not the first ptr that we check. 11562 if (LdBasePtr.Base.getNode()) { 11563 // The base ptr must be the same. 11564 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11565 break; 11566 } else { 11567 // Check that all other base pointers are the same as this one. 11568 LdBasePtr = LdPtr; 11569 } 11570 11571 // We found a potential memory operand to merge. 11572 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11573 } 11574 11575 if (LoadNodes.size() < 2) 11576 return false; 11577 11578 // If we have load/store pair instructions and we only have two values, 11579 // don't bother. 11580 unsigned RequiredAlignment; 11581 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11582 St->getAlignment() >= RequiredAlignment) 11583 return false; 11584 11585 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11586 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11587 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11588 11589 // Scan the memory operations on the chain and find the first non-consecutive 11590 // load memory address. These variables hold the index in the store node 11591 // array. 11592 unsigned LastConsecutiveLoad = 0; 11593 // This variable refers to the size and not index in the array. 11594 unsigned LastLegalVectorType = 0; 11595 unsigned LastLegalIntegerType = 0; 11596 StartAddress = LoadNodes[0].OffsetFromBase; 11597 SDValue FirstChain = FirstLoad->getChain(); 11598 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11599 // All loads must share the same chain. 11600 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11601 break; 11602 11603 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11604 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11605 break; 11606 LastConsecutiveLoad = i; 11607 // Find a legal type for the vector store. 11608 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11609 bool IsFastSt, IsFastLd; 11610 if (TLI.isTypeLegal(StoreTy) && 11611 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11612 FirstStoreAlign, &IsFastSt) && IsFastSt && 11613 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11614 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11615 LastLegalVectorType = i + 1; 11616 } 11617 11618 // Find a legal type for the integer store. 11619 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11620 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11621 if (TLI.isTypeLegal(StoreTy) && 11622 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11623 FirstStoreAlign, &IsFastSt) && IsFastSt && 11624 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11625 FirstLoadAlign, &IsFastLd) && IsFastLd) 11626 LastLegalIntegerType = i + 1; 11627 // Or check whether a truncstore and extload is legal. 11628 else if (TLI.getTypeAction(Context, StoreTy) == 11629 TargetLowering::TypePromoteInteger) { 11630 EVT LegalizedStoredValueTy = 11631 TLI.getTypeToTransformTo(Context, StoreTy); 11632 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11633 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11634 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11635 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11636 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11637 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11638 IsFastSt && 11639 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11640 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11641 IsFastLd) 11642 LastLegalIntegerType = i+1; 11643 } 11644 } 11645 11646 // Only use vector types if the vector type is larger than the integer type. 11647 // If they are the same, use integers. 11648 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11649 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11650 11651 // We add +1 here because the LastXXX variables refer to location while 11652 // the NumElem refers to array/index size. 11653 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11654 NumElem = std::min(LastLegalType, NumElem); 11655 11656 if (NumElem < 2) 11657 return false; 11658 11659 // Collect the chains from all merged stores. 11660 SmallVector<SDValue, 8> MergeStoreChains; 11661 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11662 11663 // The latest Node in the DAG. 11664 unsigned LatestNodeUsed = 0; 11665 for (unsigned i=1; i<NumElem; ++i) { 11666 // Find a chain for the new wide-store operand. Notice that some 11667 // of the store nodes that we found may not be selected for inclusion 11668 // in the wide store. The chain we use needs to be the chain of the 11669 // latest store node which is *used* and replaced by the wide store. 11670 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11671 LatestNodeUsed = i; 11672 11673 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11674 } 11675 11676 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11677 11678 // Find if it is better to use vectors or integers to load and store 11679 // to memory. 11680 EVT JointMemOpVT; 11681 if (UseVectorTy) { 11682 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11683 } else { 11684 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11685 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11686 } 11687 11688 SDLoc LoadDL(LoadNodes[0].MemNode); 11689 SDLoc StoreDL(StoreNodes[0].MemNode); 11690 11691 // The merged loads are required to have the same incoming chain, so 11692 // using the first's chain is acceptable. 11693 SDValue NewLoad = DAG.getLoad( 11694 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11695 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11696 11697 SDValue NewStoreChain = 11698 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11699 11700 SDValue NewStore = DAG.getStore( 11701 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11702 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11703 11704 // Transfer chain users from old loads to the new load. 11705 for (unsigned i = 0; i < NumElem; ++i) { 11706 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11707 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11708 SDValue(NewLoad.getNode(), 1)); 11709 } 11710 11711 // Replace the last store with the new store. 11712 CombineTo(LatestOp, NewStore); 11713 // Erase all other stores. 11714 for (unsigned i = 0; i < NumElem ; ++i) { 11715 // Remove all Store nodes. 11716 if (StoreNodes[i].MemNode == LatestOp) 11717 continue; 11718 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11719 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11720 deleteAndRecombine(St); 11721 } 11722 11723 return true; 11724 } 11725 11726 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11727 SDLoc SL(ST); 11728 SDValue ReplStore; 11729 11730 // Replace the chain to avoid dependency. 11731 if (ST->isTruncatingStore()) { 11732 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11733 ST->getBasePtr(), ST->getMemoryVT(), 11734 ST->getMemOperand()); 11735 } else { 11736 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11737 ST->getMemOperand()); 11738 } 11739 11740 // Create token to keep both nodes around. 11741 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11742 MVT::Other, ST->getChain(), ReplStore); 11743 11744 // Make sure the new and old chains are cleaned up. 11745 AddToWorklist(Token.getNode()); 11746 11747 // Don't add users to work list. 11748 return CombineTo(ST, Token, false); 11749 } 11750 11751 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11752 SDValue Value = ST->getValue(); 11753 if (Value.getOpcode() == ISD::TargetConstantFP) 11754 return SDValue(); 11755 11756 SDLoc DL(ST); 11757 11758 SDValue Chain = ST->getChain(); 11759 SDValue Ptr = ST->getBasePtr(); 11760 11761 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11762 11763 // NOTE: If the original store is volatile, this transform must not increase 11764 // the number of stores. For example, on x86-32 an f64 can be stored in one 11765 // processor operation but an i64 (which is not legal) requires two. So the 11766 // transform should not be done in this case. 11767 11768 SDValue Tmp; 11769 switch (CFP->getSimpleValueType(0).SimpleTy) { 11770 default: 11771 llvm_unreachable("Unknown FP type"); 11772 case MVT::f16: // We don't do this for these yet. 11773 case MVT::f80: 11774 case MVT::f128: 11775 case MVT::ppcf128: 11776 return SDValue(); 11777 case MVT::f32: 11778 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11779 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11780 ; 11781 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11782 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11783 MVT::i32); 11784 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11785 } 11786 11787 return SDValue(); 11788 case MVT::f64: 11789 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11790 !ST->isVolatile()) || 11791 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11792 ; 11793 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11794 getZExtValue(), SDLoc(CFP), MVT::i64); 11795 return DAG.getStore(Chain, DL, Tmp, 11796 Ptr, ST->getMemOperand()); 11797 } 11798 11799 if (!ST->isVolatile() && 11800 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11801 // Many FP stores are not made apparent until after legalize, e.g. for 11802 // argument passing. Since this is so common, custom legalize the 11803 // 64-bit integer store into two 32-bit stores. 11804 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11805 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11806 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11807 if (DAG.getDataLayout().isBigEndian()) 11808 std::swap(Lo, Hi); 11809 11810 unsigned Alignment = ST->getAlignment(); 11811 bool isVolatile = ST->isVolatile(); 11812 bool isNonTemporal = ST->isNonTemporal(); 11813 AAMDNodes AAInfo = ST->getAAInfo(); 11814 11815 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11816 Ptr, ST->getPointerInfo(), 11817 isVolatile, isNonTemporal, 11818 ST->getAlignment(), AAInfo); 11819 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11820 DAG.getConstant(4, DL, Ptr.getValueType())); 11821 Alignment = MinAlign(Alignment, 4U); 11822 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11823 Ptr, ST->getPointerInfo().getWithOffset(4), 11824 isVolatile, isNonTemporal, 11825 Alignment, AAInfo); 11826 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11827 St0, St1); 11828 } 11829 11830 return SDValue(); 11831 } 11832 } 11833 11834 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11835 StoreSDNode *ST = cast<StoreSDNode>(N); 11836 SDValue Chain = ST->getChain(); 11837 SDValue Value = ST->getValue(); 11838 SDValue Ptr = ST->getBasePtr(); 11839 11840 // If this is a store of a bit convert, store the input value if the 11841 // resultant store does not need a higher alignment than the original. 11842 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11843 ST->isUnindexed()) { 11844 unsigned OrigAlign = ST->getAlignment(); 11845 EVT SVT = Value.getOperand(0).getValueType(); 11846 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11847 SVT.getTypeForEVT(*DAG.getContext())); 11848 if (Align <= OrigAlign && 11849 ((!LegalOperations && !ST->isVolatile()) || 11850 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11851 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11852 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11853 ST->isNonTemporal(), OrigAlign, 11854 ST->getAAInfo()); 11855 } 11856 11857 // Turn 'store undef, Ptr' -> nothing. 11858 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11859 return Chain; 11860 11861 // Try to infer better alignment information than the store already has. 11862 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11863 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11864 if (Align > ST->getAlignment()) { 11865 SDValue NewStore = 11866 DAG.getTruncStore(Chain, SDLoc(N), Value, 11867 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11868 ST->isVolatile(), ST->isNonTemporal(), Align, 11869 ST->getAAInfo()); 11870 if (NewStore.getNode() != N) 11871 return CombineTo(ST, NewStore, true); 11872 } 11873 } 11874 } 11875 11876 // Try transforming a pair floating point load / store ops to integer 11877 // load / store ops. 11878 if (SDValue NewST = TransformFPLoadStorePair(N)) 11879 return NewST; 11880 11881 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11882 : DAG.getSubtarget().useAA(); 11883 #ifndef NDEBUG 11884 if (CombinerAAOnlyFunc.getNumOccurrences() && 11885 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11886 UseAA = false; 11887 #endif 11888 if (UseAA && ST->isUnindexed()) { 11889 // FIXME: We should do this even without AA enabled. AA will just allow 11890 // FindBetterChain to work in more situations. The problem with this is that 11891 // any combine that expects memory operations to be on consecutive chains 11892 // first needs to be updated to look for users of the same chain. 11893 11894 // Walk up chain skipping non-aliasing memory nodes, on this store and any 11895 // adjacent stores. 11896 if (findBetterNeighborChains(ST)) { 11897 // replaceStoreChain uses CombineTo, which handled all of the worklist 11898 // manipulation. Return the original node to not do anything else. 11899 return SDValue(ST, 0); 11900 } 11901 } 11902 11903 // Try transforming N to an indexed store. 11904 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11905 return SDValue(N, 0); 11906 11907 // FIXME: is there such a thing as a truncating indexed store? 11908 if (ST->isTruncatingStore() && ST->isUnindexed() && 11909 Value.getValueType().isInteger()) { 11910 // See if we can simplify the input to this truncstore with knowledge that 11911 // only the low bits are being used. For example: 11912 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11913 SDValue Shorter = 11914 GetDemandedBits(Value, 11915 APInt::getLowBitsSet( 11916 Value.getValueType().getScalarType().getSizeInBits(), 11917 ST->getMemoryVT().getScalarType().getSizeInBits())); 11918 AddToWorklist(Value.getNode()); 11919 if (Shorter.getNode()) 11920 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11921 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11922 11923 // Otherwise, see if we can simplify the operation with 11924 // SimplifyDemandedBits, which only works if the value has a single use. 11925 if (SimplifyDemandedBits(Value, 11926 APInt::getLowBitsSet( 11927 Value.getValueType().getScalarType().getSizeInBits(), 11928 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11929 return SDValue(N, 0); 11930 } 11931 11932 // If this is a load followed by a store to the same location, then the store 11933 // is dead/noop. 11934 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11935 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11936 ST->isUnindexed() && !ST->isVolatile() && 11937 // There can't be any side effects between the load and store, such as 11938 // a call or store. 11939 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11940 // The store is dead, remove it. 11941 return Chain; 11942 } 11943 } 11944 11945 // If this is a store followed by a store with the same value to the same 11946 // location, then the store is dead/noop. 11947 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11948 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11949 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11950 ST1->isUnindexed() && !ST1->isVolatile()) { 11951 // The store is dead, remove it. 11952 return Chain; 11953 } 11954 } 11955 11956 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11957 // truncating store. We can do this even if this is already a truncstore. 11958 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11959 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11960 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11961 ST->getMemoryVT())) { 11962 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11963 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11964 } 11965 11966 // Only perform this optimization before the types are legal, because we 11967 // don't want to perform this optimization on every DAGCombine invocation. 11968 if (!LegalTypes) { 11969 bool EverChanged = false; 11970 11971 do { 11972 // There can be multiple store sequences on the same chain. 11973 // Keep trying to merge store sequences until we are unable to do so 11974 // or until we merge the last store on the chain. 11975 bool Changed = MergeConsecutiveStores(ST); 11976 EverChanged |= Changed; 11977 if (!Changed) break; 11978 } while (ST->getOpcode() != ISD::DELETED_NODE); 11979 11980 if (EverChanged) 11981 return SDValue(N, 0); 11982 } 11983 11984 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11985 // 11986 // Make sure to do this only after attempting to merge stores in order to 11987 // avoid changing the types of some subset of stores due to visit order, 11988 // preventing their merging. 11989 if (isa<ConstantFPSDNode>(Value)) { 11990 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 11991 return NewSt; 11992 } 11993 11994 return ReduceLoadOpStoreWidth(N); 11995 } 11996 11997 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11998 SDValue InVec = N->getOperand(0); 11999 SDValue InVal = N->getOperand(1); 12000 SDValue EltNo = N->getOperand(2); 12001 SDLoc dl(N); 12002 12003 // If the inserted element is an UNDEF, just use the input vector. 12004 if (InVal.getOpcode() == ISD::UNDEF) 12005 return InVec; 12006 12007 EVT VT = InVec.getValueType(); 12008 12009 // If we can't generate a legal BUILD_VECTOR, exit 12010 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12011 return SDValue(); 12012 12013 // Check that we know which element is being inserted 12014 if (!isa<ConstantSDNode>(EltNo)) 12015 return SDValue(); 12016 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12017 12018 // Canonicalize insert_vector_elt dag nodes. 12019 // Example: 12020 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12021 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12022 // 12023 // Do this only if the child insert_vector node has one use; also 12024 // do this only if indices are both constants and Idx1 < Idx0. 12025 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12026 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12027 unsigned OtherElt = 12028 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12029 if (Elt < OtherElt) { 12030 // Swap nodes. 12031 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12032 InVec.getOperand(0), InVal, EltNo); 12033 AddToWorklist(NewOp.getNode()); 12034 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12035 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12036 } 12037 } 12038 12039 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12040 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12041 // vector elements. 12042 SmallVector<SDValue, 8> Ops; 12043 // Do not combine these two vectors if the output vector will not replace 12044 // the input vector. 12045 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12046 Ops.append(InVec.getNode()->op_begin(), 12047 InVec.getNode()->op_end()); 12048 } else if (InVec.getOpcode() == ISD::UNDEF) { 12049 unsigned NElts = VT.getVectorNumElements(); 12050 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12051 } else { 12052 return SDValue(); 12053 } 12054 12055 // Insert the element 12056 if (Elt < Ops.size()) { 12057 // All the operands of BUILD_VECTOR must have the same type; 12058 // we enforce that here. 12059 EVT OpVT = Ops[0].getValueType(); 12060 if (InVal.getValueType() != OpVT) 12061 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12062 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12063 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12064 Ops[Elt] = InVal; 12065 } 12066 12067 // Return the new vector 12068 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 12069 } 12070 12071 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12072 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12073 EVT ResultVT = EVE->getValueType(0); 12074 EVT VecEltVT = InVecVT.getVectorElementType(); 12075 unsigned Align = OriginalLoad->getAlignment(); 12076 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12077 VecEltVT.getTypeForEVT(*DAG.getContext())); 12078 12079 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12080 return SDValue(); 12081 12082 Align = NewAlign; 12083 12084 SDValue NewPtr = OriginalLoad->getBasePtr(); 12085 SDValue Offset; 12086 EVT PtrType = NewPtr.getValueType(); 12087 MachinePointerInfo MPI; 12088 SDLoc DL(EVE); 12089 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12090 int Elt = ConstEltNo->getZExtValue(); 12091 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12092 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12093 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12094 } else { 12095 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12096 Offset = DAG.getNode( 12097 ISD::MUL, DL, PtrType, Offset, 12098 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12099 MPI = OriginalLoad->getPointerInfo(); 12100 } 12101 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12102 12103 // The replacement we need to do here is a little tricky: we need to 12104 // replace an extractelement of a load with a load. 12105 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12106 // Note that this replacement assumes that the extractvalue is the only 12107 // use of the load; that's okay because we don't want to perform this 12108 // transformation in other cases anyway. 12109 SDValue Load; 12110 SDValue Chain; 12111 if (ResultVT.bitsGT(VecEltVT)) { 12112 // If the result type of vextract is wider than the load, then issue an 12113 // extending load instead. 12114 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12115 VecEltVT) 12116 ? ISD::ZEXTLOAD 12117 : ISD::EXTLOAD; 12118 Load = DAG.getExtLoad( 12119 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 12120 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12121 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12122 Chain = Load.getValue(1); 12123 } else { 12124 Load = DAG.getLoad( 12125 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 12126 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12127 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12128 Chain = Load.getValue(1); 12129 if (ResultVT.bitsLT(VecEltVT)) 12130 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12131 else 12132 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 12133 } 12134 WorklistRemover DeadNodes(*this); 12135 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12136 SDValue To[] = { Load, Chain }; 12137 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12138 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12139 // worklist explicitly as well. 12140 AddToWorklist(Load.getNode()); 12141 AddUsersToWorklist(Load.getNode()); // Add users too 12142 // Make sure to revisit this node to clean it up; it will usually be dead. 12143 AddToWorklist(EVE); 12144 ++OpsNarrowed; 12145 return SDValue(EVE, 0); 12146 } 12147 12148 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12149 // (vextract (scalar_to_vector val, 0) -> val 12150 SDValue InVec = N->getOperand(0); 12151 EVT VT = InVec.getValueType(); 12152 EVT NVT = N->getValueType(0); 12153 12154 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12155 // Check if the result type doesn't match the inserted element type. A 12156 // SCALAR_TO_VECTOR may truncate the inserted element and the 12157 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12158 SDValue InOp = InVec.getOperand(0); 12159 if (InOp.getValueType() != NVT) { 12160 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12161 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12162 } 12163 return InOp; 12164 } 12165 12166 SDValue EltNo = N->getOperand(1); 12167 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12168 12169 // extract_vector_elt (build_vector x, y), 1 -> y 12170 if (ConstEltNo && 12171 InVec.getOpcode() == ISD::BUILD_VECTOR && 12172 TLI.isTypeLegal(VT) && 12173 (InVec.hasOneUse() || 12174 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12175 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12176 EVT InEltVT = Elt.getValueType(); 12177 12178 // Sometimes build_vector's scalar input types do not match result type. 12179 if (NVT == InEltVT) 12180 return Elt; 12181 12182 // TODO: It may be useful to truncate if free if the build_vector implicitly 12183 // converts. 12184 } 12185 12186 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12187 // We only perform this optimization before the op legalization phase because 12188 // we may introduce new vector instructions which are not backed by TD 12189 // patterns. For example on AVX, extracting elements from a wide vector 12190 // without using extract_subvector. However, if we can find an underlying 12191 // scalar value, then we can always use that. 12192 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12193 int NumElem = VT.getVectorNumElements(); 12194 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12195 // Find the new index to extract from. 12196 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12197 12198 // Extracting an undef index is undef. 12199 if (OrigElt == -1) 12200 return DAG.getUNDEF(NVT); 12201 12202 // Select the right vector half to extract from. 12203 SDValue SVInVec; 12204 if (OrigElt < NumElem) { 12205 SVInVec = InVec->getOperand(0); 12206 } else { 12207 SVInVec = InVec->getOperand(1); 12208 OrigElt -= NumElem; 12209 } 12210 12211 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12212 SDValue InOp = SVInVec.getOperand(OrigElt); 12213 if (InOp.getValueType() != NVT) { 12214 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12215 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12216 } 12217 12218 return InOp; 12219 } 12220 12221 // FIXME: We should handle recursing on other vector shuffles and 12222 // scalar_to_vector here as well. 12223 12224 if (!LegalOperations) { 12225 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12226 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12227 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12228 } 12229 } 12230 12231 bool BCNumEltsChanged = false; 12232 EVT ExtVT = VT.getVectorElementType(); 12233 EVT LVT = ExtVT; 12234 12235 // If the result of load has to be truncated, then it's not necessarily 12236 // profitable. 12237 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12238 return SDValue(); 12239 12240 if (InVec.getOpcode() == ISD::BITCAST) { 12241 // Don't duplicate a load with other uses. 12242 if (!InVec.hasOneUse()) 12243 return SDValue(); 12244 12245 EVT BCVT = InVec.getOperand(0).getValueType(); 12246 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12247 return SDValue(); 12248 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12249 BCNumEltsChanged = true; 12250 InVec = InVec.getOperand(0); 12251 ExtVT = BCVT.getVectorElementType(); 12252 } 12253 12254 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12255 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12256 ISD::isNormalLoad(InVec.getNode()) && 12257 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12258 SDValue Index = N->getOperand(1); 12259 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 12260 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12261 OrigLoad); 12262 } 12263 12264 // Perform only after legalization to ensure build_vector / vector_shuffle 12265 // optimizations have already been done. 12266 if (!LegalOperations) return SDValue(); 12267 12268 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12269 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12270 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12271 12272 if (ConstEltNo) { 12273 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12274 12275 LoadSDNode *LN0 = nullptr; 12276 const ShuffleVectorSDNode *SVN = nullptr; 12277 if (ISD::isNormalLoad(InVec.getNode())) { 12278 LN0 = cast<LoadSDNode>(InVec); 12279 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12280 InVec.getOperand(0).getValueType() == ExtVT && 12281 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12282 // Don't duplicate a load with other uses. 12283 if (!InVec.hasOneUse()) 12284 return SDValue(); 12285 12286 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12287 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12288 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12289 // => 12290 // (load $addr+1*size) 12291 12292 // Don't duplicate a load with other uses. 12293 if (!InVec.hasOneUse()) 12294 return SDValue(); 12295 12296 // If the bit convert changed the number of elements, it is unsafe 12297 // to examine the mask. 12298 if (BCNumEltsChanged) 12299 return SDValue(); 12300 12301 // Select the input vector, guarding against out of range extract vector. 12302 unsigned NumElems = VT.getVectorNumElements(); 12303 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12304 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12305 12306 if (InVec.getOpcode() == ISD::BITCAST) { 12307 // Don't duplicate a load with other uses. 12308 if (!InVec.hasOneUse()) 12309 return SDValue(); 12310 12311 InVec = InVec.getOperand(0); 12312 } 12313 if (ISD::isNormalLoad(InVec.getNode())) { 12314 LN0 = cast<LoadSDNode>(InVec); 12315 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12316 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12317 } 12318 } 12319 12320 // Make sure we found a non-volatile load and the extractelement is 12321 // the only use. 12322 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12323 return SDValue(); 12324 12325 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12326 if (Elt == -1) 12327 return DAG.getUNDEF(LVT); 12328 12329 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12330 } 12331 12332 return SDValue(); 12333 } 12334 12335 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12336 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12337 // We perform this optimization post type-legalization because 12338 // the type-legalizer often scalarizes integer-promoted vectors. 12339 // Performing this optimization before may create bit-casts which 12340 // will be type-legalized to complex code sequences. 12341 // We perform this optimization only before the operation legalizer because we 12342 // may introduce illegal operations. 12343 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12344 return SDValue(); 12345 12346 unsigned NumInScalars = N->getNumOperands(); 12347 SDLoc dl(N); 12348 EVT VT = N->getValueType(0); 12349 12350 // Check to see if this is a BUILD_VECTOR of a bunch of values 12351 // which come from any_extend or zero_extend nodes. If so, we can create 12352 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12353 // optimizations. We do not handle sign-extend because we can't fill the sign 12354 // using shuffles. 12355 EVT SourceType = MVT::Other; 12356 bool AllAnyExt = true; 12357 12358 for (unsigned i = 0; i != NumInScalars; ++i) { 12359 SDValue In = N->getOperand(i); 12360 // Ignore undef inputs. 12361 if (In.getOpcode() == ISD::UNDEF) continue; 12362 12363 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12364 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12365 12366 // Abort if the element is not an extension. 12367 if (!ZeroExt && !AnyExt) { 12368 SourceType = MVT::Other; 12369 break; 12370 } 12371 12372 // The input is a ZeroExt or AnyExt. Check the original type. 12373 EVT InTy = In.getOperand(0).getValueType(); 12374 12375 // Check that all of the widened source types are the same. 12376 if (SourceType == MVT::Other) 12377 // First time. 12378 SourceType = InTy; 12379 else if (InTy != SourceType) { 12380 // Multiple income types. Abort. 12381 SourceType = MVT::Other; 12382 break; 12383 } 12384 12385 // Check if all of the extends are ANY_EXTENDs. 12386 AllAnyExt &= AnyExt; 12387 } 12388 12389 // In order to have valid types, all of the inputs must be extended from the 12390 // same source type and all of the inputs must be any or zero extend. 12391 // Scalar sizes must be a power of two. 12392 EVT OutScalarTy = VT.getScalarType(); 12393 bool ValidTypes = SourceType != MVT::Other && 12394 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12395 isPowerOf2_32(SourceType.getSizeInBits()); 12396 12397 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12398 // turn into a single shuffle instruction. 12399 if (!ValidTypes) 12400 return SDValue(); 12401 12402 bool isLE = DAG.getDataLayout().isLittleEndian(); 12403 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12404 assert(ElemRatio > 1 && "Invalid element size ratio"); 12405 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12406 DAG.getConstant(0, SDLoc(N), SourceType); 12407 12408 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12409 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12410 12411 // Populate the new build_vector 12412 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12413 SDValue Cast = N->getOperand(i); 12414 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12415 Cast.getOpcode() == ISD::ZERO_EXTEND || 12416 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 12417 SDValue In; 12418 if (Cast.getOpcode() == ISD::UNDEF) 12419 In = DAG.getUNDEF(SourceType); 12420 else 12421 In = Cast->getOperand(0); 12422 unsigned Index = isLE ? (i * ElemRatio) : 12423 (i * ElemRatio + (ElemRatio - 1)); 12424 12425 assert(Index < Ops.size() && "Invalid index"); 12426 Ops[Index] = In; 12427 } 12428 12429 // The type of the new BUILD_VECTOR node. 12430 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12431 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12432 "Invalid vector size"); 12433 // Check if the new vector type is legal. 12434 if (!isTypeLegal(VecVT)) return SDValue(); 12435 12436 // Make the new BUILD_VECTOR. 12437 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 12438 12439 // The new BUILD_VECTOR node has the potential to be further optimized. 12440 AddToWorklist(BV.getNode()); 12441 // Bitcast to the desired type. 12442 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12443 } 12444 12445 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12446 EVT VT = N->getValueType(0); 12447 12448 unsigned NumInScalars = N->getNumOperands(); 12449 SDLoc dl(N); 12450 12451 EVT SrcVT = MVT::Other; 12452 unsigned Opcode = ISD::DELETED_NODE; 12453 unsigned NumDefs = 0; 12454 12455 for (unsigned i = 0; i != NumInScalars; ++i) { 12456 SDValue In = N->getOperand(i); 12457 unsigned Opc = In.getOpcode(); 12458 12459 if (Opc == ISD::UNDEF) 12460 continue; 12461 12462 // If all scalar values are floats and converted from integers. 12463 if (Opcode == ISD::DELETED_NODE && 12464 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12465 Opcode = Opc; 12466 } 12467 12468 if (Opc != Opcode) 12469 return SDValue(); 12470 12471 EVT InVT = In.getOperand(0).getValueType(); 12472 12473 // If all scalar values are typed differently, bail out. It's chosen to 12474 // simplify BUILD_VECTOR of integer types. 12475 if (SrcVT == MVT::Other) 12476 SrcVT = InVT; 12477 if (SrcVT != InVT) 12478 return SDValue(); 12479 NumDefs++; 12480 } 12481 12482 // If the vector has just one element defined, it's not worth to fold it into 12483 // a vectorized one. 12484 if (NumDefs < 2) 12485 return SDValue(); 12486 12487 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12488 && "Should only handle conversion from integer to float."); 12489 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12490 12491 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12492 12493 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12494 return SDValue(); 12495 12496 // Just because the floating-point vector type is legal does not necessarily 12497 // mean that the corresponding integer vector type is. 12498 if (!isTypeLegal(NVT)) 12499 return SDValue(); 12500 12501 SmallVector<SDValue, 8> Opnds; 12502 for (unsigned i = 0; i != NumInScalars; ++i) { 12503 SDValue In = N->getOperand(i); 12504 12505 if (In.getOpcode() == ISD::UNDEF) 12506 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12507 else 12508 Opnds.push_back(In.getOperand(0)); 12509 } 12510 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 12511 AddToWorklist(BV.getNode()); 12512 12513 return DAG.getNode(Opcode, dl, VT, BV); 12514 } 12515 12516 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12517 unsigned NumInScalars = N->getNumOperands(); 12518 SDLoc dl(N); 12519 EVT VT = N->getValueType(0); 12520 12521 // A vector built entirely of undefs is undef. 12522 if (ISD::allOperandsUndef(N)) 12523 return DAG.getUNDEF(VT); 12524 12525 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12526 return V; 12527 12528 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12529 return V; 12530 12531 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12532 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12533 // at most two distinct vectors, turn this into a shuffle node. 12534 12535 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12536 if (!isTypeLegal(VT)) 12537 return SDValue(); 12538 12539 // May only combine to shuffle after legalize if shuffle is legal. 12540 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12541 return SDValue(); 12542 12543 SDValue VecIn1, VecIn2; 12544 bool UsesZeroVector = false; 12545 for (unsigned i = 0; i != NumInScalars; ++i) { 12546 SDValue Op = N->getOperand(i); 12547 // Ignore undef inputs. 12548 if (Op.getOpcode() == ISD::UNDEF) continue; 12549 12550 // See if we can combine this build_vector into a blend with a zero vector. 12551 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12552 UsesZeroVector = true; 12553 continue; 12554 } 12555 12556 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12557 // constant index, bail out. 12558 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12559 !isa<ConstantSDNode>(Op.getOperand(1))) { 12560 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12561 break; 12562 } 12563 12564 // We allow up to two distinct input vectors. 12565 SDValue ExtractedFromVec = Op.getOperand(0); 12566 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12567 continue; 12568 12569 if (!VecIn1.getNode()) { 12570 VecIn1 = ExtractedFromVec; 12571 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12572 VecIn2 = ExtractedFromVec; 12573 } else { 12574 // Too many inputs. 12575 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12576 break; 12577 } 12578 } 12579 12580 // If everything is good, we can make a shuffle operation. 12581 if (VecIn1.getNode()) { 12582 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12583 SmallVector<int, 8> Mask; 12584 for (unsigned i = 0; i != NumInScalars; ++i) { 12585 unsigned Opcode = N->getOperand(i).getOpcode(); 12586 if (Opcode == ISD::UNDEF) { 12587 Mask.push_back(-1); 12588 continue; 12589 } 12590 12591 // Operands can also be zero. 12592 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12593 assert(UsesZeroVector && 12594 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12595 "Unexpected node found!"); 12596 Mask.push_back(NumInScalars+i); 12597 continue; 12598 } 12599 12600 // If extracting from the first vector, just use the index directly. 12601 SDValue Extract = N->getOperand(i); 12602 SDValue ExtVal = Extract.getOperand(1); 12603 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12604 if (Extract.getOperand(0) == VecIn1) { 12605 Mask.push_back(ExtIndex); 12606 continue; 12607 } 12608 12609 // Otherwise, use InIdx + InputVecSize 12610 Mask.push_back(InNumElements + ExtIndex); 12611 } 12612 12613 // Avoid introducing illegal shuffles with zero. 12614 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12615 return SDValue(); 12616 12617 // We can't generate a shuffle node with mismatched input and output types. 12618 // Attempt to transform a single input vector to the correct type. 12619 if ((VT != VecIn1.getValueType())) { 12620 // If the input vector type has a different base type to the output 12621 // vector type, bail out. 12622 EVT VTElemType = VT.getVectorElementType(); 12623 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12624 (VecIn2.getNode() && 12625 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12626 return SDValue(); 12627 12628 // If the input vector is too small, widen it. 12629 // We only support widening of vectors which are half the size of the 12630 // output registers. For example XMM->YMM widening on X86 with AVX. 12631 EVT VecInT = VecIn1.getValueType(); 12632 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12633 // If we only have one small input, widen it by adding undef values. 12634 if (!VecIn2.getNode()) 12635 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12636 DAG.getUNDEF(VecIn1.getValueType())); 12637 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12638 // If we have two small inputs of the same type, try to concat them. 12639 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12640 VecIn2 = SDValue(nullptr, 0); 12641 } else 12642 return SDValue(); 12643 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12644 // If the input vector is too large, try to split it. 12645 // We don't support having two input vectors that are too large. 12646 // If the zero vector was used, we can not split the vector, 12647 // since we'd need 3 inputs. 12648 if (UsesZeroVector || VecIn2.getNode()) 12649 return SDValue(); 12650 12651 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12652 return SDValue(); 12653 12654 // Try to replace VecIn1 with two extract_subvectors 12655 // No need to update the masks, they should still be correct. 12656 VecIn2 = DAG.getNode( 12657 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12658 DAG.getConstant(VT.getVectorNumElements(), dl, 12659 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12660 VecIn1 = DAG.getNode( 12661 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12662 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12663 } else 12664 return SDValue(); 12665 } 12666 12667 if (UsesZeroVector) 12668 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12669 DAG.getConstantFP(0.0, dl, VT); 12670 else 12671 // If VecIn2 is unused then change it to undef. 12672 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12673 12674 // Check that we were able to transform all incoming values to the same 12675 // type. 12676 if (VecIn2.getValueType() != VecIn1.getValueType() || 12677 VecIn1.getValueType() != VT) 12678 return SDValue(); 12679 12680 // Return the new VECTOR_SHUFFLE node. 12681 SDValue Ops[2]; 12682 Ops[0] = VecIn1; 12683 Ops[1] = VecIn2; 12684 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12685 } 12686 12687 return SDValue(); 12688 } 12689 12690 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12692 EVT OpVT = N->getOperand(0).getValueType(); 12693 12694 // If the operands are legal vectors, leave them alone. 12695 if (TLI.isTypeLegal(OpVT)) 12696 return SDValue(); 12697 12698 SDLoc DL(N); 12699 EVT VT = N->getValueType(0); 12700 SmallVector<SDValue, 8> Ops; 12701 12702 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12703 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12704 12705 // Keep track of what we encounter. 12706 bool AnyInteger = false; 12707 bool AnyFP = false; 12708 for (const SDValue &Op : N->ops()) { 12709 if (ISD::BITCAST == Op.getOpcode() && 12710 !Op.getOperand(0).getValueType().isVector()) 12711 Ops.push_back(Op.getOperand(0)); 12712 else if (ISD::UNDEF == Op.getOpcode()) 12713 Ops.push_back(ScalarUndef); 12714 else 12715 return SDValue(); 12716 12717 // Note whether we encounter an integer or floating point scalar. 12718 // If it's neither, bail out, it could be something weird like x86mmx. 12719 EVT LastOpVT = Ops.back().getValueType(); 12720 if (LastOpVT.isFloatingPoint()) 12721 AnyFP = true; 12722 else if (LastOpVT.isInteger()) 12723 AnyInteger = true; 12724 else 12725 return SDValue(); 12726 } 12727 12728 // If any of the operands is a floating point scalar bitcast to a vector, 12729 // use floating point types throughout, and bitcast everything. 12730 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12731 if (AnyFP) { 12732 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12733 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12734 if (AnyInteger) { 12735 for (SDValue &Op : Ops) { 12736 if (Op.getValueType() == SVT) 12737 continue; 12738 if (Op.getOpcode() == ISD::UNDEF) 12739 Op = ScalarUndef; 12740 else 12741 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12742 } 12743 } 12744 } 12745 12746 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12747 VT.getSizeInBits() / SVT.getSizeInBits()); 12748 return DAG.getNode(ISD::BITCAST, DL, VT, 12749 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12750 } 12751 12752 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12753 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12754 // most two distinct vectors the same size as the result, attempt to turn this 12755 // into a legal shuffle. 12756 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12757 EVT VT = N->getValueType(0); 12758 EVT OpVT = N->getOperand(0).getValueType(); 12759 int NumElts = VT.getVectorNumElements(); 12760 int NumOpElts = OpVT.getVectorNumElements(); 12761 12762 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12763 SmallVector<int, 8> Mask; 12764 12765 for (SDValue Op : N->ops()) { 12766 // Peek through any bitcast. 12767 while (Op.getOpcode() == ISD::BITCAST) 12768 Op = Op.getOperand(0); 12769 12770 // UNDEF nodes convert to UNDEF shuffle mask values. 12771 if (Op.getOpcode() == ISD::UNDEF) { 12772 Mask.append((unsigned)NumOpElts, -1); 12773 continue; 12774 } 12775 12776 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12777 return SDValue(); 12778 12779 // What vector are we extracting the subvector from and at what index? 12780 SDValue ExtVec = Op.getOperand(0); 12781 12782 // We want the EVT of the original extraction to correctly scale the 12783 // extraction index. 12784 EVT ExtVT = ExtVec.getValueType(); 12785 12786 // Peek through any bitcast. 12787 while (ExtVec.getOpcode() == ISD::BITCAST) 12788 ExtVec = ExtVec.getOperand(0); 12789 12790 // UNDEF nodes convert to UNDEF shuffle mask values. 12791 if (ExtVec.getOpcode() == ISD::UNDEF) { 12792 Mask.append((unsigned)NumOpElts, -1); 12793 continue; 12794 } 12795 12796 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12797 return SDValue(); 12798 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12799 12800 // Ensure that we are extracting a subvector from a vector the same 12801 // size as the result. 12802 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12803 return SDValue(); 12804 12805 // Scale the subvector index to account for any bitcast. 12806 int NumExtElts = ExtVT.getVectorNumElements(); 12807 if (0 == (NumExtElts % NumElts)) 12808 ExtIdx /= (NumExtElts / NumElts); 12809 else if (0 == (NumElts % NumExtElts)) 12810 ExtIdx *= (NumElts / NumExtElts); 12811 else 12812 return SDValue(); 12813 12814 // At most we can reference 2 inputs in the final shuffle. 12815 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) { 12816 SV0 = ExtVec; 12817 for (int i = 0; i != NumOpElts; ++i) 12818 Mask.push_back(i + ExtIdx); 12819 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) { 12820 SV1 = ExtVec; 12821 for (int i = 0; i != NumOpElts; ++i) 12822 Mask.push_back(i + ExtIdx + NumElts); 12823 } else { 12824 return SDValue(); 12825 } 12826 } 12827 12828 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12829 return SDValue(); 12830 12831 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12832 DAG.getBitcast(VT, SV1), Mask); 12833 } 12834 12835 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12836 // If we only have one input vector, we don't need to do any concatenation. 12837 if (N->getNumOperands() == 1) 12838 return N->getOperand(0); 12839 12840 // Check if all of the operands are undefs. 12841 EVT VT = N->getValueType(0); 12842 if (ISD::allOperandsUndef(N)) 12843 return DAG.getUNDEF(VT); 12844 12845 // Optimize concat_vectors where all but the first of the vectors are undef. 12846 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12847 return Op.getOpcode() == ISD::UNDEF; 12848 })) { 12849 SDValue In = N->getOperand(0); 12850 assert(In.getValueType().isVector() && "Must concat vectors"); 12851 12852 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12853 if (In->getOpcode() == ISD::BITCAST && 12854 !In->getOperand(0)->getValueType(0).isVector()) { 12855 SDValue Scalar = In->getOperand(0); 12856 12857 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12858 // look through the trunc so we can still do the transform: 12859 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12860 if (Scalar->getOpcode() == ISD::TRUNCATE && 12861 !TLI.isTypeLegal(Scalar.getValueType()) && 12862 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12863 Scalar = Scalar->getOperand(0); 12864 12865 EVT SclTy = Scalar->getValueType(0); 12866 12867 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12868 return SDValue(); 12869 12870 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12871 VT.getSizeInBits() / SclTy.getSizeInBits()); 12872 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12873 return SDValue(); 12874 12875 SDLoc dl = SDLoc(N); 12876 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12877 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12878 } 12879 } 12880 12881 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12882 // We have already tested above for an UNDEF only concatenation. 12883 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12884 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12885 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12886 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12887 }; 12888 bool AllBuildVectorsOrUndefs = 12889 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12890 if (AllBuildVectorsOrUndefs) { 12891 SmallVector<SDValue, 8> Opnds; 12892 EVT SVT = VT.getScalarType(); 12893 12894 EVT MinVT = SVT; 12895 if (!SVT.isFloatingPoint()) { 12896 // If BUILD_VECTOR are from built from integer, they may have different 12897 // operand types. Get the smallest type and truncate all operands to it. 12898 bool FoundMinVT = false; 12899 for (const SDValue &Op : N->ops()) 12900 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12901 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12902 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12903 FoundMinVT = true; 12904 } 12905 assert(FoundMinVT && "Concat vector type mismatch"); 12906 } 12907 12908 for (const SDValue &Op : N->ops()) { 12909 EVT OpVT = Op.getValueType(); 12910 unsigned NumElts = OpVT.getVectorNumElements(); 12911 12912 if (ISD::UNDEF == Op.getOpcode()) 12913 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12914 12915 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12916 if (SVT.isFloatingPoint()) { 12917 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12918 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12919 } else { 12920 for (unsigned i = 0; i != NumElts; ++i) 12921 Opnds.push_back( 12922 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12923 } 12924 } 12925 } 12926 12927 assert(VT.getVectorNumElements() == Opnds.size() && 12928 "Concat vector type mismatch"); 12929 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12930 } 12931 12932 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12933 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12934 return V; 12935 12936 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 12937 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 12938 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 12939 return V; 12940 12941 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12942 // nodes often generate nop CONCAT_VECTOR nodes. 12943 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12944 // place the incoming vectors at the exact same location. 12945 SDValue SingleSource = SDValue(); 12946 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12947 12948 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12949 SDValue Op = N->getOperand(i); 12950 12951 if (Op.getOpcode() == ISD::UNDEF) 12952 continue; 12953 12954 // Check if this is the identity extract: 12955 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12956 return SDValue(); 12957 12958 // Find the single incoming vector for the extract_subvector. 12959 if (SingleSource.getNode()) { 12960 if (Op.getOperand(0) != SingleSource) 12961 return SDValue(); 12962 } else { 12963 SingleSource = Op.getOperand(0); 12964 12965 // Check the source type is the same as the type of the result. 12966 // If not, this concat may extend the vector, so we can not 12967 // optimize it away. 12968 if (SingleSource.getValueType() != N->getValueType(0)) 12969 return SDValue(); 12970 } 12971 12972 unsigned IdentityIndex = i * PartNumElem; 12973 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12974 // The extract index must be constant. 12975 if (!CS) 12976 return SDValue(); 12977 12978 // Check that we are reading from the identity index. 12979 if (CS->getZExtValue() != IdentityIndex) 12980 return SDValue(); 12981 } 12982 12983 if (SingleSource.getNode()) 12984 return SingleSource; 12985 12986 return SDValue(); 12987 } 12988 12989 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12990 EVT NVT = N->getValueType(0); 12991 SDValue V = N->getOperand(0); 12992 12993 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12994 // Combine: 12995 // (extract_subvec (concat V1, V2, ...), i) 12996 // Into: 12997 // Vi if possible 12998 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12999 // type. 13000 if (V->getOperand(0).getValueType() != NVT) 13001 return SDValue(); 13002 unsigned Idx = N->getConstantOperandVal(1); 13003 unsigned NumElems = NVT.getVectorNumElements(); 13004 assert((Idx % NumElems) == 0 && 13005 "IDX in concat is not a multiple of the result vector length."); 13006 return V->getOperand(Idx / NumElems); 13007 } 13008 13009 // Skip bitcasting 13010 if (V->getOpcode() == ISD::BITCAST) 13011 V = V.getOperand(0); 13012 13013 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13014 SDLoc dl(N); 13015 // Handle only simple case where vector being inserted and vector 13016 // being extracted are of same type, and are half size of larger vectors. 13017 EVT BigVT = V->getOperand(0).getValueType(); 13018 EVT SmallVT = V->getOperand(1).getValueType(); 13019 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13020 return SDValue(); 13021 13022 // Only handle cases where both indexes are constants with the same type. 13023 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13024 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13025 13026 if (InsIdx && ExtIdx && 13027 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13028 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13029 // Combine: 13030 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13031 // Into: 13032 // indices are equal or bit offsets are equal => V1 13033 // otherwise => (extract_subvec V1, ExtIdx) 13034 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13035 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13036 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 13037 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 13038 DAG.getNode(ISD::BITCAST, dl, 13039 N->getOperand(0).getValueType(), 13040 V->getOperand(0)), N->getOperand(1)); 13041 } 13042 } 13043 13044 return SDValue(); 13045 } 13046 13047 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13048 SDValue V, SelectionDAG &DAG) { 13049 SDLoc DL(V); 13050 EVT VT = V.getValueType(); 13051 13052 switch (V.getOpcode()) { 13053 default: 13054 return V; 13055 13056 case ISD::CONCAT_VECTORS: { 13057 EVT OpVT = V->getOperand(0).getValueType(); 13058 int OpSize = OpVT.getVectorNumElements(); 13059 SmallBitVector OpUsedElements(OpSize, false); 13060 bool FoundSimplification = false; 13061 SmallVector<SDValue, 4> NewOps; 13062 NewOps.reserve(V->getNumOperands()); 13063 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13064 SDValue Op = V->getOperand(i); 13065 bool OpUsed = false; 13066 for (int j = 0; j < OpSize; ++j) 13067 if (UsedElements[i * OpSize + j]) { 13068 OpUsedElements[j] = true; 13069 OpUsed = true; 13070 } 13071 NewOps.push_back( 13072 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13073 : DAG.getUNDEF(OpVT)); 13074 FoundSimplification |= Op == NewOps.back(); 13075 OpUsedElements.reset(); 13076 } 13077 if (FoundSimplification) 13078 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13079 return V; 13080 } 13081 13082 case ISD::INSERT_SUBVECTOR: { 13083 SDValue BaseV = V->getOperand(0); 13084 SDValue SubV = V->getOperand(1); 13085 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13086 if (!IdxN) 13087 return V; 13088 13089 int SubSize = SubV.getValueType().getVectorNumElements(); 13090 int Idx = IdxN->getZExtValue(); 13091 bool SubVectorUsed = false; 13092 SmallBitVector SubUsedElements(SubSize, false); 13093 for (int i = 0; i < SubSize; ++i) 13094 if (UsedElements[i + Idx]) { 13095 SubVectorUsed = true; 13096 SubUsedElements[i] = true; 13097 UsedElements[i + Idx] = false; 13098 } 13099 13100 // Now recurse on both the base and sub vectors. 13101 SDValue SimplifiedSubV = 13102 SubVectorUsed 13103 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13104 : DAG.getUNDEF(SubV.getValueType()); 13105 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13106 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13107 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13108 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13109 return V; 13110 } 13111 } 13112 } 13113 13114 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13115 SDValue N1, SelectionDAG &DAG) { 13116 EVT VT = SVN->getValueType(0); 13117 int NumElts = VT.getVectorNumElements(); 13118 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13119 for (int M : SVN->getMask()) 13120 if (M >= 0 && M < NumElts) 13121 N0UsedElements[M] = true; 13122 else if (M >= NumElts) 13123 N1UsedElements[M - NumElts] = true; 13124 13125 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13126 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13127 if (S0 == N0 && S1 == N1) 13128 return SDValue(); 13129 13130 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13131 } 13132 13133 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13134 // or turn a shuffle of a single concat into simpler shuffle then concat. 13135 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13136 EVT VT = N->getValueType(0); 13137 unsigned NumElts = VT.getVectorNumElements(); 13138 13139 SDValue N0 = N->getOperand(0); 13140 SDValue N1 = N->getOperand(1); 13141 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13142 13143 SmallVector<SDValue, 4> Ops; 13144 EVT ConcatVT = N0.getOperand(0).getValueType(); 13145 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13146 unsigned NumConcats = NumElts / NumElemsPerConcat; 13147 13148 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13149 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13150 // half vector elements. 13151 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 13152 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13153 SVN->getMask().end(), [](int i) { return i == -1; })) { 13154 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13155 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13156 N1 = DAG.getUNDEF(ConcatVT); 13157 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13158 } 13159 13160 // Look at every vector that's inserted. We're looking for exact 13161 // subvector-sized copies from a concatenated vector 13162 for (unsigned I = 0; I != NumConcats; ++I) { 13163 // Make sure we're dealing with a copy. 13164 unsigned Begin = I * NumElemsPerConcat; 13165 bool AllUndef = true, NoUndef = true; 13166 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13167 if (SVN->getMaskElt(J) >= 0) 13168 AllUndef = false; 13169 else 13170 NoUndef = false; 13171 } 13172 13173 if (NoUndef) { 13174 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13175 return SDValue(); 13176 13177 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13178 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13179 return SDValue(); 13180 13181 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13182 if (FirstElt < N0.getNumOperands()) 13183 Ops.push_back(N0.getOperand(FirstElt)); 13184 else 13185 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13186 13187 } else if (AllUndef) { 13188 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13189 } else { // Mixed with general masks and undefs, can't do optimization. 13190 return SDValue(); 13191 } 13192 } 13193 13194 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13195 } 13196 13197 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13198 EVT VT = N->getValueType(0); 13199 unsigned NumElts = VT.getVectorNumElements(); 13200 13201 SDValue N0 = N->getOperand(0); 13202 SDValue N1 = N->getOperand(1); 13203 13204 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13205 13206 // Canonicalize shuffle undef, undef -> undef 13207 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 13208 return DAG.getUNDEF(VT); 13209 13210 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13211 13212 // Canonicalize shuffle v, v -> v, undef 13213 if (N0 == N1) { 13214 SmallVector<int, 8> NewMask; 13215 for (unsigned i = 0; i != NumElts; ++i) { 13216 int Idx = SVN->getMaskElt(i); 13217 if (Idx >= (int)NumElts) Idx -= NumElts; 13218 NewMask.push_back(Idx); 13219 } 13220 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 13221 &NewMask[0]); 13222 } 13223 13224 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13225 if (N0.getOpcode() == ISD::UNDEF) { 13226 SmallVector<int, 8> NewMask; 13227 for (unsigned i = 0; i != NumElts; ++i) { 13228 int Idx = SVN->getMaskElt(i); 13229 if (Idx >= 0) { 13230 if (Idx >= (int)NumElts) 13231 Idx -= NumElts; 13232 else 13233 Idx = -1; // remove reference to lhs 13234 } 13235 NewMask.push_back(Idx); 13236 } 13237 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 13238 &NewMask[0]); 13239 } 13240 13241 // Remove references to rhs if it is undef 13242 if (N1.getOpcode() == ISD::UNDEF) { 13243 bool Changed = false; 13244 SmallVector<int, 8> NewMask; 13245 for (unsigned i = 0; i != NumElts; ++i) { 13246 int Idx = SVN->getMaskElt(i); 13247 if (Idx >= (int)NumElts) { 13248 Idx = -1; 13249 Changed = true; 13250 } 13251 NewMask.push_back(Idx); 13252 } 13253 if (Changed) 13254 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 13255 } 13256 13257 // If it is a splat, check if the argument vector is another splat or a 13258 // build_vector. 13259 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13260 SDNode *V = N0.getNode(); 13261 13262 // If this is a bit convert that changes the element type of the vector but 13263 // not the number of vector elements, look through it. Be careful not to 13264 // look though conversions that change things like v4f32 to v2f64. 13265 if (V->getOpcode() == ISD::BITCAST) { 13266 SDValue ConvInput = V->getOperand(0); 13267 if (ConvInput.getValueType().isVector() && 13268 ConvInput.getValueType().getVectorNumElements() == NumElts) 13269 V = ConvInput.getNode(); 13270 } 13271 13272 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13273 assert(V->getNumOperands() == NumElts && 13274 "BUILD_VECTOR has wrong number of operands"); 13275 SDValue Base; 13276 bool AllSame = true; 13277 for (unsigned i = 0; i != NumElts; ++i) { 13278 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 13279 Base = V->getOperand(i); 13280 break; 13281 } 13282 } 13283 // Splat of <u, u, u, u>, return <u, u, u, u> 13284 if (!Base.getNode()) 13285 return N0; 13286 for (unsigned i = 0; i != NumElts; ++i) { 13287 if (V->getOperand(i) != Base) { 13288 AllSame = false; 13289 break; 13290 } 13291 } 13292 // Splat of <x, x, x, x>, return <x, x, x, x> 13293 if (AllSame) 13294 return N0; 13295 13296 // Canonicalize any other splat as a build_vector. 13297 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13298 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13299 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 13300 V->getValueType(0), Ops); 13301 13302 // We may have jumped through bitcasts, so the type of the 13303 // BUILD_VECTOR may not match the type of the shuffle. 13304 if (V->getValueType(0) != VT) 13305 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13306 return NewBV; 13307 } 13308 } 13309 13310 // There are various patterns used to build up a vector from smaller vectors, 13311 // subvectors, or elements. Scan chains of these and replace unused insertions 13312 // or components with undef. 13313 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13314 return S; 13315 13316 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13317 Level < AfterLegalizeVectorOps && 13318 (N1.getOpcode() == ISD::UNDEF || 13319 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13320 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13321 SDValue V = partitionShuffleOfConcats(N, DAG); 13322 13323 if (V.getNode()) 13324 return V; 13325 } 13326 13327 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13328 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13329 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13330 SmallVector<SDValue, 8> Ops; 13331 for (int M : SVN->getMask()) { 13332 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13333 if (M >= 0) { 13334 int Idx = M % NumElts; 13335 SDValue &S = (M < (int)NumElts ? N0 : N1); 13336 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13337 Op = S.getOperand(Idx); 13338 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13339 if (Idx == 0) 13340 Op = S.getOperand(0); 13341 } else { 13342 // Operand can't be combined - bail out. 13343 break; 13344 } 13345 } 13346 Ops.push_back(Op); 13347 } 13348 if (Ops.size() == VT.getVectorNumElements()) { 13349 // BUILD_VECTOR requires all inputs to be of the same type, find the 13350 // maximum type and extend them all. 13351 EVT SVT = VT.getScalarType(); 13352 if (SVT.isInteger()) 13353 for (SDValue &Op : Ops) 13354 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13355 if (SVT != VT.getScalarType()) 13356 for (SDValue &Op : Ops) 13357 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13358 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13359 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13360 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 13361 } 13362 } 13363 13364 // If this shuffle only has a single input that is a bitcasted shuffle, 13365 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13366 // back to their original types. 13367 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13368 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 13369 TLI.isTypeLegal(VT)) { 13370 13371 // Peek through the bitcast only if there is one user. 13372 SDValue BC0 = N0; 13373 while (BC0.getOpcode() == ISD::BITCAST) { 13374 if (!BC0.hasOneUse()) 13375 break; 13376 BC0 = BC0.getOperand(0); 13377 } 13378 13379 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13380 if (Scale == 1) 13381 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13382 13383 SmallVector<int, 8> NewMask; 13384 for (int M : Mask) 13385 for (int s = 0; s != Scale; ++s) 13386 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13387 return NewMask; 13388 }; 13389 13390 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13391 EVT SVT = VT.getScalarType(); 13392 EVT InnerVT = BC0->getValueType(0); 13393 EVT InnerSVT = InnerVT.getScalarType(); 13394 13395 // Determine which shuffle works with the smaller scalar type. 13396 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13397 EVT ScaleSVT = ScaleVT.getScalarType(); 13398 13399 if (TLI.isTypeLegal(ScaleVT) && 13400 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13401 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13402 13403 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13404 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13405 13406 // Scale the shuffle masks to the smaller scalar type. 13407 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13408 SmallVector<int, 8> InnerMask = 13409 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13410 SmallVector<int, 8> OuterMask = 13411 ScaleShuffleMask(SVN->getMask(), OuterScale); 13412 13413 // Merge the shuffle masks. 13414 SmallVector<int, 8> NewMask; 13415 for (int M : OuterMask) 13416 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13417 13418 // Test for shuffle mask legality over both commutations. 13419 SDValue SV0 = BC0->getOperand(0); 13420 SDValue SV1 = BC0->getOperand(1); 13421 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13422 if (!LegalMask) { 13423 std::swap(SV0, SV1); 13424 ShuffleVectorSDNode::commuteMask(NewMask); 13425 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13426 } 13427 13428 if (LegalMask) { 13429 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13430 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13431 return DAG.getNode( 13432 ISD::BITCAST, SDLoc(N), VT, 13433 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13434 } 13435 } 13436 } 13437 } 13438 13439 // Canonicalize shuffles according to rules: 13440 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13441 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13442 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13443 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13444 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13445 TLI.isTypeLegal(VT)) { 13446 // The incoming shuffle must be of the same type as the result of the 13447 // current shuffle. 13448 assert(N1->getOperand(0).getValueType() == VT && 13449 "Shuffle types don't match"); 13450 13451 SDValue SV0 = N1->getOperand(0); 13452 SDValue SV1 = N1->getOperand(1); 13453 bool HasSameOp0 = N0 == SV0; 13454 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 13455 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13456 // Commute the operands of this shuffle so that next rule 13457 // will trigger. 13458 return DAG.getCommutedVectorShuffle(*SVN); 13459 } 13460 13461 // Try to fold according to rules: 13462 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13463 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13464 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13465 // Don't try to fold shuffles with illegal type. 13466 // Only fold if this shuffle is the only user of the other shuffle. 13467 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13468 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13469 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13470 13471 // The incoming shuffle must be of the same type as the result of the 13472 // current shuffle. 13473 assert(OtherSV->getOperand(0).getValueType() == VT && 13474 "Shuffle types don't match"); 13475 13476 SDValue SV0, SV1; 13477 SmallVector<int, 4> Mask; 13478 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13479 // operand, and SV1 as the second operand. 13480 for (unsigned i = 0; i != NumElts; ++i) { 13481 int Idx = SVN->getMaskElt(i); 13482 if (Idx < 0) { 13483 // Propagate Undef. 13484 Mask.push_back(Idx); 13485 continue; 13486 } 13487 13488 SDValue CurrentVec; 13489 if (Idx < (int)NumElts) { 13490 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13491 // shuffle mask to identify which vector is actually referenced. 13492 Idx = OtherSV->getMaskElt(Idx); 13493 if (Idx < 0) { 13494 // Propagate Undef. 13495 Mask.push_back(Idx); 13496 continue; 13497 } 13498 13499 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13500 : OtherSV->getOperand(1); 13501 } else { 13502 // This shuffle index references an element within N1. 13503 CurrentVec = N1; 13504 } 13505 13506 // Simple case where 'CurrentVec' is UNDEF. 13507 if (CurrentVec.getOpcode() == ISD::UNDEF) { 13508 Mask.push_back(-1); 13509 continue; 13510 } 13511 13512 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13513 // will be the first or second operand of the combined shuffle. 13514 Idx = Idx % NumElts; 13515 if (!SV0.getNode() || SV0 == CurrentVec) { 13516 // Ok. CurrentVec is the left hand side. 13517 // Update the mask accordingly. 13518 SV0 = CurrentVec; 13519 Mask.push_back(Idx); 13520 continue; 13521 } 13522 13523 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13524 if (SV1.getNode() && SV1 != CurrentVec) 13525 return SDValue(); 13526 13527 // Ok. CurrentVec is the right hand side. 13528 // Update the mask accordingly. 13529 SV1 = CurrentVec; 13530 Mask.push_back(Idx + NumElts); 13531 } 13532 13533 // Check if all indices in Mask are Undef. In case, propagate Undef. 13534 bool isUndefMask = true; 13535 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13536 isUndefMask &= Mask[i] < 0; 13537 13538 if (isUndefMask) 13539 return DAG.getUNDEF(VT); 13540 13541 if (!SV0.getNode()) 13542 SV0 = DAG.getUNDEF(VT); 13543 if (!SV1.getNode()) 13544 SV1 = DAG.getUNDEF(VT); 13545 13546 // Avoid introducing shuffles with illegal mask. 13547 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13548 ShuffleVectorSDNode::commuteMask(Mask); 13549 13550 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13551 return SDValue(); 13552 13553 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13554 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13555 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13556 std::swap(SV0, SV1); 13557 } 13558 13559 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13560 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13561 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13562 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13563 } 13564 13565 return SDValue(); 13566 } 13567 13568 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13569 SDValue InVal = N->getOperand(0); 13570 EVT VT = N->getValueType(0); 13571 13572 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13573 // with a VECTOR_SHUFFLE. 13574 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13575 SDValue InVec = InVal->getOperand(0); 13576 SDValue EltNo = InVal->getOperand(1); 13577 13578 // FIXME: We could support implicit truncation if the shuffle can be 13579 // scaled to a smaller vector scalar type. 13580 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13581 if (C0 && VT == InVec.getValueType() && 13582 VT.getScalarType() == InVal.getValueType()) { 13583 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13584 int Elt = C0->getZExtValue(); 13585 NewMask[0] = Elt; 13586 13587 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13588 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13589 NewMask); 13590 } 13591 } 13592 13593 return SDValue(); 13594 } 13595 13596 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13597 SDValue N0 = N->getOperand(0); 13598 SDValue N2 = N->getOperand(2); 13599 13600 // If the input vector is a concatenation, and the insert replaces 13601 // one of the halves, we can optimize into a single concat_vectors. 13602 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13603 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13604 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13605 EVT VT = N->getValueType(0); 13606 13607 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13608 // (concat_vectors Z, Y) 13609 if (InsIdx == 0) 13610 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13611 N->getOperand(1), N0.getOperand(1)); 13612 13613 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13614 // (concat_vectors X, Z) 13615 if (InsIdx == VT.getVectorNumElements()/2) 13616 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13617 N0.getOperand(0), N->getOperand(1)); 13618 } 13619 13620 return SDValue(); 13621 } 13622 13623 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13624 SDValue N0 = N->getOperand(0); 13625 13626 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13627 if (N0->getOpcode() == ISD::FP16_TO_FP) 13628 return N0->getOperand(0); 13629 13630 return SDValue(); 13631 } 13632 13633 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13634 SDValue N0 = N->getOperand(0); 13635 13636 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13637 if (N0->getOpcode() == ISD::AND) { 13638 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13639 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13640 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13641 N0.getOperand(0)); 13642 } 13643 } 13644 13645 return SDValue(); 13646 } 13647 13648 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13649 /// with the destination vector and a zero vector. 13650 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13651 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13652 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13653 EVT VT = N->getValueType(0); 13654 SDValue LHS = N->getOperand(0); 13655 SDValue RHS = N->getOperand(1); 13656 SDLoc dl(N); 13657 13658 // Make sure we're not running after operation legalization where it 13659 // may have custom lowered the vector shuffles. 13660 if (LegalOperations) 13661 return SDValue(); 13662 13663 if (N->getOpcode() != ISD::AND) 13664 return SDValue(); 13665 13666 if (RHS.getOpcode() == ISD::BITCAST) 13667 RHS = RHS.getOperand(0); 13668 13669 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13670 return SDValue(); 13671 13672 EVT RVT = RHS.getValueType(); 13673 unsigned NumElts = RHS.getNumOperands(); 13674 13675 // Attempt to create a valid clear mask, splitting the mask into 13676 // sub elements and checking to see if each is 13677 // all zeros or all ones - suitable for shuffle masking. 13678 auto BuildClearMask = [&](int Split) { 13679 int NumSubElts = NumElts * Split; 13680 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13681 13682 SmallVector<int, 8> Indices; 13683 for (int i = 0; i != NumSubElts; ++i) { 13684 int EltIdx = i / Split; 13685 int SubIdx = i % Split; 13686 SDValue Elt = RHS.getOperand(EltIdx); 13687 if (Elt.getOpcode() == ISD::UNDEF) { 13688 Indices.push_back(-1); 13689 continue; 13690 } 13691 13692 APInt Bits; 13693 if (isa<ConstantSDNode>(Elt)) 13694 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13695 else if (isa<ConstantFPSDNode>(Elt)) 13696 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13697 else 13698 return SDValue(); 13699 13700 // Extract the sub element from the constant bit mask. 13701 if (DAG.getDataLayout().isBigEndian()) { 13702 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13703 } else { 13704 Bits = Bits.lshr(SubIdx * NumSubBits); 13705 } 13706 13707 if (Split > 1) 13708 Bits = Bits.trunc(NumSubBits); 13709 13710 if (Bits.isAllOnesValue()) 13711 Indices.push_back(i); 13712 else if (Bits == 0) 13713 Indices.push_back(i + NumSubElts); 13714 else 13715 return SDValue(); 13716 } 13717 13718 // Let's see if the target supports this vector_shuffle. 13719 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13720 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13721 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13722 return SDValue(); 13723 13724 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13725 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13726 DAG.getBitcast(ClearVT, LHS), 13727 Zero, &Indices[0])); 13728 }; 13729 13730 // Determine maximum split level (byte level masking). 13731 int MaxSplit = 1; 13732 if (RVT.getScalarSizeInBits() % 8 == 0) 13733 MaxSplit = RVT.getScalarSizeInBits() / 8; 13734 13735 for (int Split = 1; Split <= MaxSplit; ++Split) 13736 if (RVT.getScalarSizeInBits() % Split == 0) 13737 if (SDValue S = BuildClearMask(Split)) 13738 return S; 13739 13740 return SDValue(); 13741 } 13742 13743 /// Visit a binary vector operation, like ADD. 13744 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13745 assert(N->getValueType(0).isVector() && 13746 "SimplifyVBinOp only works on vectors!"); 13747 13748 SDValue LHS = N->getOperand(0); 13749 SDValue RHS = N->getOperand(1); 13750 SDValue Ops[] = {LHS, RHS}; 13751 13752 // See if we can constant fold the vector operation. 13753 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13754 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13755 return Fold; 13756 13757 // Try to convert a constant mask AND into a shuffle clear mask. 13758 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13759 return Shuffle; 13760 13761 // Type legalization might introduce new shuffles in the DAG. 13762 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13763 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13764 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13765 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13766 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 13767 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 13768 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13769 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13770 13771 if (SVN0->getMask().equals(SVN1->getMask())) { 13772 EVT VT = N->getValueType(0); 13773 SDValue UndefVector = LHS.getOperand(1); 13774 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13775 LHS.getOperand(0), RHS.getOperand(0), 13776 N->getFlags()); 13777 AddUsersToWorklist(N); 13778 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13779 &SVN0->getMask()[0]); 13780 } 13781 } 13782 13783 return SDValue(); 13784 } 13785 13786 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13787 SDValue N1, SDValue N2){ 13788 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13789 13790 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13791 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13792 13793 // If we got a simplified select_cc node back from SimplifySelectCC, then 13794 // break it down into a new SETCC node, and a new SELECT node, and then return 13795 // the SELECT node, since we were called with a SELECT node. 13796 if (SCC.getNode()) { 13797 // Check to see if we got a select_cc back (to turn into setcc/select). 13798 // Otherwise, just return whatever node we got back, like fabs. 13799 if (SCC.getOpcode() == ISD::SELECT_CC) { 13800 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13801 N0.getValueType(), 13802 SCC.getOperand(0), SCC.getOperand(1), 13803 SCC.getOperand(4)); 13804 AddToWorklist(SETCC.getNode()); 13805 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13806 SCC.getOperand(2), SCC.getOperand(3)); 13807 } 13808 13809 return SCC; 13810 } 13811 return SDValue(); 13812 } 13813 13814 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13815 /// being selected between, see if we can simplify the select. Callers of this 13816 /// should assume that TheSelect is deleted if this returns true. As such, they 13817 /// should return the appropriate thing (e.g. the node) back to the top-level of 13818 /// the DAG combiner loop to avoid it being looked at. 13819 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13820 SDValue RHS) { 13821 13822 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13823 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13824 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13825 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13826 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13827 SDValue Sqrt = RHS; 13828 ISD::CondCode CC; 13829 SDValue CmpLHS; 13830 const ConstantFPSDNode *NegZero = nullptr; 13831 13832 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13833 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13834 CmpLHS = TheSelect->getOperand(0); 13835 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13836 } else { 13837 // SELECT or VSELECT 13838 SDValue Cmp = TheSelect->getOperand(0); 13839 if (Cmp.getOpcode() == ISD::SETCC) { 13840 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13841 CmpLHS = Cmp.getOperand(0); 13842 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13843 } 13844 } 13845 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13846 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13847 CC == ISD::SETULT || CC == ISD::SETLT)) { 13848 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13849 CombineTo(TheSelect, Sqrt); 13850 return true; 13851 } 13852 } 13853 } 13854 // Cannot simplify select with vector condition 13855 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13856 13857 // If this is a select from two identical things, try to pull the operation 13858 // through the select. 13859 if (LHS.getOpcode() != RHS.getOpcode() || 13860 !LHS.hasOneUse() || !RHS.hasOneUse()) 13861 return false; 13862 13863 // If this is a load and the token chain is identical, replace the select 13864 // of two loads with a load through a select of the address to load from. 13865 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13866 // constants have been dropped into the constant pool. 13867 if (LHS.getOpcode() == ISD::LOAD) { 13868 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13869 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13870 13871 // Token chains must be identical. 13872 if (LHS.getOperand(0) != RHS.getOperand(0) || 13873 // Do not let this transformation reduce the number of volatile loads. 13874 LLD->isVolatile() || RLD->isVolatile() || 13875 // FIXME: If either is a pre/post inc/dec load, 13876 // we'd need to split out the address adjustment. 13877 LLD->isIndexed() || RLD->isIndexed() || 13878 // If this is an EXTLOAD, the VT's must match. 13879 LLD->getMemoryVT() != RLD->getMemoryVT() || 13880 // If this is an EXTLOAD, the kind of extension must match. 13881 (LLD->getExtensionType() != RLD->getExtensionType() && 13882 // The only exception is if one of the extensions is anyext. 13883 LLD->getExtensionType() != ISD::EXTLOAD && 13884 RLD->getExtensionType() != ISD::EXTLOAD) || 13885 // FIXME: this discards src value information. This is 13886 // over-conservative. It would be beneficial to be able to remember 13887 // both potential memory locations. Since we are discarding 13888 // src value info, don't do the transformation if the memory 13889 // locations are not in the default address space. 13890 LLD->getPointerInfo().getAddrSpace() != 0 || 13891 RLD->getPointerInfo().getAddrSpace() != 0 || 13892 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13893 LLD->getBasePtr().getValueType())) 13894 return false; 13895 13896 // Check that the select condition doesn't reach either load. If so, 13897 // folding this will induce a cycle into the DAG. If not, this is safe to 13898 // xform, so create a select of the addresses. 13899 SDValue Addr; 13900 if (TheSelect->getOpcode() == ISD::SELECT) { 13901 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13902 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13903 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13904 return false; 13905 // The loads must not depend on one another. 13906 if (LLD->isPredecessorOf(RLD) || 13907 RLD->isPredecessorOf(LLD)) 13908 return false; 13909 Addr = DAG.getSelect(SDLoc(TheSelect), 13910 LLD->getBasePtr().getValueType(), 13911 TheSelect->getOperand(0), LLD->getBasePtr(), 13912 RLD->getBasePtr()); 13913 } else { // Otherwise SELECT_CC 13914 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13915 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13916 13917 if ((LLD->hasAnyUseOfValue(1) && 13918 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13919 (RLD->hasAnyUseOfValue(1) && 13920 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13921 return false; 13922 13923 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13924 LLD->getBasePtr().getValueType(), 13925 TheSelect->getOperand(0), 13926 TheSelect->getOperand(1), 13927 LLD->getBasePtr(), RLD->getBasePtr(), 13928 TheSelect->getOperand(4)); 13929 } 13930 13931 SDValue Load; 13932 // It is safe to replace the two loads if they have different alignments, 13933 // but the new load must be the minimum (most restrictive) alignment of the 13934 // inputs. 13935 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13936 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13937 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13938 Load = DAG.getLoad(TheSelect->getValueType(0), 13939 SDLoc(TheSelect), 13940 // FIXME: Discards pointer and AA info. 13941 LLD->getChain(), Addr, MachinePointerInfo(), 13942 LLD->isVolatile(), LLD->isNonTemporal(), 13943 isInvariant, Alignment); 13944 } else { 13945 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13946 RLD->getExtensionType() : LLD->getExtensionType(), 13947 SDLoc(TheSelect), 13948 TheSelect->getValueType(0), 13949 // FIXME: Discards pointer and AA info. 13950 LLD->getChain(), Addr, MachinePointerInfo(), 13951 LLD->getMemoryVT(), LLD->isVolatile(), 13952 LLD->isNonTemporal(), isInvariant, Alignment); 13953 } 13954 13955 // Users of the select now use the result of the load. 13956 CombineTo(TheSelect, Load); 13957 13958 // Users of the old loads now use the new load's chain. We know the 13959 // old-load value is dead now. 13960 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13961 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13962 return true; 13963 } 13964 13965 return false; 13966 } 13967 13968 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13969 /// where 'cond' is the comparison specified by CC. 13970 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13971 SDValue N2, SDValue N3, 13972 ISD::CondCode CC, bool NotExtCompare) { 13973 // (x ? y : y) -> y. 13974 if (N2 == N3) return N2; 13975 13976 EVT VT = N2.getValueType(); 13977 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13978 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13979 13980 // Determine if the condition we're dealing with is constant 13981 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13982 N0, N1, CC, DL, false); 13983 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13984 13985 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 13986 // fold select_cc true, x, y -> x 13987 // fold select_cc false, x, y -> y 13988 return !SCCC->isNullValue() ? N2 : N3; 13989 } 13990 13991 // Check to see if we can simplify the select into an fabs node 13992 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13993 // Allow either -0.0 or 0.0 13994 if (CFP->isZero()) { 13995 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13996 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13997 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13998 N2 == N3.getOperand(0)) 13999 return DAG.getNode(ISD::FABS, DL, VT, N0); 14000 14001 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14002 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14003 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14004 N2.getOperand(0) == N3) 14005 return DAG.getNode(ISD::FABS, DL, VT, N3); 14006 } 14007 } 14008 14009 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14010 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14011 // in it. This is a win when the constant is not otherwise available because 14012 // it replaces two constant pool loads with one. We only do this if the FP 14013 // type is known to be legal, because if it isn't, then we are before legalize 14014 // types an we want the other legalization to happen first (e.g. to avoid 14015 // messing with soft float) and if the ConstantFP is not legal, because if 14016 // it is legal, we may not need to store the FP constant in a constant pool. 14017 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14018 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14019 if (TLI.isTypeLegal(N2.getValueType()) && 14020 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14021 TargetLowering::Legal && 14022 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14023 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14024 // If both constants have multiple uses, then we won't need to do an 14025 // extra load, they are likely around in registers for other users. 14026 (TV->hasOneUse() || FV->hasOneUse())) { 14027 Constant *Elts[] = { 14028 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14029 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14030 }; 14031 Type *FPTy = Elts[0]->getType(); 14032 const DataLayout &TD = DAG.getDataLayout(); 14033 14034 // Create a ConstantArray of the two constants. 14035 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14036 SDValue CPIdx = 14037 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14038 TD.getPrefTypeAlignment(FPTy)); 14039 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14040 14041 // Get the offsets to the 0 and 1 element of the array so that we can 14042 // select between them. 14043 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14044 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14045 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14046 14047 SDValue Cond = DAG.getSetCC(DL, 14048 getSetCCResultType(N0.getValueType()), 14049 N0, N1, CC); 14050 AddToWorklist(Cond.getNode()); 14051 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14052 Cond, One, Zero); 14053 AddToWorklist(CstOffset.getNode()); 14054 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14055 CstOffset); 14056 AddToWorklist(CPIdx.getNode()); 14057 return DAG.getLoad( 14058 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14059 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14060 false, false, false, Alignment); 14061 } 14062 } 14063 14064 // Check to see if we can perform the "gzip trick", transforming 14065 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14066 if (isNullConstant(N3) && CC == ISD::SETLT && 14067 (isNullConstant(N1) || // (a < 0) ? b : 0 14068 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14069 EVT XType = N0.getValueType(); 14070 EVT AType = N2.getValueType(); 14071 if (XType.bitsGE(AType)) { 14072 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14073 // single-bit constant. 14074 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14075 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14076 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14077 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14078 getShiftAmountTy(N0.getValueType())); 14079 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14080 XType, N0, ShCt); 14081 AddToWorklist(Shift.getNode()); 14082 14083 if (XType.bitsGT(AType)) { 14084 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14085 AddToWorklist(Shift.getNode()); 14086 } 14087 14088 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14089 } 14090 14091 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14092 XType, N0, 14093 DAG.getConstant(XType.getSizeInBits() - 1, 14094 SDLoc(N0), 14095 getShiftAmountTy(N0.getValueType()))); 14096 AddToWorklist(Shift.getNode()); 14097 14098 if (XType.bitsGT(AType)) { 14099 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14100 AddToWorklist(Shift.getNode()); 14101 } 14102 14103 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14104 } 14105 } 14106 14107 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14108 // where y is has a single bit set. 14109 // A plaintext description would be, we can turn the SELECT_CC into an AND 14110 // when the condition can be materialized as an all-ones register. Any 14111 // single bit-test can be materialized as an all-ones register with 14112 // shift-left and shift-right-arith. 14113 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14114 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14115 SDValue AndLHS = N0->getOperand(0); 14116 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14117 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14118 // Shift the tested bit over the sign bit. 14119 APInt AndMask = ConstAndRHS->getAPIntValue(); 14120 SDValue ShlAmt = 14121 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14122 getShiftAmountTy(AndLHS.getValueType())); 14123 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14124 14125 // Now arithmetic right shift it all the way over, so the result is either 14126 // all-ones, or zero. 14127 SDValue ShrAmt = 14128 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14129 getShiftAmountTy(Shl.getValueType())); 14130 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14131 14132 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14133 } 14134 } 14135 14136 // fold select C, 16, 0 -> shl C, 4 14137 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14138 TLI.getBooleanContents(N0.getValueType()) == 14139 TargetLowering::ZeroOrOneBooleanContent) { 14140 14141 // If the caller doesn't want us to simplify this into a zext of a compare, 14142 // don't do it. 14143 if (NotExtCompare && N2C->isOne()) 14144 return SDValue(); 14145 14146 // Get a SetCC of the condition 14147 // NOTE: Don't create a SETCC if it's not legal on this target. 14148 if (!LegalOperations || 14149 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14150 SDValue Temp, SCC; 14151 // cast from setcc result type to select result type 14152 if (LegalTypes) { 14153 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14154 N0, N1, CC); 14155 if (N2.getValueType().bitsLT(SCC.getValueType())) 14156 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14157 N2.getValueType()); 14158 else 14159 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14160 N2.getValueType(), SCC); 14161 } else { 14162 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14163 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14164 N2.getValueType(), SCC); 14165 } 14166 14167 AddToWorklist(SCC.getNode()); 14168 AddToWorklist(Temp.getNode()); 14169 14170 if (N2C->isOne()) 14171 return Temp; 14172 14173 // shl setcc result by log2 n2c 14174 return DAG.getNode( 14175 ISD::SHL, DL, N2.getValueType(), Temp, 14176 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14177 getShiftAmountTy(Temp.getValueType()))); 14178 } 14179 } 14180 14181 // Check to see if this is an integer abs. 14182 // select_cc setg[te] X, 0, X, -X -> 14183 // select_cc setgt X, -1, X, -X -> 14184 // select_cc setl[te] X, 0, -X, X -> 14185 // select_cc setlt X, 1, -X, X -> 14186 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14187 if (N1C) { 14188 ConstantSDNode *SubC = nullptr; 14189 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14190 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14191 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14192 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14193 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14194 (N1C->isOne() && CC == ISD::SETLT)) && 14195 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14196 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14197 14198 EVT XType = N0.getValueType(); 14199 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14200 SDLoc DL(N0); 14201 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14202 N0, 14203 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14204 getShiftAmountTy(N0.getValueType()))); 14205 SDValue Add = DAG.getNode(ISD::ADD, DL, 14206 XType, N0, Shift); 14207 AddToWorklist(Shift.getNode()); 14208 AddToWorklist(Add.getNode()); 14209 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14210 } 14211 } 14212 14213 return SDValue(); 14214 } 14215 14216 /// This is a stub for TargetLowering::SimplifySetCC. 14217 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 14218 SDValue N1, ISD::CondCode Cond, 14219 SDLoc DL, bool foldBooleans) { 14220 TargetLowering::DAGCombinerInfo 14221 DagCombineInfo(DAG, Level, false, this); 14222 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14223 } 14224 14225 /// Given an ISD::SDIV node expressing a divide by constant, return 14226 /// a DAG expression to select that will generate the same value by multiplying 14227 /// by a magic number. 14228 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14229 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14230 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14231 if (!C) 14232 return SDValue(); 14233 14234 // Avoid division by zero. 14235 if (C->isNullValue()) 14236 return SDValue(); 14237 14238 std::vector<SDNode*> Built; 14239 SDValue S = 14240 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14241 14242 for (SDNode *N : Built) 14243 AddToWorklist(N); 14244 return S; 14245 } 14246 14247 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14248 /// DAG expression that will generate the same value by right shifting. 14249 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14250 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14251 if (!C) 14252 return SDValue(); 14253 14254 // Avoid division by zero. 14255 if (C->isNullValue()) 14256 return SDValue(); 14257 14258 std::vector<SDNode *> Built; 14259 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14260 14261 for (SDNode *N : Built) 14262 AddToWorklist(N); 14263 return S; 14264 } 14265 14266 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14267 /// expression that will generate the same value by multiplying by a magic 14268 /// number. 14269 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14270 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14271 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14272 if (!C) 14273 return SDValue(); 14274 14275 // Avoid division by zero. 14276 if (C->isNullValue()) 14277 return SDValue(); 14278 14279 std::vector<SDNode*> Built; 14280 SDValue S = 14281 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14282 14283 for (SDNode *N : Built) 14284 AddToWorklist(N); 14285 return S; 14286 } 14287 14288 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14289 if (Level >= AfterLegalizeDAG) 14290 return SDValue(); 14291 14292 // Expose the DAG combiner to the target combiner implementations. 14293 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14294 14295 unsigned Iterations = 0; 14296 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14297 if (Iterations) { 14298 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14299 // For the reciprocal, we need to find the zero of the function: 14300 // F(X) = A X - 1 [which has a zero at X = 1/A] 14301 // => 14302 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14303 // does not require additional intermediate precision] 14304 EVT VT = Op.getValueType(); 14305 SDLoc DL(Op); 14306 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14307 14308 AddToWorklist(Est.getNode()); 14309 14310 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14311 for (unsigned i = 0; i < Iterations; ++i) { 14312 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14313 AddToWorklist(NewEst.getNode()); 14314 14315 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14316 AddToWorklist(NewEst.getNode()); 14317 14318 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14319 AddToWorklist(NewEst.getNode()); 14320 14321 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14322 AddToWorklist(Est.getNode()); 14323 } 14324 } 14325 return Est; 14326 } 14327 14328 return SDValue(); 14329 } 14330 14331 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14332 /// For the reciprocal sqrt, we need to find the zero of the function: 14333 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14334 /// => 14335 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14336 /// As a result, we precompute A/2 prior to the iteration loop. 14337 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14338 unsigned Iterations, 14339 SDNodeFlags *Flags) { 14340 EVT VT = Arg.getValueType(); 14341 SDLoc DL(Arg); 14342 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14343 14344 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14345 // this entire sequence requires only one FP constant. 14346 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14347 AddToWorklist(HalfArg.getNode()); 14348 14349 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14350 AddToWorklist(HalfArg.getNode()); 14351 14352 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14353 for (unsigned i = 0; i < Iterations; ++i) { 14354 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14355 AddToWorklist(NewEst.getNode()); 14356 14357 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14358 AddToWorklist(NewEst.getNode()); 14359 14360 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14361 AddToWorklist(NewEst.getNode()); 14362 14363 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14364 AddToWorklist(Est.getNode()); 14365 } 14366 return Est; 14367 } 14368 14369 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14370 /// For the reciprocal sqrt, we need to find the zero of the function: 14371 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14372 /// => 14373 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14374 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14375 unsigned Iterations, 14376 SDNodeFlags *Flags) { 14377 EVT VT = Arg.getValueType(); 14378 SDLoc DL(Arg); 14379 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14380 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14381 14382 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14383 for (unsigned i = 0; i < Iterations; ++i) { 14384 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14385 AddToWorklist(HalfEst.getNode()); 14386 14387 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14388 AddToWorklist(Est.getNode()); 14389 14390 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14391 AddToWorklist(Est.getNode()); 14392 14393 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14394 AddToWorklist(Est.getNode()); 14395 14396 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14397 AddToWorklist(Est.getNode()); 14398 } 14399 return Est; 14400 } 14401 14402 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14403 if (Level >= AfterLegalizeDAG) 14404 return SDValue(); 14405 14406 // Expose the DAG combiner to the target combiner implementations. 14407 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14408 unsigned Iterations = 0; 14409 bool UseOneConstNR = false; 14410 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14411 AddToWorklist(Est.getNode()); 14412 if (Iterations) { 14413 Est = UseOneConstNR ? 14414 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14415 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14416 } 14417 return Est; 14418 } 14419 14420 return SDValue(); 14421 } 14422 14423 /// Return true if base is a frame index, which is known not to alias with 14424 /// anything but itself. Provides base object and offset as results. 14425 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14426 const GlobalValue *&GV, const void *&CV) { 14427 // Assume it is a primitive operation. 14428 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14429 14430 // If it's an adding a simple constant then integrate the offset. 14431 if (Base.getOpcode() == ISD::ADD) { 14432 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14433 Base = Base.getOperand(0); 14434 Offset += C->getZExtValue(); 14435 } 14436 } 14437 14438 // Return the underlying GlobalValue, and update the Offset. Return false 14439 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14440 // by multiple nodes with different offsets. 14441 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14442 GV = G->getGlobal(); 14443 Offset += G->getOffset(); 14444 return false; 14445 } 14446 14447 // Return the underlying Constant value, and update the Offset. Return false 14448 // for ConstantSDNodes since the same constant pool entry may be represented 14449 // by multiple nodes with different offsets. 14450 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14451 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14452 : (const void *)C->getConstVal(); 14453 Offset += C->getOffset(); 14454 return false; 14455 } 14456 // If it's any of the following then it can't alias with anything but itself. 14457 return isa<FrameIndexSDNode>(Base); 14458 } 14459 14460 /// Return true if there is any possibility that the two addresses overlap. 14461 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14462 // If they are the same then they must be aliases. 14463 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14464 14465 // If they are both volatile then they cannot be reordered. 14466 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14467 14468 // If one operation reads from invariant memory, and the other may store, they 14469 // cannot alias. These should really be checking the equivalent of mayWrite, 14470 // but it only matters for memory nodes other than load /store. 14471 if (Op0->isInvariant() && Op1->writeMem()) 14472 return false; 14473 14474 if (Op1->isInvariant() && Op0->writeMem()) 14475 return false; 14476 14477 // Gather base node and offset information. 14478 SDValue Base1, Base2; 14479 int64_t Offset1, Offset2; 14480 const GlobalValue *GV1, *GV2; 14481 const void *CV1, *CV2; 14482 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14483 Base1, Offset1, GV1, CV1); 14484 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14485 Base2, Offset2, GV2, CV2); 14486 14487 // If they have a same base address then check to see if they overlap. 14488 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14489 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14490 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14491 14492 // It is possible for different frame indices to alias each other, mostly 14493 // when tail call optimization reuses return address slots for arguments. 14494 // To catch this case, look up the actual index of frame indices to compute 14495 // the real alias relationship. 14496 if (isFrameIndex1 && isFrameIndex2) { 14497 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14498 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14499 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14500 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14501 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14502 } 14503 14504 // Otherwise, if we know what the bases are, and they aren't identical, then 14505 // we know they cannot alias. 14506 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14507 return false; 14508 14509 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14510 // compared to the size and offset of the access, we may be able to prove they 14511 // do not alias. This check is conservative for now to catch cases created by 14512 // splitting vector types. 14513 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14514 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14515 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14516 Op1->getMemoryVT().getSizeInBits() >> 3) && 14517 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14518 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14519 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14520 14521 // There is no overlap between these relatively aligned accesses of similar 14522 // size, return no alias. 14523 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14524 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14525 return false; 14526 } 14527 14528 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14529 ? CombinerGlobalAA 14530 : DAG.getSubtarget().useAA(); 14531 #ifndef NDEBUG 14532 if (CombinerAAOnlyFunc.getNumOccurrences() && 14533 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14534 UseAA = false; 14535 #endif 14536 if (UseAA && 14537 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14538 // Use alias analysis information. 14539 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14540 Op1->getSrcValueOffset()); 14541 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14542 Op0->getSrcValueOffset() - MinOffset; 14543 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14544 Op1->getSrcValueOffset() - MinOffset; 14545 AliasResult AAResult = 14546 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14547 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14548 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14549 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14550 if (AAResult == NoAlias) 14551 return false; 14552 } 14553 14554 // Otherwise we have to assume they alias. 14555 return true; 14556 } 14557 14558 /// Walk up chain skipping non-aliasing memory nodes, 14559 /// looking for aliasing nodes and adding them to the Aliases vector. 14560 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14561 SmallVectorImpl<SDValue> &Aliases) { 14562 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14563 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14564 14565 // Get alias information for node. 14566 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14567 14568 // Starting off. 14569 Chains.push_back(OriginalChain); 14570 unsigned Depth = 0; 14571 14572 // Look at each chain and determine if it is an alias. If so, add it to the 14573 // aliases list. If not, then continue up the chain looking for the next 14574 // candidate. 14575 while (!Chains.empty()) { 14576 SDValue Chain = Chains.pop_back_val(); 14577 14578 // For TokenFactor nodes, look at each operand and only continue up the 14579 // chain until we reach the depth limit. 14580 // 14581 // FIXME: The depth check could be made to return the last non-aliasing 14582 // chain we found before we hit a tokenfactor rather than the original 14583 // chain. 14584 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14585 Aliases.clear(); 14586 Aliases.push_back(OriginalChain); 14587 return; 14588 } 14589 14590 // Don't bother if we've been before. 14591 if (!Visited.insert(Chain.getNode()).second) 14592 continue; 14593 14594 switch (Chain.getOpcode()) { 14595 case ISD::EntryToken: 14596 // Entry token is ideal chain operand, but handled in FindBetterChain. 14597 break; 14598 14599 case ISD::LOAD: 14600 case ISD::STORE: { 14601 // Get alias information for Chain. 14602 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14603 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14604 14605 // If chain is alias then stop here. 14606 if (!(IsLoad && IsOpLoad) && 14607 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14608 Aliases.push_back(Chain); 14609 } else { 14610 // Look further up the chain. 14611 Chains.push_back(Chain.getOperand(0)); 14612 ++Depth; 14613 } 14614 break; 14615 } 14616 14617 case ISD::TokenFactor: 14618 // We have to check each of the operands of the token factor for "small" 14619 // token factors, so we queue them up. Adding the operands to the queue 14620 // (stack) in reverse order maintains the original order and increases the 14621 // likelihood that getNode will find a matching token factor (CSE.) 14622 if (Chain.getNumOperands() > 16) { 14623 Aliases.push_back(Chain); 14624 break; 14625 } 14626 for (unsigned n = Chain.getNumOperands(); n;) 14627 Chains.push_back(Chain.getOperand(--n)); 14628 ++Depth; 14629 break; 14630 14631 default: 14632 // For all other instructions we will just have to take what we can get. 14633 Aliases.push_back(Chain); 14634 break; 14635 } 14636 } 14637 14638 // We need to be careful here to also search for aliases through the 14639 // value operand of a store, etc. Consider the following situation: 14640 // Token1 = ... 14641 // L1 = load Token1, %52 14642 // S1 = store Token1, L1, %51 14643 // L2 = load Token1, %52+8 14644 // S2 = store Token1, L2, %51+8 14645 // Token2 = Token(S1, S2) 14646 // L3 = load Token2, %53 14647 // S3 = store Token2, L3, %52 14648 // L4 = load Token2, %53+8 14649 // S4 = store Token2, L4, %52+8 14650 // If we search for aliases of S3 (which loads address %52), and we look 14651 // only through the chain, then we'll miss the trivial dependence on L1 14652 // (which also loads from %52). We then might change all loads and 14653 // stores to use Token1 as their chain operand, which could result in 14654 // copying %53 into %52 before copying %52 into %51 (which should 14655 // happen first). 14656 // 14657 // The problem is, however, that searching for such data dependencies 14658 // can become expensive, and the cost is not directly related to the 14659 // chain depth. Instead, we'll rule out such configurations here by 14660 // insisting that we've visited all chain users (except for users 14661 // of the original chain, which is not necessary). When doing this, 14662 // we need to look through nodes we don't care about (otherwise, things 14663 // like register copies will interfere with trivial cases). 14664 14665 SmallVector<const SDNode *, 16> Worklist; 14666 for (const SDNode *N : Visited) 14667 if (N != OriginalChain.getNode()) 14668 Worklist.push_back(N); 14669 14670 while (!Worklist.empty()) { 14671 const SDNode *M = Worklist.pop_back_val(); 14672 14673 // We have already visited M, and want to make sure we've visited any uses 14674 // of M that we care about. For uses that we've not visisted, and don't 14675 // care about, queue them to the worklist. 14676 14677 for (SDNode::use_iterator UI = M->use_begin(), 14678 UIE = M->use_end(); UI != UIE; ++UI) 14679 if (UI.getUse().getValueType() == MVT::Other && 14680 Visited.insert(*UI).second) { 14681 if (isa<MemSDNode>(*UI)) { 14682 // We've not visited this use, and we care about it (it could have an 14683 // ordering dependency with the original node). 14684 Aliases.clear(); 14685 Aliases.push_back(OriginalChain); 14686 return; 14687 } 14688 14689 // We've not visited this use, but we don't care about it. Mark it as 14690 // visited and enqueue it to the worklist. 14691 Worklist.push_back(*UI); 14692 } 14693 } 14694 } 14695 14696 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14697 /// (aliasing node.) 14698 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14699 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14700 14701 // Accumulate all the aliases to this node. 14702 GatherAllAliases(N, OldChain, Aliases); 14703 14704 // If no operands then chain to entry token. 14705 if (Aliases.size() == 0) 14706 return DAG.getEntryNode(); 14707 14708 // If a single operand then chain to it. We don't need to revisit it. 14709 if (Aliases.size() == 1) 14710 return Aliases[0]; 14711 14712 // Construct a custom tailored token factor. 14713 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14714 } 14715 14716 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14717 // This holds the base pointer, index, and the offset in bytes from the base 14718 // pointer. 14719 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14720 14721 // We must have a base and an offset. 14722 if (!BasePtr.Base.getNode()) 14723 return false; 14724 14725 // Do not handle stores to undef base pointers. 14726 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 14727 return false; 14728 14729 SmallVector<StoreSDNode *, 8> ChainedStores; 14730 ChainedStores.push_back(St); 14731 14732 // Walk up the chain and look for nodes with offsets from the same 14733 // base pointer. Stop when reaching an instruction with a different kind 14734 // or instruction which has a different base pointer. 14735 StoreSDNode *Index = St; 14736 while (Index) { 14737 // If the chain has more than one use, then we can't reorder the mem ops. 14738 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14739 break; 14740 14741 if (Index->isVolatile() || Index->isIndexed()) 14742 break; 14743 14744 // Find the base pointer and offset for this memory node. 14745 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 14746 14747 // Check that the base pointer is the same as the original one. 14748 if (!Ptr.equalBaseIndex(BasePtr)) 14749 break; 14750 14751 // Find the next memory operand in the chain. If the next operand in the 14752 // chain is a store then move up and continue the scan with the next 14753 // memory operand. If the next operand is a load save it and use alias 14754 // information to check if it interferes with anything. 14755 SDNode *NextInChain = Index->getChain().getNode(); 14756 while (true) { 14757 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14758 // We found a store node. Use it for the next iteration. 14759 ChainedStores.push_back(STn); 14760 Index = STn; 14761 break; 14762 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14763 NextInChain = Ldn->getChain().getNode(); 14764 continue; 14765 } else { 14766 Index = nullptr; 14767 break; 14768 } 14769 } 14770 } 14771 14772 bool MadeChange = false; 14773 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14774 14775 for (StoreSDNode *ChainedStore : ChainedStores) { 14776 SDValue Chain = ChainedStore->getChain(); 14777 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14778 14779 if (Chain != BetterChain) { 14780 MadeChange = true; 14781 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14782 } 14783 } 14784 14785 // Do all replacements after finding the replacements to make to avoid making 14786 // the chains more complicated by introducing new TokenFactors. 14787 for (auto Replacement : BetterChains) 14788 replaceStoreChain(Replacement.first, Replacement.second); 14789 14790 return MadeChange; 14791 } 14792 14793 /// This is the entry point for the file. 14794 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14795 CodeGenOpt::Level OptLevel) { 14796 /// This is the main entry point to this class. 14797 DAGCombiner(*this, AA, OptLevel).Run(Level); 14798 } 14799