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 *, 32> 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 x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 850 // use 851 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 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.isOperationLegalOrCustom(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 // DivMod lib calls can still work on non-legal types if using lib-calls. 2157 EVT VT = Node->getValueType(0); 2158 if (VT.isVector() || !VT.isInteger()) 2159 return SDValue(); 2160 2161 unsigned Opcode = Node->getOpcode(); 2162 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2163 2164 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2165 // If DIVREM is going to get expanded into a libcall, 2166 // but there is no libcall available, then don't combine. 2167 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2168 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2169 return SDValue(); 2170 2171 // If div is legal, it's better to do the normal expansion 2172 unsigned OtherOpcode = 0; 2173 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2174 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2175 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2176 return SDValue(); 2177 } else { 2178 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2179 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2180 return SDValue(); 2181 } 2182 2183 SDValue Op0 = Node->getOperand(0); 2184 SDValue Op1 = Node->getOperand(1); 2185 SDValue combined; 2186 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2187 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2188 SDNode *User = *UI; 2189 if (User == Node || User->use_empty()) 2190 continue; 2191 // Convert the other matching node(s), too; 2192 // otherwise, the DIVREM may get target-legalized into something 2193 // target-specific that we won't be able to recognize. 2194 unsigned UserOpc = User->getOpcode(); 2195 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2196 User->getOperand(0) == Op0 && 2197 User->getOperand(1) == Op1) { 2198 if (!combined) { 2199 if (UserOpc == OtherOpcode) { 2200 SDVTList VTs = DAG.getVTList(VT, VT); 2201 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2202 } else if (UserOpc == DivRemOpc) { 2203 combined = SDValue(User, 0); 2204 } else { 2205 assert(UserOpc == Opcode); 2206 continue; 2207 } 2208 } 2209 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2210 CombineTo(User, combined); 2211 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2212 CombineTo(User, combined.getValue(1)); 2213 } 2214 } 2215 return combined; 2216 } 2217 2218 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2219 SDValue N0 = N->getOperand(0); 2220 SDValue N1 = N->getOperand(1); 2221 EVT VT = N->getValueType(0); 2222 2223 // fold vector ops 2224 if (VT.isVector()) 2225 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2226 return FoldedVOp; 2227 2228 SDLoc DL(N); 2229 2230 // fold (sdiv c1, c2) -> c1/c2 2231 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2232 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2233 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2234 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2235 // fold (sdiv X, 1) -> X 2236 if (N1C && N1C->isOne()) 2237 return N0; 2238 // fold (sdiv X, -1) -> 0-X 2239 if (N1C && N1C->isAllOnesValue()) 2240 return DAG.getNode(ISD::SUB, DL, VT, 2241 DAG.getConstant(0, DL, VT), N0); 2242 2243 // If we know the sign bits of both operands are zero, strength reduce to a 2244 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2245 if (!VT.isVector()) { 2246 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2247 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2248 } 2249 2250 // fold (sdiv X, pow2) -> simple ops after legalize 2251 // FIXME: We check for the exact bit here because the generic lowering gives 2252 // better results in that case. The target-specific lowering should learn how 2253 // to handle exact sdivs efficiently. 2254 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2255 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2256 (N1C->getAPIntValue().isPowerOf2() || 2257 (-N1C->getAPIntValue()).isPowerOf2())) { 2258 // Target-specific implementation of sdiv x, pow2. 2259 if (SDValue Res = BuildSDIVPow2(N)) 2260 return Res; 2261 2262 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2263 2264 // Splat the sign bit into the register 2265 SDValue SGN = 2266 DAG.getNode(ISD::SRA, DL, VT, N0, 2267 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2268 getShiftAmountTy(N0.getValueType()))); 2269 AddToWorklist(SGN.getNode()); 2270 2271 // Add (N0 < 0) ? abs2 - 1 : 0; 2272 SDValue SRL = 2273 DAG.getNode(ISD::SRL, DL, VT, SGN, 2274 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2275 getShiftAmountTy(SGN.getValueType()))); 2276 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2277 AddToWorklist(SRL.getNode()); 2278 AddToWorklist(ADD.getNode()); // Divide by pow2 2279 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2280 DAG.getConstant(lg2, DL, 2281 getShiftAmountTy(ADD.getValueType()))); 2282 2283 // If we're dividing by a positive value, we're done. Otherwise, we must 2284 // negate the result. 2285 if (N1C->getAPIntValue().isNonNegative()) 2286 return SRA; 2287 2288 AddToWorklist(SRA.getNode()); 2289 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2290 } 2291 2292 // If integer divide is expensive and we satisfy the requirements, emit an 2293 // alternate sequence. Targets may check function attributes for size/speed 2294 // trade-offs. 2295 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2296 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2297 if (SDValue Op = BuildSDIV(N)) 2298 return Op; 2299 2300 // sdiv, srem -> sdivrem 2301 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2302 // Otherwise, we break the simplification logic in visitREM(). 2303 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2304 if (SDValue DivRem = useDivRem(N)) 2305 return DivRem; 2306 2307 // undef / X -> 0 2308 if (N0.getOpcode() == ISD::UNDEF) 2309 return DAG.getConstant(0, DL, VT); 2310 // X / undef -> undef 2311 if (N1.getOpcode() == ISD::UNDEF) 2312 return N1; 2313 2314 return SDValue(); 2315 } 2316 2317 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2318 SDValue N0 = N->getOperand(0); 2319 SDValue N1 = N->getOperand(1); 2320 EVT VT = N->getValueType(0); 2321 2322 // fold vector ops 2323 if (VT.isVector()) 2324 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2325 return FoldedVOp; 2326 2327 SDLoc DL(N); 2328 2329 // fold (udiv c1, c2) -> c1/c2 2330 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2331 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2332 if (N0C && N1C) 2333 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2334 N0C, N1C)) 2335 return Folded; 2336 // fold (udiv x, (1 << c)) -> x >>u c 2337 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2338 return DAG.getNode(ISD::SRL, DL, VT, N0, 2339 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2340 getShiftAmountTy(N0.getValueType()))); 2341 2342 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2343 if (N1.getOpcode() == ISD::SHL) { 2344 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2345 if (SHC->getAPIntValue().isPowerOf2()) { 2346 EVT ADDVT = N1.getOperand(1).getValueType(); 2347 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2348 N1.getOperand(1), 2349 DAG.getConstant(SHC->getAPIntValue() 2350 .logBase2(), 2351 DL, ADDVT)); 2352 AddToWorklist(Add.getNode()); 2353 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2354 } 2355 } 2356 } 2357 2358 // fold (udiv x, c) -> alternate 2359 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2360 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2361 if (SDValue Op = BuildUDIV(N)) 2362 return Op; 2363 2364 // sdiv, srem -> sdivrem 2365 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2366 // Otherwise, we break the simplification logic in visitREM(). 2367 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2368 if (SDValue DivRem = useDivRem(N)) 2369 return DivRem; 2370 2371 // undef / X -> 0 2372 if (N0.getOpcode() == ISD::UNDEF) 2373 return DAG.getConstant(0, DL, VT); 2374 // X / undef -> undef 2375 if (N1.getOpcode() == ISD::UNDEF) 2376 return N1; 2377 2378 return SDValue(); 2379 } 2380 2381 // handles ISD::SREM and ISD::UREM 2382 SDValue DAGCombiner::visitREM(SDNode *N) { 2383 unsigned Opcode = N->getOpcode(); 2384 SDValue N0 = N->getOperand(0); 2385 SDValue N1 = N->getOperand(1); 2386 EVT VT = N->getValueType(0); 2387 bool isSigned = (Opcode == ISD::SREM); 2388 SDLoc DL(N); 2389 2390 // fold (rem c1, c2) -> c1%c2 2391 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2392 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2393 if (N0C && N1C) 2394 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2395 return Folded; 2396 2397 if (isSigned) { 2398 // If we know the sign bits of both operands are zero, strength reduce to a 2399 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2400 if (!VT.isVector()) { 2401 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2402 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2403 } 2404 } else { 2405 // fold (urem x, pow2) -> (and x, pow2-1) 2406 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2407 N1C->getAPIntValue().isPowerOf2()) { 2408 return DAG.getNode(ISD::AND, DL, VT, N0, 2409 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2410 } 2411 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2412 if (N1.getOpcode() == ISD::SHL) { 2413 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2414 if (SHC->getAPIntValue().isPowerOf2()) { 2415 SDValue Add = 2416 DAG.getNode(ISD::ADD, DL, VT, N1, 2417 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2418 VT)); 2419 AddToWorklist(Add.getNode()); 2420 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2421 } 2422 } 2423 } 2424 } 2425 2426 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2427 2428 // If X/C can be simplified by the division-by-constant logic, lower 2429 // X%C to the equivalent of X-X/C*C. 2430 // To avoid mangling nodes, this simplification requires that the combine() 2431 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2432 // against this by skipping the simplification if isIntDivCheap(). When 2433 // div is not cheap, combine will not return a DIVREM. Regardless, 2434 // checking cheapness here makes sense since the simplification results in 2435 // fatter code. 2436 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2437 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2438 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2439 AddToWorklist(Div.getNode()); 2440 SDValue OptimizedDiv = combine(Div.getNode()); 2441 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2442 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2443 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2444 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2445 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2446 AddToWorklist(Mul.getNode()); 2447 return Sub; 2448 } 2449 } 2450 2451 // sdiv, srem -> sdivrem 2452 if (SDValue DivRem = useDivRem(N)) 2453 return DivRem.getValue(1); 2454 2455 // undef % X -> 0 2456 if (N0.getOpcode() == ISD::UNDEF) 2457 return DAG.getConstant(0, DL, VT); 2458 // X % undef -> undef 2459 if (N1.getOpcode() == ISD::UNDEF) 2460 return N1; 2461 2462 return SDValue(); 2463 } 2464 2465 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2466 SDValue N0 = N->getOperand(0); 2467 SDValue N1 = N->getOperand(1); 2468 EVT VT = N->getValueType(0); 2469 SDLoc DL(N); 2470 2471 // fold (mulhs x, 0) -> 0 2472 if (isNullConstant(N1)) 2473 return N1; 2474 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2475 if (isOneConstant(N1)) { 2476 SDLoc DL(N); 2477 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2478 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2479 DL, 2480 getShiftAmountTy(N0.getValueType()))); 2481 } 2482 // fold (mulhs x, undef) -> 0 2483 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2484 return DAG.getConstant(0, SDLoc(N), VT); 2485 2486 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2487 // plus a shift. 2488 if (VT.isSimple() && !VT.isVector()) { 2489 MVT Simple = VT.getSimpleVT(); 2490 unsigned SimpleSize = Simple.getSizeInBits(); 2491 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2492 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2493 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2494 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2495 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2496 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2497 DAG.getConstant(SimpleSize, DL, 2498 getShiftAmountTy(N1.getValueType()))); 2499 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2500 } 2501 } 2502 2503 return SDValue(); 2504 } 2505 2506 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2507 SDValue N0 = N->getOperand(0); 2508 SDValue N1 = N->getOperand(1); 2509 EVT VT = N->getValueType(0); 2510 SDLoc DL(N); 2511 2512 // fold (mulhu x, 0) -> 0 2513 if (isNullConstant(N1)) 2514 return N1; 2515 // fold (mulhu x, 1) -> 0 2516 if (isOneConstant(N1)) 2517 return DAG.getConstant(0, DL, N0.getValueType()); 2518 // fold (mulhu x, undef) -> 0 2519 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2520 return DAG.getConstant(0, DL, VT); 2521 2522 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2523 // plus a shift. 2524 if (VT.isSimple() && !VT.isVector()) { 2525 MVT Simple = VT.getSimpleVT(); 2526 unsigned SimpleSize = Simple.getSizeInBits(); 2527 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2528 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2529 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2530 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2531 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2532 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2533 DAG.getConstant(SimpleSize, DL, 2534 getShiftAmountTy(N1.getValueType()))); 2535 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2536 } 2537 } 2538 2539 return SDValue(); 2540 } 2541 2542 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2543 /// give the opcodes for the two computations that are being performed. Return 2544 /// true if a simplification was made. 2545 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2546 unsigned HiOp) { 2547 // If the high half is not needed, just compute the low half. 2548 bool HiExists = N->hasAnyUseOfValue(1); 2549 if (!HiExists && 2550 (!LegalOperations || 2551 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2552 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2553 return CombineTo(N, Res, Res); 2554 } 2555 2556 // If the low half is not needed, just compute the high half. 2557 bool LoExists = N->hasAnyUseOfValue(0); 2558 if (!LoExists && 2559 (!LegalOperations || 2560 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2561 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2562 return CombineTo(N, Res, Res); 2563 } 2564 2565 // If both halves are used, return as it is. 2566 if (LoExists && HiExists) 2567 return SDValue(); 2568 2569 // If the two computed results can be simplified separately, separate them. 2570 if (LoExists) { 2571 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2572 AddToWorklist(Lo.getNode()); 2573 SDValue LoOpt = combine(Lo.getNode()); 2574 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2575 (!LegalOperations || 2576 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2577 return CombineTo(N, LoOpt, LoOpt); 2578 } 2579 2580 if (HiExists) { 2581 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2582 AddToWorklist(Hi.getNode()); 2583 SDValue HiOpt = combine(Hi.getNode()); 2584 if (HiOpt.getNode() && HiOpt != Hi && 2585 (!LegalOperations || 2586 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2587 return CombineTo(N, HiOpt, HiOpt); 2588 } 2589 2590 return SDValue(); 2591 } 2592 2593 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2594 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2595 return Res; 2596 2597 EVT VT = N->getValueType(0); 2598 SDLoc DL(N); 2599 2600 // If the type is twice as wide is legal, transform the mulhu to a wider 2601 // multiply plus a shift. 2602 if (VT.isSimple() && !VT.isVector()) { 2603 MVT Simple = VT.getSimpleVT(); 2604 unsigned SimpleSize = Simple.getSizeInBits(); 2605 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2606 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2607 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2608 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2609 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2610 // Compute the high part as N1. 2611 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2612 DAG.getConstant(SimpleSize, DL, 2613 getShiftAmountTy(Lo.getValueType()))); 2614 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2615 // Compute the low part as N0. 2616 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2617 return CombineTo(N, Lo, Hi); 2618 } 2619 } 2620 2621 return SDValue(); 2622 } 2623 2624 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2626 return Res; 2627 2628 EVT VT = N->getValueType(0); 2629 SDLoc DL(N); 2630 2631 // If the type is twice as wide is legal, transform the mulhu to a wider 2632 // multiply plus a shift. 2633 if (VT.isSimple() && !VT.isVector()) { 2634 MVT Simple = VT.getSimpleVT(); 2635 unsigned SimpleSize = Simple.getSizeInBits(); 2636 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2637 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2638 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2639 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2640 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2641 // Compute the high part as N1. 2642 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2643 DAG.getConstant(SimpleSize, DL, 2644 getShiftAmountTy(Lo.getValueType()))); 2645 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2646 // Compute the low part as N0. 2647 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2648 return CombineTo(N, Lo, Hi); 2649 } 2650 } 2651 2652 return SDValue(); 2653 } 2654 2655 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2656 // (smulo x, 2) -> (saddo x, x) 2657 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2658 if (C2->getAPIntValue() == 2) 2659 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2660 N->getOperand(0), N->getOperand(0)); 2661 2662 return SDValue(); 2663 } 2664 2665 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2666 // (umulo x, 2) -> (uaddo x, x) 2667 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2668 if (C2->getAPIntValue() == 2) 2669 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2670 N->getOperand(0), N->getOperand(0)); 2671 2672 return SDValue(); 2673 } 2674 2675 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2676 SDValue N0 = N->getOperand(0); 2677 SDValue N1 = N->getOperand(1); 2678 EVT VT = N0.getValueType(); 2679 2680 // fold vector ops 2681 if (VT.isVector()) 2682 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2683 return FoldedVOp; 2684 2685 // fold (add c1, c2) -> c1+c2 2686 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2687 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2688 if (N0C && N1C) 2689 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2690 2691 // canonicalize constant to RHS 2692 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2693 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2694 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2695 2696 return SDValue(); 2697 } 2698 2699 /// If this is a binary operator with two operands of the same opcode, try to 2700 /// simplify it. 2701 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2702 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2703 EVT VT = N0.getValueType(); 2704 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2705 2706 // Bail early if none of these transforms apply. 2707 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2708 2709 // For each of OP in AND/OR/XOR: 2710 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2711 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2712 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2713 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2714 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2715 // 2716 // do not sink logical op inside of a vector extend, since it may combine 2717 // into a vsetcc. 2718 EVT Op0VT = N0.getOperand(0).getValueType(); 2719 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2720 N0.getOpcode() == ISD::SIGN_EXTEND || 2721 N0.getOpcode() == ISD::BSWAP || 2722 // Avoid infinite looping with PromoteIntBinOp. 2723 (N0.getOpcode() == ISD::ANY_EXTEND && 2724 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2725 (N0.getOpcode() == ISD::TRUNCATE && 2726 (!TLI.isZExtFree(VT, Op0VT) || 2727 !TLI.isTruncateFree(Op0VT, VT)) && 2728 TLI.isTypeLegal(Op0VT))) && 2729 !VT.isVector() && 2730 Op0VT == N1.getOperand(0).getValueType() && 2731 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2732 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2733 N0.getOperand(0).getValueType(), 2734 N0.getOperand(0), N1.getOperand(0)); 2735 AddToWorklist(ORNode.getNode()); 2736 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2737 } 2738 2739 // For each of OP in SHL/SRL/SRA/AND... 2740 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2741 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2742 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2743 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2744 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2745 N0.getOperand(1) == N1.getOperand(1)) { 2746 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2747 N0.getOperand(0).getValueType(), 2748 N0.getOperand(0), N1.getOperand(0)); 2749 AddToWorklist(ORNode.getNode()); 2750 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2751 ORNode, N0.getOperand(1)); 2752 } 2753 2754 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2755 // Only perform this optimization after type legalization and before 2756 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2757 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2758 // we don't want to undo this promotion. 2759 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2760 // on scalars. 2761 if ((N0.getOpcode() == ISD::BITCAST || 2762 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2763 Level == AfterLegalizeTypes) { 2764 SDValue In0 = N0.getOperand(0); 2765 SDValue In1 = N1.getOperand(0); 2766 EVT In0Ty = In0.getValueType(); 2767 EVT In1Ty = In1.getValueType(); 2768 SDLoc DL(N); 2769 // If both incoming values are integers, and the original types are the 2770 // same. 2771 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2772 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2773 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2774 AddToWorklist(Op.getNode()); 2775 return BC; 2776 } 2777 } 2778 2779 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2780 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2781 // If both shuffles use the same mask, and both shuffle within a single 2782 // vector, then it is worthwhile to move the swizzle after the operation. 2783 // The type-legalizer generates this pattern when loading illegal 2784 // vector types from memory. In many cases this allows additional shuffle 2785 // optimizations. 2786 // There are other cases where moving the shuffle after the xor/and/or 2787 // is profitable even if shuffles don't perform a swizzle. 2788 // If both shuffles use the same mask, and both shuffles have the same first 2789 // or second operand, then it might still be profitable to move the shuffle 2790 // after the xor/and/or operation. 2791 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2792 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2793 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2794 2795 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2796 "Inputs to shuffles are not the same type"); 2797 2798 // Check that both shuffles use the same mask. The masks are known to be of 2799 // the same length because the result vector type is the same. 2800 // Check also that shuffles have only one use to avoid introducing extra 2801 // instructions. 2802 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2803 SVN0->getMask().equals(SVN1->getMask())) { 2804 SDValue ShOp = N0->getOperand(1); 2805 2806 // Don't try to fold this node if it requires introducing a 2807 // build vector of all zeros that might be illegal at this stage. 2808 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2809 if (!LegalTypes) 2810 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2811 else 2812 ShOp = SDValue(); 2813 } 2814 2815 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2816 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2817 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2818 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2819 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2820 N0->getOperand(0), N1->getOperand(0)); 2821 AddToWorklist(NewNode.getNode()); 2822 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2823 &SVN0->getMask()[0]); 2824 } 2825 2826 // Don't try to fold this node if it requires introducing a 2827 // build vector of all zeros that might be illegal at this stage. 2828 ShOp = N0->getOperand(0); 2829 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2830 if (!LegalTypes) 2831 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2832 else 2833 ShOp = SDValue(); 2834 } 2835 2836 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2837 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2838 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2839 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2840 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2841 N0->getOperand(1), N1->getOperand(1)); 2842 AddToWorklist(NewNode.getNode()); 2843 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2844 &SVN0->getMask()[0]); 2845 } 2846 } 2847 } 2848 2849 return SDValue(); 2850 } 2851 2852 /// This contains all DAGCombine rules which reduce two values combined by 2853 /// an And operation to a single value. This makes them reusable in the context 2854 /// of visitSELECT(). Rules involving constants are not included as 2855 /// visitSELECT() already handles those cases. 2856 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2857 SDNode *LocReference) { 2858 EVT VT = N1.getValueType(); 2859 2860 // fold (and x, undef) -> 0 2861 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2862 return DAG.getConstant(0, SDLoc(LocReference), VT); 2863 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2864 SDValue LL, LR, RL, RR, CC0, CC1; 2865 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2866 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2867 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2868 2869 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2870 LL.getValueType().isInteger()) { 2871 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2872 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2873 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2874 LR.getValueType(), LL, RL); 2875 AddToWorklist(ORNode.getNode()); 2876 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2877 } 2878 if (isAllOnesConstant(LR)) { 2879 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2880 if (Op1 == ISD::SETEQ) { 2881 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2882 LR.getValueType(), LL, RL); 2883 AddToWorklist(ANDNode.getNode()); 2884 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2885 } 2886 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2887 if (Op1 == ISD::SETGT) { 2888 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2889 LR.getValueType(), LL, RL); 2890 AddToWorklist(ORNode.getNode()); 2891 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2892 } 2893 } 2894 } 2895 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2896 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2897 Op0 == Op1 && LL.getValueType().isInteger() && 2898 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2899 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2900 SDLoc DL(N0); 2901 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2902 LL, DAG.getConstant(1, DL, 2903 LL.getValueType())); 2904 AddToWorklist(ADDNode.getNode()); 2905 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2906 DAG.getConstant(2, DL, LL.getValueType()), 2907 ISD::SETUGE); 2908 } 2909 // canonicalize equivalent to ll == rl 2910 if (LL == RR && LR == RL) { 2911 Op1 = ISD::getSetCCSwappedOperands(Op1); 2912 std::swap(RL, RR); 2913 } 2914 if (LL == RL && LR == RR) { 2915 bool isInteger = LL.getValueType().isInteger(); 2916 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2917 if (Result != ISD::SETCC_INVALID && 2918 (!LegalOperations || 2919 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2920 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2921 EVT CCVT = getSetCCResultType(LL.getValueType()); 2922 if (N0.getValueType() == CCVT || 2923 (!LegalOperations && N0.getValueType() == MVT::i1)) 2924 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2925 LL, LR, Result); 2926 } 2927 } 2928 } 2929 2930 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2931 VT.getSizeInBits() <= 64) { 2932 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2933 APInt ADDC = ADDI->getAPIntValue(); 2934 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2935 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2936 // immediate for an add, but it is legal if its top c2 bits are set, 2937 // transform the ADD so the immediate doesn't need to be materialized 2938 // in a register. 2939 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2940 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2941 SRLI->getZExtValue()); 2942 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2943 ADDC |= Mask; 2944 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2945 SDLoc DL(N0); 2946 SDValue NewAdd = 2947 DAG.getNode(ISD::ADD, DL, VT, 2948 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2949 CombineTo(N0.getNode(), NewAdd); 2950 // Return N so it doesn't get rechecked! 2951 return SDValue(LocReference, 0); 2952 } 2953 } 2954 } 2955 } 2956 } 2957 } 2958 2959 return SDValue(); 2960 } 2961 2962 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 2963 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 2964 bool &NarrowLoad) { 2965 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 2966 2967 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 2968 return false; 2969 2970 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2971 LoadedVT = LoadN->getMemoryVT(); 2972 2973 if (ExtVT == LoadedVT && 2974 (!LegalOperations || 2975 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 2976 // ZEXTLOAD will match without needing to change the size of the value being 2977 // loaded. 2978 NarrowLoad = false; 2979 return true; 2980 } 2981 2982 // Do not change the width of a volatile load. 2983 if (LoadN->isVolatile()) 2984 return false; 2985 2986 // Do not generate loads of non-round integer types since these can 2987 // be expensive (and would be wrong if the type is not byte sized). 2988 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 2989 return false; 2990 2991 if (LegalOperations && 2992 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 2993 return false; 2994 2995 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 2996 return false; 2997 2998 NarrowLoad = true; 2999 return true; 3000 } 3001 3002 SDValue DAGCombiner::visitAND(SDNode *N) { 3003 SDValue N0 = N->getOperand(0); 3004 SDValue N1 = N->getOperand(1); 3005 EVT VT = N1.getValueType(); 3006 3007 // fold vector ops 3008 if (VT.isVector()) { 3009 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3010 return FoldedVOp; 3011 3012 // fold (and x, 0) -> 0, vector edition 3013 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3014 // do not return N0, because undef node may exist in N0 3015 return DAG.getConstant( 3016 APInt::getNullValue( 3017 N0.getValueType().getScalarType().getSizeInBits()), 3018 SDLoc(N), N0.getValueType()); 3019 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3020 // do not return N1, because undef node may exist in N1 3021 return DAG.getConstant( 3022 APInt::getNullValue( 3023 N1.getValueType().getScalarType().getSizeInBits()), 3024 SDLoc(N), N1.getValueType()); 3025 3026 // fold (and x, -1) -> x, vector edition 3027 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3028 return N1; 3029 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3030 return N0; 3031 } 3032 3033 // fold (and c1, c2) -> c1&c2 3034 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3035 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3036 if (N0C && N1C && !N1C->isOpaque()) 3037 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3038 // canonicalize constant to RHS 3039 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3040 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3041 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3042 // fold (and x, -1) -> x 3043 if (isAllOnesConstant(N1)) 3044 return N0; 3045 // if (and x, c) is known to be zero, return 0 3046 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3047 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3048 APInt::getAllOnesValue(BitWidth))) 3049 return DAG.getConstant(0, SDLoc(N), VT); 3050 // reassociate and 3051 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3052 return RAND; 3053 // fold (and (or x, C), D) -> D if (C & D) == D 3054 if (N1C && N0.getOpcode() == ISD::OR) 3055 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3056 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3057 return N1; 3058 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3059 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3060 SDValue N0Op0 = N0.getOperand(0); 3061 APInt Mask = ~N1C->getAPIntValue(); 3062 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3063 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3064 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3065 N0.getValueType(), N0Op0); 3066 3067 // Replace uses of the AND with uses of the Zero extend node. 3068 CombineTo(N, Zext); 3069 3070 // We actually want to replace all uses of the any_extend with the 3071 // zero_extend, to avoid duplicating things. This will later cause this 3072 // AND to be folded. 3073 CombineTo(N0.getNode(), Zext); 3074 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3075 } 3076 } 3077 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3078 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3079 // already be zero by virtue of the width of the base type of the load. 3080 // 3081 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3082 // more cases. 3083 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3084 N0.getOperand(0).getOpcode() == ISD::LOAD) || 3085 N0.getOpcode() == ISD::LOAD) { 3086 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3087 N0 : N0.getOperand(0) ); 3088 3089 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3090 // This can be a pure constant or a vector splat, in which case we treat the 3091 // vector as a scalar and use the splat value. 3092 APInt Constant = APInt::getNullValue(1); 3093 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3094 Constant = C->getAPIntValue(); 3095 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3096 APInt SplatValue, SplatUndef; 3097 unsigned SplatBitSize; 3098 bool HasAnyUndefs; 3099 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3100 SplatBitSize, HasAnyUndefs); 3101 if (IsSplat) { 3102 // Undef bits can contribute to a possible optimisation if set, so 3103 // set them. 3104 SplatValue |= SplatUndef; 3105 3106 // The splat value may be something like "0x00FFFFFF", which means 0 for 3107 // the first vector value and FF for the rest, repeating. We need a mask 3108 // that will apply equally to all members of the vector, so AND all the 3109 // lanes of the constant together. 3110 EVT VT = Vector->getValueType(0); 3111 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3112 3113 // If the splat value has been compressed to a bitlength lower 3114 // than the size of the vector lane, we need to re-expand it to 3115 // the lane size. 3116 if (BitWidth > SplatBitSize) 3117 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3118 SplatBitSize < BitWidth; 3119 SplatBitSize = SplatBitSize * 2) 3120 SplatValue |= SplatValue.shl(SplatBitSize); 3121 3122 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3123 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3124 if (SplatBitSize % BitWidth == 0) { 3125 Constant = APInt::getAllOnesValue(BitWidth); 3126 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3127 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3128 } 3129 } 3130 } 3131 3132 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3133 // actually legal and isn't going to get expanded, else this is a false 3134 // optimisation. 3135 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3136 Load->getValueType(0), 3137 Load->getMemoryVT()); 3138 3139 // Resize the constant to the same size as the original memory access before 3140 // extension. If it is still the AllOnesValue then this AND is completely 3141 // unneeded. 3142 Constant = 3143 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3144 3145 bool B; 3146 switch (Load->getExtensionType()) { 3147 default: B = false; break; 3148 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3149 case ISD::ZEXTLOAD: 3150 case ISD::NON_EXTLOAD: B = true; break; 3151 } 3152 3153 if (B && Constant.isAllOnesValue()) { 3154 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3155 // preserve semantics once we get rid of the AND. 3156 SDValue NewLoad(Load, 0); 3157 if (Load->getExtensionType() == ISD::EXTLOAD) { 3158 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3159 Load->getValueType(0), SDLoc(Load), 3160 Load->getChain(), Load->getBasePtr(), 3161 Load->getOffset(), Load->getMemoryVT(), 3162 Load->getMemOperand()); 3163 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3164 if (Load->getNumValues() == 3) { 3165 // PRE/POST_INC loads have 3 values. 3166 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3167 NewLoad.getValue(2) }; 3168 CombineTo(Load, To, 3, true); 3169 } else { 3170 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3171 } 3172 } 3173 3174 // Fold the AND away, taking care not to fold to the old load node if we 3175 // replaced it. 3176 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3177 3178 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3179 } 3180 } 3181 3182 // fold (and (load x), 255) -> (zextload x, i8) 3183 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3184 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3185 if (N1C && (N0.getOpcode() == ISD::LOAD || 3186 (N0.getOpcode() == ISD::ANY_EXTEND && 3187 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3188 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3189 LoadSDNode *LN0 = HasAnyExt 3190 ? cast<LoadSDNode>(N0.getOperand(0)) 3191 : cast<LoadSDNode>(N0); 3192 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3193 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3194 auto NarrowLoad = false; 3195 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3196 EVT ExtVT, LoadedVT; 3197 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3198 NarrowLoad)) { 3199 if (!NarrowLoad) { 3200 SDValue NewLoad = 3201 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3202 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3203 LN0->getMemOperand()); 3204 AddToWorklist(N); 3205 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3206 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3207 } else { 3208 EVT PtrType = LN0->getOperand(1).getValueType(); 3209 3210 unsigned Alignment = LN0->getAlignment(); 3211 SDValue NewPtr = LN0->getBasePtr(); 3212 3213 // For big endian targets, we need to add an offset to the pointer 3214 // to load the correct bytes. For little endian systems, we merely 3215 // need to read fewer bytes from the same pointer. 3216 if (DAG.getDataLayout().isBigEndian()) { 3217 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3218 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3219 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3220 SDLoc DL(LN0); 3221 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3222 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3223 Alignment = MinAlign(Alignment, PtrOff); 3224 } 3225 3226 AddToWorklist(NewPtr.getNode()); 3227 3228 SDValue Load = 3229 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3230 LN0->getChain(), NewPtr, 3231 LN0->getPointerInfo(), 3232 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3233 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3234 AddToWorklist(N); 3235 CombineTo(LN0, Load, Load.getValue(1)); 3236 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3237 } 3238 } 3239 } 3240 } 3241 3242 if (SDValue Combined = visitANDLike(N0, N1, N)) 3243 return Combined; 3244 3245 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3246 if (N0.getOpcode() == N1.getOpcode()) 3247 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3248 return Tmp; 3249 3250 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3251 // fold (and (sra)) -> (and (srl)) when possible. 3252 if (!VT.isVector() && 3253 SimplifyDemandedBits(SDValue(N, 0))) 3254 return SDValue(N, 0); 3255 3256 // fold (zext_inreg (extload x)) -> (zextload x) 3257 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3258 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3259 EVT MemVT = LN0->getMemoryVT(); 3260 // If we zero all the possible extended bits, then we can turn this into 3261 // a zextload if we are running before legalize or the operation is legal. 3262 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3263 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3264 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3265 ((!LegalOperations && !LN0->isVolatile()) || 3266 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3267 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3268 LN0->getChain(), LN0->getBasePtr(), 3269 MemVT, LN0->getMemOperand()); 3270 AddToWorklist(N); 3271 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3272 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3273 } 3274 } 3275 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3276 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3277 N0.hasOneUse()) { 3278 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3279 EVT MemVT = LN0->getMemoryVT(); 3280 // If we zero all the possible extended bits, then we can turn this into 3281 // a zextload if we are running before legalize or the operation is legal. 3282 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3283 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3284 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3285 ((!LegalOperations && !LN0->isVolatile()) || 3286 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3287 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3288 LN0->getChain(), LN0->getBasePtr(), 3289 MemVT, LN0->getMemOperand()); 3290 AddToWorklist(N); 3291 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3292 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3293 } 3294 } 3295 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3296 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3297 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3298 N0.getOperand(1), false)) 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 if (SDValue NewOp1 = 4336 distributeTruncateThroughAnd(N->getOperand(1).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 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4401 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4402 } 4403 4404 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4405 return SDValue(N, 0); 4406 4407 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4408 if (N1C && N0.getOpcode() == ISD::SHL) { 4409 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4410 uint64_t c1 = N0C1->getZExtValue(); 4411 uint64_t c2 = N1C->getZExtValue(); 4412 SDLoc DL(N); 4413 if (c1 + c2 >= OpSizeInBits) 4414 return DAG.getConstant(0, DL, VT); 4415 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4416 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4417 } 4418 } 4419 4420 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4421 // For this to be valid, the second form must not preserve any of the bits 4422 // that are shifted out by the inner shift in the first form. This means 4423 // the outer shift size must be >= the number of bits added by the ext. 4424 // As a corollary, we don't care what kind of ext it is. 4425 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4426 N0.getOpcode() == ISD::ANY_EXTEND || 4427 N0.getOpcode() == ISD::SIGN_EXTEND) && 4428 N0.getOperand(0).getOpcode() == ISD::SHL) { 4429 SDValue N0Op0 = N0.getOperand(0); 4430 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4431 uint64_t c1 = N0Op0C1->getZExtValue(); 4432 uint64_t c2 = N1C->getZExtValue(); 4433 EVT InnerShiftVT = N0Op0.getValueType(); 4434 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4435 if (c2 >= OpSizeInBits - InnerShiftSize) { 4436 SDLoc DL(N0); 4437 if (c1 + c2 >= OpSizeInBits) 4438 return DAG.getConstant(0, DL, VT); 4439 return DAG.getNode(ISD::SHL, DL, VT, 4440 DAG.getNode(N0.getOpcode(), DL, VT, 4441 N0Op0->getOperand(0)), 4442 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4443 } 4444 } 4445 } 4446 4447 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4448 // Only fold this if the inner zext has no other uses to avoid increasing 4449 // the total number of instructions. 4450 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4451 N0.getOperand(0).getOpcode() == ISD::SRL) { 4452 SDValue N0Op0 = N0.getOperand(0); 4453 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4454 uint64_t c1 = N0Op0C1->getZExtValue(); 4455 if (c1 < VT.getScalarSizeInBits()) { 4456 uint64_t c2 = N1C->getZExtValue(); 4457 if (c1 == c2) { 4458 SDValue NewOp0 = N0.getOperand(0); 4459 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4460 SDLoc DL(N); 4461 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4462 NewOp0, 4463 DAG.getConstant(c2, DL, CountVT)); 4464 AddToWorklist(NewSHL.getNode()); 4465 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4466 } 4467 } 4468 } 4469 } 4470 4471 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4472 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4473 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4474 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4475 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4476 uint64_t C1 = N0C1->getZExtValue(); 4477 uint64_t C2 = N1C->getZExtValue(); 4478 SDLoc DL(N); 4479 if (C1 <= C2) 4480 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4481 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4482 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4483 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4484 } 4485 } 4486 4487 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4488 // (and (srl x, (sub c1, c2), MASK) 4489 // Only fold this if the inner shift has no other uses -- if it does, folding 4490 // this will increase the total number of instructions. 4491 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4492 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4493 uint64_t c1 = N0C1->getZExtValue(); 4494 if (c1 < OpSizeInBits) { 4495 uint64_t c2 = N1C->getZExtValue(); 4496 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4497 SDValue Shift; 4498 if (c2 > c1) { 4499 Mask = Mask.shl(c2 - c1); 4500 SDLoc DL(N); 4501 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4502 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4503 } else { 4504 Mask = Mask.lshr(c1 - c2); 4505 SDLoc DL(N); 4506 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4507 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4508 } 4509 SDLoc DL(N0); 4510 return DAG.getNode(ISD::AND, DL, VT, Shift, 4511 DAG.getConstant(Mask, DL, VT)); 4512 } 4513 } 4514 } 4515 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4516 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4517 unsigned BitSize = VT.getScalarSizeInBits(); 4518 SDLoc DL(N); 4519 SDValue HiBitsMask = 4520 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4521 BitSize - N1C->getZExtValue()), 4522 DL, VT); 4523 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4524 HiBitsMask); 4525 } 4526 4527 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4528 // Variant of version done on multiply, except mul by a power of 2 is turned 4529 // into a shift. 4530 APInt Val; 4531 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4532 (isa<ConstantSDNode>(N0.getOperand(1)) || 4533 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4534 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4535 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4536 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4537 } 4538 4539 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4540 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4541 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4542 if (SDValue Folded = 4543 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4544 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4545 } 4546 } 4547 4548 if (N1C && !N1C->isOpaque()) 4549 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4550 return NewSHL; 4551 4552 return SDValue(); 4553 } 4554 4555 SDValue DAGCombiner::visitSRA(SDNode *N) { 4556 SDValue N0 = N->getOperand(0); 4557 SDValue N1 = N->getOperand(1); 4558 EVT VT = N0.getValueType(); 4559 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4560 4561 // fold vector ops 4562 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4563 if (VT.isVector()) { 4564 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4565 return FoldedVOp; 4566 4567 N1C = isConstOrConstSplat(N1); 4568 } 4569 4570 // fold (sra c1, c2) -> (sra c1, c2) 4571 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4572 if (N0C && N1C && !N1C->isOpaque()) 4573 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4574 // fold (sra 0, x) -> 0 4575 if (isNullConstant(N0)) 4576 return N0; 4577 // fold (sra -1, x) -> -1 4578 if (isAllOnesConstant(N0)) 4579 return N0; 4580 // fold (sra x, (setge c, size(x))) -> undef 4581 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4582 return DAG.getUNDEF(VT); 4583 // fold (sra x, 0) -> x 4584 if (N1C && N1C->isNullValue()) 4585 return N0; 4586 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4587 // sext_inreg. 4588 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4589 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4590 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4591 if (VT.isVector()) 4592 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4593 ExtVT, VT.getVectorNumElements()); 4594 if ((!LegalOperations || 4595 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4596 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4597 N0.getOperand(0), DAG.getValueType(ExtVT)); 4598 } 4599 4600 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4601 if (N1C && N0.getOpcode() == ISD::SRA) { 4602 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4603 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4604 if (Sum >= OpSizeInBits) 4605 Sum = OpSizeInBits - 1; 4606 SDLoc DL(N); 4607 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4608 DAG.getConstant(Sum, DL, N1.getValueType())); 4609 } 4610 } 4611 4612 // fold (sra (shl X, m), (sub result_size, n)) 4613 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4614 // result_size - n != m. 4615 // If truncate is free for the target sext(shl) is likely to result in better 4616 // code. 4617 if (N0.getOpcode() == ISD::SHL && N1C) { 4618 // Get the two constanst of the shifts, CN0 = m, CN = n. 4619 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4620 if (N01C) { 4621 LLVMContext &Ctx = *DAG.getContext(); 4622 // Determine what the truncate's result bitsize and type would be. 4623 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4624 4625 if (VT.isVector()) 4626 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4627 4628 // Determine the residual right-shift amount. 4629 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4630 4631 // If the shift is not a no-op (in which case this should be just a sign 4632 // extend already), the truncated to type is legal, sign_extend is legal 4633 // on that type, and the truncate to that type is both legal and free, 4634 // perform the transform. 4635 if ((ShiftAmt > 0) && 4636 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4637 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4638 TLI.isTruncateFree(VT, TruncVT)) { 4639 4640 SDLoc DL(N); 4641 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4642 getShiftAmountTy(N0.getOperand(0).getValueType())); 4643 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4644 N0.getOperand(0), Amt); 4645 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4646 Shift); 4647 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4648 N->getValueType(0), Trunc); 4649 } 4650 } 4651 } 4652 4653 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4654 if (N1.getOpcode() == ISD::TRUNCATE && 4655 N1.getOperand(0).getOpcode() == ISD::AND) { 4656 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4657 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4658 } 4659 4660 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4661 // if c1 is equal to the number of bits the trunc removes 4662 if (N0.getOpcode() == ISD::TRUNCATE && 4663 (N0.getOperand(0).getOpcode() == ISD::SRL || 4664 N0.getOperand(0).getOpcode() == ISD::SRA) && 4665 N0.getOperand(0).hasOneUse() && 4666 N0.getOperand(0).getOperand(1).hasOneUse() && 4667 N1C) { 4668 SDValue N0Op0 = N0.getOperand(0); 4669 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4670 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4671 EVT LargeVT = N0Op0.getValueType(); 4672 4673 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4674 SDLoc DL(N); 4675 SDValue Amt = 4676 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4677 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4678 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4679 N0Op0.getOperand(0), Amt); 4680 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4681 } 4682 } 4683 } 4684 4685 // Simplify, based on bits shifted out of the LHS. 4686 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4687 return SDValue(N, 0); 4688 4689 4690 // If the sign bit is known to be zero, switch this to a SRL. 4691 if (DAG.SignBitIsZero(N0)) 4692 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4693 4694 if (N1C && !N1C->isOpaque()) 4695 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4696 return NewSRA; 4697 4698 return SDValue(); 4699 } 4700 4701 SDValue DAGCombiner::visitSRL(SDNode *N) { 4702 SDValue N0 = N->getOperand(0); 4703 SDValue N1 = N->getOperand(1); 4704 EVT VT = N0.getValueType(); 4705 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4706 4707 // fold vector ops 4708 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4709 if (VT.isVector()) { 4710 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4711 return FoldedVOp; 4712 4713 N1C = isConstOrConstSplat(N1); 4714 } 4715 4716 // fold (srl c1, c2) -> c1 >>u c2 4717 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4718 if (N0C && N1C && !N1C->isOpaque()) 4719 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4720 // fold (srl 0, x) -> 0 4721 if (isNullConstant(N0)) 4722 return N0; 4723 // fold (srl x, c >= size(x)) -> undef 4724 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4725 return DAG.getUNDEF(VT); 4726 // fold (srl x, 0) -> x 4727 if (N1C && N1C->isNullValue()) 4728 return N0; 4729 // if (srl x, c) is known to be zero, return 0 4730 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4731 APInt::getAllOnesValue(OpSizeInBits))) 4732 return DAG.getConstant(0, SDLoc(N), VT); 4733 4734 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4735 if (N1C && N0.getOpcode() == ISD::SRL) { 4736 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4737 uint64_t c1 = N01C->getZExtValue(); 4738 uint64_t c2 = N1C->getZExtValue(); 4739 SDLoc DL(N); 4740 if (c1 + c2 >= OpSizeInBits) 4741 return DAG.getConstant(0, DL, VT); 4742 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4743 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4744 } 4745 } 4746 4747 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4748 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4749 N0.getOperand(0).getOpcode() == ISD::SRL && 4750 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4751 uint64_t c1 = 4752 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4753 uint64_t c2 = N1C->getZExtValue(); 4754 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4755 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4756 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4757 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4758 if (c1 + OpSizeInBits == InnerShiftSize) { 4759 SDLoc DL(N0); 4760 if (c1 + c2 >= InnerShiftSize) 4761 return DAG.getConstant(0, DL, VT); 4762 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4763 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4764 N0.getOperand(0)->getOperand(0), 4765 DAG.getConstant(c1 + c2, DL, 4766 ShiftCountVT))); 4767 } 4768 } 4769 4770 // fold (srl (shl x, c), c) -> (and x, cst2) 4771 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4772 unsigned BitSize = N0.getScalarValueSizeInBits(); 4773 if (BitSize <= 64) { 4774 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4775 SDLoc DL(N); 4776 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4777 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4778 } 4779 } 4780 4781 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4782 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4783 // Shifting in all undef bits? 4784 EVT SmallVT = N0.getOperand(0).getValueType(); 4785 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4786 if (N1C->getZExtValue() >= BitSize) 4787 return DAG.getUNDEF(VT); 4788 4789 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4790 uint64_t ShiftAmt = N1C->getZExtValue(); 4791 SDLoc DL0(N0); 4792 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4793 N0.getOperand(0), 4794 DAG.getConstant(ShiftAmt, DL0, 4795 getShiftAmountTy(SmallVT))); 4796 AddToWorklist(SmallShift.getNode()); 4797 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4798 SDLoc DL(N); 4799 return DAG.getNode(ISD::AND, DL, VT, 4800 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4801 DAG.getConstant(Mask, DL, VT)); 4802 } 4803 } 4804 4805 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4806 // bit, which is unmodified by sra. 4807 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4808 if (N0.getOpcode() == ISD::SRA) 4809 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4810 } 4811 4812 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4813 if (N1C && N0.getOpcode() == ISD::CTLZ && 4814 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4815 APInt KnownZero, KnownOne; 4816 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4817 4818 // If any of the input bits are KnownOne, then the input couldn't be all 4819 // zeros, thus the result of the srl will always be zero. 4820 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4821 4822 // If all of the bits input the to ctlz node are known to be zero, then 4823 // the result of the ctlz is "32" and the result of the shift is one. 4824 APInt UnknownBits = ~KnownZero; 4825 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4826 4827 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4828 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4829 // Okay, we know that only that the single bit specified by UnknownBits 4830 // could be set on input to the CTLZ node. If this bit is set, the SRL 4831 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4832 // to an SRL/XOR pair, which is likely to simplify more. 4833 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4834 SDValue Op = N0.getOperand(0); 4835 4836 if (ShAmt) { 4837 SDLoc DL(N0); 4838 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4839 DAG.getConstant(ShAmt, DL, 4840 getShiftAmountTy(Op.getValueType()))); 4841 AddToWorklist(Op.getNode()); 4842 } 4843 4844 SDLoc DL(N); 4845 return DAG.getNode(ISD::XOR, DL, VT, 4846 Op, DAG.getConstant(1, DL, VT)); 4847 } 4848 } 4849 4850 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4851 if (N1.getOpcode() == ISD::TRUNCATE && 4852 N1.getOperand(0).getOpcode() == ISD::AND) { 4853 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4854 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4855 } 4856 4857 // fold operands of srl based on knowledge that the low bits are not 4858 // demanded. 4859 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4860 return SDValue(N, 0); 4861 4862 if (N1C && !N1C->isOpaque()) 4863 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4864 return NewSRL; 4865 4866 // Attempt to convert a srl of a load into a narrower zero-extending load. 4867 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4868 return NarrowLoad; 4869 4870 // Here is a common situation. We want to optimize: 4871 // 4872 // %a = ... 4873 // %b = and i32 %a, 2 4874 // %c = srl i32 %b, 1 4875 // brcond i32 %c ... 4876 // 4877 // into 4878 // 4879 // %a = ... 4880 // %b = and %a, 2 4881 // %c = setcc eq %b, 0 4882 // brcond %c ... 4883 // 4884 // However when after the source operand of SRL is optimized into AND, the SRL 4885 // itself may not be optimized further. Look for it and add the BRCOND into 4886 // the worklist. 4887 if (N->hasOneUse()) { 4888 SDNode *Use = *N->use_begin(); 4889 if (Use->getOpcode() == ISD::BRCOND) 4890 AddToWorklist(Use); 4891 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4892 // Also look pass the truncate. 4893 Use = *Use->use_begin(); 4894 if (Use->getOpcode() == ISD::BRCOND) 4895 AddToWorklist(Use); 4896 } 4897 } 4898 4899 return SDValue(); 4900 } 4901 4902 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4903 SDValue N0 = N->getOperand(0); 4904 EVT VT = N->getValueType(0); 4905 4906 // fold (bswap c1) -> c2 4907 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4908 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4909 // fold (bswap (bswap x)) -> x 4910 if (N0.getOpcode() == ISD::BSWAP) 4911 return N0->getOperand(0); 4912 return SDValue(); 4913 } 4914 4915 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4916 SDValue N0 = N->getOperand(0); 4917 EVT VT = N->getValueType(0); 4918 4919 // fold (ctlz c1) -> c2 4920 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4921 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4922 return SDValue(); 4923 } 4924 4925 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4926 SDValue N0 = N->getOperand(0); 4927 EVT VT = N->getValueType(0); 4928 4929 // fold (ctlz_zero_undef c1) -> c2 4930 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4931 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4932 return SDValue(); 4933 } 4934 4935 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4936 SDValue N0 = N->getOperand(0); 4937 EVT VT = N->getValueType(0); 4938 4939 // fold (cttz c1) -> c2 4940 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4941 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4942 return SDValue(); 4943 } 4944 4945 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4946 SDValue N0 = N->getOperand(0); 4947 EVT VT = N->getValueType(0); 4948 4949 // fold (cttz_zero_undef c1) -> c2 4950 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4951 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4952 return SDValue(); 4953 } 4954 4955 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4956 SDValue N0 = N->getOperand(0); 4957 EVT VT = N->getValueType(0); 4958 4959 // fold (ctpop c1) -> c2 4960 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4961 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4962 return SDValue(); 4963 } 4964 4965 4966 /// \brief Generate Min/Max node 4967 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4968 SDValue True, SDValue False, 4969 ISD::CondCode CC, const TargetLowering &TLI, 4970 SelectionDAG &DAG) { 4971 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4972 return SDValue(); 4973 4974 switch (CC) { 4975 case ISD::SETOLT: 4976 case ISD::SETOLE: 4977 case ISD::SETLT: 4978 case ISD::SETLE: 4979 case ISD::SETULT: 4980 case ISD::SETULE: { 4981 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4982 if (TLI.isOperationLegal(Opcode, VT)) 4983 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4984 return SDValue(); 4985 } 4986 case ISD::SETOGT: 4987 case ISD::SETOGE: 4988 case ISD::SETGT: 4989 case ISD::SETGE: 4990 case ISD::SETUGT: 4991 case ISD::SETUGE: { 4992 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4993 if (TLI.isOperationLegal(Opcode, VT)) 4994 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4995 return SDValue(); 4996 } 4997 default: 4998 return SDValue(); 4999 } 5000 } 5001 5002 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5003 SDValue N0 = N->getOperand(0); 5004 SDValue N1 = N->getOperand(1); 5005 SDValue N2 = N->getOperand(2); 5006 EVT VT = N->getValueType(0); 5007 EVT VT0 = N0.getValueType(); 5008 5009 // fold (select C, X, X) -> X 5010 if (N1 == N2) 5011 return N1; 5012 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5013 // fold (select true, X, Y) -> X 5014 // fold (select false, X, Y) -> Y 5015 return !N0C->isNullValue() ? N1 : N2; 5016 } 5017 // fold (select C, 1, X) -> (or C, X) 5018 if (VT == MVT::i1 && isOneConstant(N1)) 5019 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5020 // fold (select C, 0, 1) -> (xor C, 1) 5021 // We can't do this reliably if integer based booleans have different contents 5022 // to floating point based booleans. This is because we can't tell whether we 5023 // have an integer-based boolean or a floating-point-based boolean unless we 5024 // can find the SETCC that produced it and inspect its operands. This is 5025 // fairly easy if C is the SETCC node, but it can potentially be 5026 // undiscoverable (or not reasonably discoverable). For example, it could be 5027 // in another basic block or it could require searching a complicated 5028 // expression. 5029 if (VT.isInteger() && 5030 (VT0 == MVT::i1 || (VT0.isInteger() && 5031 TLI.getBooleanContents(false, false) == 5032 TLI.getBooleanContents(false, true) && 5033 TLI.getBooleanContents(false, false) == 5034 TargetLowering::ZeroOrOneBooleanContent)) && 5035 isNullConstant(N1) && isOneConstant(N2)) { 5036 SDValue XORNode; 5037 if (VT == VT0) { 5038 SDLoc DL(N); 5039 return DAG.getNode(ISD::XOR, DL, VT0, 5040 N0, DAG.getConstant(1, DL, VT0)); 5041 } 5042 SDLoc DL0(N0); 5043 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5044 N0, DAG.getConstant(1, DL0, VT0)); 5045 AddToWorklist(XORNode.getNode()); 5046 if (VT.bitsGT(VT0)) 5047 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5048 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5049 } 5050 // fold (select C, 0, X) -> (and (not C), X) 5051 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5052 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5053 AddToWorklist(NOTNode.getNode()); 5054 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5055 } 5056 // fold (select C, X, 1) -> (or (not C), X) 5057 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5058 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5059 AddToWorklist(NOTNode.getNode()); 5060 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5061 } 5062 // fold (select C, X, 0) -> (and C, X) 5063 if (VT == MVT::i1 && isNullConstant(N2)) 5064 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5065 // fold (select X, X, Y) -> (or X, Y) 5066 // fold (select X, 1, Y) -> (or X, Y) 5067 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5068 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5069 // fold (select X, Y, X) -> (and X, Y) 5070 // fold (select X, Y, 0) -> (and X, Y) 5071 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5072 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5073 5074 // If we can fold this based on the true/false value, do so. 5075 if (SimplifySelectOps(N, N1, N2)) 5076 return SDValue(N, 0); // Don't revisit N. 5077 5078 if (VT0 == MVT::i1) { 5079 // The code in this block deals with the following 2 equivalences: 5080 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5081 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5082 // The target can specify its prefered form with the 5083 // shouldNormalizeToSelectSequence() callback. However we always transform 5084 // to the right anyway if we find the inner select exists in the DAG anyway 5085 // and we always transform to the left side if we know that we can further 5086 // optimize the combination of the conditions. 5087 bool normalizeToSequence 5088 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5089 // select (and Cond0, Cond1), X, Y 5090 // -> select Cond0, (select Cond1, X, Y), Y 5091 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5092 SDValue Cond0 = N0->getOperand(0); 5093 SDValue Cond1 = N0->getOperand(1); 5094 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5095 N1.getValueType(), Cond1, N1, N2); 5096 if (normalizeToSequence || !InnerSelect.use_empty()) 5097 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5098 InnerSelect, N2); 5099 } 5100 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5101 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5102 SDValue Cond0 = N0->getOperand(0); 5103 SDValue Cond1 = N0->getOperand(1); 5104 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5105 N1.getValueType(), Cond1, N1, N2); 5106 if (normalizeToSequence || !InnerSelect.use_empty()) 5107 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5108 InnerSelect); 5109 } 5110 5111 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5112 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5113 SDValue N1_0 = N1->getOperand(0); 5114 SDValue N1_1 = N1->getOperand(1); 5115 SDValue N1_2 = N1->getOperand(2); 5116 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5117 // Create the actual and node if we can generate good code for it. 5118 if (!normalizeToSequence) { 5119 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5120 N0, N1_0); 5121 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5122 N1_1, N2); 5123 } 5124 // Otherwise see if we can optimize the "and" to a better pattern. 5125 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5126 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5127 N1_1, N2); 5128 } 5129 } 5130 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5131 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5132 SDValue N2_0 = N2->getOperand(0); 5133 SDValue N2_1 = N2->getOperand(1); 5134 SDValue N2_2 = N2->getOperand(2); 5135 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5136 // Create the actual or node if we can generate good code for it. 5137 if (!normalizeToSequence) { 5138 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5139 N0, N2_0); 5140 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5141 N1, N2_2); 5142 } 5143 // Otherwise see if we can optimize to a better pattern. 5144 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5145 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5146 N1, N2_2); 5147 } 5148 } 5149 } 5150 5151 // fold selects based on a setcc into other things, such as min/max/abs 5152 if (N0.getOpcode() == ISD::SETCC) { 5153 // select x, y (fcmp lt x, y) -> fminnum x, y 5154 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5155 // 5156 // This is OK if we don't care about what happens if either operand is a 5157 // NaN. 5158 // 5159 5160 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5161 // no signed zeros as well as no nans. 5162 const TargetOptions &Options = DAG.getTarget().Options; 5163 if (Options.UnsafeFPMath && 5164 VT.isFloatingPoint() && N0.hasOneUse() && 5165 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5166 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5167 5168 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5169 N0.getOperand(1), N1, N2, CC, 5170 TLI, DAG)) 5171 return FMinMax; 5172 } 5173 5174 if ((!LegalOperations && 5175 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5176 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5177 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5178 N0.getOperand(0), N0.getOperand(1), 5179 N1, N2, N0.getOperand(2)); 5180 return SimplifySelect(SDLoc(N), N0, N1, N2); 5181 } 5182 5183 return SDValue(); 5184 } 5185 5186 static 5187 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5188 SDLoc DL(N); 5189 EVT LoVT, HiVT; 5190 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5191 5192 // Split the inputs. 5193 SDValue Lo, Hi, LL, LH, RL, RH; 5194 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5195 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5196 5197 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5198 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5199 5200 return std::make_pair(Lo, Hi); 5201 } 5202 5203 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5204 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5205 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5206 SDLoc dl(N); 5207 SDValue Cond = N->getOperand(0); 5208 SDValue LHS = N->getOperand(1); 5209 SDValue RHS = N->getOperand(2); 5210 EVT VT = N->getValueType(0); 5211 int NumElems = VT.getVectorNumElements(); 5212 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5213 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5214 Cond.getOpcode() == ISD::BUILD_VECTOR); 5215 5216 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5217 // binary ones here. 5218 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5219 return SDValue(); 5220 5221 // We're sure we have an even number of elements due to the 5222 // concat_vectors we have as arguments to vselect. 5223 // Skip BV elements until we find one that's not an UNDEF 5224 // After we find an UNDEF element, keep looping until we get to half the 5225 // length of the BV and see if all the non-undef nodes are the same. 5226 ConstantSDNode *BottomHalf = nullptr; 5227 for (int i = 0; i < NumElems / 2; ++i) { 5228 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5229 continue; 5230 5231 if (BottomHalf == nullptr) 5232 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5233 else if (Cond->getOperand(i).getNode() != BottomHalf) 5234 return SDValue(); 5235 } 5236 5237 // Do the same for the second half of the BuildVector 5238 ConstantSDNode *TopHalf = nullptr; 5239 for (int i = NumElems / 2; i < NumElems; ++i) { 5240 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5241 continue; 5242 5243 if (TopHalf == nullptr) 5244 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5245 else if (Cond->getOperand(i).getNode() != TopHalf) 5246 return SDValue(); 5247 } 5248 5249 assert(TopHalf && BottomHalf && 5250 "One half of the selector was all UNDEFs and the other was all the " 5251 "same value. This should have been addressed before this function."); 5252 return DAG.getNode( 5253 ISD::CONCAT_VECTORS, dl, VT, 5254 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5255 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5256 } 5257 5258 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5259 5260 if (Level >= AfterLegalizeTypes) 5261 return SDValue(); 5262 5263 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5264 SDValue Mask = MSC->getMask(); 5265 SDValue Data = MSC->getValue(); 5266 SDLoc DL(N); 5267 5268 // If the MSCATTER data type requires splitting and the mask is provided by a 5269 // SETCC, then split both nodes and its operands before legalization. This 5270 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5271 // and enables future optimizations (e.g. min/max pattern matching on X86). 5272 if (Mask.getOpcode() != ISD::SETCC) 5273 return SDValue(); 5274 5275 // Check if any splitting is required. 5276 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5277 TargetLowering::TypeSplitVector) 5278 return SDValue(); 5279 SDValue MaskLo, MaskHi, Lo, Hi; 5280 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5281 5282 EVT LoVT, HiVT; 5283 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5284 5285 SDValue Chain = MSC->getChain(); 5286 5287 EVT MemoryVT = MSC->getMemoryVT(); 5288 unsigned Alignment = MSC->getOriginalAlignment(); 5289 5290 EVT LoMemVT, HiMemVT; 5291 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5292 5293 SDValue DataLo, DataHi; 5294 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5295 5296 SDValue BasePtr = MSC->getBasePtr(); 5297 SDValue IndexLo, IndexHi; 5298 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5299 5300 MachineMemOperand *MMO = DAG.getMachineFunction(). 5301 getMachineMemOperand(MSC->getPointerInfo(), 5302 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5303 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5304 5305 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5306 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5307 DL, OpsLo, MMO); 5308 5309 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5310 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5311 DL, OpsHi, MMO); 5312 5313 AddToWorklist(Lo.getNode()); 5314 AddToWorklist(Hi.getNode()); 5315 5316 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5317 } 5318 5319 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5320 5321 if (Level >= AfterLegalizeTypes) 5322 return SDValue(); 5323 5324 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5325 SDValue Mask = MST->getMask(); 5326 SDValue Data = MST->getValue(); 5327 SDLoc DL(N); 5328 5329 // If the MSTORE data type requires splitting and the mask is provided by a 5330 // SETCC, then split both nodes and its operands before legalization. This 5331 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5332 // and enables future optimizations (e.g. min/max pattern matching on X86). 5333 if (Mask.getOpcode() == ISD::SETCC) { 5334 5335 // Check if any splitting is required. 5336 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5337 TargetLowering::TypeSplitVector) 5338 return SDValue(); 5339 5340 SDValue MaskLo, MaskHi, Lo, Hi; 5341 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5342 5343 EVT LoVT, HiVT; 5344 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5345 5346 SDValue Chain = MST->getChain(); 5347 SDValue Ptr = MST->getBasePtr(); 5348 5349 EVT MemoryVT = MST->getMemoryVT(); 5350 unsigned Alignment = MST->getOriginalAlignment(); 5351 5352 // if Alignment is equal to the vector size, 5353 // take the half of it for the second part 5354 unsigned SecondHalfAlignment = 5355 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5356 Alignment/2 : Alignment; 5357 5358 EVT LoMemVT, HiMemVT; 5359 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5360 5361 SDValue DataLo, DataHi; 5362 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5363 5364 MachineMemOperand *MMO = DAG.getMachineFunction(). 5365 getMachineMemOperand(MST->getPointerInfo(), 5366 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5367 Alignment, MST->getAAInfo(), MST->getRanges()); 5368 5369 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5370 MST->isTruncatingStore()); 5371 5372 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5373 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5374 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5375 5376 MMO = DAG.getMachineFunction(). 5377 getMachineMemOperand(MST->getPointerInfo(), 5378 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5379 SecondHalfAlignment, MST->getAAInfo(), 5380 MST->getRanges()); 5381 5382 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5383 MST->isTruncatingStore()); 5384 5385 AddToWorklist(Lo.getNode()); 5386 AddToWorklist(Hi.getNode()); 5387 5388 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5389 } 5390 return SDValue(); 5391 } 5392 5393 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5394 5395 if (Level >= AfterLegalizeTypes) 5396 return SDValue(); 5397 5398 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5399 SDValue Mask = MGT->getMask(); 5400 SDLoc DL(N); 5401 5402 // If the MGATHER result requires splitting and the mask is provided by a 5403 // SETCC, then split both nodes and its operands before legalization. This 5404 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5405 // and enables future optimizations (e.g. min/max pattern matching on X86). 5406 5407 if (Mask.getOpcode() != ISD::SETCC) 5408 return SDValue(); 5409 5410 EVT VT = N->getValueType(0); 5411 5412 // Check if any splitting is required. 5413 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5414 TargetLowering::TypeSplitVector) 5415 return SDValue(); 5416 5417 SDValue MaskLo, MaskHi, Lo, Hi; 5418 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5419 5420 SDValue Src0 = MGT->getValue(); 5421 SDValue Src0Lo, Src0Hi; 5422 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5423 5424 EVT LoVT, HiVT; 5425 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5426 5427 SDValue Chain = MGT->getChain(); 5428 EVT MemoryVT = MGT->getMemoryVT(); 5429 unsigned Alignment = MGT->getOriginalAlignment(); 5430 5431 EVT LoMemVT, HiMemVT; 5432 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5433 5434 SDValue BasePtr = MGT->getBasePtr(); 5435 SDValue Index = MGT->getIndex(); 5436 SDValue IndexLo, IndexHi; 5437 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5438 5439 MachineMemOperand *MMO = DAG.getMachineFunction(). 5440 getMachineMemOperand(MGT->getPointerInfo(), 5441 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5442 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5443 5444 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5445 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5446 MMO); 5447 5448 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5449 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5450 MMO); 5451 5452 AddToWorklist(Lo.getNode()); 5453 AddToWorklist(Hi.getNode()); 5454 5455 // Build a factor node to remember that this load is independent of the 5456 // other one. 5457 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5458 Hi.getValue(1)); 5459 5460 // Legalized the chain result - switch anything that used the old chain to 5461 // use the new one. 5462 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5463 5464 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5465 5466 SDValue RetOps[] = { GatherRes, Chain }; 5467 return DAG.getMergeValues(RetOps, DL); 5468 } 5469 5470 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5471 5472 if (Level >= AfterLegalizeTypes) 5473 return SDValue(); 5474 5475 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5476 SDValue Mask = MLD->getMask(); 5477 SDLoc DL(N); 5478 5479 // If the MLOAD result requires splitting and the mask is provided by a 5480 // SETCC, then split both nodes and its operands before legalization. This 5481 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5482 // and enables future optimizations (e.g. min/max pattern matching on X86). 5483 5484 if (Mask.getOpcode() == ISD::SETCC) { 5485 EVT VT = N->getValueType(0); 5486 5487 // Check if any splitting is required. 5488 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5489 TargetLowering::TypeSplitVector) 5490 return SDValue(); 5491 5492 SDValue MaskLo, MaskHi, Lo, Hi; 5493 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5494 5495 SDValue Src0 = MLD->getSrc0(); 5496 SDValue Src0Lo, Src0Hi; 5497 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5498 5499 EVT LoVT, HiVT; 5500 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5501 5502 SDValue Chain = MLD->getChain(); 5503 SDValue Ptr = MLD->getBasePtr(); 5504 EVT MemoryVT = MLD->getMemoryVT(); 5505 unsigned Alignment = MLD->getOriginalAlignment(); 5506 5507 // if Alignment is equal to the vector size, 5508 // take the half of it for the second part 5509 unsigned SecondHalfAlignment = 5510 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5511 Alignment/2 : Alignment; 5512 5513 EVT LoMemVT, HiMemVT; 5514 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5515 5516 MachineMemOperand *MMO = DAG.getMachineFunction(). 5517 getMachineMemOperand(MLD->getPointerInfo(), 5518 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5519 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5520 5521 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5522 ISD::NON_EXTLOAD); 5523 5524 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5525 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5526 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5527 5528 MMO = DAG.getMachineFunction(). 5529 getMachineMemOperand(MLD->getPointerInfo(), 5530 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5531 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5532 5533 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5534 ISD::NON_EXTLOAD); 5535 5536 AddToWorklist(Lo.getNode()); 5537 AddToWorklist(Hi.getNode()); 5538 5539 // Build a factor node to remember that this load is independent of the 5540 // other one. 5541 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5542 Hi.getValue(1)); 5543 5544 // Legalized the chain result - switch anything that used the old chain to 5545 // use the new one. 5546 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5547 5548 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5549 5550 SDValue RetOps[] = { LoadRes, Chain }; 5551 return DAG.getMergeValues(RetOps, DL); 5552 } 5553 return SDValue(); 5554 } 5555 5556 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5557 SDValue N0 = N->getOperand(0); 5558 SDValue N1 = N->getOperand(1); 5559 SDValue N2 = N->getOperand(2); 5560 SDLoc DL(N); 5561 5562 // Canonicalize integer abs. 5563 // vselect (setg[te] X, 0), X, -X -> 5564 // vselect (setgt X, -1), X, -X -> 5565 // vselect (setl[te] X, 0), -X, X -> 5566 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5567 if (N0.getOpcode() == ISD::SETCC) { 5568 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5569 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5570 bool isAbs = false; 5571 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5572 5573 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5574 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5575 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5576 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5577 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5578 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5579 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5580 5581 if (isAbs) { 5582 EVT VT = LHS.getValueType(); 5583 SDValue Shift = DAG.getNode( 5584 ISD::SRA, DL, VT, LHS, 5585 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5586 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5587 AddToWorklist(Shift.getNode()); 5588 AddToWorklist(Add.getNode()); 5589 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5590 } 5591 } 5592 5593 if (SimplifySelectOps(N, N1, N2)) 5594 return SDValue(N, 0); // Don't revisit N. 5595 5596 // If the VSELECT result requires splitting and the mask is provided by a 5597 // SETCC, then split both nodes and its operands before legalization. This 5598 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5599 // and enables future optimizations (e.g. min/max pattern matching on X86). 5600 if (N0.getOpcode() == ISD::SETCC) { 5601 EVT VT = N->getValueType(0); 5602 5603 // Check if any splitting is required. 5604 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5605 TargetLowering::TypeSplitVector) 5606 return SDValue(); 5607 5608 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5609 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5610 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5611 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5612 5613 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5614 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5615 5616 // Add the new VSELECT nodes to the work list in case they need to be split 5617 // again. 5618 AddToWorklist(Lo.getNode()); 5619 AddToWorklist(Hi.getNode()); 5620 5621 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5622 } 5623 5624 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5625 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5626 return N1; 5627 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5628 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5629 return N2; 5630 5631 // The ConvertSelectToConcatVector function is assuming both the above 5632 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5633 // and addressed. 5634 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5635 N2.getOpcode() == ISD::CONCAT_VECTORS && 5636 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5637 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5638 return CV; 5639 } 5640 5641 return SDValue(); 5642 } 5643 5644 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5645 SDValue N0 = N->getOperand(0); 5646 SDValue N1 = N->getOperand(1); 5647 SDValue N2 = N->getOperand(2); 5648 SDValue N3 = N->getOperand(3); 5649 SDValue N4 = N->getOperand(4); 5650 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5651 5652 // fold select_cc lhs, rhs, x, x, cc -> x 5653 if (N2 == N3) 5654 return N2; 5655 5656 // Determine if the condition we're dealing with is constant 5657 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5658 CC, SDLoc(N), false)) { 5659 AddToWorklist(SCC.getNode()); 5660 5661 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5662 if (!SCCC->isNullValue()) 5663 return N2; // cond always true -> true val 5664 else 5665 return N3; // cond always false -> false val 5666 } else if (SCC->getOpcode() == ISD::UNDEF) { 5667 // When the condition is UNDEF, just return the first operand. This is 5668 // coherent the DAG creation, no setcc node is created in this case 5669 return N2; 5670 } else if (SCC.getOpcode() == ISD::SETCC) { 5671 // Fold to a simpler select_cc 5672 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5673 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5674 SCC.getOperand(2)); 5675 } 5676 } 5677 5678 // If we can fold this based on the true/false value, do so. 5679 if (SimplifySelectOps(N, N2, N3)) 5680 return SDValue(N, 0); // Don't revisit N. 5681 5682 // fold select_cc into other things, such as min/max/abs 5683 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5684 } 5685 5686 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5687 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5688 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5689 SDLoc(N)); 5690 } 5691 5692 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5693 SDValue LHS = N->getOperand(0); 5694 SDValue RHS = N->getOperand(1); 5695 SDValue Carry = N->getOperand(2); 5696 SDValue Cond = N->getOperand(3); 5697 5698 // If Carry is false, fold to a regular SETCC. 5699 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5700 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5701 5702 return SDValue(); 5703 } 5704 5705 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5706 /// a build_vector of constants. 5707 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5708 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5709 /// Vector extends are not folded if operations are legal; this is to 5710 /// avoid introducing illegal build_vector dag nodes. 5711 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5712 SelectionDAG &DAG, bool LegalTypes, 5713 bool LegalOperations) { 5714 unsigned Opcode = N->getOpcode(); 5715 SDValue N0 = N->getOperand(0); 5716 EVT VT = N->getValueType(0); 5717 5718 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5719 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5720 && "Expected EXTEND dag node in input!"); 5721 5722 // fold (sext c1) -> c1 5723 // fold (zext c1) -> c1 5724 // fold (aext c1) -> c1 5725 if (isa<ConstantSDNode>(N0)) 5726 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5727 5728 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5729 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5730 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5731 EVT SVT = VT.getScalarType(); 5732 if (!(VT.isVector() && 5733 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5734 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5735 return nullptr; 5736 5737 // We can fold this node into a build_vector. 5738 unsigned VTBits = SVT.getSizeInBits(); 5739 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5740 SmallVector<SDValue, 8> Elts; 5741 unsigned NumElts = VT.getVectorNumElements(); 5742 SDLoc DL(N); 5743 5744 for (unsigned i=0; i != NumElts; ++i) { 5745 SDValue Op = N0->getOperand(i); 5746 if (Op->getOpcode() == ISD::UNDEF) { 5747 Elts.push_back(DAG.getUNDEF(SVT)); 5748 continue; 5749 } 5750 5751 SDLoc DL(Op); 5752 // Get the constant value and if needed trunc it to the size of the type. 5753 // Nodes like build_vector might have constants wider than the scalar type. 5754 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5755 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5756 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5757 else 5758 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5759 } 5760 5761 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5762 } 5763 5764 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5765 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5766 // transformation. Returns true if extension are possible and the above 5767 // mentioned transformation is profitable. 5768 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5769 unsigned ExtOpc, 5770 SmallVectorImpl<SDNode *> &ExtendNodes, 5771 const TargetLowering &TLI) { 5772 bool HasCopyToRegUses = false; 5773 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5774 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5775 UE = N0.getNode()->use_end(); 5776 UI != UE; ++UI) { 5777 SDNode *User = *UI; 5778 if (User == N) 5779 continue; 5780 if (UI.getUse().getResNo() != N0.getResNo()) 5781 continue; 5782 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5783 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5784 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5785 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5786 // Sign bits will be lost after a zext. 5787 return false; 5788 bool Add = false; 5789 for (unsigned i = 0; i != 2; ++i) { 5790 SDValue UseOp = User->getOperand(i); 5791 if (UseOp == N0) 5792 continue; 5793 if (!isa<ConstantSDNode>(UseOp)) 5794 return false; 5795 Add = true; 5796 } 5797 if (Add) 5798 ExtendNodes.push_back(User); 5799 continue; 5800 } 5801 // If truncates aren't free and there are users we can't 5802 // extend, it isn't worthwhile. 5803 if (!isTruncFree) 5804 return false; 5805 // Remember if this value is live-out. 5806 if (User->getOpcode() == ISD::CopyToReg) 5807 HasCopyToRegUses = true; 5808 } 5809 5810 if (HasCopyToRegUses) { 5811 bool BothLiveOut = false; 5812 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5813 UI != UE; ++UI) { 5814 SDUse &Use = UI.getUse(); 5815 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5816 BothLiveOut = true; 5817 break; 5818 } 5819 } 5820 if (BothLiveOut) 5821 // Both unextended and extended values are live out. There had better be 5822 // a good reason for the transformation. 5823 return ExtendNodes.size(); 5824 } 5825 return true; 5826 } 5827 5828 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5829 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5830 ISD::NodeType ExtType) { 5831 // Extend SetCC uses if necessary. 5832 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5833 SDNode *SetCC = SetCCs[i]; 5834 SmallVector<SDValue, 4> Ops; 5835 5836 for (unsigned j = 0; j != 2; ++j) { 5837 SDValue SOp = SetCC->getOperand(j); 5838 if (SOp == Trunc) 5839 Ops.push_back(ExtLoad); 5840 else 5841 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5842 } 5843 5844 Ops.push_back(SetCC->getOperand(2)); 5845 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5846 } 5847 } 5848 5849 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5850 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5851 SDValue N0 = N->getOperand(0); 5852 EVT DstVT = N->getValueType(0); 5853 EVT SrcVT = N0.getValueType(); 5854 5855 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5856 N->getOpcode() == ISD::ZERO_EXTEND) && 5857 "Unexpected node type (not an extend)!"); 5858 5859 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5860 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5861 // (v8i32 (sext (v8i16 (load x)))) 5862 // into: 5863 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5864 // (v4i32 (sextload (x + 16))))) 5865 // Where uses of the original load, i.e.: 5866 // (v8i16 (load x)) 5867 // are replaced with: 5868 // (v8i16 (truncate 5869 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5870 // (v4i32 (sextload (x + 16))))))) 5871 // 5872 // This combine is only applicable to illegal, but splittable, vectors. 5873 // All legal types, and illegal non-vector types, are handled elsewhere. 5874 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5875 // 5876 if (N0->getOpcode() != ISD::LOAD) 5877 return SDValue(); 5878 5879 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5880 5881 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5882 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5883 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5884 return SDValue(); 5885 5886 SmallVector<SDNode *, 4> SetCCs; 5887 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5888 return SDValue(); 5889 5890 ISD::LoadExtType ExtType = 5891 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5892 5893 // Try to split the vector types to get down to legal types. 5894 EVT SplitSrcVT = SrcVT; 5895 EVT SplitDstVT = DstVT; 5896 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5897 SplitSrcVT.getVectorNumElements() > 1) { 5898 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5899 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5900 } 5901 5902 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5903 return SDValue(); 5904 5905 SDLoc DL(N); 5906 const unsigned NumSplits = 5907 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5908 const unsigned Stride = SplitSrcVT.getStoreSize(); 5909 SmallVector<SDValue, 4> Loads; 5910 SmallVector<SDValue, 4> Chains; 5911 5912 SDValue BasePtr = LN0->getBasePtr(); 5913 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5914 const unsigned Offset = Idx * Stride; 5915 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5916 5917 SDValue SplitLoad = DAG.getExtLoad( 5918 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5919 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5920 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5921 Align, LN0->getAAInfo()); 5922 5923 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5924 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5925 5926 Loads.push_back(SplitLoad.getValue(0)); 5927 Chains.push_back(SplitLoad.getValue(1)); 5928 } 5929 5930 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5931 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5932 5933 CombineTo(N, NewValue); 5934 5935 // Replace uses of the original load (before extension) 5936 // with a truncate of the concatenated sextloaded vectors. 5937 SDValue Trunc = 5938 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5939 CombineTo(N0.getNode(), Trunc, NewChain); 5940 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5941 (ISD::NodeType)N->getOpcode()); 5942 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5943 } 5944 5945 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5946 SDValue N0 = N->getOperand(0); 5947 EVT VT = N->getValueType(0); 5948 5949 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5950 LegalOperations)) 5951 return SDValue(Res, 0); 5952 5953 // fold (sext (sext x)) -> (sext x) 5954 // fold (sext (aext x)) -> (sext x) 5955 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5956 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5957 N0.getOperand(0)); 5958 5959 if (N0.getOpcode() == ISD::TRUNCATE) { 5960 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5961 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5962 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5963 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5964 if (NarrowLoad.getNode() != N0.getNode()) { 5965 CombineTo(N0.getNode(), NarrowLoad); 5966 // CombineTo deleted the truncate, if needed, but not what's under it. 5967 AddToWorklist(oye); 5968 } 5969 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5970 } 5971 5972 // See if the value being truncated is already sign extended. If so, just 5973 // eliminate the trunc/sext pair. 5974 SDValue Op = N0.getOperand(0); 5975 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5976 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5977 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5978 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5979 5980 if (OpBits == DestBits) { 5981 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5982 // bits, it is already ready. 5983 if (NumSignBits > DestBits-MidBits) 5984 return Op; 5985 } else if (OpBits < DestBits) { 5986 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5987 // bits, just sext from i32. 5988 if (NumSignBits > OpBits-MidBits) 5989 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5990 } else { 5991 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5992 // bits, just truncate to i32. 5993 if (NumSignBits > OpBits-MidBits) 5994 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5995 } 5996 5997 // fold (sext (truncate x)) -> (sextinreg x). 5998 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5999 N0.getValueType())) { 6000 if (OpBits < DestBits) 6001 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6002 else if (OpBits > DestBits) 6003 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6004 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6005 DAG.getValueType(N0.getValueType())); 6006 } 6007 } 6008 6009 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6010 // Only generate vector extloads when 1) they're legal, and 2) they are 6011 // deemed desirable by the target. 6012 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6013 ((!LegalOperations && !VT.isVector() && 6014 !cast<LoadSDNode>(N0)->isVolatile()) || 6015 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6016 bool DoXform = true; 6017 SmallVector<SDNode*, 4> SetCCs; 6018 if (!N0.hasOneUse()) 6019 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6020 if (VT.isVector()) 6021 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6022 if (DoXform) { 6023 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6024 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6025 LN0->getChain(), 6026 LN0->getBasePtr(), N0.getValueType(), 6027 LN0->getMemOperand()); 6028 CombineTo(N, ExtLoad); 6029 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6030 N0.getValueType(), ExtLoad); 6031 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6032 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6033 ISD::SIGN_EXTEND); 6034 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6035 } 6036 } 6037 6038 // fold (sext (load x)) to multiple smaller sextloads. 6039 // Only on illegal but splittable vectors. 6040 if (SDValue ExtLoad = CombineExtLoad(N)) 6041 return ExtLoad; 6042 6043 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6044 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6045 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6046 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6047 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6048 EVT MemVT = LN0->getMemoryVT(); 6049 if ((!LegalOperations && !LN0->isVolatile()) || 6050 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6051 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6052 LN0->getChain(), 6053 LN0->getBasePtr(), MemVT, 6054 LN0->getMemOperand()); 6055 CombineTo(N, ExtLoad); 6056 CombineTo(N0.getNode(), 6057 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6058 N0.getValueType(), ExtLoad), 6059 ExtLoad.getValue(1)); 6060 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6061 } 6062 } 6063 6064 // fold (sext (and/or/xor (load x), cst)) -> 6065 // (and/or/xor (sextload x), (sext cst)) 6066 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6067 N0.getOpcode() == ISD::XOR) && 6068 isa<LoadSDNode>(N0.getOperand(0)) && 6069 N0.getOperand(1).getOpcode() == ISD::Constant && 6070 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6071 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6072 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6073 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6074 bool DoXform = true; 6075 SmallVector<SDNode*, 4> SetCCs; 6076 if (!N0.hasOneUse()) 6077 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6078 SetCCs, TLI); 6079 if (DoXform) { 6080 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6081 LN0->getChain(), LN0->getBasePtr(), 6082 LN0->getMemoryVT(), 6083 LN0->getMemOperand()); 6084 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6085 Mask = Mask.sext(VT.getSizeInBits()); 6086 SDLoc DL(N); 6087 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6088 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6089 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6090 SDLoc(N0.getOperand(0)), 6091 N0.getOperand(0).getValueType(), ExtLoad); 6092 CombineTo(N, And); 6093 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6094 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6095 ISD::SIGN_EXTEND); 6096 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6097 } 6098 } 6099 } 6100 6101 if (N0.getOpcode() == ISD::SETCC) { 6102 EVT N0VT = N0.getOperand(0).getValueType(); 6103 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6104 // Only do this before legalize for now. 6105 if (VT.isVector() && !LegalOperations && 6106 TLI.getBooleanContents(N0VT) == 6107 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6108 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6109 // of the same size as the compared operands. Only optimize sext(setcc()) 6110 // if this is the case. 6111 EVT SVT = getSetCCResultType(N0VT); 6112 6113 // We know that the # elements of the results is the same as the 6114 // # elements of the compare (and the # elements of the compare result 6115 // for that matter). Check to see that they are the same size. If so, 6116 // we know that the element size of the sext'd result matches the 6117 // element size of the compare operands. 6118 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6119 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6120 N0.getOperand(1), 6121 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6122 6123 // If the desired elements are smaller or larger than the source 6124 // elements we can use a matching integer vector type and then 6125 // truncate/sign extend 6126 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6127 if (SVT == MatchingVectorType) { 6128 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6129 N0.getOperand(0), N0.getOperand(1), 6130 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6131 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6132 } 6133 } 6134 6135 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6136 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6137 SDLoc DL(N); 6138 SDValue NegOne = 6139 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6140 if (SDValue SCC = SimplifySelectCC( 6141 DL, N0.getOperand(0), N0.getOperand(1), NegOne, 6142 DAG.getConstant(0, DL, VT), 6143 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6144 return SCC; 6145 6146 if (!VT.isVector()) { 6147 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6148 if (!LegalOperations || 6149 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6150 SDLoc DL(N); 6151 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6152 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6153 N0.getOperand(0), N0.getOperand(1), CC); 6154 return DAG.getSelect(DL, VT, SetCC, 6155 NegOne, DAG.getConstant(0, DL, VT)); 6156 } 6157 } 6158 } 6159 6160 // fold (sext x) -> (zext x) if the sign bit is known zero. 6161 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6162 DAG.SignBitIsZero(N0)) 6163 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6164 6165 return SDValue(); 6166 } 6167 6168 // isTruncateOf - If N is a truncate of some other value, return true, record 6169 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6170 // This function computes KnownZero to avoid a duplicated call to 6171 // computeKnownBits in the caller. 6172 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6173 APInt &KnownZero) { 6174 APInt KnownOne; 6175 if (N->getOpcode() == ISD::TRUNCATE) { 6176 Op = N->getOperand(0); 6177 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6178 return true; 6179 } 6180 6181 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6182 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6183 return false; 6184 6185 SDValue Op0 = N->getOperand(0); 6186 SDValue Op1 = N->getOperand(1); 6187 assert(Op0.getValueType() == Op1.getValueType()); 6188 6189 if (isNullConstant(Op0)) 6190 Op = Op1; 6191 else if (isNullConstant(Op1)) 6192 Op = Op0; 6193 else 6194 return false; 6195 6196 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6197 6198 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6199 return false; 6200 6201 return true; 6202 } 6203 6204 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6205 SDValue N0 = N->getOperand(0); 6206 EVT VT = N->getValueType(0); 6207 6208 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6209 LegalOperations)) 6210 return SDValue(Res, 0); 6211 6212 // fold (zext (zext x)) -> (zext x) 6213 // fold (zext (aext x)) -> (zext x) 6214 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6215 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6216 N0.getOperand(0)); 6217 6218 // fold (zext (truncate x)) -> (zext x) or 6219 // (zext (truncate x)) -> (truncate x) 6220 // This is valid when the truncated bits of x are already zero. 6221 // FIXME: We should extend this to work for vectors too. 6222 SDValue Op; 6223 APInt KnownZero; 6224 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6225 APInt TruncatedBits = 6226 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6227 APInt(Op.getValueSizeInBits(), 0) : 6228 APInt::getBitsSet(Op.getValueSizeInBits(), 6229 N0.getValueSizeInBits(), 6230 std::min(Op.getValueSizeInBits(), 6231 VT.getSizeInBits())); 6232 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6233 if (VT.bitsGT(Op.getValueType())) 6234 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6235 if (VT.bitsLT(Op.getValueType())) 6236 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6237 6238 return Op; 6239 } 6240 } 6241 6242 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6243 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6244 if (N0.getOpcode() == ISD::TRUNCATE) { 6245 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6246 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6247 if (NarrowLoad.getNode() != N0.getNode()) { 6248 CombineTo(N0.getNode(), NarrowLoad); 6249 // CombineTo deleted the truncate, if needed, but not what's under it. 6250 AddToWorklist(oye); 6251 } 6252 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6253 } 6254 } 6255 6256 // fold (zext (truncate x)) -> (and x, mask) 6257 if (N0.getOpcode() == ISD::TRUNCATE) { 6258 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6259 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6260 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6261 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6262 if (NarrowLoad.getNode() != N0.getNode()) { 6263 CombineTo(N0.getNode(), NarrowLoad); 6264 // CombineTo deleted the truncate, if needed, but not what's under it. 6265 AddToWorklist(oye); 6266 } 6267 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6268 } 6269 6270 EVT SrcVT = N0.getOperand(0).getValueType(); 6271 EVT MinVT = N0.getValueType(); 6272 6273 // Try to mask before the extension to avoid having to generate a larger mask, 6274 // possibly over several sub-vectors. 6275 if (SrcVT.bitsLT(VT)) { 6276 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6277 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6278 SDValue Op = N0.getOperand(0); 6279 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6280 AddToWorklist(Op.getNode()); 6281 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6282 } 6283 } 6284 6285 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6286 SDValue Op = N0.getOperand(0); 6287 if (SrcVT.bitsLT(VT)) { 6288 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6289 AddToWorklist(Op.getNode()); 6290 } else if (SrcVT.bitsGT(VT)) { 6291 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6292 AddToWorklist(Op.getNode()); 6293 } 6294 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6295 } 6296 } 6297 6298 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6299 // if either of the casts is not free. 6300 if (N0.getOpcode() == ISD::AND && 6301 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6302 N0.getOperand(1).getOpcode() == ISD::Constant && 6303 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6304 N0.getValueType()) || 6305 !TLI.isZExtFree(N0.getValueType(), VT))) { 6306 SDValue X = N0.getOperand(0).getOperand(0); 6307 if (X.getValueType().bitsLT(VT)) { 6308 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6309 } else if (X.getValueType().bitsGT(VT)) { 6310 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6311 } 6312 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6313 Mask = Mask.zext(VT.getSizeInBits()); 6314 SDLoc DL(N); 6315 return DAG.getNode(ISD::AND, DL, VT, 6316 X, DAG.getConstant(Mask, DL, VT)); 6317 } 6318 6319 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6320 // Only generate vector extloads when 1) they're legal, and 2) they are 6321 // deemed desirable by the target. 6322 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6323 ((!LegalOperations && !VT.isVector() && 6324 !cast<LoadSDNode>(N0)->isVolatile()) || 6325 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6326 bool DoXform = true; 6327 SmallVector<SDNode*, 4> SetCCs; 6328 if (!N0.hasOneUse()) 6329 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6330 if (VT.isVector()) 6331 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6332 if (DoXform) { 6333 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6334 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6335 LN0->getChain(), 6336 LN0->getBasePtr(), N0.getValueType(), 6337 LN0->getMemOperand()); 6338 CombineTo(N, ExtLoad); 6339 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6340 N0.getValueType(), ExtLoad); 6341 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6342 6343 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6344 ISD::ZERO_EXTEND); 6345 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6346 } 6347 } 6348 6349 // fold (zext (load x)) to multiple smaller zextloads. 6350 // Only on illegal but splittable vectors. 6351 if (SDValue ExtLoad = CombineExtLoad(N)) 6352 return ExtLoad; 6353 6354 // fold (zext (and/or/xor (load x), cst)) -> 6355 // (and/or/xor (zextload x), (zext cst)) 6356 // Unless (and (load x) cst) will match as a zextload already and has 6357 // additional users. 6358 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6359 N0.getOpcode() == ISD::XOR) && 6360 isa<LoadSDNode>(N0.getOperand(0)) && 6361 N0.getOperand(1).getOpcode() == ISD::Constant && 6362 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6363 (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) { 6364 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6365 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6366 bool DoXform = true; 6367 SmallVector<SDNode*, 4> SetCCs; 6368 if (!N0.hasOneUse()) { 6369 if (N0.getOpcode() == ISD::AND) { 6370 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6371 auto NarrowLoad = false; 6372 EVT LoadResultTy = AndC->getValueType(0); 6373 EVT ExtVT, LoadedVT; 6374 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6375 NarrowLoad)) 6376 DoXform = false; 6377 } 6378 if (DoXform) 6379 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6380 ISD::ZERO_EXTEND, SetCCs, TLI); 6381 } 6382 if (DoXform) { 6383 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6384 LN0->getChain(), LN0->getBasePtr(), 6385 LN0->getMemoryVT(), 6386 LN0->getMemOperand()); 6387 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6388 Mask = Mask.zext(VT.getSizeInBits()); 6389 SDLoc DL(N); 6390 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6391 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6392 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6393 SDLoc(N0.getOperand(0)), 6394 N0.getOperand(0).getValueType(), ExtLoad); 6395 CombineTo(N, And); 6396 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6397 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6398 ISD::ZERO_EXTEND); 6399 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6400 } 6401 } 6402 } 6403 6404 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6405 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6406 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6407 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6408 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6409 EVT MemVT = LN0->getMemoryVT(); 6410 if ((!LegalOperations && !LN0->isVolatile()) || 6411 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6413 LN0->getChain(), 6414 LN0->getBasePtr(), MemVT, 6415 LN0->getMemOperand()); 6416 CombineTo(N, ExtLoad); 6417 CombineTo(N0.getNode(), 6418 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6419 ExtLoad), 6420 ExtLoad.getValue(1)); 6421 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6422 } 6423 } 6424 6425 if (N0.getOpcode() == ISD::SETCC) { 6426 if (!LegalOperations && VT.isVector() && 6427 N0.getValueType().getVectorElementType() == MVT::i1) { 6428 EVT N0VT = N0.getOperand(0).getValueType(); 6429 if (getSetCCResultType(N0VT) == N0.getValueType()) 6430 return SDValue(); 6431 6432 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6433 // Only do this before legalize for now. 6434 SDLoc DL(N); 6435 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6436 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6437 // We know that the # elements of the results is the same as the 6438 // # elements of the compare (and the # elements of the compare result 6439 // for that matter). Check to see that they are the same size. If so, 6440 // we know that the element size of the sext'd result matches the 6441 // element size of the compare operands. 6442 return DAG.getNode(ISD::AND, DL, VT, 6443 DAG.getSetCC(DL, VT, N0.getOperand(0), 6444 N0.getOperand(1), 6445 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6446 VecOnes); 6447 6448 // If the desired elements are smaller or larger than the source 6449 // elements we can use a matching integer vector type and then 6450 // truncate/sign extend 6451 EVT MatchingElementType = 6452 EVT::getIntegerVT(*DAG.getContext(), 6453 N0VT.getScalarType().getSizeInBits()); 6454 EVT MatchingVectorType = 6455 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6456 N0VT.getVectorNumElements()); 6457 SDValue VsetCC = 6458 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6459 N0.getOperand(1), 6460 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6461 return DAG.getNode(ISD::AND, DL, VT, 6462 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6463 VecOnes); 6464 } 6465 6466 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6467 SDLoc DL(N); 6468 if (SDValue SCC = SimplifySelectCC( 6469 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6470 DAG.getConstant(0, DL, VT), 6471 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6472 return SCC; 6473 } 6474 6475 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6476 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6477 isa<ConstantSDNode>(N0.getOperand(1)) && 6478 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6479 N0.hasOneUse()) { 6480 SDValue ShAmt = N0.getOperand(1); 6481 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6482 if (N0.getOpcode() == ISD::SHL) { 6483 SDValue InnerZExt = N0.getOperand(0); 6484 // If the original shl may be shifting out bits, do not perform this 6485 // transformation. 6486 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6487 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6488 if (ShAmtVal > KnownZeroBits) 6489 return SDValue(); 6490 } 6491 6492 SDLoc DL(N); 6493 6494 // Ensure that the shift amount is wide enough for the shifted value. 6495 if (VT.getSizeInBits() >= 256) 6496 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6497 6498 return DAG.getNode(N0.getOpcode(), DL, VT, 6499 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6500 ShAmt); 6501 } 6502 6503 return SDValue(); 6504 } 6505 6506 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6507 SDValue N0 = N->getOperand(0); 6508 EVT VT = N->getValueType(0); 6509 6510 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6511 LegalOperations)) 6512 return SDValue(Res, 0); 6513 6514 // fold (aext (aext x)) -> (aext x) 6515 // fold (aext (zext x)) -> (zext x) 6516 // fold (aext (sext x)) -> (sext x) 6517 if (N0.getOpcode() == ISD::ANY_EXTEND || 6518 N0.getOpcode() == ISD::ZERO_EXTEND || 6519 N0.getOpcode() == ISD::SIGN_EXTEND) 6520 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6521 6522 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6523 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6524 if (N0.getOpcode() == ISD::TRUNCATE) { 6525 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6526 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6527 if (NarrowLoad.getNode() != N0.getNode()) { 6528 CombineTo(N0.getNode(), NarrowLoad); 6529 // CombineTo deleted the truncate, if needed, but not what's under it. 6530 AddToWorklist(oye); 6531 } 6532 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6533 } 6534 } 6535 6536 // fold (aext (truncate x)) 6537 if (N0.getOpcode() == ISD::TRUNCATE) { 6538 SDValue TruncOp = N0.getOperand(0); 6539 if (TruncOp.getValueType() == VT) 6540 return TruncOp; // x iff x size == zext size. 6541 if (TruncOp.getValueType().bitsGT(VT)) 6542 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6543 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6544 } 6545 6546 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6547 // if the trunc is not free. 6548 if (N0.getOpcode() == ISD::AND && 6549 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6550 N0.getOperand(1).getOpcode() == ISD::Constant && 6551 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6552 N0.getValueType())) { 6553 SDValue X = N0.getOperand(0).getOperand(0); 6554 if (X.getValueType().bitsLT(VT)) { 6555 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6556 } else if (X.getValueType().bitsGT(VT)) { 6557 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6558 } 6559 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6560 Mask = Mask.zext(VT.getSizeInBits()); 6561 SDLoc DL(N); 6562 return DAG.getNode(ISD::AND, DL, VT, 6563 X, DAG.getConstant(Mask, DL, VT)); 6564 } 6565 6566 // fold (aext (load x)) -> (aext (truncate (extload x))) 6567 // None of the supported targets knows how to perform load and any_ext 6568 // on vectors in one instruction. We only perform this transformation on 6569 // scalars. 6570 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6571 ISD::isUNINDEXEDLoad(N0.getNode()) && 6572 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6573 bool DoXform = true; 6574 SmallVector<SDNode*, 4> SetCCs; 6575 if (!N0.hasOneUse()) 6576 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6577 if (DoXform) { 6578 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6579 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6580 LN0->getChain(), 6581 LN0->getBasePtr(), N0.getValueType(), 6582 LN0->getMemOperand()); 6583 CombineTo(N, ExtLoad); 6584 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6585 N0.getValueType(), ExtLoad); 6586 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6587 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6588 ISD::ANY_EXTEND); 6589 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6590 } 6591 } 6592 6593 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6594 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6595 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6596 if (N0.getOpcode() == ISD::LOAD && 6597 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6598 N0.hasOneUse()) { 6599 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6600 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6601 EVT MemVT = LN0->getMemoryVT(); 6602 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6603 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6604 VT, LN0->getChain(), LN0->getBasePtr(), 6605 MemVT, LN0->getMemOperand()); 6606 CombineTo(N, ExtLoad); 6607 CombineTo(N0.getNode(), 6608 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6609 N0.getValueType(), ExtLoad), 6610 ExtLoad.getValue(1)); 6611 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6612 } 6613 } 6614 6615 if (N0.getOpcode() == ISD::SETCC) { 6616 // For vectors: 6617 // aext(setcc) -> vsetcc 6618 // aext(setcc) -> truncate(vsetcc) 6619 // aext(setcc) -> aext(vsetcc) 6620 // Only do this before legalize for now. 6621 if (VT.isVector() && !LegalOperations) { 6622 EVT N0VT = N0.getOperand(0).getValueType(); 6623 // We know that the # elements of the results is the same as the 6624 // # elements of the compare (and the # elements of the compare result 6625 // for that matter). Check to see that they are the same size. If so, 6626 // we know that the element size of the sext'd result matches the 6627 // element size of the compare operands. 6628 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6629 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6630 N0.getOperand(1), 6631 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6632 // If the desired elements are smaller or larger than the source 6633 // elements we can use a matching integer vector type and then 6634 // truncate/any extend 6635 else { 6636 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6637 SDValue VsetCC = 6638 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6639 N0.getOperand(1), 6640 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6641 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6642 } 6643 } 6644 6645 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6646 SDLoc DL(N); 6647 if (SDValue SCC = SimplifySelectCC( 6648 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6649 DAG.getConstant(0, DL, VT), 6650 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6651 return SCC; 6652 } 6653 6654 return SDValue(); 6655 } 6656 6657 /// See if the specified operand can be simplified with the knowledge that only 6658 /// the bits specified by Mask are used. If so, return the simpler operand, 6659 /// otherwise return a null SDValue. 6660 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6661 switch (V.getOpcode()) { 6662 default: break; 6663 case ISD::Constant: { 6664 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6665 assert(CV && "Const value should be ConstSDNode."); 6666 const APInt &CVal = CV->getAPIntValue(); 6667 APInt NewVal = CVal & Mask; 6668 if (NewVal != CVal) 6669 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6670 break; 6671 } 6672 case ISD::OR: 6673 case ISD::XOR: 6674 // If the LHS or RHS don't contribute bits to the or, drop them. 6675 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6676 return V.getOperand(1); 6677 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6678 return V.getOperand(0); 6679 break; 6680 case ISD::SRL: 6681 // Only look at single-use SRLs. 6682 if (!V.getNode()->hasOneUse()) 6683 break; 6684 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6685 // See if we can recursively simplify the LHS. 6686 unsigned Amt = RHSC->getZExtValue(); 6687 6688 // Watch out for shift count overflow though. 6689 if (Amt >= Mask.getBitWidth()) break; 6690 APInt NewMask = Mask << Amt; 6691 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6692 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6693 SimplifyLHS, V.getOperand(1)); 6694 } 6695 } 6696 return SDValue(); 6697 } 6698 6699 /// If the result of a wider load is shifted to right of N bits and then 6700 /// truncated to a narrower type and where N is a multiple of number of bits of 6701 /// the narrower type, transform it to a narrower load from address + N / num of 6702 /// bits of new type. If the result is to be extended, also fold the extension 6703 /// to form a extending load. 6704 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6705 unsigned Opc = N->getOpcode(); 6706 6707 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6708 SDValue N0 = N->getOperand(0); 6709 EVT VT = N->getValueType(0); 6710 EVT ExtVT = VT; 6711 6712 // This transformation isn't valid for vector loads. 6713 if (VT.isVector()) 6714 return SDValue(); 6715 6716 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6717 // extended to VT. 6718 if (Opc == ISD::SIGN_EXTEND_INREG) { 6719 ExtType = ISD::SEXTLOAD; 6720 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6721 } else if (Opc == ISD::SRL) { 6722 // Another special-case: SRL is basically zero-extending a narrower value. 6723 ExtType = ISD::ZEXTLOAD; 6724 N0 = SDValue(N, 0); 6725 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6726 if (!N01) return SDValue(); 6727 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6728 VT.getSizeInBits() - N01->getZExtValue()); 6729 } 6730 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6731 return SDValue(); 6732 6733 unsigned EVTBits = ExtVT.getSizeInBits(); 6734 6735 // Do not generate loads of non-round integer types since these can 6736 // be expensive (and would be wrong if the type is not byte sized). 6737 if (!ExtVT.isRound()) 6738 return SDValue(); 6739 6740 unsigned ShAmt = 0; 6741 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6742 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6743 ShAmt = N01->getZExtValue(); 6744 // Is the shift amount a multiple of size of VT? 6745 if ((ShAmt & (EVTBits-1)) == 0) { 6746 N0 = N0.getOperand(0); 6747 // Is the load width a multiple of size of VT? 6748 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6749 return SDValue(); 6750 } 6751 6752 // At this point, we must have a load or else we can't do the transform. 6753 if (!isa<LoadSDNode>(N0)) return SDValue(); 6754 6755 // Because a SRL must be assumed to *need* to zero-extend the high bits 6756 // (as opposed to anyext the high bits), we can't combine the zextload 6757 // lowering of SRL and an sextload. 6758 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6759 return SDValue(); 6760 6761 // If the shift amount is larger than the input type then we're not 6762 // accessing any of the loaded bytes. If the load was a zextload/extload 6763 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6764 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6765 return SDValue(); 6766 } 6767 } 6768 6769 // If the load is shifted left (and the result isn't shifted back right), 6770 // we can fold the truncate through the shift. 6771 unsigned ShLeftAmt = 0; 6772 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6773 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6774 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6775 ShLeftAmt = N01->getZExtValue(); 6776 N0 = N0.getOperand(0); 6777 } 6778 } 6779 6780 // If we haven't found a load, we can't narrow it. Don't transform one with 6781 // multiple uses, this would require adding a new load. 6782 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6783 return SDValue(); 6784 6785 // Don't change the width of a volatile load. 6786 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6787 if (LN0->isVolatile()) 6788 return SDValue(); 6789 6790 // Verify that we are actually reducing a load width here. 6791 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6792 return SDValue(); 6793 6794 // For the transform to be legal, the load must produce only two values 6795 // (the value loaded and the chain). Don't transform a pre-increment 6796 // load, for example, which produces an extra value. Otherwise the 6797 // transformation is not equivalent, and the downstream logic to replace 6798 // uses gets things wrong. 6799 if (LN0->getNumValues() > 2) 6800 return SDValue(); 6801 6802 // If the load that we're shrinking is an extload and we're not just 6803 // discarding the extension we can't simply shrink the load. Bail. 6804 // TODO: It would be possible to merge the extensions in some cases. 6805 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6806 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6807 return SDValue(); 6808 6809 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6810 return SDValue(); 6811 6812 EVT PtrType = N0.getOperand(1).getValueType(); 6813 6814 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6815 // It's not possible to generate a constant of extended or untyped type. 6816 return SDValue(); 6817 6818 // For big endian targets, we need to adjust the offset to the pointer to 6819 // load the correct bytes. 6820 if (DAG.getDataLayout().isBigEndian()) { 6821 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6822 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6823 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6824 } 6825 6826 uint64_t PtrOff = ShAmt / 8; 6827 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6828 SDLoc DL(LN0); 6829 // The original load itself didn't wrap, so an offset within it doesn't. 6830 SDNodeFlags Flags; 6831 Flags.setNoUnsignedWrap(true); 6832 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6833 PtrType, LN0->getBasePtr(), 6834 DAG.getConstant(PtrOff, DL, PtrType), 6835 &Flags); 6836 AddToWorklist(NewPtr.getNode()); 6837 6838 SDValue Load; 6839 if (ExtType == ISD::NON_EXTLOAD) 6840 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6841 LN0->getPointerInfo().getWithOffset(PtrOff), 6842 LN0->isVolatile(), LN0->isNonTemporal(), 6843 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6844 else 6845 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6846 LN0->getPointerInfo().getWithOffset(PtrOff), 6847 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6848 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6849 6850 // Replace the old load's chain with the new load's chain. 6851 WorklistRemover DeadNodes(*this); 6852 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6853 6854 // Shift the result left, if we've swallowed a left shift. 6855 SDValue Result = Load; 6856 if (ShLeftAmt != 0) { 6857 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6858 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6859 ShImmTy = VT; 6860 // If the shift amount is as large as the result size (but, presumably, 6861 // no larger than the source) then the useful bits of the result are 6862 // zero; we can't simply return the shortened shift, because the result 6863 // of that operation is undefined. 6864 SDLoc DL(N0); 6865 if (ShLeftAmt >= VT.getSizeInBits()) 6866 Result = DAG.getConstant(0, DL, VT); 6867 else 6868 Result = DAG.getNode(ISD::SHL, DL, VT, 6869 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6870 } 6871 6872 // Return the new loaded value. 6873 return Result; 6874 } 6875 6876 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6877 SDValue N0 = N->getOperand(0); 6878 SDValue N1 = N->getOperand(1); 6879 EVT VT = N->getValueType(0); 6880 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6881 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6882 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6883 6884 if (N0.isUndef()) 6885 return DAG.getUNDEF(VT); 6886 6887 // fold (sext_in_reg c1) -> c1 6888 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6889 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6890 6891 // If the input is already sign extended, just drop the extension. 6892 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6893 return N0; 6894 6895 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6896 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6897 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6898 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6899 N0.getOperand(0), N1); 6900 6901 // fold (sext_in_reg (sext x)) -> (sext x) 6902 // fold (sext_in_reg (aext x)) -> (sext x) 6903 // if x is small enough. 6904 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6905 SDValue N00 = N0.getOperand(0); 6906 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6907 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6908 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6909 } 6910 6911 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6912 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6913 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6914 6915 // fold operands of sext_in_reg based on knowledge that the top bits are not 6916 // demanded. 6917 if (SimplifyDemandedBits(SDValue(N, 0))) 6918 return SDValue(N, 0); 6919 6920 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6921 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6922 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6923 return NarrowLoad; 6924 6925 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6926 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6927 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6928 if (N0.getOpcode() == ISD::SRL) { 6929 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6930 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6931 // We can turn this into an SRA iff the input to the SRL is already sign 6932 // extended enough. 6933 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6934 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6935 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6936 N0.getOperand(0), N0.getOperand(1)); 6937 } 6938 } 6939 6940 // fold (sext_inreg (extload x)) -> (sextload x) 6941 if (ISD::isEXTLoad(N0.getNode()) && 6942 ISD::isUNINDEXEDLoad(N0.getNode()) && 6943 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6944 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6945 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6946 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6947 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6948 LN0->getChain(), 6949 LN0->getBasePtr(), EVT, 6950 LN0->getMemOperand()); 6951 CombineTo(N, ExtLoad); 6952 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6953 AddToWorklist(ExtLoad.getNode()); 6954 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6955 } 6956 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6957 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6958 N0.hasOneUse() && 6959 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6960 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6961 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6962 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6963 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6964 LN0->getChain(), 6965 LN0->getBasePtr(), EVT, 6966 LN0->getMemOperand()); 6967 CombineTo(N, ExtLoad); 6968 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6969 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6970 } 6971 6972 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6973 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6974 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6975 N0.getOperand(1), false)) 6976 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6977 BSwap, N1); 6978 } 6979 6980 return SDValue(); 6981 } 6982 6983 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 6984 SDValue N0 = N->getOperand(0); 6985 EVT VT = N->getValueType(0); 6986 6987 if (N0.getOpcode() == ISD::UNDEF) 6988 return DAG.getUNDEF(VT); 6989 6990 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6991 LegalOperations)) 6992 return SDValue(Res, 0); 6993 6994 return SDValue(); 6995 } 6996 6997 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6998 SDValue N0 = N->getOperand(0); 6999 EVT VT = N->getValueType(0); 7000 bool isLE = DAG.getDataLayout().isLittleEndian(); 7001 7002 // noop truncate 7003 if (N0.getValueType() == N->getValueType(0)) 7004 return N0; 7005 // fold (truncate c1) -> c1 7006 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7007 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7008 // fold (truncate (truncate x)) -> (truncate x) 7009 if (N0.getOpcode() == ISD::TRUNCATE) 7010 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7011 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7012 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7013 N0.getOpcode() == ISD::SIGN_EXTEND || 7014 N0.getOpcode() == ISD::ANY_EXTEND) { 7015 // if the source is smaller than the dest, we still need an extend. 7016 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7017 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7018 // if the source is larger than the dest, than we just need the truncate. 7019 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7020 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7021 // if the source and dest are the same type, we can drop both the extend 7022 // and the truncate. 7023 return N0.getOperand(0); 7024 } 7025 7026 // Fold extract-and-trunc into a narrow extract. For example: 7027 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7028 // i32 y = TRUNCATE(i64 x) 7029 // -- becomes -- 7030 // v16i8 b = BITCAST (v2i64 val) 7031 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7032 // 7033 // Note: We only run this optimization after type legalization (which often 7034 // creates this pattern) and before operation legalization after which 7035 // we need to be more careful about the vector instructions that we generate. 7036 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7037 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7038 7039 EVT VecTy = N0.getOperand(0).getValueType(); 7040 EVT ExTy = N0.getValueType(); 7041 EVT TrTy = N->getValueType(0); 7042 7043 unsigned NumElem = VecTy.getVectorNumElements(); 7044 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7045 7046 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7047 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7048 7049 SDValue EltNo = N0->getOperand(1); 7050 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7051 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7052 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7053 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7054 7055 SDLoc DL(N); 7056 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7057 DAG.getBitcast(NVT, N0.getOperand(0)), 7058 DAG.getConstant(Index, DL, IndexTy)); 7059 } 7060 } 7061 7062 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7063 if (N0.getOpcode() == ISD::SELECT) { 7064 EVT SrcVT = N0.getValueType(); 7065 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7066 TLI.isTruncateFree(SrcVT, VT)) { 7067 SDLoc SL(N0); 7068 SDValue Cond = N0.getOperand(0); 7069 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7070 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7071 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7072 } 7073 } 7074 7075 // Fold a series of buildvector, bitcast, and truncate if possible. 7076 // For example fold 7077 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7078 // (2xi32 (buildvector x, y)). 7079 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7080 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7081 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7082 N0.getOperand(0).hasOneUse()) { 7083 7084 SDValue BuildVect = N0.getOperand(0); 7085 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7086 EVT TruncVecEltTy = VT.getVectorElementType(); 7087 7088 // Check that the element types match. 7089 if (BuildVectEltTy == TruncVecEltTy) { 7090 // Now we only need to compute the offset of the truncated elements. 7091 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7092 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7093 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7094 7095 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7096 "Invalid number of elements"); 7097 7098 SmallVector<SDValue, 8> Opnds; 7099 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7100 Opnds.push_back(BuildVect.getOperand(i)); 7101 7102 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 7103 } 7104 } 7105 7106 // See if we can simplify the input to this truncate through knowledge that 7107 // only the low bits are being used. 7108 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7109 // Currently we only perform this optimization on scalars because vectors 7110 // may have different active low bits. 7111 if (!VT.isVector()) { 7112 if (SDValue Shorter = 7113 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7114 VT.getSizeInBits()))) 7115 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7116 } 7117 // fold (truncate (load x)) -> (smaller load x) 7118 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7119 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7120 if (SDValue Reduced = ReduceLoadWidth(N)) 7121 return Reduced; 7122 7123 // Handle the case where the load remains an extending load even 7124 // after truncation. 7125 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7126 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7127 if (!LN0->isVolatile() && 7128 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7129 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7130 VT, LN0->getChain(), LN0->getBasePtr(), 7131 LN0->getMemoryVT(), 7132 LN0->getMemOperand()); 7133 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7134 return NewLoad; 7135 } 7136 } 7137 } 7138 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7139 // where ... are all 'undef'. 7140 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7141 SmallVector<EVT, 8> VTs; 7142 SDValue V; 7143 unsigned Idx = 0; 7144 unsigned NumDefs = 0; 7145 7146 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7147 SDValue X = N0.getOperand(i); 7148 if (X.getOpcode() != ISD::UNDEF) { 7149 V = X; 7150 Idx = i; 7151 NumDefs++; 7152 } 7153 // Stop if more than one members are non-undef. 7154 if (NumDefs > 1) 7155 break; 7156 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7157 VT.getVectorElementType(), 7158 X.getValueType().getVectorNumElements())); 7159 } 7160 7161 if (NumDefs == 0) 7162 return DAG.getUNDEF(VT); 7163 7164 if (NumDefs == 1) { 7165 assert(V.getNode() && "The single defined operand is empty!"); 7166 SmallVector<SDValue, 8> Opnds; 7167 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7168 if (i != Idx) { 7169 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7170 continue; 7171 } 7172 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7173 AddToWorklist(NV.getNode()); 7174 Opnds.push_back(NV); 7175 } 7176 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7177 } 7178 } 7179 7180 // Fold truncate of a bitcast of a vector to an extract of the low vector 7181 // element. 7182 // 7183 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7184 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7185 SDValue VecSrc = N0.getOperand(0); 7186 EVT SrcVT = VecSrc.getValueType(); 7187 if (SrcVT.isVector() && SrcVT.getScalarType() == VT) { 7188 SDLoc SL(N); 7189 7190 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7191 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7192 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7193 } 7194 } 7195 7196 // Simplify the operands using demanded-bits information. 7197 if (!VT.isVector() && 7198 SimplifyDemandedBits(SDValue(N, 0))) 7199 return SDValue(N, 0); 7200 7201 return SDValue(); 7202 } 7203 7204 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7205 SDValue Elt = N->getOperand(i); 7206 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7207 return Elt.getNode(); 7208 return Elt.getOperand(Elt.getResNo()).getNode(); 7209 } 7210 7211 /// build_pair (load, load) -> load 7212 /// if load locations are consecutive. 7213 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7214 assert(N->getOpcode() == ISD::BUILD_PAIR); 7215 7216 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7217 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7218 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7219 LD1->getAddressSpace() != LD2->getAddressSpace()) 7220 return SDValue(); 7221 EVT LD1VT = LD1->getValueType(0); 7222 7223 if (ISD::isNON_EXTLoad(LD2) && 7224 LD2->hasOneUse() && 7225 // If both are volatile this would reduce the number of volatile loads. 7226 // If one is volatile it might be ok, but play conservative and bail out. 7227 !LD1->isVolatile() && 7228 !LD2->isVolatile() && 7229 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7230 unsigned Align = LD1->getAlignment(); 7231 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7232 VT.getTypeForEVT(*DAG.getContext())); 7233 7234 if (NewAlign <= Align && 7235 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7236 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7237 LD1->getBasePtr(), LD1->getPointerInfo(), 7238 false, false, false, Align); 7239 } 7240 7241 return SDValue(); 7242 } 7243 7244 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7245 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7246 // and Lo parts; on big-endian machines it doesn't. 7247 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7248 } 7249 7250 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7251 SDValue N0 = N->getOperand(0); 7252 EVT VT = N->getValueType(0); 7253 7254 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7255 // Only do this before legalize, since afterward the target may be depending 7256 // on the bitconvert. 7257 // First check to see if this is all constant. 7258 if (!LegalTypes && 7259 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7260 VT.isVector()) { 7261 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7262 7263 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7264 assert(!DestEltVT.isVector() && 7265 "Element type of vector ValueType must not be vector!"); 7266 if (isSimple) 7267 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7268 } 7269 7270 // If the input is a constant, let getNode fold it. 7271 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7272 // If we can't allow illegal operations, we need to check that this is just 7273 // a fp -> int or int -> conversion and that the resulting operation will 7274 // be legal. 7275 if (!LegalOperations || 7276 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7277 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7278 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7279 TLI.isOperationLegal(ISD::Constant, VT))) 7280 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7281 } 7282 7283 // (conv (conv x, t1), t2) -> (conv x, t2) 7284 if (N0.getOpcode() == ISD::BITCAST) 7285 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7286 N0.getOperand(0)); 7287 7288 // fold (conv (load x)) -> (load (conv*)x) 7289 // If the resultant load doesn't need a higher alignment than the original! 7290 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7291 // Do not change the width of a volatile load. 7292 !cast<LoadSDNode>(N0)->isVolatile() && 7293 // Do not remove the cast if the types differ in endian layout. 7294 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7295 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7296 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7297 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7298 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7299 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7300 VT.getTypeForEVT(*DAG.getContext())); 7301 unsigned OrigAlign = LN0->getAlignment(); 7302 7303 if (Align <= OrigAlign) { 7304 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7305 LN0->getBasePtr(), LN0->getPointerInfo(), 7306 LN0->isVolatile(), LN0->isNonTemporal(), 7307 LN0->isInvariant(), OrigAlign, 7308 LN0->getAAInfo()); 7309 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7310 return Load; 7311 } 7312 } 7313 7314 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7315 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7316 // 7317 // For ppc_fp128: 7318 // fold (bitcast (fneg x)) -> 7319 // flipbit = signbit 7320 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7321 // 7322 // fold (bitcast (fabs x)) -> 7323 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7324 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7325 // This often reduces constant pool loads. 7326 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7327 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7328 N0.getNode()->hasOneUse() && VT.isInteger() && 7329 !VT.isVector() && !N0.getValueType().isVector()) { 7330 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7331 N0.getOperand(0)); 7332 AddToWorklist(NewConv.getNode()); 7333 7334 SDLoc DL(N); 7335 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7336 assert(VT.getSizeInBits() == 128); 7337 SDValue SignBit = DAG.getConstant( 7338 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7339 SDValue FlipBit; 7340 if (N0.getOpcode() == ISD::FNEG) { 7341 FlipBit = SignBit; 7342 AddToWorklist(FlipBit.getNode()); 7343 } else { 7344 assert(N0.getOpcode() == ISD::FABS); 7345 SDValue Hi = 7346 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7347 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7348 SDLoc(NewConv))); 7349 AddToWorklist(Hi.getNode()); 7350 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7351 AddToWorklist(FlipBit.getNode()); 7352 } 7353 SDValue FlipBits = 7354 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7355 AddToWorklist(FlipBits.getNode()); 7356 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7357 } 7358 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7359 if (N0.getOpcode() == ISD::FNEG) 7360 return DAG.getNode(ISD::XOR, DL, VT, 7361 NewConv, DAG.getConstant(SignBit, DL, VT)); 7362 assert(N0.getOpcode() == ISD::FABS); 7363 return DAG.getNode(ISD::AND, DL, VT, 7364 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7365 } 7366 7367 // fold (bitconvert (fcopysign cst, x)) -> 7368 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7369 // Note that we don't handle (copysign x, cst) because this can always be 7370 // folded to an fneg or fabs. 7371 // 7372 // For ppc_fp128: 7373 // fold (bitcast (fcopysign cst, x)) -> 7374 // flipbit = (and (extract_element 7375 // (xor (bitcast cst), (bitcast x)), 0), 7376 // signbit) 7377 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7378 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7379 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7380 VT.isInteger() && !VT.isVector()) { 7381 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7382 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7383 if (isTypeLegal(IntXVT)) { 7384 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7385 IntXVT, N0.getOperand(1)); 7386 AddToWorklist(X.getNode()); 7387 7388 // If X has a different width than the result/lhs, sext it or truncate it. 7389 unsigned VTWidth = VT.getSizeInBits(); 7390 if (OrigXWidth < VTWidth) { 7391 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7392 AddToWorklist(X.getNode()); 7393 } else if (OrigXWidth > VTWidth) { 7394 // To get the sign bit in the right place, we have to shift it right 7395 // before truncating. 7396 SDLoc DL(X); 7397 X = DAG.getNode(ISD::SRL, DL, 7398 X.getValueType(), X, 7399 DAG.getConstant(OrigXWidth-VTWidth, DL, 7400 X.getValueType())); 7401 AddToWorklist(X.getNode()); 7402 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7403 AddToWorklist(X.getNode()); 7404 } 7405 7406 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7407 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7408 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7409 AddToWorklist(Cst.getNode()); 7410 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7411 AddToWorklist(X.getNode()); 7412 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7413 AddToWorklist(XorResult.getNode()); 7414 SDValue XorResult64 = DAG.getNode( 7415 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7416 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7417 SDLoc(XorResult))); 7418 AddToWorklist(XorResult64.getNode()); 7419 SDValue FlipBit = 7420 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7421 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7422 AddToWorklist(FlipBit.getNode()); 7423 SDValue FlipBits = 7424 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7425 AddToWorklist(FlipBits.getNode()); 7426 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7427 } 7428 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7429 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7430 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7431 AddToWorklist(X.getNode()); 7432 7433 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7434 VT, N0.getOperand(0)); 7435 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7436 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7437 AddToWorklist(Cst.getNode()); 7438 7439 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7440 } 7441 } 7442 7443 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7444 if (N0.getOpcode() == ISD::BUILD_PAIR) 7445 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7446 return CombineLD; 7447 7448 // Remove double bitcasts from shuffles - this is often a legacy of 7449 // XformToShuffleWithZero being used to combine bitmaskings (of 7450 // float vectors bitcast to integer vectors) into shuffles. 7451 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7452 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7453 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7454 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7455 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7456 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7457 7458 // If operands are a bitcast, peek through if it casts the original VT. 7459 // If operands are a constant, just bitcast back to original VT. 7460 auto PeekThroughBitcast = [&](SDValue Op) { 7461 if (Op.getOpcode() == ISD::BITCAST && 7462 Op.getOperand(0).getValueType() == VT) 7463 return SDValue(Op.getOperand(0)); 7464 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7465 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7466 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7467 return SDValue(); 7468 }; 7469 7470 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7471 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7472 if (!(SV0 && SV1)) 7473 return SDValue(); 7474 7475 int MaskScale = 7476 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7477 SmallVector<int, 8> NewMask; 7478 for (int M : SVN->getMask()) 7479 for (int i = 0; i != MaskScale; ++i) 7480 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7481 7482 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7483 if (!LegalMask) { 7484 std::swap(SV0, SV1); 7485 ShuffleVectorSDNode::commuteMask(NewMask); 7486 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7487 } 7488 7489 if (LegalMask) 7490 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7491 } 7492 7493 return SDValue(); 7494 } 7495 7496 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7497 EVT VT = N->getValueType(0); 7498 return CombineConsecutiveLoads(N, VT); 7499 } 7500 7501 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7502 /// operands. DstEltVT indicates the destination element value type. 7503 SDValue DAGCombiner:: 7504 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7505 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7506 7507 // If this is already the right type, we're done. 7508 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7509 7510 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7511 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7512 7513 // If this is a conversion of N elements of one type to N elements of another 7514 // type, convert each element. This handles FP<->INT cases. 7515 if (SrcBitSize == DstBitSize) { 7516 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7517 BV->getValueType(0).getVectorNumElements()); 7518 7519 // Due to the FP element handling below calling this routine recursively, 7520 // we can end up with a scalar-to-vector node here. 7521 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7522 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7523 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7524 DstEltVT, BV->getOperand(0))); 7525 7526 SmallVector<SDValue, 8> Ops; 7527 for (SDValue Op : BV->op_values()) { 7528 // If the vector element type is not legal, the BUILD_VECTOR operands 7529 // are promoted and implicitly truncated. Make that explicit here. 7530 if (Op.getValueType() != SrcEltVT) 7531 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7532 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7533 DstEltVT, Op)); 7534 AddToWorklist(Ops.back().getNode()); 7535 } 7536 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7537 } 7538 7539 // Otherwise, we're growing or shrinking the elements. To avoid having to 7540 // handle annoying details of growing/shrinking FP values, we convert them to 7541 // int first. 7542 if (SrcEltVT.isFloatingPoint()) { 7543 // Convert the input float vector to a int vector where the elements are the 7544 // same sizes. 7545 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7546 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7547 SrcEltVT = IntVT; 7548 } 7549 7550 // Now we know the input is an integer vector. If the output is a FP type, 7551 // convert to integer first, then to FP of the right size. 7552 if (DstEltVT.isFloatingPoint()) { 7553 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7554 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7555 7556 // Next, convert to FP elements of the same size. 7557 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7558 } 7559 7560 SDLoc DL(BV); 7561 7562 // Okay, we know the src/dst types are both integers of differing types. 7563 // Handling growing first. 7564 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7565 if (SrcBitSize < DstBitSize) { 7566 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7567 7568 SmallVector<SDValue, 8> Ops; 7569 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7570 i += NumInputsPerOutput) { 7571 bool isLE = DAG.getDataLayout().isLittleEndian(); 7572 APInt NewBits = APInt(DstBitSize, 0); 7573 bool EltIsUndef = true; 7574 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7575 // Shift the previously computed bits over. 7576 NewBits <<= SrcBitSize; 7577 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7578 if (Op.getOpcode() == ISD::UNDEF) continue; 7579 EltIsUndef = false; 7580 7581 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7582 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7583 } 7584 7585 if (EltIsUndef) 7586 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7587 else 7588 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7589 } 7590 7591 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7592 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7593 } 7594 7595 // Finally, this must be the case where we are shrinking elements: each input 7596 // turns into multiple outputs. 7597 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7598 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7599 NumOutputsPerInput*BV->getNumOperands()); 7600 SmallVector<SDValue, 8> Ops; 7601 7602 for (const SDValue &Op : BV->op_values()) { 7603 if (Op.getOpcode() == ISD::UNDEF) { 7604 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7605 continue; 7606 } 7607 7608 APInt OpVal = cast<ConstantSDNode>(Op)-> 7609 getAPIntValue().zextOrTrunc(SrcBitSize); 7610 7611 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7612 APInt ThisVal = OpVal.trunc(DstBitSize); 7613 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7614 OpVal = OpVal.lshr(DstBitSize); 7615 } 7616 7617 // For big endian targets, swap the order of the pieces of each element. 7618 if (DAG.getDataLayout().isBigEndian()) 7619 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7620 } 7621 7622 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7623 } 7624 7625 /// Try to perform FMA combining on a given FADD node. 7626 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7627 SDValue N0 = N->getOperand(0); 7628 SDValue N1 = N->getOperand(1); 7629 EVT VT = N->getValueType(0); 7630 SDLoc SL(N); 7631 7632 const TargetOptions &Options = DAG.getTarget().Options; 7633 bool AllowFusion = 7634 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7635 7636 // Floating-point multiply-add with intermediate rounding. 7637 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7638 7639 // Floating-point multiply-add without intermediate rounding. 7640 bool HasFMA = 7641 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7642 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7643 7644 // No valid opcode, do not combine. 7645 if (!HasFMAD && !HasFMA) 7646 return SDValue(); 7647 7648 // Always prefer FMAD to FMA for precision. 7649 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7650 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7651 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7652 7653 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7654 // prefer to fold the multiply with fewer uses. 7655 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7656 N1.getOpcode() == ISD::FMUL) { 7657 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7658 std::swap(N0, N1); 7659 } 7660 7661 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7662 if (N0.getOpcode() == ISD::FMUL && 7663 (Aggressive || N0->hasOneUse())) { 7664 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7665 N0.getOperand(0), N0.getOperand(1), N1); 7666 } 7667 7668 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7669 // Note: Commutes FADD operands. 7670 if (N1.getOpcode() == ISD::FMUL && 7671 (Aggressive || N1->hasOneUse())) { 7672 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7673 N1.getOperand(0), N1.getOperand(1), N0); 7674 } 7675 7676 // Look through FP_EXTEND nodes to do more combining. 7677 if (AllowFusion && LookThroughFPExt) { 7678 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7679 if (N0.getOpcode() == ISD::FP_EXTEND) { 7680 SDValue N00 = N0.getOperand(0); 7681 if (N00.getOpcode() == ISD::FMUL) 7682 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7683 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7684 N00.getOperand(0)), 7685 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7686 N00.getOperand(1)), N1); 7687 } 7688 7689 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7690 // Note: Commutes FADD operands. 7691 if (N1.getOpcode() == ISD::FP_EXTEND) { 7692 SDValue N10 = N1.getOperand(0); 7693 if (N10.getOpcode() == ISD::FMUL) 7694 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7695 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7696 N10.getOperand(0)), 7697 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7698 N10.getOperand(1)), N0); 7699 } 7700 } 7701 7702 // More folding opportunities when target permits. 7703 if ((AllowFusion || HasFMAD) && Aggressive) { 7704 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7705 if (N0.getOpcode() == PreferredFusedOpcode && 7706 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7707 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7708 N0.getOperand(0), N0.getOperand(1), 7709 DAG.getNode(PreferredFusedOpcode, SL, VT, 7710 N0.getOperand(2).getOperand(0), 7711 N0.getOperand(2).getOperand(1), 7712 N1)); 7713 } 7714 7715 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7716 if (N1->getOpcode() == PreferredFusedOpcode && 7717 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7718 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7719 N1.getOperand(0), N1.getOperand(1), 7720 DAG.getNode(PreferredFusedOpcode, SL, VT, 7721 N1.getOperand(2).getOperand(0), 7722 N1.getOperand(2).getOperand(1), 7723 N0)); 7724 } 7725 7726 if (AllowFusion && LookThroughFPExt) { 7727 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7728 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7729 auto FoldFAddFMAFPExtFMul = [&] ( 7730 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7731 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7732 DAG.getNode(PreferredFusedOpcode, SL, VT, 7733 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7734 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7735 Z)); 7736 }; 7737 if (N0.getOpcode() == PreferredFusedOpcode) { 7738 SDValue N02 = N0.getOperand(2); 7739 if (N02.getOpcode() == ISD::FP_EXTEND) { 7740 SDValue N020 = N02.getOperand(0); 7741 if (N020.getOpcode() == ISD::FMUL) 7742 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7743 N020.getOperand(0), N020.getOperand(1), 7744 N1); 7745 } 7746 } 7747 7748 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7749 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7750 // FIXME: This turns two single-precision and one double-precision 7751 // operation into two double-precision operations, which might not be 7752 // interesting for all targets, especially GPUs. 7753 auto FoldFAddFPExtFMAFMul = [&] ( 7754 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7755 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7756 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7757 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7758 DAG.getNode(PreferredFusedOpcode, SL, VT, 7759 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7760 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7761 Z)); 7762 }; 7763 if (N0.getOpcode() == ISD::FP_EXTEND) { 7764 SDValue N00 = N0.getOperand(0); 7765 if (N00.getOpcode() == PreferredFusedOpcode) { 7766 SDValue N002 = N00.getOperand(2); 7767 if (N002.getOpcode() == ISD::FMUL) 7768 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7769 N002.getOperand(0), N002.getOperand(1), 7770 N1); 7771 } 7772 } 7773 7774 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7775 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7776 if (N1.getOpcode() == PreferredFusedOpcode) { 7777 SDValue N12 = N1.getOperand(2); 7778 if (N12.getOpcode() == ISD::FP_EXTEND) { 7779 SDValue N120 = N12.getOperand(0); 7780 if (N120.getOpcode() == ISD::FMUL) 7781 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7782 N120.getOperand(0), N120.getOperand(1), 7783 N0); 7784 } 7785 } 7786 7787 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7788 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7789 // FIXME: This turns two single-precision and one double-precision 7790 // operation into two double-precision operations, which might not be 7791 // interesting for all targets, especially GPUs. 7792 if (N1.getOpcode() == ISD::FP_EXTEND) { 7793 SDValue N10 = N1.getOperand(0); 7794 if (N10.getOpcode() == PreferredFusedOpcode) { 7795 SDValue N102 = N10.getOperand(2); 7796 if (N102.getOpcode() == ISD::FMUL) 7797 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7798 N102.getOperand(0), N102.getOperand(1), 7799 N0); 7800 } 7801 } 7802 } 7803 } 7804 7805 return SDValue(); 7806 } 7807 7808 /// Try to perform FMA combining on a given FSUB node. 7809 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7810 SDValue N0 = N->getOperand(0); 7811 SDValue N1 = N->getOperand(1); 7812 EVT VT = N->getValueType(0); 7813 SDLoc SL(N); 7814 7815 const TargetOptions &Options = DAG.getTarget().Options; 7816 bool AllowFusion = 7817 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7818 7819 // Floating-point multiply-add with intermediate rounding. 7820 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7821 7822 // Floating-point multiply-add without intermediate rounding. 7823 bool HasFMA = 7824 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7825 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7826 7827 // No valid opcode, do not combine. 7828 if (!HasFMAD && !HasFMA) 7829 return SDValue(); 7830 7831 // Always prefer FMAD to FMA for precision. 7832 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7833 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7834 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7835 7836 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7837 if (N0.getOpcode() == ISD::FMUL && 7838 (Aggressive || N0->hasOneUse())) { 7839 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7840 N0.getOperand(0), N0.getOperand(1), 7841 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7842 } 7843 7844 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7845 // Note: Commutes FSUB operands. 7846 if (N1.getOpcode() == ISD::FMUL && 7847 (Aggressive || N1->hasOneUse())) 7848 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7849 DAG.getNode(ISD::FNEG, SL, VT, 7850 N1.getOperand(0)), 7851 N1.getOperand(1), N0); 7852 7853 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7854 if (N0.getOpcode() == ISD::FNEG && 7855 N0.getOperand(0).getOpcode() == ISD::FMUL && 7856 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7857 SDValue N00 = N0.getOperand(0).getOperand(0); 7858 SDValue N01 = N0.getOperand(0).getOperand(1); 7859 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7860 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7861 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7862 } 7863 7864 // Look through FP_EXTEND nodes to do more combining. 7865 if (AllowFusion && LookThroughFPExt) { 7866 // fold (fsub (fpext (fmul x, y)), z) 7867 // -> (fma (fpext x), (fpext y), (fneg z)) 7868 if (N0.getOpcode() == ISD::FP_EXTEND) { 7869 SDValue N00 = N0.getOperand(0); 7870 if (N00.getOpcode() == ISD::FMUL) 7871 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7872 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7873 N00.getOperand(0)), 7874 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7875 N00.getOperand(1)), 7876 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7877 } 7878 7879 // fold (fsub x, (fpext (fmul y, z))) 7880 // -> (fma (fneg (fpext y)), (fpext z), x) 7881 // Note: Commutes FSUB operands. 7882 if (N1.getOpcode() == ISD::FP_EXTEND) { 7883 SDValue N10 = N1.getOperand(0); 7884 if (N10.getOpcode() == ISD::FMUL) 7885 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7886 DAG.getNode(ISD::FNEG, SL, VT, 7887 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7888 N10.getOperand(0))), 7889 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7890 N10.getOperand(1)), 7891 N0); 7892 } 7893 7894 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7895 // -> (fneg (fma (fpext x), (fpext y), z)) 7896 // Note: This could be removed with appropriate canonicalization of the 7897 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7898 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7899 // from implementing the canonicalization in visitFSUB. 7900 if (N0.getOpcode() == ISD::FP_EXTEND) { 7901 SDValue N00 = N0.getOperand(0); 7902 if (N00.getOpcode() == ISD::FNEG) { 7903 SDValue N000 = N00.getOperand(0); 7904 if (N000.getOpcode() == ISD::FMUL) { 7905 return DAG.getNode(ISD::FNEG, SL, VT, 7906 DAG.getNode(PreferredFusedOpcode, SL, VT, 7907 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7908 N000.getOperand(0)), 7909 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7910 N000.getOperand(1)), 7911 N1)); 7912 } 7913 } 7914 } 7915 7916 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7917 // -> (fneg (fma (fpext x)), (fpext y), z) 7918 // Note: This could be removed with appropriate canonicalization of the 7919 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7920 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7921 // from implementing the canonicalization in visitFSUB. 7922 if (N0.getOpcode() == ISD::FNEG) { 7923 SDValue N00 = N0.getOperand(0); 7924 if (N00.getOpcode() == ISD::FP_EXTEND) { 7925 SDValue N000 = N00.getOperand(0); 7926 if (N000.getOpcode() == ISD::FMUL) { 7927 return DAG.getNode(ISD::FNEG, SL, VT, 7928 DAG.getNode(PreferredFusedOpcode, SL, VT, 7929 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7930 N000.getOperand(0)), 7931 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7932 N000.getOperand(1)), 7933 N1)); 7934 } 7935 } 7936 } 7937 7938 } 7939 7940 // More folding opportunities when target permits. 7941 if ((AllowFusion || HasFMAD) && Aggressive) { 7942 // fold (fsub (fma x, y, (fmul u, v)), z) 7943 // -> (fma x, y (fma u, v, (fneg z))) 7944 if (N0.getOpcode() == PreferredFusedOpcode && 7945 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7946 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7947 N0.getOperand(0), N0.getOperand(1), 7948 DAG.getNode(PreferredFusedOpcode, SL, VT, 7949 N0.getOperand(2).getOperand(0), 7950 N0.getOperand(2).getOperand(1), 7951 DAG.getNode(ISD::FNEG, SL, VT, 7952 N1))); 7953 } 7954 7955 // fold (fsub x, (fma y, z, (fmul u, v))) 7956 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7957 if (N1.getOpcode() == PreferredFusedOpcode && 7958 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7959 SDValue N20 = N1.getOperand(2).getOperand(0); 7960 SDValue N21 = N1.getOperand(2).getOperand(1); 7961 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7962 DAG.getNode(ISD::FNEG, SL, VT, 7963 N1.getOperand(0)), 7964 N1.getOperand(1), 7965 DAG.getNode(PreferredFusedOpcode, SL, VT, 7966 DAG.getNode(ISD::FNEG, SL, VT, N20), 7967 7968 N21, N0)); 7969 } 7970 7971 if (AllowFusion && LookThroughFPExt) { 7972 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7973 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7974 if (N0.getOpcode() == PreferredFusedOpcode) { 7975 SDValue N02 = N0.getOperand(2); 7976 if (N02.getOpcode() == ISD::FP_EXTEND) { 7977 SDValue N020 = N02.getOperand(0); 7978 if (N020.getOpcode() == ISD::FMUL) 7979 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7980 N0.getOperand(0), N0.getOperand(1), 7981 DAG.getNode(PreferredFusedOpcode, SL, VT, 7982 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7983 N020.getOperand(0)), 7984 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7985 N020.getOperand(1)), 7986 DAG.getNode(ISD::FNEG, SL, VT, 7987 N1))); 7988 } 7989 } 7990 7991 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7992 // -> (fma (fpext x), (fpext y), 7993 // (fma (fpext u), (fpext v), (fneg z))) 7994 // FIXME: This turns two single-precision and one double-precision 7995 // operation into two double-precision operations, which might not be 7996 // interesting for all targets, especially GPUs. 7997 if (N0.getOpcode() == ISD::FP_EXTEND) { 7998 SDValue N00 = N0.getOperand(0); 7999 if (N00.getOpcode() == PreferredFusedOpcode) { 8000 SDValue N002 = N00.getOperand(2); 8001 if (N002.getOpcode() == ISD::FMUL) 8002 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8003 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8004 N00.getOperand(0)), 8005 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8006 N00.getOperand(1)), 8007 DAG.getNode(PreferredFusedOpcode, SL, VT, 8008 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8009 N002.getOperand(0)), 8010 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8011 N002.getOperand(1)), 8012 DAG.getNode(ISD::FNEG, SL, VT, 8013 N1))); 8014 } 8015 } 8016 8017 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8018 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8019 if (N1.getOpcode() == PreferredFusedOpcode && 8020 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8021 SDValue N120 = N1.getOperand(2).getOperand(0); 8022 if (N120.getOpcode() == ISD::FMUL) { 8023 SDValue N1200 = N120.getOperand(0); 8024 SDValue N1201 = N120.getOperand(1); 8025 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8026 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8027 N1.getOperand(1), 8028 DAG.getNode(PreferredFusedOpcode, SL, VT, 8029 DAG.getNode(ISD::FNEG, SL, VT, 8030 DAG.getNode(ISD::FP_EXTEND, SL, 8031 VT, N1200)), 8032 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8033 N1201), 8034 N0)); 8035 } 8036 } 8037 8038 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8039 // -> (fma (fneg (fpext y)), (fpext z), 8040 // (fma (fneg (fpext u)), (fpext v), x)) 8041 // FIXME: This turns two single-precision and one double-precision 8042 // operation into two double-precision operations, which might not be 8043 // interesting for all targets, especially GPUs. 8044 if (N1.getOpcode() == ISD::FP_EXTEND && 8045 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8046 SDValue N100 = N1.getOperand(0).getOperand(0); 8047 SDValue N101 = N1.getOperand(0).getOperand(1); 8048 SDValue N102 = N1.getOperand(0).getOperand(2); 8049 if (N102.getOpcode() == ISD::FMUL) { 8050 SDValue N1020 = N102.getOperand(0); 8051 SDValue N1021 = N102.getOperand(1); 8052 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8053 DAG.getNode(ISD::FNEG, SL, VT, 8054 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8055 N100)), 8056 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8057 DAG.getNode(PreferredFusedOpcode, SL, VT, 8058 DAG.getNode(ISD::FNEG, SL, VT, 8059 DAG.getNode(ISD::FP_EXTEND, SL, 8060 VT, N1020)), 8061 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8062 N1021), 8063 N0)); 8064 } 8065 } 8066 } 8067 } 8068 8069 return SDValue(); 8070 } 8071 8072 /// Try to perform FMA combining on a given FMUL node. 8073 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8074 SDValue N0 = N->getOperand(0); 8075 SDValue N1 = N->getOperand(1); 8076 EVT VT = N->getValueType(0); 8077 SDLoc SL(N); 8078 8079 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8080 8081 const TargetOptions &Options = DAG.getTarget().Options; 8082 bool AllowFusion = 8083 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8084 8085 // Floating-point multiply-add with intermediate rounding. 8086 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8087 8088 // Floating-point multiply-add without intermediate rounding. 8089 bool HasFMA = 8090 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8091 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8092 8093 // No valid opcode, do not combine. 8094 if (!HasFMAD && !HasFMA) 8095 return SDValue(); 8096 8097 // Always prefer FMAD to FMA for precision. 8098 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8099 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8100 8101 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8102 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8103 auto FuseFADD = [&](SDValue X, SDValue Y) { 8104 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8105 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8106 if (XC1 && XC1->isExactlyValue(+1.0)) 8107 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8108 if (XC1 && XC1->isExactlyValue(-1.0)) 8109 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8110 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8111 } 8112 return SDValue(); 8113 }; 8114 8115 if (SDValue FMA = FuseFADD(N0, N1)) 8116 return FMA; 8117 if (SDValue FMA = FuseFADD(N1, N0)) 8118 return FMA; 8119 8120 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8121 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8122 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8123 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8124 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8125 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8126 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8127 if (XC0 && XC0->isExactlyValue(+1.0)) 8128 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8129 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8130 Y); 8131 if (XC0 && XC0->isExactlyValue(-1.0)) 8132 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8133 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8134 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8135 8136 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8137 if (XC1 && XC1->isExactlyValue(+1.0)) 8138 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8139 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8140 if (XC1 && XC1->isExactlyValue(-1.0)) 8141 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8142 } 8143 return SDValue(); 8144 }; 8145 8146 if (SDValue FMA = FuseFSUB(N0, N1)) 8147 return FMA; 8148 if (SDValue FMA = FuseFSUB(N1, N0)) 8149 return FMA; 8150 8151 return SDValue(); 8152 } 8153 8154 SDValue DAGCombiner::visitFADD(SDNode *N) { 8155 SDValue N0 = N->getOperand(0); 8156 SDValue N1 = N->getOperand(1); 8157 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8158 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8159 EVT VT = N->getValueType(0); 8160 SDLoc DL(N); 8161 const TargetOptions &Options = DAG.getTarget().Options; 8162 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8163 8164 // fold vector ops 8165 if (VT.isVector()) 8166 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8167 return FoldedVOp; 8168 8169 // fold (fadd c1, c2) -> c1 + c2 8170 if (N0CFP && N1CFP) 8171 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8172 8173 // canonicalize constant to RHS 8174 if (N0CFP && !N1CFP) 8175 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8176 8177 // fold (fadd A, (fneg B)) -> (fsub A, B) 8178 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8179 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8180 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8181 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8182 8183 // fold (fadd (fneg A), B) -> (fsub B, A) 8184 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8185 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8186 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8187 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8188 8189 // If 'unsafe math' is enabled, fold lots of things. 8190 if (Options.UnsafeFPMath) { 8191 // No FP constant should be created after legalization as Instruction 8192 // Selection pass has a hard time dealing with FP constants. 8193 bool AllowNewConst = (Level < AfterLegalizeDAG); 8194 8195 // fold (fadd A, 0) -> A 8196 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8197 if (N1C->isZero()) 8198 return N0; 8199 8200 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8201 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8202 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8203 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8204 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8205 Flags), 8206 Flags); 8207 8208 // If allowed, fold (fadd (fneg x), x) -> 0.0 8209 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8210 return DAG.getConstantFP(0.0, DL, VT); 8211 8212 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8213 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8214 return DAG.getConstantFP(0.0, DL, VT); 8215 8216 // We can fold chains of FADD's of the same value into multiplications. 8217 // This transform is not safe in general because we are reducing the number 8218 // of rounding steps. 8219 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8220 if (N0.getOpcode() == ISD::FMUL) { 8221 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8222 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8223 8224 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8225 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8226 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8227 DAG.getConstantFP(1.0, DL, VT), Flags); 8228 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8229 } 8230 8231 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8232 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8233 N1.getOperand(0) == N1.getOperand(1) && 8234 N0.getOperand(0) == N1.getOperand(0)) { 8235 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8236 DAG.getConstantFP(2.0, DL, VT), Flags); 8237 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8238 } 8239 } 8240 8241 if (N1.getOpcode() == ISD::FMUL) { 8242 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8243 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8244 8245 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8246 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8247 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8248 DAG.getConstantFP(1.0, DL, VT), Flags); 8249 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8250 } 8251 8252 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8253 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8254 N0.getOperand(0) == N0.getOperand(1) && 8255 N1.getOperand(0) == N0.getOperand(0)) { 8256 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8257 DAG.getConstantFP(2.0, DL, VT), Flags); 8258 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8259 } 8260 } 8261 8262 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8263 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8264 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8265 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8266 (N0.getOperand(0) == N1)) { 8267 return DAG.getNode(ISD::FMUL, DL, VT, 8268 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8269 } 8270 } 8271 8272 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8273 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8274 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8275 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8276 N1.getOperand(0) == N0) { 8277 return DAG.getNode(ISD::FMUL, DL, VT, 8278 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8279 } 8280 } 8281 8282 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8283 if (AllowNewConst && 8284 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8285 N0.getOperand(0) == N0.getOperand(1) && 8286 N1.getOperand(0) == N1.getOperand(1) && 8287 N0.getOperand(0) == N1.getOperand(0)) { 8288 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8289 DAG.getConstantFP(4.0, DL, VT), Flags); 8290 } 8291 } 8292 } // enable-unsafe-fp-math 8293 8294 // FADD -> FMA combines: 8295 if (SDValue Fused = visitFADDForFMACombine(N)) { 8296 AddToWorklist(Fused.getNode()); 8297 return Fused; 8298 } 8299 8300 return SDValue(); 8301 } 8302 8303 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8304 SDValue N0 = N->getOperand(0); 8305 SDValue N1 = N->getOperand(1); 8306 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8307 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8308 EVT VT = N->getValueType(0); 8309 SDLoc dl(N); 8310 const TargetOptions &Options = DAG.getTarget().Options; 8311 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8312 8313 // fold vector ops 8314 if (VT.isVector()) 8315 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8316 return FoldedVOp; 8317 8318 // fold (fsub c1, c2) -> c1-c2 8319 if (N0CFP && N1CFP) 8320 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8321 8322 // fold (fsub A, (fneg B)) -> (fadd A, B) 8323 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8324 return DAG.getNode(ISD::FADD, dl, VT, N0, 8325 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8326 8327 // If 'unsafe math' is enabled, fold lots of things. 8328 if (Options.UnsafeFPMath) { 8329 // (fsub A, 0) -> A 8330 if (N1CFP && N1CFP->isZero()) 8331 return N0; 8332 8333 // (fsub 0, B) -> -B 8334 if (N0CFP && N0CFP->isZero()) { 8335 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8336 return GetNegatedExpression(N1, DAG, LegalOperations); 8337 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8338 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8339 } 8340 8341 // (fsub x, x) -> 0.0 8342 if (N0 == N1) 8343 return DAG.getConstantFP(0.0f, dl, VT); 8344 8345 // (fsub x, (fadd x, y)) -> (fneg y) 8346 // (fsub x, (fadd y, x)) -> (fneg y) 8347 if (N1.getOpcode() == ISD::FADD) { 8348 SDValue N10 = N1->getOperand(0); 8349 SDValue N11 = N1->getOperand(1); 8350 8351 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8352 return GetNegatedExpression(N11, DAG, LegalOperations); 8353 8354 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8355 return GetNegatedExpression(N10, DAG, LegalOperations); 8356 } 8357 } 8358 8359 // FSUB -> FMA combines: 8360 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8361 AddToWorklist(Fused.getNode()); 8362 return Fused; 8363 } 8364 8365 return SDValue(); 8366 } 8367 8368 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8369 SDValue N0 = N->getOperand(0); 8370 SDValue N1 = N->getOperand(1); 8371 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8372 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8373 EVT VT = N->getValueType(0); 8374 SDLoc DL(N); 8375 const TargetOptions &Options = DAG.getTarget().Options; 8376 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8377 8378 // fold vector ops 8379 if (VT.isVector()) { 8380 // This just handles C1 * C2 for vectors. Other vector folds are below. 8381 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8382 return FoldedVOp; 8383 } 8384 8385 // fold (fmul c1, c2) -> c1*c2 8386 if (N0CFP && N1CFP) 8387 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8388 8389 // canonicalize constant to RHS 8390 if (isConstantFPBuildVectorOrConstantFP(N0) && 8391 !isConstantFPBuildVectorOrConstantFP(N1)) 8392 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8393 8394 // fold (fmul A, 1.0) -> A 8395 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8396 return N0; 8397 8398 if (Options.UnsafeFPMath) { 8399 // fold (fmul A, 0) -> 0 8400 if (N1CFP && N1CFP->isZero()) 8401 return N1; 8402 8403 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8404 if (N0.getOpcode() == ISD::FMUL) { 8405 // Fold scalars or any vector constants (not just splats). 8406 // This fold is done in general by InstCombine, but extra fmul insts 8407 // may have been generated during lowering. 8408 SDValue N00 = N0.getOperand(0); 8409 SDValue N01 = N0.getOperand(1); 8410 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8411 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8412 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8413 8414 // Check 1: Make sure that the first operand of the inner multiply is NOT 8415 // a constant. Otherwise, we may induce infinite looping. 8416 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8417 // Check 2: Make sure that the second operand of the inner multiply and 8418 // the second operand of the outer multiply are constants. 8419 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8420 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8421 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8422 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8423 } 8424 } 8425 } 8426 8427 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8428 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8429 // during an early run of DAGCombiner can prevent folding with fmuls 8430 // inserted during lowering. 8431 if (N0.getOpcode() == ISD::FADD && 8432 (N0.getOperand(0) == N0.getOperand(1)) && 8433 N0.hasOneUse()) { 8434 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8435 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8436 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8437 } 8438 } 8439 8440 // fold (fmul X, 2.0) -> (fadd X, X) 8441 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8442 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8443 8444 // fold (fmul X, -1.0) -> (fneg X) 8445 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8446 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8447 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8448 8449 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8450 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8451 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8452 // Both can be negated for free, check to see if at least one is cheaper 8453 // negated. 8454 if (LHSNeg == 2 || RHSNeg == 2) 8455 return DAG.getNode(ISD::FMUL, DL, VT, 8456 GetNegatedExpression(N0, DAG, LegalOperations), 8457 GetNegatedExpression(N1, DAG, LegalOperations), 8458 Flags); 8459 } 8460 } 8461 8462 // FMUL -> FMA combines: 8463 if (SDValue Fused = visitFMULForFMACombine(N)) { 8464 AddToWorklist(Fused.getNode()); 8465 return Fused; 8466 } 8467 8468 return SDValue(); 8469 } 8470 8471 SDValue DAGCombiner::visitFMA(SDNode *N) { 8472 SDValue N0 = N->getOperand(0); 8473 SDValue N1 = N->getOperand(1); 8474 SDValue N2 = N->getOperand(2); 8475 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8476 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8477 EVT VT = N->getValueType(0); 8478 SDLoc dl(N); 8479 const TargetOptions &Options = DAG.getTarget().Options; 8480 8481 // Constant fold FMA. 8482 if (isa<ConstantFPSDNode>(N0) && 8483 isa<ConstantFPSDNode>(N1) && 8484 isa<ConstantFPSDNode>(N2)) { 8485 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8486 } 8487 8488 if (Options.UnsafeFPMath) { 8489 if (N0CFP && N0CFP->isZero()) 8490 return N2; 8491 if (N1CFP && N1CFP->isZero()) 8492 return N2; 8493 } 8494 // TODO: The FMA node should have flags that propagate to these nodes. 8495 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8496 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8497 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8498 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8499 8500 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8501 if (isConstantFPBuildVectorOrConstantFP(N0) && 8502 !isConstantFPBuildVectorOrConstantFP(N1)) 8503 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8504 8505 // TODO: FMA nodes should have flags that propagate to the created nodes. 8506 // For now, create a Flags object for use with all unsafe math transforms. 8507 SDNodeFlags Flags; 8508 Flags.setUnsafeAlgebra(true); 8509 8510 if (Options.UnsafeFPMath) { 8511 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8512 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8513 isConstantFPBuildVectorOrConstantFP(N1) && 8514 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8515 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8516 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8517 &Flags), &Flags); 8518 } 8519 8520 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8521 if (N0.getOpcode() == ISD::FMUL && 8522 isConstantFPBuildVectorOrConstantFP(N1) && 8523 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8524 return DAG.getNode(ISD::FMA, dl, VT, 8525 N0.getOperand(0), 8526 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8527 &Flags), 8528 N2); 8529 } 8530 } 8531 8532 // (fma x, 1, y) -> (fadd x, y) 8533 // (fma x, -1, y) -> (fadd (fneg x), y) 8534 if (N1CFP) { 8535 if (N1CFP->isExactlyValue(1.0)) 8536 // TODO: The FMA node should have flags that propagate to this node. 8537 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8538 8539 if (N1CFP->isExactlyValue(-1.0) && 8540 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8541 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8542 AddToWorklist(RHSNeg.getNode()); 8543 // TODO: The FMA node should have flags that propagate to this node. 8544 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8545 } 8546 } 8547 8548 if (Options.UnsafeFPMath) { 8549 // (fma x, c, x) -> (fmul x, (c+1)) 8550 if (N1CFP && N0 == N2) { 8551 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8552 DAG.getNode(ISD::FADD, dl, VT, 8553 N1, DAG.getConstantFP(1.0, dl, VT), 8554 &Flags), &Flags); 8555 } 8556 8557 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8558 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8559 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8560 DAG.getNode(ISD::FADD, dl, VT, 8561 N1, DAG.getConstantFP(-1.0, dl, VT), 8562 &Flags), &Flags); 8563 } 8564 } 8565 8566 return SDValue(); 8567 } 8568 8569 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8570 // reciprocal. 8571 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8572 // Notice that this is not always beneficial. One reason is different target 8573 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8574 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8575 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8576 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8577 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8578 const SDNodeFlags *Flags = N->getFlags(); 8579 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8580 return SDValue(); 8581 8582 // Skip if current node is a reciprocal. 8583 SDValue N0 = N->getOperand(0); 8584 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8585 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8586 return SDValue(); 8587 8588 // Exit early if the target does not want this transform or if there can't 8589 // possibly be enough uses of the divisor to make the transform worthwhile. 8590 SDValue N1 = N->getOperand(1); 8591 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8592 if (!MinUses || N1->use_size() < MinUses) 8593 return SDValue(); 8594 8595 // Find all FDIV users of the same divisor. 8596 // Use a set because duplicates may be present in the user list. 8597 SetVector<SDNode *> Users; 8598 for (auto *U : N1->uses()) { 8599 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8600 // This division is eligible for optimization only if global unsafe math 8601 // is enabled or if this division allows reciprocal formation. 8602 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8603 Users.insert(U); 8604 } 8605 } 8606 8607 // Now that we have the actual number of divisor uses, make sure it meets 8608 // the minimum threshold specified by the target. 8609 if (Users.size() < MinUses) 8610 return SDValue(); 8611 8612 EVT VT = N->getValueType(0); 8613 SDLoc DL(N); 8614 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8615 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8616 8617 // Dividend / Divisor -> Dividend * Reciprocal 8618 for (auto *U : Users) { 8619 SDValue Dividend = U->getOperand(0); 8620 if (Dividend != FPOne) { 8621 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8622 Reciprocal, Flags); 8623 CombineTo(U, NewNode); 8624 } else if (U != Reciprocal.getNode()) { 8625 // In the absence of fast-math-flags, this user node is always the 8626 // same node as Reciprocal, but with FMF they may be different nodes. 8627 CombineTo(U, Reciprocal); 8628 } 8629 } 8630 return SDValue(N, 0); // N was replaced. 8631 } 8632 8633 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8634 SDValue N0 = N->getOperand(0); 8635 SDValue N1 = N->getOperand(1); 8636 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8637 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8638 EVT VT = N->getValueType(0); 8639 SDLoc DL(N); 8640 const TargetOptions &Options = DAG.getTarget().Options; 8641 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8642 8643 // fold vector ops 8644 if (VT.isVector()) 8645 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8646 return FoldedVOp; 8647 8648 // fold (fdiv c1, c2) -> c1/c2 8649 if (N0CFP && N1CFP) 8650 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8651 8652 if (Options.UnsafeFPMath) { 8653 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8654 if (N1CFP) { 8655 // Compute the reciprocal 1.0 / c2. 8656 APFloat N1APF = N1CFP->getValueAPF(); 8657 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8658 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8659 // Only do the transform if the reciprocal is a legal fp immediate that 8660 // isn't too nasty (eg NaN, denormal, ...). 8661 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8662 (!LegalOperations || 8663 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8664 // backend)... we should handle this gracefully after Legalize. 8665 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8666 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8667 TLI.isFPImmLegal(Recip, VT))) 8668 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8669 DAG.getConstantFP(Recip, DL, VT), Flags); 8670 } 8671 8672 // If this FDIV is part of a reciprocal square root, it may be folded 8673 // into a target-specific square root estimate instruction. 8674 if (N1.getOpcode() == ISD::FSQRT) { 8675 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8676 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8677 } 8678 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8679 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8680 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8681 Flags)) { 8682 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8683 AddToWorklist(RV.getNode()); 8684 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8685 } 8686 } else if (N1.getOpcode() == ISD::FP_ROUND && 8687 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8688 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8689 Flags)) { 8690 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8691 AddToWorklist(RV.getNode()); 8692 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8693 } 8694 } else if (N1.getOpcode() == ISD::FMUL) { 8695 // Look through an FMUL. Even though this won't remove the FDIV directly, 8696 // it's still worthwhile to get rid of the FSQRT if possible. 8697 SDValue SqrtOp; 8698 SDValue OtherOp; 8699 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8700 SqrtOp = N1.getOperand(0); 8701 OtherOp = N1.getOperand(1); 8702 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8703 SqrtOp = N1.getOperand(1); 8704 OtherOp = N1.getOperand(0); 8705 } 8706 if (SqrtOp.getNode()) { 8707 // We found a FSQRT, so try to make this fold: 8708 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8709 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8710 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8711 AddToWorklist(RV.getNode()); 8712 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8713 } 8714 } 8715 } 8716 8717 // Fold into a reciprocal estimate and multiply instead of a real divide. 8718 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8719 AddToWorklist(RV.getNode()); 8720 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8721 } 8722 } 8723 8724 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8725 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8726 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8727 // Both can be negated for free, check to see if at least one is cheaper 8728 // negated. 8729 if (LHSNeg == 2 || RHSNeg == 2) 8730 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8731 GetNegatedExpression(N0, DAG, LegalOperations), 8732 GetNegatedExpression(N1, DAG, LegalOperations), 8733 Flags); 8734 } 8735 } 8736 8737 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8738 return CombineRepeatedDivisors; 8739 8740 return SDValue(); 8741 } 8742 8743 SDValue DAGCombiner::visitFREM(SDNode *N) { 8744 SDValue N0 = N->getOperand(0); 8745 SDValue N1 = N->getOperand(1); 8746 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8747 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8748 EVT VT = N->getValueType(0); 8749 8750 // fold (frem c1, c2) -> fmod(c1,c2) 8751 if (N0CFP && N1CFP) 8752 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8753 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8754 8755 return SDValue(); 8756 } 8757 8758 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8759 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8760 return SDValue(); 8761 8762 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8763 // For now, create a Flags object for use with all unsafe math transforms. 8764 SDNodeFlags Flags; 8765 Flags.setUnsafeAlgebra(true); 8766 8767 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8768 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8769 if (!RV) 8770 return SDValue(); 8771 8772 EVT VT = RV.getValueType(); 8773 SDLoc DL(N); 8774 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8775 AddToWorklist(RV.getNode()); 8776 8777 // Unfortunately, RV is now NaN if the input was exactly 0. 8778 // Select out this case and force the answer to 0. 8779 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8780 EVT CCVT = getSetCCResultType(VT); 8781 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8782 AddToWorklist(ZeroCmp.getNode()); 8783 AddToWorklist(RV.getNode()); 8784 8785 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8786 ZeroCmp, Zero, RV); 8787 } 8788 8789 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8790 /// copysign(x, fp_round(y)) -> copysign(x, y) 8791 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8792 SDValue N1 = N->getOperand(1); 8793 if ((N1.getOpcode() == ISD::FP_EXTEND || 8794 N1.getOpcode() == ISD::FP_ROUND)) { 8795 // Do not optimize out type conversion of f128 type yet. 8796 // For some targets like x86_64, configuration is changed to keep one f128 8797 // value in one SSE register, but instruction selection cannot handle 8798 // FCOPYSIGN on SSE registers yet. 8799 EVT N1VT = N1->getValueType(0); 8800 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8801 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8802 } 8803 return false; 8804 } 8805 8806 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8807 SDValue N0 = N->getOperand(0); 8808 SDValue N1 = N->getOperand(1); 8809 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8810 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8811 EVT VT = N->getValueType(0); 8812 8813 if (N0CFP && N1CFP) // Constant fold 8814 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8815 8816 if (N1CFP) { 8817 const APFloat& V = N1CFP->getValueAPF(); 8818 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8819 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8820 if (!V.isNegative()) { 8821 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8822 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8823 } else { 8824 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8825 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8826 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8827 } 8828 } 8829 8830 // copysign(fabs(x), y) -> copysign(x, y) 8831 // copysign(fneg(x), y) -> copysign(x, y) 8832 // copysign(copysign(x,z), y) -> copysign(x, y) 8833 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8834 N0.getOpcode() == ISD::FCOPYSIGN) 8835 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8836 N0.getOperand(0), N1); 8837 8838 // copysign(x, abs(y)) -> abs(x) 8839 if (N1.getOpcode() == ISD::FABS) 8840 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8841 8842 // copysign(x, copysign(y,z)) -> copysign(x, z) 8843 if (N1.getOpcode() == ISD::FCOPYSIGN) 8844 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8845 N0, N1.getOperand(1)); 8846 8847 // copysign(x, fp_extend(y)) -> copysign(x, y) 8848 // copysign(x, fp_round(y)) -> copysign(x, y) 8849 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 8850 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8851 N0, N1.getOperand(0)); 8852 8853 return SDValue(); 8854 } 8855 8856 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8857 SDValue N0 = N->getOperand(0); 8858 EVT VT = N->getValueType(0); 8859 EVT OpVT = N0.getValueType(); 8860 8861 // fold (sint_to_fp c1) -> c1fp 8862 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8863 // ...but only if the target supports immediate floating-point values 8864 (!LegalOperations || 8865 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8866 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8867 8868 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8869 // but UINT_TO_FP is legal on this target, try to convert. 8870 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8871 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8872 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8873 if (DAG.SignBitIsZero(N0)) 8874 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8875 } 8876 8877 // The next optimizations are desirable only if SELECT_CC can be lowered. 8878 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8879 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8880 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8881 !VT.isVector() && 8882 (!LegalOperations || 8883 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8884 SDLoc DL(N); 8885 SDValue Ops[] = 8886 { N0.getOperand(0), N0.getOperand(1), 8887 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8888 N0.getOperand(2) }; 8889 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8890 } 8891 8892 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8893 // (select_cc x, y, 1.0, 0.0,, cc) 8894 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8895 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8896 (!LegalOperations || 8897 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8898 SDLoc DL(N); 8899 SDValue Ops[] = 8900 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8901 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8902 N0.getOperand(0).getOperand(2) }; 8903 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8904 } 8905 } 8906 8907 return SDValue(); 8908 } 8909 8910 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8911 SDValue N0 = N->getOperand(0); 8912 EVT VT = N->getValueType(0); 8913 EVT OpVT = N0.getValueType(); 8914 8915 // fold (uint_to_fp c1) -> c1fp 8916 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8917 // ...but only if the target supports immediate floating-point values 8918 (!LegalOperations || 8919 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8920 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8921 8922 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8923 // but SINT_TO_FP is legal on this target, try to convert. 8924 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8925 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8926 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8927 if (DAG.SignBitIsZero(N0)) 8928 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8929 } 8930 8931 // The next optimizations are desirable only if SELECT_CC can be lowered. 8932 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8933 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8934 8935 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8936 (!LegalOperations || 8937 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8938 SDLoc DL(N); 8939 SDValue Ops[] = 8940 { N0.getOperand(0), N0.getOperand(1), 8941 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8942 N0.getOperand(2) }; 8943 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8944 } 8945 } 8946 8947 return SDValue(); 8948 } 8949 8950 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8951 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8952 SDValue N0 = N->getOperand(0); 8953 EVT VT = N->getValueType(0); 8954 8955 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8956 return SDValue(); 8957 8958 SDValue Src = N0.getOperand(0); 8959 EVT SrcVT = Src.getValueType(); 8960 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8961 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8962 8963 // We can safely assume the conversion won't overflow the output range, 8964 // because (for example) (uint8_t)18293.f is undefined behavior. 8965 8966 // Since we can assume the conversion won't overflow, our decision as to 8967 // whether the input will fit in the float should depend on the minimum 8968 // of the input range and output range. 8969 8970 // This means this is also safe for a signed input and unsigned output, since 8971 // a negative input would lead to undefined behavior. 8972 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8973 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8974 unsigned ActualSize = std::min(InputSize, OutputSize); 8975 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8976 8977 // We can only fold away the float conversion if the input range can be 8978 // represented exactly in the float range. 8979 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8980 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8981 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8982 : ISD::ZERO_EXTEND; 8983 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8984 } 8985 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8986 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8987 return DAG.getBitcast(VT, Src); 8988 } 8989 return SDValue(); 8990 } 8991 8992 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8993 SDValue N0 = N->getOperand(0); 8994 EVT VT = N->getValueType(0); 8995 8996 // fold (fp_to_sint c1fp) -> c1 8997 if (isConstantFPBuildVectorOrConstantFP(N0)) 8998 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8999 9000 return FoldIntToFPToInt(N, DAG); 9001 } 9002 9003 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9004 SDValue N0 = N->getOperand(0); 9005 EVT VT = N->getValueType(0); 9006 9007 // fold (fp_to_uint c1fp) -> c1 9008 if (isConstantFPBuildVectorOrConstantFP(N0)) 9009 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9010 9011 return FoldIntToFPToInt(N, DAG); 9012 } 9013 9014 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9015 SDValue N0 = N->getOperand(0); 9016 SDValue N1 = N->getOperand(1); 9017 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9018 EVT VT = N->getValueType(0); 9019 9020 // fold (fp_round c1fp) -> c1fp 9021 if (N0CFP) 9022 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9023 9024 // fold (fp_round (fp_extend x)) -> x 9025 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9026 return N0.getOperand(0); 9027 9028 // fold (fp_round (fp_round x)) -> (fp_round x) 9029 if (N0.getOpcode() == ISD::FP_ROUND) { 9030 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9031 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9032 9033 // Skip this folding if it results in an fp_round from f80 to f16. 9034 // 9035 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9036 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9037 // instructions from f32 or f64. Moreover, the first (value-preserving) 9038 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9039 // x86. 9040 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9041 return SDValue(); 9042 9043 // If the first fp_round isn't a value preserving truncation, it might 9044 // introduce a tie in the second fp_round, that wouldn't occur in the 9045 // single-step fp_round we want to fold to. 9046 // In other words, double rounding isn't the same as rounding. 9047 // Also, this is a value preserving truncation iff both fp_round's are. 9048 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9049 SDLoc DL(N); 9050 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9051 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9052 } 9053 } 9054 9055 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9056 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9057 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9058 N0.getOperand(0), N1); 9059 AddToWorklist(Tmp.getNode()); 9060 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9061 Tmp, N0.getOperand(1)); 9062 } 9063 9064 return SDValue(); 9065 } 9066 9067 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9068 SDValue N0 = N->getOperand(0); 9069 EVT VT = N->getValueType(0); 9070 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9071 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9072 9073 // fold (fp_round_inreg c1fp) -> c1fp 9074 if (N0CFP && isTypeLegal(EVT)) { 9075 SDLoc DL(N); 9076 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9077 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9078 } 9079 9080 return SDValue(); 9081 } 9082 9083 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9084 SDValue N0 = N->getOperand(0); 9085 EVT VT = N->getValueType(0); 9086 9087 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9088 if (N->hasOneUse() && 9089 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9090 return SDValue(); 9091 9092 // fold (fp_extend c1fp) -> c1fp 9093 if (isConstantFPBuildVectorOrConstantFP(N0)) 9094 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9095 9096 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9097 if (N0.getOpcode() == ISD::FP16_TO_FP && 9098 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9099 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9100 9101 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9102 // value of X. 9103 if (N0.getOpcode() == ISD::FP_ROUND 9104 && N0.getNode()->getConstantOperandVal(1) == 1) { 9105 SDValue In = N0.getOperand(0); 9106 if (In.getValueType() == VT) return In; 9107 if (VT.bitsLT(In.getValueType())) 9108 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9109 In, N0.getOperand(1)); 9110 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9111 } 9112 9113 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9114 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9115 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9116 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9117 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9118 LN0->getChain(), 9119 LN0->getBasePtr(), N0.getValueType(), 9120 LN0->getMemOperand()); 9121 CombineTo(N, ExtLoad); 9122 CombineTo(N0.getNode(), 9123 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9124 N0.getValueType(), ExtLoad, 9125 DAG.getIntPtrConstant(1, SDLoc(N0))), 9126 ExtLoad.getValue(1)); 9127 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9128 } 9129 9130 return SDValue(); 9131 } 9132 9133 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9134 SDValue N0 = N->getOperand(0); 9135 EVT VT = N->getValueType(0); 9136 9137 // fold (fceil c1) -> fceil(c1) 9138 if (isConstantFPBuildVectorOrConstantFP(N0)) 9139 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9140 9141 return SDValue(); 9142 } 9143 9144 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9145 SDValue N0 = N->getOperand(0); 9146 EVT VT = N->getValueType(0); 9147 9148 // fold (ftrunc c1) -> ftrunc(c1) 9149 if (isConstantFPBuildVectorOrConstantFP(N0)) 9150 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9151 9152 return SDValue(); 9153 } 9154 9155 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9156 SDValue N0 = N->getOperand(0); 9157 EVT VT = N->getValueType(0); 9158 9159 // fold (ffloor c1) -> ffloor(c1) 9160 if (isConstantFPBuildVectorOrConstantFP(N0)) 9161 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9162 9163 return SDValue(); 9164 } 9165 9166 // FIXME: FNEG and FABS have a lot in common; refactor. 9167 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9168 SDValue N0 = N->getOperand(0); 9169 EVT VT = N->getValueType(0); 9170 9171 // Constant fold FNEG. 9172 if (isConstantFPBuildVectorOrConstantFP(N0)) 9173 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9174 9175 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9176 &DAG.getTarget().Options)) 9177 return GetNegatedExpression(N0, DAG, LegalOperations); 9178 9179 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9180 // constant pool values. 9181 if (!TLI.isFNegFree(VT) && 9182 N0.getOpcode() == ISD::BITCAST && 9183 N0.getNode()->hasOneUse()) { 9184 SDValue Int = N0.getOperand(0); 9185 EVT IntVT = Int.getValueType(); 9186 if (IntVT.isInteger() && !IntVT.isVector()) { 9187 APInt SignMask; 9188 if (N0.getValueType().isVector()) { 9189 // For a vector, get a mask such as 0x80... per scalar element 9190 // and splat it. 9191 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9192 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9193 } else { 9194 // For a scalar, just generate 0x80... 9195 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9196 } 9197 SDLoc DL0(N0); 9198 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9199 DAG.getConstant(SignMask, DL0, IntVT)); 9200 AddToWorklist(Int.getNode()); 9201 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9202 } 9203 } 9204 9205 // (fneg (fmul c, x)) -> (fmul -c, x) 9206 if (N0.getOpcode() == ISD::FMUL && 9207 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9208 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9209 if (CFP1) { 9210 APFloat CVal = CFP1->getValueAPF(); 9211 CVal.changeSign(); 9212 if (Level >= AfterLegalizeDAG && 9213 (TLI.isFPImmLegal(CVal, VT) || 9214 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9215 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9216 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9217 N0.getOperand(1)), 9218 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9219 } 9220 } 9221 9222 return SDValue(); 9223 } 9224 9225 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9226 SDValue N0 = N->getOperand(0); 9227 SDValue N1 = N->getOperand(1); 9228 EVT VT = N->getValueType(0); 9229 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9230 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9231 9232 if (N0CFP && N1CFP) { 9233 const APFloat &C0 = N0CFP->getValueAPF(); 9234 const APFloat &C1 = N1CFP->getValueAPF(); 9235 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9236 } 9237 9238 // Canonicalize to constant on RHS. 9239 if (isConstantFPBuildVectorOrConstantFP(N0) && 9240 !isConstantFPBuildVectorOrConstantFP(N1)) 9241 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9242 9243 return SDValue(); 9244 } 9245 9246 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9247 SDValue N0 = N->getOperand(0); 9248 SDValue N1 = N->getOperand(1); 9249 EVT VT = N->getValueType(0); 9250 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9251 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9252 9253 if (N0CFP && N1CFP) { 9254 const APFloat &C0 = N0CFP->getValueAPF(); 9255 const APFloat &C1 = N1CFP->getValueAPF(); 9256 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9257 } 9258 9259 // Canonicalize to constant on RHS. 9260 if (isConstantFPBuildVectorOrConstantFP(N0) && 9261 !isConstantFPBuildVectorOrConstantFP(N1)) 9262 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9263 9264 return SDValue(); 9265 } 9266 9267 SDValue DAGCombiner::visitFABS(SDNode *N) { 9268 SDValue N0 = N->getOperand(0); 9269 EVT VT = N->getValueType(0); 9270 9271 // fold (fabs c1) -> fabs(c1) 9272 if (isConstantFPBuildVectorOrConstantFP(N0)) 9273 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9274 9275 // fold (fabs (fabs x)) -> (fabs x) 9276 if (N0.getOpcode() == ISD::FABS) 9277 return N->getOperand(0); 9278 9279 // fold (fabs (fneg x)) -> (fabs x) 9280 // fold (fabs (fcopysign x, y)) -> (fabs x) 9281 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9282 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9283 9284 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9285 // constant pool values. 9286 if (!TLI.isFAbsFree(VT) && 9287 N0.getOpcode() == ISD::BITCAST && 9288 N0.getNode()->hasOneUse()) { 9289 SDValue Int = N0.getOperand(0); 9290 EVT IntVT = Int.getValueType(); 9291 if (IntVT.isInteger() && !IntVT.isVector()) { 9292 APInt SignMask; 9293 if (N0.getValueType().isVector()) { 9294 // For a vector, get a mask such as 0x7f... per scalar element 9295 // and splat it. 9296 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9297 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9298 } else { 9299 // For a scalar, just generate 0x7f... 9300 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9301 } 9302 SDLoc DL(N0); 9303 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9304 DAG.getConstant(SignMask, DL, IntVT)); 9305 AddToWorklist(Int.getNode()); 9306 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9307 } 9308 } 9309 9310 return SDValue(); 9311 } 9312 9313 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9314 SDValue Chain = N->getOperand(0); 9315 SDValue N1 = N->getOperand(1); 9316 SDValue N2 = N->getOperand(2); 9317 9318 // If N is a constant we could fold this into a fallthrough or unconditional 9319 // branch. However that doesn't happen very often in normal code, because 9320 // Instcombine/SimplifyCFG should have handled the available opportunities. 9321 // If we did this folding here, it would be necessary to update the 9322 // MachineBasicBlock CFG, which is awkward. 9323 9324 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9325 // on the target. 9326 if (N1.getOpcode() == ISD::SETCC && 9327 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9328 N1.getOperand(0).getValueType())) { 9329 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9330 Chain, N1.getOperand(2), 9331 N1.getOperand(0), N1.getOperand(1), N2); 9332 } 9333 9334 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9335 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9336 (N1.getOperand(0).hasOneUse() && 9337 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9338 SDNode *Trunc = nullptr; 9339 if (N1.getOpcode() == ISD::TRUNCATE) { 9340 // Look pass the truncate. 9341 Trunc = N1.getNode(); 9342 N1 = N1.getOperand(0); 9343 } 9344 9345 // Match this pattern so that we can generate simpler code: 9346 // 9347 // %a = ... 9348 // %b = and i32 %a, 2 9349 // %c = srl i32 %b, 1 9350 // brcond i32 %c ... 9351 // 9352 // into 9353 // 9354 // %a = ... 9355 // %b = and i32 %a, 2 9356 // %c = setcc eq %b, 0 9357 // brcond %c ... 9358 // 9359 // This applies only when the AND constant value has one bit set and the 9360 // SRL constant is equal to the log2 of the AND constant. The back-end is 9361 // smart enough to convert the result into a TEST/JMP sequence. 9362 SDValue Op0 = N1.getOperand(0); 9363 SDValue Op1 = N1.getOperand(1); 9364 9365 if (Op0.getOpcode() == ISD::AND && 9366 Op1.getOpcode() == ISD::Constant) { 9367 SDValue AndOp1 = Op0.getOperand(1); 9368 9369 if (AndOp1.getOpcode() == ISD::Constant) { 9370 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9371 9372 if (AndConst.isPowerOf2() && 9373 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9374 SDLoc DL(N); 9375 SDValue SetCC = 9376 DAG.getSetCC(DL, 9377 getSetCCResultType(Op0.getValueType()), 9378 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9379 ISD::SETNE); 9380 9381 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9382 MVT::Other, Chain, SetCC, N2); 9383 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9384 // will convert it back to (X & C1) >> C2. 9385 CombineTo(N, NewBRCond, false); 9386 // Truncate is dead. 9387 if (Trunc) 9388 deleteAndRecombine(Trunc); 9389 // Replace the uses of SRL with SETCC 9390 WorklistRemover DeadNodes(*this); 9391 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9392 deleteAndRecombine(N1.getNode()); 9393 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9394 } 9395 } 9396 } 9397 9398 if (Trunc) 9399 // Restore N1 if the above transformation doesn't match. 9400 N1 = N->getOperand(1); 9401 } 9402 9403 // Transform br(xor(x, y)) -> br(x != y) 9404 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9405 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9406 SDNode *TheXor = N1.getNode(); 9407 SDValue Op0 = TheXor->getOperand(0); 9408 SDValue Op1 = TheXor->getOperand(1); 9409 if (Op0.getOpcode() == Op1.getOpcode()) { 9410 // Avoid missing important xor optimizations. 9411 if (SDValue Tmp = visitXOR(TheXor)) { 9412 if (Tmp.getNode() != TheXor) { 9413 DEBUG(dbgs() << "\nReplacing.8 "; 9414 TheXor->dump(&DAG); 9415 dbgs() << "\nWith: "; 9416 Tmp.getNode()->dump(&DAG); 9417 dbgs() << '\n'); 9418 WorklistRemover DeadNodes(*this); 9419 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9420 deleteAndRecombine(TheXor); 9421 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9422 MVT::Other, Chain, Tmp, N2); 9423 } 9424 9425 // visitXOR has changed XOR's operands or replaced the XOR completely, 9426 // bail out. 9427 return SDValue(N, 0); 9428 } 9429 } 9430 9431 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9432 bool Equal = false; 9433 if (isOneConstant(Op0) && Op0.hasOneUse() && 9434 Op0.getOpcode() == ISD::XOR) { 9435 TheXor = Op0.getNode(); 9436 Equal = true; 9437 } 9438 9439 EVT SetCCVT = N1.getValueType(); 9440 if (LegalTypes) 9441 SetCCVT = getSetCCResultType(SetCCVT); 9442 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9443 SetCCVT, 9444 Op0, Op1, 9445 Equal ? ISD::SETEQ : ISD::SETNE); 9446 // Replace the uses of XOR with SETCC 9447 WorklistRemover DeadNodes(*this); 9448 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9449 deleteAndRecombine(N1.getNode()); 9450 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9451 MVT::Other, Chain, SetCC, N2); 9452 } 9453 } 9454 9455 return SDValue(); 9456 } 9457 9458 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9459 // 9460 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9461 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9462 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9463 9464 // If N is a constant we could fold this into a fallthrough or unconditional 9465 // branch. However that doesn't happen very often in normal code, because 9466 // Instcombine/SimplifyCFG should have handled the available opportunities. 9467 // If we did this folding here, it would be necessary to update the 9468 // MachineBasicBlock CFG, which is awkward. 9469 9470 // Use SimplifySetCC to simplify SETCC's. 9471 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9472 CondLHS, CondRHS, CC->get(), SDLoc(N), 9473 false); 9474 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9475 9476 // fold to a simpler setcc 9477 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9478 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9479 N->getOperand(0), Simp.getOperand(2), 9480 Simp.getOperand(0), Simp.getOperand(1), 9481 N->getOperand(4)); 9482 9483 return SDValue(); 9484 } 9485 9486 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9487 /// and that N may be folded in the load / store addressing mode. 9488 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9489 SelectionDAG &DAG, 9490 const TargetLowering &TLI) { 9491 EVT VT; 9492 unsigned AS; 9493 9494 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9495 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9496 return false; 9497 VT = LD->getMemoryVT(); 9498 AS = LD->getAddressSpace(); 9499 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9500 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9501 return false; 9502 VT = ST->getMemoryVT(); 9503 AS = ST->getAddressSpace(); 9504 } else 9505 return false; 9506 9507 TargetLowering::AddrMode AM; 9508 if (N->getOpcode() == ISD::ADD) { 9509 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9510 if (Offset) 9511 // [reg +/- imm] 9512 AM.BaseOffs = Offset->getSExtValue(); 9513 else 9514 // [reg +/- reg] 9515 AM.Scale = 1; 9516 } else if (N->getOpcode() == ISD::SUB) { 9517 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9518 if (Offset) 9519 // [reg +/- imm] 9520 AM.BaseOffs = -Offset->getSExtValue(); 9521 else 9522 // [reg +/- reg] 9523 AM.Scale = 1; 9524 } else 9525 return false; 9526 9527 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9528 VT.getTypeForEVT(*DAG.getContext()), AS); 9529 } 9530 9531 /// Try turning a load/store into a pre-indexed load/store when the base 9532 /// pointer is an add or subtract and it has other uses besides the load/store. 9533 /// After the transformation, the new indexed load/store has effectively folded 9534 /// the add/subtract in and all of its other uses are redirected to the 9535 /// new load/store. 9536 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9537 if (Level < AfterLegalizeDAG) 9538 return false; 9539 9540 bool isLoad = true; 9541 SDValue Ptr; 9542 EVT VT; 9543 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9544 if (LD->isIndexed()) 9545 return false; 9546 VT = LD->getMemoryVT(); 9547 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9548 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9549 return false; 9550 Ptr = LD->getBasePtr(); 9551 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9552 if (ST->isIndexed()) 9553 return false; 9554 VT = ST->getMemoryVT(); 9555 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9556 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9557 return false; 9558 Ptr = ST->getBasePtr(); 9559 isLoad = false; 9560 } else { 9561 return false; 9562 } 9563 9564 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9565 // out. There is no reason to make this a preinc/predec. 9566 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9567 Ptr.getNode()->hasOneUse()) 9568 return false; 9569 9570 // Ask the target to do addressing mode selection. 9571 SDValue BasePtr; 9572 SDValue Offset; 9573 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9574 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9575 return false; 9576 9577 // Backends without true r+i pre-indexed forms may need to pass a 9578 // constant base with a variable offset so that constant coercion 9579 // will work with the patterns in canonical form. 9580 bool Swapped = false; 9581 if (isa<ConstantSDNode>(BasePtr)) { 9582 std::swap(BasePtr, Offset); 9583 Swapped = true; 9584 } 9585 9586 // Don't create a indexed load / store with zero offset. 9587 if (isNullConstant(Offset)) 9588 return false; 9589 9590 // Try turning it into a pre-indexed load / store except when: 9591 // 1) The new base ptr is a frame index. 9592 // 2) If N is a store and the new base ptr is either the same as or is a 9593 // predecessor of the value being stored. 9594 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9595 // that would create a cycle. 9596 // 4) All uses are load / store ops that use it as old base ptr. 9597 9598 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9599 // (plus the implicit offset) to a register to preinc anyway. 9600 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9601 return false; 9602 9603 // Check #2. 9604 if (!isLoad) { 9605 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9606 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9607 return false; 9608 } 9609 9610 // Caches for hasPredecessorHelper. 9611 SmallPtrSet<const SDNode *, 32> Visited; 9612 SmallVector<const SDNode *, 16> Worklist; 9613 9614 // If the offset is a constant, there may be other adds of constants that 9615 // can be folded with this one. We should do this to avoid having to keep 9616 // a copy of the original base pointer. 9617 SmallVector<SDNode *, 16> OtherUses; 9618 if (isa<ConstantSDNode>(Offset)) 9619 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9620 UE = BasePtr.getNode()->use_end(); 9621 UI != UE; ++UI) { 9622 SDUse &Use = UI.getUse(); 9623 // Skip the use that is Ptr and uses of other results from BasePtr's 9624 // node (important for nodes that return multiple results). 9625 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9626 continue; 9627 9628 if (N->hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9629 continue; 9630 9631 if (Use.getUser()->getOpcode() != ISD::ADD && 9632 Use.getUser()->getOpcode() != ISD::SUB) { 9633 OtherUses.clear(); 9634 break; 9635 } 9636 9637 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9638 if (!isa<ConstantSDNode>(Op1)) { 9639 OtherUses.clear(); 9640 break; 9641 } 9642 9643 // FIXME: In some cases, we can be smarter about this. 9644 if (Op1.getValueType() != Offset.getValueType()) { 9645 OtherUses.clear(); 9646 break; 9647 } 9648 9649 OtherUses.push_back(Use.getUser()); 9650 } 9651 9652 if (Swapped) 9653 std::swap(BasePtr, Offset); 9654 9655 // Now check for #3 and #4. 9656 bool RealUse = false; 9657 9658 for (SDNode *Use : Ptr.getNode()->uses()) { 9659 if (Use == N) 9660 continue; 9661 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9662 return false; 9663 9664 // If Ptr may be folded in addressing mode of other use, then it's 9665 // not profitable to do this transformation. 9666 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9667 RealUse = true; 9668 } 9669 9670 if (!RealUse) 9671 return false; 9672 9673 SDValue Result; 9674 if (isLoad) 9675 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9676 BasePtr, Offset, AM); 9677 else 9678 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9679 BasePtr, Offset, AM); 9680 ++PreIndexedNodes; 9681 ++NodesCombined; 9682 DEBUG(dbgs() << "\nReplacing.4 "; 9683 N->dump(&DAG); 9684 dbgs() << "\nWith: "; 9685 Result.getNode()->dump(&DAG); 9686 dbgs() << '\n'); 9687 WorklistRemover DeadNodes(*this); 9688 if (isLoad) { 9689 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9690 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9691 } else { 9692 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9693 } 9694 9695 // Finally, since the node is now dead, remove it from the graph. 9696 deleteAndRecombine(N); 9697 9698 if (Swapped) 9699 std::swap(BasePtr, Offset); 9700 9701 // Replace other uses of BasePtr that can be updated to use Ptr 9702 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9703 unsigned OffsetIdx = 1; 9704 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9705 OffsetIdx = 0; 9706 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9707 BasePtr.getNode() && "Expected BasePtr operand"); 9708 9709 // We need to replace ptr0 in the following expression: 9710 // x0 * offset0 + y0 * ptr0 = t0 9711 // knowing that 9712 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9713 // 9714 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9715 // indexed load/store and the expresion that needs to be re-written. 9716 // 9717 // Therefore, we have: 9718 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9719 9720 ConstantSDNode *CN = 9721 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9722 int X0, X1, Y0, Y1; 9723 APInt Offset0 = CN->getAPIntValue(); 9724 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9725 9726 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9727 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9728 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9729 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9730 9731 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9732 9733 APInt CNV = Offset0; 9734 if (X0 < 0) CNV = -CNV; 9735 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9736 else CNV = CNV - Offset1; 9737 9738 SDLoc DL(OtherUses[i]); 9739 9740 // We can now generate the new expression. 9741 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9742 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9743 9744 SDValue NewUse = DAG.getNode(Opcode, 9745 DL, 9746 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9747 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9748 deleteAndRecombine(OtherUses[i]); 9749 } 9750 9751 // Replace the uses of Ptr with uses of the updated base value. 9752 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9753 deleteAndRecombine(Ptr.getNode()); 9754 9755 return true; 9756 } 9757 9758 /// Try to combine a load/store with a add/sub of the base pointer node into a 9759 /// post-indexed load/store. The transformation folded the add/subtract into the 9760 /// new indexed load/store effectively and all of its uses are redirected to the 9761 /// new load/store. 9762 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9763 if (Level < AfterLegalizeDAG) 9764 return false; 9765 9766 bool isLoad = true; 9767 SDValue Ptr; 9768 EVT VT; 9769 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9770 if (LD->isIndexed()) 9771 return false; 9772 VT = LD->getMemoryVT(); 9773 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9774 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9775 return false; 9776 Ptr = LD->getBasePtr(); 9777 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9778 if (ST->isIndexed()) 9779 return false; 9780 VT = ST->getMemoryVT(); 9781 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9782 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9783 return false; 9784 Ptr = ST->getBasePtr(); 9785 isLoad = false; 9786 } else { 9787 return false; 9788 } 9789 9790 if (Ptr.getNode()->hasOneUse()) 9791 return false; 9792 9793 for (SDNode *Op : Ptr.getNode()->uses()) { 9794 if (Op == N || 9795 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9796 continue; 9797 9798 SDValue BasePtr; 9799 SDValue Offset; 9800 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9801 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9802 // Don't create a indexed load / store with zero offset. 9803 if (isNullConstant(Offset)) 9804 continue; 9805 9806 // Try turning it into a post-indexed load / store except when 9807 // 1) All uses are load / store ops that use it as base ptr (and 9808 // it may be folded as addressing mmode). 9809 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9810 // nor a successor of N. Otherwise, if Op is folded that would 9811 // create a cycle. 9812 9813 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9814 continue; 9815 9816 // Check for #1. 9817 bool TryNext = false; 9818 for (SDNode *Use : BasePtr.getNode()->uses()) { 9819 if (Use == Ptr.getNode()) 9820 continue; 9821 9822 // If all the uses are load / store addresses, then don't do the 9823 // transformation. 9824 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9825 bool RealUse = false; 9826 for (SDNode *UseUse : Use->uses()) { 9827 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9828 RealUse = true; 9829 } 9830 9831 if (!RealUse) { 9832 TryNext = true; 9833 break; 9834 } 9835 } 9836 } 9837 9838 if (TryNext) 9839 continue; 9840 9841 // Check for #2 9842 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9843 SDValue Result = isLoad 9844 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9845 BasePtr, Offset, AM) 9846 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9847 BasePtr, Offset, AM); 9848 ++PostIndexedNodes; 9849 ++NodesCombined; 9850 DEBUG(dbgs() << "\nReplacing.5 "; 9851 N->dump(&DAG); 9852 dbgs() << "\nWith: "; 9853 Result.getNode()->dump(&DAG); 9854 dbgs() << '\n'); 9855 WorklistRemover DeadNodes(*this); 9856 if (isLoad) { 9857 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9858 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9859 } else { 9860 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9861 } 9862 9863 // Finally, since the node is now dead, remove it from the graph. 9864 deleteAndRecombine(N); 9865 9866 // Replace the uses of Use with uses of the updated base value. 9867 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9868 Result.getValue(isLoad ? 1 : 0)); 9869 deleteAndRecombine(Op); 9870 return true; 9871 } 9872 } 9873 } 9874 9875 return false; 9876 } 9877 9878 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9879 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9880 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9881 assert(AM != ISD::UNINDEXED); 9882 SDValue BP = LD->getOperand(1); 9883 SDValue Inc = LD->getOperand(2); 9884 9885 // Some backends use TargetConstants for load offsets, but don't expect 9886 // TargetConstants in general ADD nodes. We can convert these constants into 9887 // regular Constants (if the constant is not opaque). 9888 assert((Inc.getOpcode() != ISD::TargetConstant || 9889 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9890 "Cannot split out indexing using opaque target constants"); 9891 if (Inc.getOpcode() == ISD::TargetConstant) { 9892 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9893 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9894 ConstInc->getValueType(0)); 9895 } 9896 9897 unsigned Opc = 9898 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9899 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9900 } 9901 9902 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9903 LoadSDNode *LD = cast<LoadSDNode>(N); 9904 SDValue Chain = LD->getChain(); 9905 SDValue Ptr = LD->getBasePtr(); 9906 9907 // If load is not volatile and there are no uses of the loaded value (and 9908 // the updated indexed value in case of indexed loads), change uses of the 9909 // chain value into uses of the chain input (i.e. delete the dead load). 9910 if (!LD->isVolatile()) { 9911 if (N->getValueType(1) == MVT::Other) { 9912 // Unindexed loads. 9913 if (!N->hasAnyUseOfValue(0)) { 9914 // It's not safe to use the two value CombineTo variant here. e.g. 9915 // v1, chain2 = load chain1, loc 9916 // v2, chain3 = load chain2, loc 9917 // v3 = add v2, c 9918 // Now we replace use of chain2 with chain1. This makes the second load 9919 // isomorphic to the one we are deleting, and thus makes this load live. 9920 DEBUG(dbgs() << "\nReplacing.6 "; 9921 N->dump(&DAG); 9922 dbgs() << "\nWith chain: "; 9923 Chain.getNode()->dump(&DAG); 9924 dbgs() << "\n"); 9925 WorklistRemover DeadNodes(*this); 9926 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9927 9928 if (N->use_empty()) 9929 deleteAndRecombine(N); 9930 9931 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9932 } 9933 } else { 9934 // Indexed loads. 9935 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9936 9937 // If this load has an opaque TargetConstant offset, then we cannot split 9938 // the indexing into an add/sub directly (that TargetConstant may not be 9939 // valid for a different type of node, and we cannot convert an opaque 9940 // target constant into a regular constant). 9941 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9942 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9943 9944 if (!N->hasAnyUseOfValue(0) && 9945 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9946 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9947 SDValue Index; 9948 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9949 Index = SplitIndexingFromLoad(LD); 9950 // Try to fold the base pointer arithmetic into subsequent loads and 9951 // stores. 9952 AddUsersToWorklist(N); 9953 } else 9954 Index = DAG.getUNDEF(N->getValueType(1)); 9955 DEBUG(dbgs() << "\nReplacing.7 "; 9956 N->dump(&DAG); 9957 dbgs() << "\nWith: "; 9958 Undef.getNode()->dump(&DAG); 9959 dbgs() << " and 2 other values\n"); 9960 WorklistRemover DeadNodes(*this); 9961 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9962 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9963 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9964 deleteAndRecombine(N); 9965 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9966 } 9967 } 9968 } 9969 9970 // If this load is directly stored, replace the load value with the stored 9971 // value. 9972 // TODO: Handle store large -> read small portion. 9973 // TODO: Handle TRUNCSTORE/LOADEXT 9974 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9975 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9976 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9977 if (PrevST->getBasePtr() == Ptr && 9978 PrevST->getValue().getValueType() == N->getValueType(0)) 9979 return CombineTo(N, Chain.getOperand(1), Chain); 9980 } 9981 } 9982 9983 // Try to infer better alignment information than the load already has. 9984 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9985 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9986 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9987 SDValue NewLoad = 9988 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9989 LD->getValueType(0), 9990 Chain, Ptr, LD->getPointerInfo(), 9991 LD->getMemoryVT(), 9992 LD->isVolatile(), LD->isNonTemporal(), 9993 LD->isInvariant(), Align, LD->getAAInfo()); 9994 if (NewLoad.getNode() != N) 9995 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9996 } 9997 } 9998 } 9999 10000 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10001 : DAG.getSubtarget().useAA(); 10002 #ifndef NDEBUG 10003 if (CombinerAAOnlyFunc.getNumOccurrences() && 10004 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10005 UseAA = false; 10006 #endif 10007 if (UseAA && LD->isUnindexed()) { 10008 // Walk up chain skipping non-aliasing memory nodes. 10009 SDValue BetterChain = FindBetterChain(N, Chain); 10010 10011 // If there is a better chain. 10012 if (Chain != BetterChain) { 10013 SDValue ReplLoad; 10014 10015 // Replace the chain to void dependency. 10016 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10017 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10018 BetterChain, Ptr, LD->getMemOperand()); 10019 } else { 10020 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10021 LD->getValueType(0), 10022 BetterChain, Ptr, LD->getMemoryVT(), 10023 LD->getMemOperand()); 10024 } 10025 10026 // Create token factor to keep old chain connected. 10027 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10028 MVT::Other, Chain, ReplLoad.getValue(1)); 10029 10030 // Make sure the new and old chains are cleaned up. 10031 AddToWorklist(Token.getNode()); 10032 10033 // Replace uses with load result and token factor. Don't add users 10034 // to work list. 10035 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10036 } 10037 } 10038 10039 // Try transforming N to an indexed load. 10040 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10041 return SDValue(N, 0); 10042 10043 // Try to slice up N to more direct loads if the slices are mapped to 10044 // different register banks or pairing can take place. 10045 if (SliceUpLoad(N)) 10046 return SDValue(N, 0); 10047 10048 return SDValue(); 10049 } 10050 10051 namespace { 10052 /// \brief Helper structure used to slice a load in smaller loads. 10053 /// Basically a slice is obtained from the following sequence: 10054 /// Origin = load Ty1, Base 10055 /// Shift = srl Ty1 Origin, CstTy Amount 10056 /// Inst = trunc Shift to Ty2 10057 /// 10058 /// Then, it will be rewriten into: 10059 /// Slice = load SliceTy, Base + SliceOffset 10060 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10061 /// 10062 /// SliceTy is deduced from the number of bits that are actually used to 10063 /// build Inst. 10064 struct LoadedSlice { 10065 /// \brief Helper structure used to compute the cost of a slice. 10066 struct Cost { 10067 /// Are we optimizing for code size. 10068 bool ForCodeSize; 10069 /// Various cost. 10070 unsigned Loads; 10071 unsigned Truncates; 10072 unsigned CrossRegisterBanksCopies; 10073 unsigned ZExts; 10074 unsigned Shift; 10075 10076 Cost(bool ForCodeSize = false) 10077 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10078 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10079 10080 /// \brief Get the cost of one isolated slice. 10081 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10082 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10083 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10084 EVT TruncType = LS.Inst->getValueType(0); 10085 EVT LoadedType = LS.getLoadedType(); 10086 if (TruncType != LoadedType && 10087 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10088 ZExts = 1; 10089 } 10090 10091 /// \brief Account for slicing gain in the current cost. 10092 /// Slicing provide a few gains like removing a shift or a 10093 /// truncate. This method allows to grow the cost of the original 10094 /// load with the gain from this slice. 10095 void addSliceGain(const LoadedSlice &LS) { 10096 // Each slice saves a truncate. 10097 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10098 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10099 LS.Inst->getValueType(0))) 10100 ++Truncates; 10101 // If there is a shift amount, this slice gets rid of it. 10102 if (LS.Shift) 10103 ++Shift; 10104 // If this slice can merge a cross register bank copy, account for it. 10105 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10106 ++CrossRegisterBanksCopies; 10107 } 10108 10109 Cost &operator+=(const Cost &RHS) { 10110 Loads += RHS.Loads; 10111 Truncates += RHS.Truncates; 10112 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10113 ZExts += RHS.ZExts; 10114 Shift += RHS.Shift; 10115 return *this; 10116 } 10117 10118 bool operator==(const Cost &RHS) const { 10119 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10120 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10121 ZExts == RHS.ZExts && Shift == RHS.Shift; 10122 } 10123 10124 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10125 10126 bool operator<(const Cost &RHS) const { 10127 // Assume cross register banks copies are as expensive as loads. 10128 // FIXME: Do we want some more target hooks? 10129 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10130 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10131 // Unless we are optimizing for code size, consider the 10132 // expensive operation first. 10133 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10134 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10135 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10136 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10137 } 10138 10139 bool operator>(const Cost &RHS) const { return RHS < *this; } 10140 10141 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10142 10143 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10144 }; 10145 // The last instruction that represent the slice. This should be a 10146 // truncate instruction. 10147 SDNode *Inst; 10148 // The original load instruction. 10149 LoadSDNode *Origin; 10150 // The right shift amount in bits from the original load. 10151 unsigned Shift; 10152 // The DAG from which Origin came from. 10153 // This is used to get some contextual information about legal types, etc. 10154 SelectionDAG *DAG; 10155 10156 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10157 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10158 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10159 10160 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10161 /// \return Result is \p BitWidth and has used bits set to 1 and 10162 /// not used bits set to 0. 10163 APInt getUsedBits() const { 10164 // Reproduce the trunc(lshr) sequence: 10165 // - Start from the truncated value. 10166 // - Zero extend to the desired bit width. 10167 // - Shift left. 10168 assert(Origin && "No original load to compare against."); 10169 unsigned BitWidth = Origin->getValueSizeInBits(0); 10170 assert(Inst && "This slice is not bound to an instruction"); 10171 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10172 "Extracted slice is bigger than the whole type!"); 10173 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10174 UsedBits.setAllBits(); 10175 UsedBits = UsedBits.zext(BitWidth); 10176 UsedBits <<= Shift; 10177 return UsedBits; 10178 } 10179 10180 /// \brief Get the size of the slice to be loaded in bytes. 10181 unsigned getLoadedSize() const { 10182 unsigned SliceSize = getUsedBits().countPopulation(); 10183 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10184 return SliceSize / 8; 10185 } 10186 10187 /// \brief Get the type that will be loaded for this slice. 10188 /// Note: This may not be the final type for the slice. 10189 EVT getLoadedType() const { 10190 assert(DAG && "Missing context"); 10191 LLVMContext &Ctxt = *DAG->getContext(); 10192 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10193 } 10194 10195 /// \brief Get the alignment of the load used for this slice. 10196 unsigned getAlignment() const { 10197 unsigned Alignment = Origin->getAlignment(); 10198 unsigned Offset = getOffsetFromBase(); 10199 if (Offset != 0) 10200 Alignment = MinAlign(Alignment, Alignment + Offset); 10201 return Alignment; 10202 } 10203 10204 /// \brief Check if this slice can be rewritten with legal operations. 10205 bool isLegal() const { 10206 // An invalid slice is not legal. 10207 if (!Origin || !Inst || !DAG) 10208 return false; 10209 10210 // Offsets are for indexed load only, we do not handle that. 10211 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 10212 return false; 10213 10214 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10215 10216 // Check that the type is legal. 10217 EVT SliceType = getLoadedType(); 10218 if (!TLI.isTypeLegal(SliceType)) 10219 return false; 10220 10221 // Check that the load is legal for this type. 10222 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10223 return false; 10224 10225 // Check that the offset can be computed. 10226 // 1. Check its type. 10227 EVT PtrType = Origin->getBasePtr().getValueType(); 10228 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10229 return false; 10230 10231 // 2. Check that it fits in the immediate. 10232 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10233 return false; 10234 10235 // 3. Check that the computation is legal. 10236 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10237 return false; 10238 10239 // Check that the zext is legal if it needs one. 10240 EVT TruncateType = Inst->getValueType(0); 10241 if (TruncateType != SliceType && 10242 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10243 return false; 10244 10245 return true; 10246 } 10247 10248 /// \brief Get the offset in bytes of this slice in the original chunk of 10249 /// bits. 10250 /// \pre DAG != nullptr. 10251 uint64_t getOffsetFromBase() const { 10252 assert(DAG && "Missing context."); 10253 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10254 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10255 uint64_t Offset = Shift / 8; 10256 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10257 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10258 "The size of the original loaded type is not a multiple of a" 10259 " byte."); 10260 // If Offset is bigger than TySizeInBytes, it means we are loading all 10261 // zeros. This should have been optimized before in the process. 10262 assert(TySizeInBytes > Offset && 10263 "Invalid shift amount for given loaded size"); 10264 if (IsBigEndian) 10265 Offset = TySizeInBytes - Offset - getLoadedSize(); 10266 return Offset; 10267 } 10268 10269 /// \brief Generate the sequence of instructions to load the slice 10270 /// represented by this object and redirect the uses of this slice to 10271 /// this new sequence of instructions. 10272 /// \pre this->Inst && this->Origin are valid Instructions and this 10273 /// object passed the legal check: LoadedSlice::isLegal returned true. 10274 /// \return The last instruction of the sequence used to load the slice. 10275 SDValue loadSlice() const { 10276 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10277 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10278 SDValue BaseAddr = OldBaseAddr; 10279 // Get the offset in that chunk of bytes w.r.t. the endianess. 10280 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10281 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10282 if (Offset) { 10283 // BaseAddr = BaseAddr + Offset. 10284 EVT ArithType = BaseAddr.getValueType(); 10285 SDLoc DL(Origin); 10286 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10287 DAG->getConstant(Offset, DL, ArithType)); 10288 } 10289 10290 // Create the type of the loaded slice according to its size. 10291 EVT SliceType = getLoadedType(); 10292 10293 // Create the load for the slice. 10294 SDValue LastInst = DAG->getLoad( 10295 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10296 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10297 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10298 // If the final type is not the same as the loaded type, this means that 10299 // we have to pad with zero. Create a zero extend for that. 10300 EVT FinalType = Inst->getValueType(0); 10301 if (SliceType != FinalType) 10302 LastInst = 10303 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10304 return LastInst; 10305 } 10306 10307 /// \brief Check if this slice can be merged with an expensive cross register 10308 /// bank copy. E.g., 10309 /// i = load i32 10310 /// f = bitcast i32 i to float 10311 bool canMergeExpensiveCrossRegisterBankCopy() const { 10312 if (!Inst || !Inst->hasOneUse()) 10313 return false; 10314 SDNode *Use = *Inst->use_begin(); 10315 if (Use->getOpcode() != ISD::BITCAST) 10316 return false; 10317 assert(DAG && "Missing context"); 10318 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10319 EVT ResVT = Use->getValueType(0); 10320 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10321 const TargetRegisterClass *ArgRC = 10322 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10323 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10324 return false; 10325 10326 // At this point, we know that we perform a cross-register-bank copy. 10327 // Check if it is expensive. 10328 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10329 // Assume bitcasts are cheap, unless both register classes do not 10330 // explicitly share a common sub class. 10331 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10332 return false; 10333 10334 // Check if it will be merged with the load. 10335 // 1. Check the alignment constraint. 10336 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10337 ResVT.getTypeForEVT(*DAG->getContext())); 10338 10339 if (RequiredAlignment > getAlignment()) 10340 return false; 10341 10342 // 2. Check that the load is a legal operation for that type. 10343 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10344 return false; 10345 10346 // 3. Check that we do not have a zext in the way. 10347 if (Inst->getValueType(0) != getLoadedType()) 10348 return false; 10349 10350 return true; 10351 } 10352 }; 10353 } 10354 10355 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10356 /// \p UsedBits looks like 0..0 1..1 0..0. 10357 static bool areUsedBitsDense(const APInt &UsedBits) { 10358 // If all the bits are one, this is dense! 10359 if (UsedBits.isAllOnesValue()) 10360 return true; 10361 10362 // Get rid of the unused bits on the right. 10363 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10364 // Get rid of the unused bits on the left. 10365 if (NarrowedUsedBits.countLeadingZeros()) 10366 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10367 // Check that the chunk of bits is completely used. 10368 return NarrowedUsedBits.isAllOnesValue(); 10369 } 10370 10371 /// \brief Check whether or not \p First and \p Second are next to each other 10372 /// in memory. This means that there is no hole between the bits loaded 10373 /// by \p First and the bits loaded by \p Second. 10374 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10375 const LoadedSlice &Second) { 10376 assert(First.Origin == Second.Origin && First.Origin && 10377 "Unable to match different memory origins."); 10378 APInt UsedBits = First.getUsedBits(); 10379 assert((UsedBits & Second.getUsedBits()) == 0 && 10380 "Slices are not supposed to overlap."); 10381 UsedBits |= Second.getUsedBits(); 10382 return areUsedBitsDense(UsedBits); 10383 } 10384 10385 /// \brief Adjust the \p GlobalLSCost according to the target 10386 /// paring capabilities and the layout of the slices. 10387 /// \pre \p GlobalLSCost should account for at least as many loads as 10388 /// there is in the slices in \p LoadedSlices. 10389 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10390 LoadedSlice::Cost &GlobalLSCost) { 10391 unsigned NumberOfSlices = LoadedSlices.size(); 10392 // If there is less than 2 elements, no pairing is possible. 10393 if (NumberOfSlices < 2) 10394 return; 10395 10396 // Sort the slices so that elements that are likely to be next to each 10397 // other in memory are next to each other in the list. 10398 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10399 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10400 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10401 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10402 }); 10403 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10404 // First (resp. Second) is the first (resp. Second) potentially candidate 10405 // to be placed in a paired load. 10406 const LoadedSlice *First = nullptr; 10407 const LoadedSlice *Second = nullptr; 10408 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10409 // Set the beginning of the pair. 10410 First = Second) { 10411 10412 Second = &LoadedSlices[CurrSlice]; 10413 10414 // If First is NULL, it means we start a new pair. 10415 // Get to the next slice. 10416 if (!First) 10417 continue; 10418 10419 EVT LoadedType = First->getLoadedType(); 10420 10421 // If the types of the slices are different, we cannot pair them. 10422 if (LoadedType != Second->getLoadedType()) 10423 continue; 10424 10425 // Check if the target supplies paired loads for this type. 10426 unsigned RequiredAlignment = 0; 10427 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10428 // move to the next pair, this type is hopeless. 10429 Second = nullptr; 10430 continue; 10431 } 10432 // Check if we meet the alignment requirement. 10433 if (RequiredAlignment > First->getAlignment()) 10434 continue; 10435 10436 // Check that both loads are next to each other in memory. 10437 if (!areSlicesNextToEachOther(*First, *Second)) 10438 continue; 10439 10440 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10441 --GlobalLSCost.Loads; 10442 // Move to the next pair. 10443 Second = nullptr; 10444 } 10445 } 10446 10447 /// \brief Check the profitability of all involved LoadedSlice. 10448 /// Currently, it is considered profitable if there is exactly two 10449 /// involved slices (1) which are (2) next to each other in memory, and 10450 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10451 /// 10452 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10453 /// the elements themselves. 10454 /// 10455 /// FIXME: When the cost model will be mature enough, we can relax 10456 /// constraints (1) and (2). 10457 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10458 const APInt &UsedBits, bool ForCodeSize) { 10459 unsigned NumberOfSlices = LoadedSlices.size(); 10460 if (StressLoadSlicing) 10461 return NumberOfSlices > 1; 10462 10463 // Check (1). 10464 if (NumberOfSlices != 2) 10465 return false; 10466 10467 // Check (2). 10468 if (!areUsedBitsDense(UsedBits)) 10469 return false; 10470 10471 // Check (3). 10472 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10473 // The original code has one big load. 10474 OrigCost.Loads = 1; 10475 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10476 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10477 // Accumulate the cost of all the slices. 10478 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10479 GlobalSlicingCost += SliceCost; 10480 10481 // Account as cost in the original configuration the gain obtained 10482 // with the current slices. 10483 OrigCost.addSliceGain(LS); 10484 } 10485 10486 // If the target supports paired load, adjust the cost accordingly. 10487 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10488 return OrigCost > GlobalSlicingCost; 10489 } 10490 10491 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10492 /// operations, split it in the various pieces being extracted. 10493 /// 10494 /// This sort of thing is introduced by SROA. 10495 /// This slicing takes care not to insert overlapping loads. 10496 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10497 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10498 if (Level < AfterLegalizeDAG) 10499 return false; 10500 10501 LoadSDNode *LD = cast<LoadSDNode>(N); 10502 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10503 !LD->getValueType(0).isInteger()) 10504 return false; 10505 10506 // Keep track of already used bits to detect overlapping values. 10507 // In that case, we will just abort the transformation. 10508 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10509 10510 SmallVector<LoadedSlice, 4> LoadedSlices; 10511 10512 // Check if this load is used as several smaller chunks of bits. 10513 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10514 // of computation for each trunc. 10515 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10516 UI != UIEnd; ++UI) { 10517 // Skip the uses of the chain. 10518 if (UI.getUse().getResNo() != 0) 10519 continue; 10520 10521 SDNode *User = *UI; 10522 unsigned Shift = 0; 10523 10524 // Check if this is a trunc(lshr). 10525 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10526 isa<ConstantSDNode>(User->getOperand(1))) { 10527 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10528 User = *User->use_begin(); 10529 } 10530 10531 // At this point, User is a Truncate, iff we encountered, trunc or 10532 // trunc(lshr). 10533 if (User->getOpcode() != ISD::TRUNCATE) 10534 return false; 10535 10536 // The width of the type must be a power of 2 and greater than 8-bits. 10537 // Otherwise the load cannot be represented in LLVM IR. 10538 // Moreover, if we shifted with a non-8-bits multiple, the slice 10539 // will be across several bytes. We do not support that. 10540 unsigned Width = User->getValueSizeInBits(0); 10541 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10542 return 0; 10543 10544 // Build the slice for this chain of computations. 10545 LoadedSlice LS(User, LD, Shift, &DAG); 10546 APInt CurrentUsedBits = LS.getUsedBits(); 10547 10548 // Check if this slice overlaps with another. 10549 if ((CurrentUsedBits & UsedBits) != 0) 10550 return false; 10551 // Update the bits used globally. 10552 UsedBits |= CurrentUsedBits; 10553 10554 // Check if the new slice would be legal. 10555 if (!LS.isLegal()) 10556 return false; 10557 10558 // Record the slice. 10559 LoadedSlices.push_back(LS); 10560 } 10561 10562 // Abort slicing if it does not seem to be profitable. 10563 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10564 return false; 10565 10566 ++SlicedLoads; 10567 10568 // Rewrite each chain to use an independent load. 10569 // By construction, each chain can be represented by a unique load. 10570 10571 // Prepare the argument for the new token factor for all the slices. 10572 SmallVector<SDValue, 8> ArgChains; 10573 for (SmallVectorImpl<LoadedSlice>::const_iterator 10574 LSIt = LoadedSlices.begin(), 10575 LSItEnd = LoadedSlices.end(); 10576 LSIt != LSItEnd; ++LSIt) { 10577 SDValue SliceInst = LSIt->loadSlice(); 10578 CombineTo(LSIt->Inst, SliceInst, true); 10579 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10580 SliceInst = SliceInst.getOperand(0); 10581 assert(SliceInst->getOpcode() == ISD::LOAD && 10582 "It takes more than a zext to get to the loaded slice!!"); 10583 ArgChains.push_back(SliceInst.getValue(1)); 10584 } 10585 10586 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10587 ArgChains); 10588 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10589 return true; 10590 } 10591 10592 /// Check to see if V is (and load (ptr), imm), where the load is having 10593 /// specific bytes cleared out. If so, return the byte size being masked out 10594 /// and the shift amount. 10595 static std::pair<unsigned, unsigned> 10596 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10597 std::pair<unsigned, unsigned> Result(0, 0); 10598 10599 // Check for the structure we're looking for. 10600 if (V->getOpcode() != ISD::AND || 10601 !isa<ConstantSDNode>(V->getOperand(1)) || 10602 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10603 return Result; 10604 10605 // Check the chain and pointer. 10606 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10607 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10608 10609 // The store should be chained directly to the load or be an operand of a 10610 // tokenfactor. 10611 if (LD == Chain.getNode()) 10612 ; // ok. 10613 else if (Chain->getOpcode() != ISD::TokenFactor) 10614 return Result; // Fail. 10615 else { 10616 bool isOk = false; 10617 for (const SDValue &ChainOp : Chain->op_values()) 10618 if (ChainOp.getNode() == LD) { 10619 isOk = true; 10620 break; 10621 } 10622 if (!isOk) return Result; 10623 } 10624 10625 // This only handles simple types. 10626 if (V.getValueType() != MVT::i16 && 10627 V.getValueType() != MVT::i32 && 10628 V.getValueType() != MVT::i64) 10629 return Result; 10630 10631 // Check the constant mask. Invert it so that the bits being masked out are 10632 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10633 // follow the sign bit for uniformity. 10634 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10635 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10636 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10637 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10638 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10639 if (NotMaskLZ == 64) return Result; // All zero mask. 10640 10641 // See if we have a continuous run of bits. If so, we have 0*1+0* 10642 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10643 return Result; 10644 10645 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10646 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10647 NotMaskLZ -= 64-V.getValueSizeInBits(); 10648 10649 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10650 switch (MaskedBytes) { 10651 case 1: 10652 case 2: 10653 case 4: break; 10654 default: return Result; // All one mask, or 5-byte mask. 10655 } 10656 10657 // Verify that the first bit starts at a multiple of mask so that the access 10658 // is aligned the same as the access width. 10659 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10660 10661 Result.first = MaskedBytes; 10662 Result.second = NotMaskTZ/8; 10663 return Result; 10664 } 10665 10666 10667 /// Check to see if IVal is something that provides a value as specified by 10668 /// MaskInfo. If so, replace the specified store with a narrower store of 10669 /// truncated IVal. 10670 static SDNode * 10671 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10672 SDValue IVal, StoreSDNode *St, 10673 DAGCombiner *DC) { 10674 unsigned NumBytes = MaskInfo.first; 10675 unsigned ByteShift = MaskInfo.second; 10676 SelectionDAG &DAG = DC->getDAG(); 10677 10678 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10679 // that uses this. If not, this is not a replacement. 10680 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10681 ByteShift*8, (ByteShift+NumBytes)*8); 10682 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10683 10684 // Check that it is legal on the target to do this. It is legal if the new 10685 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10686 // legalization. 10687 MVT VT = MVT::getIntegerVT(NumBytes*8); 10688 if (!DC->isTypeLegal(VT)) 10689 return nullptr; 10690 10691 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10692 // shifted by ByteShift and truncated down to NumBytes. 10693 if (ByteShift) { 10694 SDLoc DL(IVal); 10695 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10696 DAG.getConstant(ByteShift*8, DL, 10697 DC->getShiftAmountTy(IVal.getValueType()))); 10698 } 10699 10700 // Figure out the offset for the store and the alignment of the access. 10701 unsigned StOffset; 10702 unsigned NewAlign = St->getAlignment(); 10703 10704 if (DAG.getDataLayout().isLittleEndian()) 10705 StOffset = ByteShift; 10706 else 10707 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10708 10709 SDValue Ptr = St->getBasePtr(); 10710 if (StOffset) { 10711 SDLoc DL(IVal); 10712 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10713 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10714 NewAlign = MinAlign(NewAlign, StOffset); 10715 } 10716 10717 // Truncate down to the new size. 10718 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10719 10720 ++OpsNarrowed; 10721 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10722 St->getPointerInfo().getWithOffset(StOffset), 10723 false, false, NewAlign).getNode(); 10724 } 10725 10726 10727 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10728 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10729 /// narrowing the load and store if it would end up being a win for performance 10730 /// or code size. 10731 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10732 StoreSDNode *ST = cast<StoreSDNode>(N); 10733 if (ST->isVolatile()) 10734 return SDValue(); 10735 10736 SDValue Chain = ST->getChain(); 10737 SDValue Value = ST->getValue(); 10738 SDValue Ptr = ST->getBasePtr(); 10739 EVT VT = Value.getValueType(); 10740 10741 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10742 return SDValue(); 10743 10744 unsigned Opc = Value.getOpcode(); 10745 10746 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10747 // is a byte mask indicating a consecutive number of bytes, check to see if 10748 // Y is known to provide just those bytes. If so, we try to replace the 10749 // load + replace + store sequence with a single (narrower) store, which makes 10750 // the load dead. 10751 if (Opc == ISD::OR) { 10752 std::pair<unsigned, unsigned> MaskedLoad; 10753 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10754 if (MaskedLoad.first) 10755 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10756 Value.getOperand(1), ST,this)) 10757 return SDValue(NewST, 0); 10758 10759 // Or is commutative, so try swapping X and Y. 10760 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10761 if (MaskedLoad.first) 10762 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10763 Value.getOperand(0), ST,this)) 10764 return SDValue(NewST, 0); 10765 } 10766 10767 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10768 Value.getOperand(1).getOpcode() != ISD::Constant) 10769 return SDValue(); 10770 10771 SDValue N0 = Value.getOperand(0); 10772 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10773 Chain == SDValue(N0.getNode(), 1)) { 10774 LoadSDNode *LD = cast<LoadSDNode>(N0); 10775 if (LD->getBasePtr() != Ptr || 10776 LD->getPointerInfo().getAddrSpace() != 10777 ST->getPointerInfo().getAddrSpace()) 10778 return SDValue(); 10779 10780 // Find the type to narrow it the load / op / store to. 10781 SDValue N1 = Value.getOperand(1); 10782 unsigned BitWidth = N1.getValueSizeInBits(); 10783 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10784 if (Opc == ISD::AND) 10785 Imm ^= APInt::getAllOnesValue(BitWidth); 10786 if (Imm == 0 || Imm.isAllOnesValue()) 10787 return SDValue(); 10788 unsigned ShAmt = Imm.countTrailingZeros(); 10789 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10790 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10791 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10792 // The narrowing should be profitable, the load/store operation should be 10793 // legal (or custom) and the store size should be equal to the NewVT width. 10794 while (NewBW < BitWidth && 10795 (NewVT.getStoreSizeInBits() != NewBW || 10796 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10797 !TLI.isNarrowingProfitable(VT, NewVT))) { 10798 NewBW = NextPowerOf2(NewBW); 10799 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10800 } 10801 if (NewBW >= BitWidth) 10802 return SDValue(); 10803 10804 // If the lsb changed does not start at the type bitwidth boundary, 10805 // start at the previous one. 10806 if (ShAmt % NewBW) 10807 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10808 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10809 std::min(BitWidth, ShAmt + NewBW)); 10810 if ((Imm & Mask) == Imm) { 10811 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10812 if (Opc == ISD::AND) 10813 NewImm ^= APInt::getAllOnesValue(NewBW); 10814 uint64_t PtrOff = ShAmt / 8; 10815 // For big endian targets, we need to adjust the offset to the pointer to 10816 // load the correct bytes. 10817 if (DAG.getDataLayout().isBigEndian()) 10818 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10819 10820 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10821 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10822 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10823 return SDValue(); 10824 10825 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10826 Ptr.getValueType(), Ptr, 10827 DAG.getConstant(PtrOff, SDLoc(LD), 10828 Ptr.getValueType())); 10829 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10830 LD->getChain(), NewPtr, 10831 LD->getPointerInfo().getWithOffset(PtrOff), 10832 LD->isVolatile(), LD->isNonTemporal(), 10833 LD->isInvariant(), NewAlign, 10834 LD->getAAInfo()); 10835 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10836 DAG.getConstant(NewImm, SDLoc(Value), 10837 NewVT)); 10838 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10839 NewVal, NewPtr, 10840 ST->getPointerInfo().getWithOffset(PtrOff), 10841 false, false, NewAlign); 10842 10843 AddToWorklist(NewPtr.getNode()); 10844 AddToWorklist(NewLD.getNode()); 10845 AddToWorklist(NewVal.getNode()); 10846 WorklistRemover DeadNodes(*this); 10847 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10848 ++OpsNarrowed; 10849 return NewST; 10850 } 10851 } 10852 10853 return SDValue(); 10854 } 10855 10856 /// For a given floating point load / store pair, if the load value isn't used 10857 /// by any other operations, then consider transforming the pair to integer 10858 /// load / store operations if the target deems the transformation profitable. 10859 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10860 StoreSDNode *ST = cast<StoreSDNode>(N); 10861 SDValue Chain = ST->getChain(); 10862 SDValue Value = ST->getValue(); 10863 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10864 Value.hasOneUse() && 10865 Chain == SDValue(Value.getNode(), 1)) { 10866 LoadSDNode *LD = cast<LoadSDNode>(Value); 10867 EVT VT = LD->getMemoryVT(); 10868 if (!VT.isFloatingPoint() || 10869 VT != ST->getMemoryVT() || 10870 LD->isNonTemporal() || 10871 ST->isNonTemporal() || 10872 LD->getPointerInfo().getAddrSpace() != 0 || 10873 ST->getPointerInfo().getAddrSpace() != 0) 10874 return SDValue(); 10875 10876 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10877 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10878 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10879 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10880 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10881 return SDValue(); 10882 10883 unsigned LDAlign = LD->getAlignment(); 10884 unsigned STAlign = ST->getAlignment(); 10885 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10886 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10887 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10888 return SDValue(); 10889 10890 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10891 LD->getChain(), LD->getBasePtr(), 10892 LD->getPointerInfo(), 10893 false, false, false, LDAlign); 10894 10895 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10896 NewLD, ST->getBasePtr(), 10897 ST->getPointerInfo(), 10898 false, false, STAlign); 10899 10900 AddToWorklist(NewLD.getNode()); 10901 AddToWorklist(NewST.getNode()); 10902 WorklistRemover DeadNodes(*this); 10903 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10904 ++LdStFP2Int; 10905 return NewST; 10906 } 10907 10908 return SDValue(); 10909 } 10910 10911 namespace { 10912 /// Helper struct to parse and store a memory address as base + index + offset. 10913 /// We ignore sign extensions when it is safe to do so. 10914 /// The following two expressions are not equivalent. To differentiate we need 10915 /// to store whether there was a sign extension involved in the index 10916 /// computation. 10917 /// (load (i64 add (i64 copyfromreg %c) 10918 /// (i64 signextend (add (i8 load %index) 10919 /// (i8 1)))) 10920 /// vs 10921 /// 10922 /// (load (i64 add (i64 copyfromreg %c) 10923 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10924 /// (i32 1))))) 10925 struct BaseIndexOffset { 10926 SDValue Base; 10927 SDValue Index; 10928 int64_t Offset; 10929 bool IsIndexSignExt; 10930 10931 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10932 10933 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10934 bool IsIndexSignExt) : 10935 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10936 10937 bool equalBaseIndex(const BaseIndexOffset &Other) { 10938 return Other.Base == Base && Other.Index == Index && 10939 Other.IsIndexSignExt == IsIndexSignExt; 10940 } 10941 10942 /// Parses tree in Ptr for base, index, offset addresses. 10943 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 10944 bool IsIndexSignExt = false; 10945 10946 // Split up a folded GlobalAddress+Offset into its component parts. 10947 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 10948 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 10949 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 10950 SDLoc(GA), 10951 GA->getValueType(0), 10952 /*Offset=*/0, 10953 /*isTargetGA=*/false, 10954 GA->getTargetFlags()), 10955 SDValue(), 10956 GA->getOffset(), 10957 IsIndexSignExt); 10958 } 10959 10960 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10961 // instruction, then it could be just the BASE or everything else we don't 10962 // know how to handle. Just use Ptr as BASE and give up. 10963 if (Ptr->getOpcode() != ISD::ADD) 10964 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10965 10966 // We know that we have at least an ADD instruction. Try to pattern match 10967 // the simple case of BASE + OFFSET. 10968 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10969 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10970 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10971 IsIndexSignExt); 10972 } 10973 10974 // Inside a loop the current BASE pointer is calculated using an ADD and a 10975 // MUL instruction. In this case Ptr is the actual BASE pointer. 10976 // (i64 add (i64 %array_ptr) 10977 // (i64 mul (i64 %induction_var) 10978 // (i64 %element_size))) 10979 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10980 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10981 10982 // Look at Base + Index + Offset cases. 10983 SDValue Base = Ptr->getOperand(0); 10984 SDValue IndexOffset = Ptr->getOperand(1); 10985 10986 // Skip signextends. 10987 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10988 IndexOffset = IndexOffset->getOperand(0); 10989 IsIndexSignExt = true; 10990 } 10991 10992 // Either the case of Base + Index (no offset) or something else. 10993 if (IndexOffset->getOpcode() != ISD::ADD) 10994 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10995 10996 // Now we have the case of Base + Index + offset. 10997 SDValue Index = IndexOffset->getOperand(0); 10998 SDValue Offset = IndexOffset->getOperand(1); 10999 11000 if (!isa<ConstantSDNode>(Offset)) 11001 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11002 11003 // Ignore signextends. 11004 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11005 Index = Index->getOperand(0); 11006 IsIndexSignExt = true; 11007 } else IsIndexSignExt = false; 11008 11009 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11010 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11011 } 11012 }; 11013 } // namespace 11014 11015 // This is a helper function for visitMUL to check the profitability 11016 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11017 // MulNode is the original multiply, AddNode is (add x, c1), 11018 // and ConstNode is c2. 11019 // 11020 // If the (add x, c1) has multiple uses, we could increase 11021 // the number of adds if we make this transformation. 11022 // It would only be worth doing this if we can remove a 11023 // multiply in the process. Check for that here. 11024 // To illustrate: 11025 // (A + c1) * c3 11026 // (A + c2) * c3 11027 // We're checking for cases where we have common "c3 * A" expressions. 11028 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11029 SDValue &AddNode, 11030 SDValue &ConstNode) { 11031 APInt Val; 11032 11033 // If the add only has one use, this would be OK to do. 11034 if (AddNode.getNode()->hasOneUse()) 11035 return true; 11036 11037 // Walk all the users of the constant with which we're multiplying. 11038 for (SDNode *Use : ConstNode->uses()) { 11039 11040 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11041 continue; 11042 11043 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11044 SDNode *OtherOp; 11045 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11046 11047 // OtherOp is what we're multiplying against the constant. 11048 if (Use->getOperand(0) == ConstNode) 11049 OtherOp = Use->getOperand(1).getNode(); 11050 else 11051 OtherOp = Use->getOperand(0).getNode(); 11052 11053 // Check to see if multiply is with the same operand of our "add". 11054 // 11055 // ConstNode = CONST 11056 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11057 // ... 11058 // AddNode = (A + c1) <-- MulVar is A. 11059 // = AddNode * ConstNode <-- current visiting instruction. 11060 // 11061 // If we make this transformation, we will have a common 11062 // multiply (ConstNode * A) that we can save. 11063 if (OtherOp == MulVar) 11064 return true; 11065 11066 // Now check to see if a future expansion will give us a common 11067 // multiply. 11068 // 11069 // ConstNode = CONST 11070 // AddNode = (A + c1) 11071 // ... = AddNode * ConstNode <-- current visiting instruction. 11072 // ... 11073 // OtherOp = (A + c2) 11074 // Use = OtherOp * ConstNode <-- visiting Use. 11075 // 11076 // If we make this transformation, we will have a common 11077 // multiply (CONST * A) after we also do the same transformation 11078 // to the "t2" instruction. 11079 if (OtherOp->getOpcode() == ISD::ADD && 11080 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11081 OtherOp->getOperand(0).getNode() == MulVar) 11082 return true; 11083 } 11084 } 11085 11086 // Didn't find a case where this would be profitable. 11087 return false; 11088 } 11089 11090 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 11091 SDLoc SL, 11092 ArrayRef<MemOpLink> Stores, 11093 SmallVectorImpl<SDValue> &Chains, 11094 EVT Ty) const { 11095 SmallVector<SDValue, 8> BuildVector; 11096 11097 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11098 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11099 Chains.push_back(St->getChain()); 11100 BuildVector.push_back(St->getValue()); 11101 } 11102 11103 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 11104 } 11105 11106 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11107 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11108 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11109 // Make sure we have something to merge. 11110 if (NumStores < 2) 11111 return false; 11112 11113 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11114 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11115 unsigned LatestNodeUsed = 0; 11116 11117 for (unsigned i=0; i < NumStores; ++i) { 11118 // Find a chain for the new wide-store operand. Notice that some 11119 // of the store nodes that we found may not be selected for inclusion 11120 // in the wide store. The chain we use needs to be the chain of the 11121 // latest store node which is *used* and replaced by the wide store. 11122 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11123 LatestNodeUsed = i; 11124 } 11125 11126 SmallVector<SDValue, 8> Chains; 11127 11128 // The latest Node in the DAG. 11129 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11130 SDLoc DL(StoreNodes[0].MemNode); 11131 11132 SDValue StoredVal; 11133 if (UseVector) { 11134 bool IsVec = MemVT.isVector(); 11135 unsigned Elts = NumStores; 11136 if (IsVec) { 11137 // When merging vector stores, get the total number of elements. 11138 Elts *= MemVT.getVectorNumElements(); 11139 } 11140 // Get the type for the merged vector store. 11141 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11142 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11143 11144 if (IsConstantSrc) { 11145 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11146 } else { 11147 SmallVector<SDValue, 8> Ops; 11148 for (unsigned i = 0; i < NumStores; ++i) { 11149 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11150 SDValue Val = St->getValue(); 11151 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11152 if (Val.getValueType() != MemVT) 11153 return false; 11154 Ops.push_back(Val); 11155 Chains.push_back(St->getChain()); 11156 } 11157 11158 // Build the extracted vector elements back into a vector. 11159 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11160 DL, Ty, Ops); } 11161 } else { 11162 // We should always use a vector store when merging extracted vector 11163 // elements, so this path implies a store of constants. 11164 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11165 11166 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11167 APInt StoreInt(SizeInBits, 0); 11168 11169 // Construct a single integer constant which is made of the smaller 11170 // constant inputs. 11171 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11172 for (unsigned i = 0; i < NumStores; ++i) { 11173 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11174 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11175 Chains.push_back(St->getChain()); 11176 11177 SDValue Val = St->getValue(); 11178 StoreInt <<= ElementSizeBytes * 8; 11179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11180 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11181 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11182 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11183 } else { 11184 llvm_unreachable("Invalid constant element type"); 11185 } 11186 } 11187 11188 // Create the new Load and Store operations. 11189 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11190 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11191 } 11192 11193 assert(!Chains.empty()); 11194 11195 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11196 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11197 FirstInChain->getBasePtr(), 11198 FirstInChain->getPointerInfo(), 11199 false, false, 11200 FirstInChain->getAlignment()); 11201 11202 // Replace the last store with the new store 11203 CombineTo(LatestOp, NewStore); 11204 // Erase all other stores. 11205 for (unsigned i = 0; i < NumStores; ++i) { 11206 if (StoreNodes[i].MemNode == LatestOp) 11207 continue; 11208 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11209 // ReplaceAllUsesWith will replace all uses that existed when it was 11210 // called, but graph optimizations may cause new ones to appear. For 11211 // example, the case in pr14333 looks like 11212 // 11213 // St's chain -> St -> another store -> X 11214 // 11215 // And the only difference from St to the other store is the chain. 11216 // When we change it's chain to be St's chain they become identical, 11217 // get CSEed and the net result is that X is now a use of St. 11218 // Since we know that St is redundant, just iterate. 11219 while (!St->use_empty()) 11220 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11221 deleteAndRecombine(St); 11222 } 11223 11224 return true; 11225 } 11226 11227 void DAGCombiner::getStoreMergeAndAliasCandidates( 11228 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11229 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11230 // This holds the base pointer, index, and the offset in bytes from the base 11231 // pointer. 11232 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11233 11234 // We must have a base and an offset. 11235 if (!BasePtr.Base.getNode()) 11236 return; 11237 11238 // Do not handle stores to undef base pointers. 11239 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 11240 return; 11241 11242 // Walk up the chain and look for nodes with offsets from the same 11243 // base pointer. Stop when reaching an instruction with a different kind 11244 // or instruction which has a different base pointer. 11245 EVT MemVT = St->getMemoryVT(); 11246 unsigned Seq = 0; 11247 StoreSDNode *Index = St; 11248 11249 11250 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11251 : DAG.getSubtarget().useAA(); 11252 11253 if (UseAA) { 11254 // Look at other users of the same chain. Stores on the same chain do not 11255 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11256 // to be on the same chain, so don't bother looking at adjacent chains. 11257 11258 SDValue Chain = St->getChain(); 11259 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11260 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11261 if (I.getOperandNo() != 0) 11262 continue; 11263 11264 if (OtherST->isVolatile() || OtherST->isIndexed()) 11265 continue; 11266 11267 if (OtherST->getMemoryVT() != MemVT) 11268 continue; 11269 11270 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11271 11272 if (Ptr.equalBaseIndex(BasePtr)) 11273 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11274 } 11275 } 11276 11277 return; 11278 } 11279 11280 while (Index) { 11281 // If the chain has more than one use, then we can't reorder the mem ops. 11282 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11283 break; 11284 11285 // Find the base pointer and offset for this memory node. 11286 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11287 11288 // Check that the base pointer is the same as the original one. 11289 if (!Ptr.equalBaseIndex(BasePtr)) 11290 break; 11291 11292 // The memory operands must not be volatile. 11293 if (Index->isVolatile() || Index->isIndexed()) 11294 break; 11295 11296 // No truncation. 11297 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 11298 if (St->isTruncatingStore()) 11299 break; 11300 11301 // The stored memory type must be the same. 11302 if (Index->getMemoryVT() != MemVT) 11303 break; 11304 11305 // We do not allow under-aligned stores in order to prevent 11306 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11307 // be irrelevant here; what MATTERS is that we not move memory 11308 // operations that potentially overlap past each-other. 11309 if (Index->getAlignment() < MemVT.getStoreSize()) 11310 break; 11311 11312 // We found a potential memory operand to merge. 11313 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11314 11315 // Find the next memory operand in the chain. If the next operand in the 11316 // chain is a store then move up and continue the scan with the next 11317 // memory operand. If the next operand is a load save it and use alias 11318 // information to check if it interferes with anything. 11319 SDNode *NextInChain = Index->getChain().getNode(); 11320 while (1) { 11321 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11322 // We found a store node. Use it for the next iteration. 11323 Index = STn; 11324 break; 11325 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11326 if (Ldn->isVolatile()) { 11327 Index = nullptr; 11328 break; 11329 } 11330 11331 // Save the load node for later. Continue the scan. 11332 AliasLoadNodes.push_back(Ldn); 11333 NextInChain = Ldn->getChain().getNode(); 11334 continue; 11335 } else { 11336 Index = nullptr; 11337 break; 11338 } 11339 } 11340 } 11341 } 11342 11343 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11344 if (OptLevel == CodeGenOpt::None) 11345 return false; 11346 11347 EVT MemVT = St->getMemoryVT(); 11348 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11349 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11350 Attribute::NoImplicitFloat); 11351 11352 // This function cannot currently deal with non-byte-sized memory sizes. 11353 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11354 return false; 11355 11356 if (!MemVT.isSimple()) 11357 return false; 11358 11359 // Perform an early exit check. Do not bother looking at stored values that 11360 // are not constants, loads, or extracted vector elements. 11361 SDValue StoredVal = St->getValue(); 11362 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11363 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11364 isa<ConstantFPSDNode>(StoredVal); 11365 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11366 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11367 11368 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11369 return false; 11370 11371 // Don't merge vectors into wider vectors if the source data comes from loads. 11372 // TODO: This restriction can be lifted by using logic similar to the 11373 // ExtractVecSrc case. 11374 if (MemVT.isVector() && IsLoadSrc) 11375 return false; 11376 11377 // Only look at ends of store sequences. 11378 SDValue Chain = SDValue(St, 0); 11379 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11380 return false; 11381 11382 // Save the LoadSDNodes that we find in the chain. 11383 // We need to make sure that these nodes do not interfere with 11384 // any of the store nodes. 11385 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11386 11387 // Save the StoreSDNodes that we find in the chain. 11388 SmallVector<MemOpLink, 8> StoreNodes; 11389 11390 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11391 11392 // Check if there is anything to merge. 11393 if (StoreNodes.size() < 2) 11394 return false; 11395 11396 // Sort the memory operands according to their distance from the 11397 // base pointer. As a secondary criteria: make sure stores coming 11398 // later in the code come first in the list. This is important for 11399 // the non-UseAA case, because we're merging stores into the FINAL 11400 // store along a chain which potentially contains aliasing stores. 11401 // Thus, if there are multiple stores to the same address, the last 11402 // one can be considered for merging but not the others. 11403 std::sort(StoreNodes.begin(), StoreNodes.end(), 11404 [](MemOpLink LHS, MemOpLink RHS) { 11405 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11406 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11407 LHS.SequenceNum < RHS.SequenceNum); 11408 }); 11409 11410 // Scan the memory operations on the chain and find the first non-consecutive 11411 // store memory address. 11412 unsigned LastConsecutiveStore = 0; 11413 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11414 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11415 11416 // Check that the addresses are consecutive starting from the second 11417 // element in the list of stores. 11418 if (i > 0) { 11419 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11420 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11421 break; 11422 } 11423 11424 // Check if this store interferes with any of the loads that we found. 11425 // If we find a load that alias with this store. Stop the sequence. 11426 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(), 11427 [&](LSBaseSDNode* Ldn) { 11428 return isAlias(Ldn, StoreNodes[i].MemNode); 11429 })) 11430 break; 11431 11432 // Mark this node as useful. 11433 LastConsecutiveStore = i; 11434 } 11435 11436 // The node with the lowest store address. 11437 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11438 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11439 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11440 LLVMContext &Context = *DAG.getContext(); 11441 const DataLayout &DL = DAG.getDataLayout(); 11442 11443 // Store the constants into memory as one consecutive store. 11444 if (IsConstantSrc) { 11445 unsigned LastLegalType = 0; 11446 unsigned LastLegalVectorType = 0; 11447 bool NonZero = false; 11448 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11449 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11450 SDValue StoredVal = St->getValue(); 11451 11452 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11453 NonZero |= !C->isNullValue(); 11454 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11455 NonZero |= !C->getConstantFPValue()->isNullValue(); 11456 } else { 11457 // Non-constant. 11458 break; 11459 } 11460 11461 // Find a legal type for the constant store. 11462 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11463 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11464 bool IsFast; 11465 if (TLI.isTypeLegal(StoreTy) && 11466 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11467 FirstStoreAlign, &IsFast) && IsFast) { 11468 LastLegalType = i+1; 11469 // Or check whether a truncstore is legal. 11470 } else if (TLI.getTypeAction(Context, StoreTy) == 11471 TargetLowering::TypePromoteInteger) { 11472 EVT LegalizedStoredValueTy = 11473 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11474 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11475 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11476 FirstStoreAS, FirstStoreAlign, &IsFast) && 11477 IsFast) { 11478 LastLegalType = i + 1; 11479 } 11480 } 11481 11482 // We only use vectors if the constant is known to be zero or the target 11483 // allows it and the function is not marked with the noimplicitfloat 11484 // attribute. 11485 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11486 FirstStoreAS)) && 11487 !NoVectors) { 11488 // Find a legal type for the vector store. 11489 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11490 if (TLI.isTypeLegal(Ty) && 11491 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11492 FirstStoreAlign, &IsFast) && IsFast) 11493 LastLegalVectorType = i + 1; 11494 } 11495 } 11496 11497 // Check if we found a legal integer type to store. 11498 if (LastLegalType == 0 && LastLegalVectorType == 0) 11499 return false; 11500 11501 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11502 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11503 11504 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11505 true, UseVector); 11506 } 11507 11508 // When extracting multiple vector elements, try to store them 11509 // in one vector store rather than a sequence of scalar stores. 11510 if (IsExtractVecSrc) { 11511 unsigned NumStoresToMerge = 0; 11512 bool IsVec = MemVT.isVector(); 11513 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11514 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11515 unsigned StoreValOpcode = St->getValue().getOpcode(); 11516 // This restriction could be loosened. 11517 // Bail out if any stored values are not elements extracted from a vector. 11518 // It should be possible to handle mixed sources, but load sources need 11519 // more careful handling (see the block of code below that handles 11520 // consecutive loads). 11521 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11522 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11523 return false; 11524 11525 // Find a legal type for the vector store. 11526 unsigned Elts = i + 1; 11527 if (IsVec) { 11528 // When merging vector stores, get the total number of elements. 11529 Elts *= MemVT.getVectorNumElements(); 11530 } 11531 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11532 bool IsFast; 11533 if (TLI.isTypeLegal(Ty) && 11534 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11535 FirstStoreAlign, &IsFast) && IsFast) 11536 NumStoresToMerge = i + 1; 11537 } 11538 11539 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11540 false, true); 11541 } 11542 11543 // Below we handle the case of multiple consecutive stores that 11544 // come from multiple consecutive loads. We merge them into a single 11545 // wide load and a single wide store. 11546 11547 // Look for load nodes which are used by the stored values. 11548 SmallVector<MemOpLink, 8> LoadNodes; 11549 11550 // Find acceptable loads. Loads need to have the same chain (token factor), 11551 // must not be zext, volatile, indexed, and they must be consecutive. 11552 BaseIndexOffset LdBasePtr; 11553 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11554 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11555 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11556 if (!Ld) break; 11557 11558 // Loads must only have one use. 11559 if (!Ld->hasNUsesOfValue(1, 0)) 11560 break; 11561 11562 // The memory operands must not be volatile. 11563 if (Ld->isVolatile() || Ld->isIndexed()) 11564 break; 11565 11566 // We do not accept ext loads. 11567 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11568 break; 11569 11570 // The stored memory type must be the same. 11571 if (Ld->getMemoryVT() != MemVT) 11572 break; 11573 11574 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11575 // If this is not the first ptr that we check. 11576 if (LdBasePtr.Base.getNode()) { 11577 // The base ptr must be the same. 11578 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11579 break; 11580 } else { 11581 // Check that all other base pointers are the same as this one. 11582 LdBasePtr = LdPtr; 11583 } 11584 11585 // We found a potential memory operand to merge. 11586 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11587 } 11588 11589 if (LoadNodes.size() < 2) 11590 return false; 11591 11592 // If we have load/store pair instructions and we only have two values, 11593 // don't bother. 11594 unsigned RequiredAlignment; 11595 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11596 St->getAlignment() >= RequiredAlignment) 11597 return false; 11598 11599 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11600 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11601 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11602 11603 // Scan the memory operations on the chain and find the first non-consecutive 11604 // load memory address. These variables hold the index in the store node 11605 // array. 11606 unsigned LastConsecutiveLoad = 0; 11607 // This variable refers to the size and not index in the array. 11608 unsigned LastLegalVectorType = 0; 11609 unsigned LastLegalIntegerType = 0; 11610 StartAddress = LoadNodes[0].OffsetFromBase; 11611 SDValue FirstChain = FirstLoad->getChain(); 11612 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11613 // All loads must share the same chain. 11614 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11615 break; 11616 11617 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11618 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11619 break; 11620 LastConsecutiveLoad = i; 11621 // Find a legal type for the vector store. 11622 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11623 bool IsFastSt, IsFastLd; 11624 if (TLI.isTypeLegal(StoreTy) && 11625 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11626 FirstStoreAlign, &IsFastSt) && IsFastSt && 11627 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11628 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11629 LastLegalVectorType = i + 1; 11630 } 11631 11632 // Find a legal type for the integer store. 11633 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11634 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11635 if (TLI.isTypeLegal(StoreTy) && 11636 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11637 FirstStoreAlign, &IsFastSt) && IsFastSt && 11638 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11639 FirstLoadAlign, &IsFastLd) && IsFastLd) 11640 LastLegalIntegerType = i + 1; 11641 // Or check whether a truncstore and extload is legal. 11642 else if (TLI.getTypeAction(Context, StoreTy) == 11643 TargetLowering::TypePromoteInteger) { 11644 EVT LegalizedStoredValueTy = 11645 TLI.getTypeToTransformTo(Context, StoreTy); 11646 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11647 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11648 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11649 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11650 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11651 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11652 IsFastSt && 11653 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11654 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11655 IsFastLd) 11656 LastLegalIntegerType = i+1; 11657 } 11658 } 11659 11660 // Only use vector types if the vector type is larger than the integer type. 11661 // If they are the same, use integers. 11662 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11663 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11664 11665 // We add +1 here because the LastXXX variables refer to location while 11666 // the NumElem refers to array/index size. 11667 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11668 NumElem = std::min(LastLegalType, NumElem); 11669 11670 if (NumElem < 2) 11671 return false; 11672 11673 // Collect the chains from all merged stores. 11674 SmallVector<SDValue, 8> MergeStoreChains; 11675 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11676 11677 // The latest Node in the DAG. 11678 unsigned LatestNodeUsed = 0; 11679 for (unsigned i=1; i<NumElem; ++i) { 11680 // Find a chain for the new wide-store operand. Notice that some 11681 // of the store nodes that we found may not be selected for inclusion 11682 // in the wide store. The chain we use needs to be the chain of the 11683 // latest store node which is *used* and replaced by the wide store. 11684 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11685 LatestNodeUsed = i; 11686 11687 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11688 } 11689 11690 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11691 11692 // Find if it is better to use vectors or integers to load and store 11693 // to memory. 11694 EVT JointMemOpVT; 11695 if (UseVectorTy) { 11696 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11697 } else { 11698 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11699 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11700 } 11701 11702 SDLoc LoadDL(LoadNodes[0].MemNode); 11703 SDLoc StoreDL(StoreNodes[0].MemNode); 11704 11705 // The merged loads are required to have the same incoming chain, so 11706 // using the first's chain is acceptable. 11707 SDValue NewLoad = DAG.getLoad( 11708 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11709 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11710 11711 SDValue NewStoreChain = 11712 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11713 11714 SDValue NewStore = DAG.getStore( 11715 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11716 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11717 11718 // Transfer chain users from old loads to the new load. 11719 for (unsigned i = 0; i < NumElem; ++i) { 11720 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11721 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11722 SDValue(NewLoad.getNode(), 1)); 11723 } 11724 11725 // Replace the last store with the new store. 11726 CombineTo(LatestOp, NewStore); 11727 // Erase all other stores. 11728 for (unsigned i = 0; i < NumElem ; ++i) { 11729 // Remove all Store nodes. 11730 if (StoreNodes[i].MemNode == LatestOp) 11731 continue; 11732 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11733 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11734 deleteAndRecombine(St); 11735 } 11736 11737 return true; 11738 } 11739 11740 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11741 SDLoc SL(ST); 11742 SDValue ReplStore; 11743 11744 // Replace the chain to avoid dependency. 11745 if (ST->isTruncatingStore()) { 11746 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11747 ST->getBasePtr(), ST->getMemoryVT(), 11748 ST->getMemOperand()); 11749 } else { 11750 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11751 ST->getMemOperand()); 11752 } 11753 11754 // Create token to keep both nodes around. 11755 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11756 MVT::Other, ST->getChain(), ReplStore); 11757 11758 // Make sure the new and old chains are cleaned up. 11759 AddToWorklist(Token.getNode()); 11760 11761 // Don't add users to work list. 11762 return CombineTo(ST, Token, false); 11763 } 11764 11765 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11766 SDValue Value = ST->getValue(); 11767 if (Value.getOpcode() == ISD::TargetConstantFP) 11768 return SDValue(); 11769 11770 SDLoc DL(ST); 11771 11772 SDValue Chain = ST->getChain(); 11773 SDValue Ptr = ST->getBasePtr(); 11774 11775 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11776 11777 // NOTE: If the original store is volatile, this transform must not increase 11778 // the number of stores. For example, on x86-32 an f64 can be stored in one 11779 // processor operation but an i64 (which is not legal) requires two. So the 11780 // transform should not be done in this case. 11781 11782 SDValue Tmp; 11783 switch (CFP->getSimpleValueType(0).SimpleTy) { 11784 default: 11785 llvm_unreachable("Unknown FP type"); 11786 case MVT::f16: // We don't do this for these yet. 11787 case MVT::f80: 11788 case MVT::f128: 11789 case MVT::ppcf128: 11790 return SDValue(); 11791 case MVT::f32: 11792 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11793 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11794 ; 11795 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11796 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11797 MVT::i32); 11798 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11799 } 11800 11801 return SDValue(); 11802 case MVT::f64: 11803 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11804 !ST->isVolatile()) || 11805 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11806 ; 11807 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11808 getZExtValue(), SDLoc(CFP), MVT::i64); 11809 return DAG.getStore(Chain, DL, Tmp, 11810 Ptr, ST->getMemOperand()); 11811 } 11812 11813 if (!ST->isVolatile() && 11814 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11815 // Many FP stores are not made apparent until after legalize, e.g. for 11816 // argument passing. Since this is so common, custom legalize the 11817 // 64-bit integer store into two 32-bit stores. 11818 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11819 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11820 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11821 if (DAG.getDataLayout().isBigEndian()) 11822 std::swap(Lo, Hi); 11823 11824 unsigned Alignment = ST->getAlignment(); 11825 bool isVolatile = ST->isVolatile(); 11826 bool isNonTemporal = ST->isNonTemporal(); 11827 AAMDNodes AAInfo = ST->getAAInfo(); 11828 11829 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11830 Ptr, ST->getPointerInfo(), 11831 isVolatile, isNonTemporal, 11832 ST->getAlignment(), AAInfo); 11833 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11834 DAG.getConstant(4, DL, Ptr.getValueType())); 11835 Alignment = MinAlign(Alignment, 4U); 11836 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11837 Ptr, ST->getPointerInfo().getWithOffset(4), 11838 isVolatile, isNonTemporal, 11839 Alignment, AAInfo); 11840 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11841 St0, St1); 11842 } 11843 11844 return SDValue(); 11845 } 11846 } 11847 11848 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11849 StoreSDNode *ST = cast<StoreSDNode>(N); 11850 SDValue Chain = ST->getChain(); 11851 SDValue Value = ST->getValue(); 11852 SDValue Ptr = ST->getBasePtr(); 11853 11854 // If this is a store of a bit convert, store the input value if the 11855 // resultant store does not need a higher alignment than the original. 11856 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11857 ST->isUnindexed()) { 11858 unsigned OrigAlign = ST->getAlignment(); 11859 EVT SVT = Value.getOperand(0).getValueType(); 11860 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11861 SVT.getTypeForEVT(*DAG.getContext())); 11862 if (Align <= OrigAlign && 11863 ((!LegalOperations && !ST->isVolatile()) || 11864 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11865 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11866 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11867 ST->isNonTemporal(), OrigAlign, 11868 ST->getAAInfo()); 11869 } 11870 11871 // Turn 'store undef, Ptr' -> nothing. 11872 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11873 return Chain; 11874 11875 // Try to infer better alignment information than the store already has. 11876 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11877 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11878 if (Align > ST->getAlignment()) { 11879 SDValue NewStore = 11880 DAG.getTruncStore(Chain, SDLoc(N), Value, 11881 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11882 ST->isVolatile(), ST->isNonTemporal(), Align, 11883 ST->getAAInfo()); 11884 if (NewStore.getNode() != N) 11885 return CombineTo(ST, NewStore, true); 11886 } 11887 } 11888 } 11889 11890 // Try transforming a pair floating point load / store ops to integer 11891 // load / store ops. 11892 if (SDValue NewST = TransformFPLoadStorePair(N)) 11893 return NewST; 11894 11895 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11896 : DAG.getSubtarget().useAA(); 11897 #ifndef NDEBUG 11898 if (CombinerAAOnlyFunc.getNumOccurrences() && 11899 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11900 UseAA = false; 11901 #endif 11902 if (UseAA && ST->isUnindexed()) { 11903 // FIXME: We should do this even without AA enabled. AA will just allow 11904 // FindBetterChain to work in more situations. The problem with this is that 11905 // any combine that expects memory operations to be on consecutive chains 11906 // first needs to be updated to look for users of the same chain. 11907 11908 // Walk up chain skipping non-aliasing memory nodes, on this store and any 11909 // adjacent stores. 11910 if (findBetterNeighborChains(ST)) { 11911 // replaceStoreChain uses CombineTo, which handled all of the worklist 11912 // manipulation. Return the original node to not do anything else. 11913 return SDValue(ST, 0); 11914 } 11915 } 11916 11917 // Try transforming N to an indexed store. 11918 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11919 return SDValue(N, 0); 11920 11921 // FIXME: is there such a thing as a truncating indexed store? 11922 if (ST->isTruncatingStore() && ST->isUnindexed() && 11923 Value.getValueType().isInteger()) { 11924 // See if we can simplify the input to this truncstore with knowledge that 11925 // only the low bits are being used. For example: 11926 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11927 SDValue Shorter = 11928 GetDemandedBits(Value, 11929 APInt::getLowBitsSet( 11930 Value.getValueType().getScalarType().getSizeInBits(), 11931 ST->getMemoryVT().getScalarType().getSizeInBits())); 11932 AddToWorklist(Value.getNode()); 11933 if (Shorter.getNode()) 11934 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11935 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11936 11937 // Otherwise, see if we can simplify the operation with 11938 // SimplifyDemandedBits, which only works if the value has a single use. 11939 if (SimplifyDemandedBits(Value, 11940 APInt::getLowBitsSet( 11941 Value.getValueType().getScalarType().getSizeInBits(), 11942 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11943 return SDValue(N, 0); 11944 } 11945 11946 // If this is a load followed by a store to the same location, then the store 11947 // is dead/noop. 11948 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11949 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11950 ST->isUnindexed() && !ST->isVolatile() && 11951 // There can't be any side effects between the load and store, such as 11952 // a call or store. 11953 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11954 // The store is dead, remove it. 11955 return Chain; 11956 } 11957 } 11958 11959 // If this is a store followed by a store with the same value to the same 11960 // location, then the store is dead/noop. 11961 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11962 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11963 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11964 ST1->isUnindexed() && !ST1->isVolatile()) { 11965 // The store is dead, remove it. 11966 return Chain; 11967 } 11968 } 11969 11970 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11971 // truncating store. We can do this even if this is already a truncstore. 11972 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11973 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11974 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11975 ST->getMemoryVT())) { 11976 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11977 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11978 } 11979 11980 // Only perform this optimization before the types are legal, because we 11981 // don't want to perform this optimization on every DAGCombine invocation. 11982 if (!LegalTypes) { 11983 bool EverChanged = false; 11984 11985 do { 11986 // There can be multiple store sequences on the same chain. 11987 // Keep trying to merge store sequences until we are unable to do so 11988 // or until we merge the last store on the chain. 11989 bool Changed = MergeConsecutiveStores(ST); 11990 EverChanged |= Changed; 11991 if (!Changed) break; 11992 } while (ST->getOpcode() != ISD::DELETED_NODE); 11993 11994 if (EverChanged) 11995 return SDValue(N, 0); 11996 } 11997 11998 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11999 // 12000 // Make sure to do this only after attempting to merge stores in order to 12001 // avoid changing the types of some subset of stores due to visit order, 12002 // preventing their merging. 12003 if (isa<ConstantFPSDNode>(Value)) { 12004 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12005 return NewSt; 12006 } 12007 12008 return ReduceLoadOpStoreWidth(N); 12009 } 12010 12011 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12012 SDValue InVec = N->getOperand(0); 12013 SDValue InVal = N->getOperand(1); 12014 SDValue EltNo = N->getOperand(2); 12015 SDLoc dl(N); 12016 12017 // If the inserted element is an UNDEF, just use the input vector. 12018 if (InVal.getOpcode() == ISD::UNDEF) 12019 return InVec; 12020 12021 EVT VT = InVec.getValueType(); 12022 12023 // If we can't generate a legal BUILD_VECTOR, exit 12024 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12025 return SDValue(); 12026 12027 // Check that we know which element is being inserted 12028 if (!isa<ConstantSDNode>(EltNo)) 12029 return SDValue(); 12030 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12031 12032 // Canonicalize insert_vector_elt dag nodes. 12033 // Example: 12034 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12035 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12036 // 12037 // Do this only if the child insert_vector node has one use; also 12038 // do this only if indices are both constants and Idx1 < Idx0. 12039 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12040 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12041 unsigned OtherElt = 12042 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12043 if (Elt < OtherElt) { 12044 // Swap nodes. 12045 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12046 InVec.getOperand(0), InVal, EltNo); 12047 AddToWorklist(NewOp.getNode()); 12048 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12049 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12050 } 12051 } 12052 12053 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12054 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12055 // vector elements. 12056 SmallVector<SDValue, 8> Ops; 12057 // Do not combine these two vectors if the output vector will not replace 12058 // the input vector. 12059 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12060 Ops.append(InVec.getNode()->op_begin(), 12061 InVec.getNode()->op_end()); 12062 } else if (InVec.getOpcode() == ISD::UNDEF) { 12063 unsigned NElts = VT.getVectorNumElements(); 12064 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12065 } else { 12066 return SDValue(); 12067 } 12068 12069 // Insert the element 12070 if (Elt < Ops.size()) { 12071 // All the operands of BUILD_VECTOR must have the same type; 12072 // we enforce that here. 12073 EVT OpVT = Ops[0].getValueType(); 12074 if (InVal.getValueType() != OpVT) 12075 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12076 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12077 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12078 Ops[Elt] = InVal; 12079 } 12080 12081 // Return the new vector 12082 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 12083 } 12084 12085 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12086 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12087 EVT ResultVT = EVE->getValueType(0); 12088 EVT VecEltVT = InVecVT.getVectorElementType(); 12089 unsigned Align = OriginalLoad->getAlignment(); 12090 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12091 VecEltVT.getTypeForEVT(*DAG.getContext())); 12092 12093 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12094 return SDValue(); 12095 12096 Align = NewAlign; 12097 12098 SDValue NewPtr = OriginalLoad->getBasePtr(); 12099 SDValue Offset; 12100 EVT PtrType = NewPtr.getValueType(); 12101 MachinePointerInfo MPI; 12102 SDLoc DL(EVE); 12103 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12104 int Elt = ConstEltNo->getZExtValue(); 12105 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12106 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12107 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12108 } else { 12109 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12110 Offset = DAG.getNode( 12111 ISD::MUL, DL, PtrType, Offset, 12112 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12113 MPI = OriginalLoad->getPointerInfo(); 12114 } 12115 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12116 12117 // The replacement we need to do here is a little tricky: we need to 12118 // replace an extractelement of a load with a load. 12119 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12120 // Note that this replacement assumes that the extractvalue is the only 12121 // use of the load; that's okay because we don't want to perform this 12122 // transformation in other cases anyway. 12123 SDValue Load; 12124 SDValue Chain; 12125 if (ResultVT.bitsGT(VecEltVT)) { 12126 // If the result type of vextract is wider than the load, then issue an 12127 // extending load instead. 12128 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12129 VecEltVT) 12130 ? ISD::ZEXTLOAD 12131 : ISD::EXTLOAD; 12132 Load = DAG.getExtLoad( 12133 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 12134 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12135 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12136 Chain = Load.getValue(1); 12137 } else { 12138 Load = DAG.getLoad( 12139 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 12140 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12141 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12142 Chain = Load.getValue(1); 12143 if (ResultVT.bitsLT(VecEltVT)) 12144 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12145 else 12146 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 12147 } 12148 WorklistRemover DeadNodes(*this); 12149 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12150 SDValue To[] = { Load, Chain }; 12151 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12152 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12153 // worklist explicitly as well. 12154 AddToWorklist(Load.getNode()); 12155 AddUsersToWorklist(Load.getNode()); // Add users too 12156 // Make sure to revisit this node to clean it up; it will usually be dead. 12157 AddToWorklist(EVE); 12158 ++OpsNarrowed; 12159 return SDValue(EVE, 0); 12160 } 12161 12162 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12163 // (vextract (scalar_to_vector val, 0) -> val 12164 SDValue InVec = N->getOperand(0); 12165 EVT VT = InVec.getValueType(); 12166 EVT NVT = N->getValueType(0); 12167 12168 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12169 // Check if the result type doesn't match the inserted element type. A 12170 // SCALAR_TO_VECTOR may truncate the inserted element and the 12171 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12172 SDValue InOp = InVec.getOperand(0); 12173 if (InOp.getValueType() != NVT) { 12174 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12175 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12176 } 12177 return InOp; 12178 } 12179 12180 SDValue EltNo = N->getOperand(1); 12181 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12182 12183 // extract_vector_elt (build_vector x, y), 1 -> y 12184 if (ConstEltNo && 12185 InVec.getOpcode() == ISD::BUILD_VECTOR && 12186 TLI.isTypeLegal(VT) && 12187 (InVec.hasOneUse() || 12188 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12189 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12190 EVT InEltVT = Elt.getValueType(); 12191 12192 // Sometimes build_vector's scalar input types do not match result type. 12193 if (NVT == InEltVT) 12194 return Elt; 12195 12196 // TODO: It may be useful to truncate if free if the build_vector implicitly 12197 // converts. 12198 } 12199 12200 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12201 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12202 ConstEltNo->isNullValue() && VT.isInteger()) { 12203 SDValue BCSrc = InVec.getOperand(0); 12204 if (BCSrc.getValueType().isScalarInteger()) 12205 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12206 } 12207 12208 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12209 // We only perform this optimization before the op legalization phase because 12210 // we may introduce new vector instructions which are not backed by TD 12211 // patterns. For example on AVX, extracting elements from a wide vector 12212 // without using extract_subvector. However, if we can find an underlying 12213 // scalar value, then we can always use that. 12214 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12215 int NumElem = VT.getVectorNumElements(); 12216 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12217 // Find the new index to extract from. 12218 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12219 12220 // Extracting an undef index is undef. 12221 if (OrigElt == -1) 12222 return DAG.getUNDEF(NVT); 12223 12224 // Select the right vector half to extract from. 12225 SDValue SVInVec; 12226 if (OrigElt < NumElem) { 12227 SVInVec = InVec->getOperand(0); 12228 } else { 12229 SVInVec = InVec->getOperand(1); 12230 OrigElt -= NumElem; 12231 } 12232 12233 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12234 SDValue InOp = SVInVec.getOperand(OrigElt); 12235 if (InOp.getValueType() != NVT) { 12236 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12237 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12238 } 12239 12240 return InOp; 12241 } 12242 12243 // FIXME: We should handle recursing on other vector shuffles and 12244 // scalar_to_vector here as well. 12245 12246 if (!LegalOperations) { 12247 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12248 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12249 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12250 } 12251 } 12252 12253 bool BCNumEltsChanged = false; 12254 EVT ExtVT = VT.getVectorElementType(); 12255 EVT LVT = ExtVT; 12256 12257 // If the result of load has to be truncated, then it's not necessarily 12258 // profitable. 12259 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12260 return SDValue(); 12261 12262 if (InVec.getOpcode() == ISD::BITCAST) { 12263 // Don't duplicate a load with other uses. 12264 if (!InVec.hasOneUse()) 12265 return SDValue(); 12266 12267 EVT BCVT = InVec.getOperand(0).getValueType(); 12268 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12269 return SDValue(); 12270 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12271 BCNumEltsChanged = true; 12272 InVec = InVec.getOperand(0); 12273 ExtVT = BCVT.getVectorElementType(); 12274 } 12275 12276 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12277 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12278 ISD::isNormalLoad(InVec.getNode()) && 12279 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12280 SDValue Index = N->getOperand(1); 12281 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 12282 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12283 OrigLoad); 12284 } 12285 12286 // Perform only after legalization to ensure build_vector / vector_shuffle 12287 // optimizations have already been done. 12288 if (!LegalOperations) return SDValue(); 12289 12290 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12291 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12292 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12293 12294 if (ConstEltNo) { 12295 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12296 12297 LoadSDNode *LN0 = nullptr; 12298 const ShuffleVectorSDNode *SVN = nullptr; 12299 if (ISD::isNormalLoad(InVec.getNode())) { 12300 LN0 = cast<LoadSDNode>(InVec); 12301 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12302 InVec.getOperand(0).getValueType() == ExtVT && 12303 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12304 // Don't duplicate a load with other uses. 12305 if (!InVec.hasOneUse()) 12306 return SDValue(); 12307 12308 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12309 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12310 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12311 // => 12312 // (load $addr+1*size) 12313 12314 // Don't duplicate a load with other uses. 12315 if (!InVec.hasOneUse()) 12316 return SDValue(); 12317 12318 // If the bit convert changed the number of elements, it is unsafe 12319 // to examine the mask. 12320 if (BCNumEltsChanged) 12321 return SDValue(); 12322 12323 // Select the input vector, guarding against out of range extract vector. 12324 unsigned NumElems = VT.getVectorNumElements(); 12325 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12326 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12327 12328 if (InVec.getOpcode() == ISD::BITCAST) { 12329 // Don't duplicate a load with other uses. 12330 if (!InVec.hasOneUse()) 12331 return SDValue(); 12332 12333 InVec = InVec.getOperand(0); 12334 } 12335 if (ISD::isNormalLoad(InVec.getNode())) { 12336 LN0 = cast<LoadSDNode>(InVec); 12337 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12338 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12339 } 12340 } 12341 12342 // Make sure we found a non-volatile load and the extractelement is 12343 // the only use. 12344 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12345 return SDValue(); 12346 12347 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12348 if (Elt == -1) 12349 return DAG.getUNDEF(LVT); 12350 12351 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12352 } 12353 12354 return SDValue(); 12355 } 12356 12357 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12358 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12359 // We perform this optimization post type-legalization because 12360 // the type-legalizer often scalarizes integer-promoted vectors. 12361 // Performing this optimization before may create bit-casts which 12362 // will be type-legalized to complex code sequences. 12363 // We perform this optimization only before the operation legalizer because we 12364 // may introduce illegal operations. 12365 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12366 return SDValue(); 12367 12368 unsigned NumInScalars = N->getNumOperands(); 12369 SDLoc dl(N); 12370 EVT VT = N->getValueType(0); 12371 12372 // Check to see if this is a BUILD_VECTOR of a bunch of values 12373 // which come from any_extend or zero_extend nodes. If so, we can create 12374 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12375 // optimizations. We do not handle sign-extend because we can't fill the sign 12376 // using shuffles. 12377 EVT SourceType = MVT::Other; 12378 bool AllAnyExt = true; 12379 12380 for (unsigned i = 0; i != NumInScalars; ++i) { 12381 SDValue In = N->getOperand(i); 12382 // Ignore undef inputs. 12383 if (In.getOpcode() == ISD::UNDEF) continue; 12384 12385 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12386 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12387 12388 // Abort if the element is not an extension. 12389 if (!ZeroExt && !AnyExt) { 12390 SourceType = MVT::Other; 12391 break; 12392 } 12393 12394 // The input is a ZeroExt or AnyExt. Check the original type. 12395 EVT InTy = In.getOperand(0).getValueType(); 12396 12397 // Check that all of the widened source types are the same. 12398 if (SourceType == MVT::Other) 12399 // First time. 12400 SourceType = InTy; 12401 else if (InTy != SourceType) { 12402 // Multiple income types. Abort. 12403 SourceType = MVT::Other; 12404 break; 12405 } 12406 12407 // Check if all of the extends are ANY_EXTENDs. 12408 AllAnyExt &= AnyExt; 12409 } 12410 12411 // In order to have valid types, all of the inputs must be extended from the 12412 // same source type and all of the inputs must be any or zero extend. 12413 // Scalar sizes must be a power of two. 12414 EVT OutScalarTy = VT.getScalarType(); 12415 bool ValidTypes = SourceType != MVT::Other && 12416 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12417 isPowerOf2_32(SourceType.getSizeInBits()); 12418 12419 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12420 // turn into a single shuffle instruction. 12421 if (!ValidTypes) 12422 return SDValue(); 12423 12424 bool isLE = DAG.getDataLayout().isLittleEndian(); 12425 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12426 assert(ElemRatio > 1 && "Invalid element size ratio"); 12427 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12428 DAG.getConstant(0, SDLoc(N), SourceType); 12429 12430 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12431 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12432 12433 // Populate the new build_vector 12434 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12435 SDValue Cast = N->getOperand(i); 12436 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12437 Cast.getOpcode() == ISD::ZERO_EXTEND || 12438 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 12439 SDValue In; 12440 if (Cast.getOpcode() == ISD::UNDEF) 12441 In = DAG.getUNDEF(SourceType); 12442 else 12443 In = Cast->getOperand(0); 12444 unsigned Index = isLE ? (i * ElemRatio) : 12445 (i * ElemRatio + (ElemRatio - 1)); 12446 12447 assert(Index < Ops.size() && "Invalid index"); 12448 Ops[Index] = In; 12449 } 12450 12451 // The type of the new BUILD_VECTOR node. 12452 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12453 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12454 "Invalid vector size"); 12455 // Check if the new vector type is legal. 12456 if (!isTypeLegal(VecVT)) return SDValue(); 12457 12458 // Make the new BUILD_VECTOR. 12459 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 12460 12461 // The new BUILD_VECTOR node has the potential to be further optimized. 12462 AddToWorklist(BV.getNode()); 12463 // Bitcast to the desired type. 12464 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12465 } 12466 12467 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12468 EVT VT = N->getValueType(0); 12469 12470 unsigned NumInScalars = N->getNumOperands(); 12471 SDLoc dl(N); 12472 12473 EVT SrcVT = MVT::Other; 12474 unsigned Opcode = ISD::DELETED_NODE; 12475 unsigned NumDefs = 0; 12476 12477 for (unsigned i = 0; i != NumInScalars; ++i) { 12478 SDValue In = N->getOperand(i); 12479 unsigned Opc = In.getOpcode(); 12480 12481 if (Opc == ISD::UNDEF) 12482 continue; 12483 12484 // If all scalar values are floats and converted from integers. 12485 if (Opcode == ISD::DELETED_NODE && 12486 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12487 Opcode = Opc; 12488 } 12489 12490 if (Opc != Opcode) 12491 return SDValue(); 12492 12493 EVT InVT = In.getOperand(0).getValueType(); 12494 12495 // If all scalar values are typed differently, bail out. It's chosen to 12496 // simplify BUILD_VECTOR of integer types. 12497 if (SrcVT == MVT::Other) 12498 SrcVT = InVT; 12499 if (SrcVT != InVT) 12500 return SDValue(); 12501 NumDefs++; 12502 } 12503 12504 // If the vector has just one element defined, it's not worth to fold it into 12505 // a vectorized one. 12506 if (NumDefs < 2) 12507 return SDValue(); 12508 12509 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12510 && "Should only handle conversion from integer to float."); 12511 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12512 12513 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12514 12515 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12516 return SDValue(); 12517 12518 // Just because the floating-point vector type is legal does not necessarily 12519 // mean that the corresponding integer vector type is. 12520 if (!isTypeLegal(NVT)) 12521 return SDValue(); 12522 12523 SmallVector<SDValue, 8> Opnds; 12524 for (unsigned i = 0; i != NumInScalars; ++i) { 12525 SDValue In = N->getOperand(i); 12526 12527 if (In.getOpcode() == ISD::UNDEF) 12528 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12529 else 12530 Opnds.push_back(In.getOperand(0)); 12531 } 12532 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 12533 AddToWorklist(BV.getNode()); 12534 12535 return DAG.getNode(Opcode, dl, VT, BV); 12536 } 12537 12538 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12539 unsigned NumInScalars = N->getNumOperands(); 12540 SDLoc dl(N); 12541 EVT VT = N->getValueType(0); 12542 12543 // A vector built entirely of undefs is undef. 12544 if (ISD::allOperandsUndef(N)) 12545 return DAG.getUNDEF(VT); 12546 12547 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12548 return V; 12549 12550 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12551 return V; 12552 12553 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12554 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12555 // at most two distinct vectors, turn this into a shuffle node. 12556 12557 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12558 if (!isTypeLegal(VT)) 12559 return SDValue(); 12560 12561 // May only combine to shuffle after legalize if shuffle is legal. 12562 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12563 return SDValue(); 12564 12565 SDValue VecIn1, VecIn2; 12566 bool UsesZeroVector = false; 12567 for (unsigned i = 0; i != NumInScalars; ++i) { 12568 SDValue Op = N->getOperand(i); 12569 // Ignore undef inputs. 12570 if (Op.getOpcode() == ISD::UNDEF) continue; 12571 12572 // See if we can combine this build_vector into a blend with a zero vector. 12573 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12574 UsesZeroVector = true; 12575 continue; 12576 } 12577 12578 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12579 // constant index, bail out. 12580 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12581 !isa<ConstantSDNode>(Op.getOperand(1))) { 12582 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12583 break; 12584 } 12585 12586 // We allow up to two distinct input vectors. 12587 SDValue ExtractedFromVec = Op.getOperand(0); 12588 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12589 continue; 12590 12591 if (!VecIn1.getNode()) { 12592 VecIn1 = ExtractedFromVec; 12593 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12594 VecIn2 = ExtractedFromVec; 12595 } else { 12596 // Too many inputs. 12597 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12598 break; 12599 } 12600 } 12601 12602 // If everything is good, we can make a shuffle operation. 12603 if (VecIn1.getNode()) { 12604 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12605 SmallVector<int, 8> Mask; 12606 for (unsigned i = 0; i != NumInScalars; ++i) { 12607 unsigned Opcode = N->getOperand(i).getOpcode(); 12608 if (Opcode == ISD::UNDEF) { 12609 Mask.push_back(-1); 12610 continue; 12611 } 12612 12613 // Operands can also be zero. 12614 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12615 assert(UsesZeroVector && 12616 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12617 "Unexpected node found!"); 12618 Mask.push_back(NumInScalars+i); 12619 continue; 12620 } 12621 12622 // If extracting from the first vector, just use the index directly. 12623 SDValue Extract = N->getOperand(i); 12624 SDValue ExtVal = Extract.getOperand(1); 12625 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12626 if (Extract.getOperand(0) == VecIn1) { 12627 Mask.push_back(ExtIndex); 12628 continue; 12629 } 12630 12631 // Otherwise, use InIdx + InputVecSize 12632 Mask.push_back(InNumElements + ExtIndex); 12633 } 12634 12635 // Avoid introducing illegal shuffles with zero. 12636 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12637 return SDValue(); 12638 12639 // We can't generate a shuffle node with mismatched input and output types. 12640 // Attempt to transform a single input vector to the correct type. 12641 if ((VT != VecIn1.getValueType())) { 12642 // If the input vector type has a different base type to the output 12643 // vector type, bail out. 12644 EVT VTElemType = VT.getVectorElementType(); 12645 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12646 (VecIn2.getNode() && 12647 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12648 return SDValue(); 12649 12650 // If the input vector is too small, widen it. 12651 // We only support widening of vectors which are half the size of the 12652 // output registers. For example XMM->YMM widening on X86 with AVX. 12653 EVT VecInT = VecIn1.getValueType(); 12654 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12655 // If we only have one small input, widen it by adding undef values. 12656 if (!VecIn2.getNode()) 12657 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12658 DAG.getUNDEF(VecIn1.getValueType())); 12659 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12660 // If we have two small inputs of the same type, try to concat them. 12661 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12662 VecIn2 = SDValue(nullptr, 0); 12663 } else 12664 return SDValue(); 12665 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12666 // If the input vector is too large, try to split it. 12667 // We don't support having two input vectors that are too large. 12668 // If the zero vector was used, we can not split the vector, 12669 // since we'd need 3 inputs. 12670 if (UsesZeroVector || VecIn2.getNode()) 12671 return SDValue(); 12672 12673 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12674 return SDValue(); 12675 12676 // Try to replace VecIn1 with two extract_subvectors 12677 // No need to update the masks, they should still be correct. 12678 VecIn2 = DAG.getNode( 12679 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12680 DAG.getConstant(VT.getVectorNumElements(), dl, 12681 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12682 VecIn1 = DAG.getNode( 12683 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12684 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12685 } else 12686 return SDValue(); 12687 } 12688 12689 if (UsesZeroVector) 12690 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12691 DAG.getConstantFP(0.0, dl, VT); 12692 else 12693 // If VecIn2 is unused then change it to undef. 12694 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12695 12696 // Check that we were able to transform all incoming values to the same 12697 // type. 12698 if (VecIn2.getValueType() != VecIn1.getValueType() || 12699 VecIn1.getValueType() != VT) 12700 return SDValue(); 12701 12702 // Return the new VECTOR_SHUFFLE node. 12703 SDValue Ops[2]; 12704 Ops[0] = VecIn1; 12705 Ops[1] = VecIn2; 12706 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12707 } 12708 12709 return SDValue(); 12710 } 12711 12712 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12713 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12714 EVT OpVT = N->getOperand(0).getValueType(); 12715 12716 // If the operands are legal vectors, leave them alone. 12717 if (TLI.isTypeLegal(OpVT)) 12718 return SDValue(); 12719 12720 SDLoc DL(N); 12721 EVT VT = N->getValueType(0); 12722 SmallVector<SDValue, 8> Ops; 12723 12724 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12725 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12726 12727 // Keep track of what we encounter. 12728 bool AnyInteger = false; 12729 bool AnyFP = false; 12730 for (const SDValue &Op : N->ops()) { 12731 if (ISD::BITCAST == Op.getOpcode() && 12732 !Op.getOperand(0).getValueType().isVector()) 12733 Ops.push_back(Op.getOperand(0)); 12734 else if (ISD::UNDEF == Op.getOpcode()) 12735 Ops.push_back(ScalarUndef); 12736 else 12737 return SDValue(); 12738 12739 // Note whether we encounter an integer or floating point scalar. 12740 // If it's neither, bail out, it could be something weird like x86mmx. 12741 EVT LastOpVT = Ops.back().getValueType(); 12742 if (LastOpVT.isFloatingPoint()) 12743 AnyFP = true; 12744 else if (LastOpVT.isInteger()) 12745 AnyInteger = true; 12746 else 12747 return SDValue(); 12748 } 12749 12750 // If any of the operands is a floating point scalar bitcast to a vector, 12751 // use floating point types throughout, and bitcast everything. 12752 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12753 if (AnyFP) { 12754 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12755 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12756 if (AnyInteger) { 12757 for (SDValue &Op : Ops) { 12758 if (Op.getValueType() == SVT) 12759 continue; 12760 if (Op.getOpcode() == ISD::UNDEF) 12761 Op = ScalarUndef; 12762 else 12763 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12764 } 12765 } 12766 } 12767 12768 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12769 VT.getSizeInBits() / SVT.getSizeInBits()); 12770 return DAG.getNode(ISD::BITCAST, DL, VT, 12771 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12772 } 12773 12774 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12775 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12776 // most two distinct vectors the same size as the result, attempt to turn this 12777 // into a legal shuffle. 12778 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12779 EVT VT = N->getValueType(0); 12780 EVT OpVT = N->getOperand(0).getValueType(); 12781 int NumElts = VT.getVectorNumElements(); 12782 int NumOpElts = OpVT.getVectorNumElements(); 12783 12784 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12785 SmallVector<int, 8> Mask; 12786 12787 for (SDValue Op : N->ops()) { 12788 // Peek through any bitcast. 12789 while (Op.getOpcode() == ISD::BITCAST) 12790 Op = Op.getOperand(0); 12791 12792 // UNDEF nodes convert to UNDEF shuffle mask values. 12793 if (Op.getOpcode() == ISD::UNDEF) { 12794 Mask.append((unsigned)NumOpElts, -1); 12795 continue; 12796 } 12797 12798 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12799 return SDValue(); 12800 12801 // What vector are we extracting the subvector from and at what index? 12802 SDValue ExtVec = Op.getOperand(0); 12803 12804 // We want the EVT of the original extraction to correctly scale the 12805 // extraction index. 12806 EVT ExtVT = ExtVec.getValueType(); 12807 12808 // Peek through any bitcast. 12809 while (ExtVec.getOpcode() == ISD::BITCAST) 12810 ExtVec = ExtVec.getOperand(0); 12811 12812 // UNDEF nodes convert to UNDEF shuffle mask values. 12813 if (ExtVec.getOpcode() == ISD::UNDEF) { 12814 Mask.append((unsigned)NumOpElts, -1); 12815 continue; 12816 } 12817 12818 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12819 return SDValue(); 12820 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12821 12822 // Ensure that we are extracting a subvector from a vector the same 12823 // size as the result. 12824 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12825 return SDValue(); 12826 12827 // Scale the subvector index to account for any bitcast. 12828 int NumExtElts = ExtVT.getVectorNumElements(); 12829 if (0 == (NumExtElts % NumElts)) 12830 ExtIdx /= (NumExtElts / NumElts); 12831 else if (0 == (NumElts % NumExtElts)) 12832 ExtIdx *= (NumElts / NumExtElts); 12833 else 12834 return SDValue(); 12835 12836 // At most we can reference 2 inputs in the final shuffle. 12837 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) { 12838 SV0 = ExtVec; 12839 for (int i = 0; i != NumOpElts; ++i) 12840 Mask.push_back(i + ExtIdx); 12841 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) { 12842 SV1 = ExtVec; 12843 for (int i = 0; i != NumOpElts; ++i) 12844 Mask.push_back(i + ExtIdx + NumElts); 12845 } else { 12846 return SDValue(); 12847 } 12848 } 12849 12850 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12851 return SDValue(); 12852 12853 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12854 DAG.getBitcast(VT, SV1), Mask); 12855 } 12856 12857 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12858 // If we only have one input vector, we don't need to do any concatenation. 12859 if (N->getNumOperands() == 1) 12860 return N->getOperand(0); 12861 12862 // Check if all of the operands are undefs. 12863 EVT VT = N->getValueType(0); 12864 if (ISD::allOperandsUndef(N)) 12865 return DAG.getUNDEF(VT); 12866 12867 // Optimize concat_vectors where all but the first of the vectors are undef. 12868 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12869 return Op.getOpcode() == ISD::UNDEF; 12870 })) { 12871 SDValue In = N->getOperand(0); 12872 assert(In.getValueType().isVector() && "Must concat vectors"); 12873 12874 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12875 if (In->getOpcode() == ISD::BITCAST && 12876 !In->getOperand(0)->getValueType(0).isVector()) { 12877 SDValue Scalar = In->getOperand(0); 12878 12879 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12880 // look through the trunc so we can still do the transform: 12881 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12882 if (Scalar->getOpcode() == ISD::TRUNCATE && 12883 !TLI.isTypeLegal(Scalar.getValueType()) && 12884 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12885 Scalar = Scalar->getOperand(0); 12886 12887 EVT SclTy = Scalar->getValueType(0); 12888 12889 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12890 return SDValue(); 12891 12892 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12893 VT.getSizeInBits() / SclTy.getSizeInBits()); 12894 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12895 return SDValue(); 12896 12897 SDLoc dl = SDLoc(N); 12898 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12899 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12900 } 12901 } 12902 12903 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12904 // We have already tested above for an UNDEF only concatenation. 12905 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12906 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12907 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12908 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12909 }; 12910 bool AllBuildVectorsOrUndefs = 12911 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12912 if (AllBuildVectorsOrUndefs) { 12913 SmallVector<SDValue, 8> Opnds; 12914 EVT SVT = VT.getScalarType(); 12915 12916 EVT MinVT = SVT; 12917 if (!SVT.isFloatingPoint()) { 12918 // If BUILD_VECTOR are from built from integer, they may have different 12919 // operand types. Get the smallest type and truncate all operands to it. 12920 bool FoundMinVT = false; 12921 for (const SDValue &Op : N->ops()) 12922 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12923 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12924 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12925 FoundMinVT = true; 12926 } 12927 assert(FoundMinVT && "Concat vector type mismatch"); 12928 } 12929 12930 for (const SDValue &Op : N->ops()) { 12931 EVT OpVT = Op.getValueType(); 12932 unsigned NumElts = OpVT.getVectorNumElements(); 12933 12934 if (ISD::UNDEF == Op.getOpcode()) 12935 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12936 12937 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12938 if (SVT.isFloatingPoint()) { 12939 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12940 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12941 } else { 12942 for (unsigned i = 0; i != NumElts; ++i) 12943 Opnds.push_back( 12944 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12945 } 12946 } 12947 } 12948 12949 assert(VT.getVectorNumElements() == Opnds.size() && 12950 "Concat vector type mismatch"); 12951 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12952 } 12953 12954 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12955 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12956 return V; 12957 12958 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 12959 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 12960 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 12961 return V; 12962 12963 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12964 // nodes often generate nop CONCAT_VECTOR nodes. 12965 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12966 // place the incoming vectors at the exact same location. 12967 SDValue SingleSource = SDValue(); 12968 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12969 12970 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12971 SDValue Op = N->getOperand(i); 12972 12973 if (Op.getOpcode() == ISD::UNDEF) 12974 continue; 12975 12976 // Check if this is the identity extract: 12977 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12978 return SDValue(); 12979 12980 // Find the single incoming vector for the extract_subvector. 12981 if (SingleSource.getNode()) { 12982 if (Op.getOperand(0) != SingleSource) 12983 return SDValue(); 12984 } else { 12985 SingleSource = Op.getOperand(0); 12986 12987 // Check the source type is the same as the type of the result. 12988 // If not, this concat may extend the vector, so we can not 12989 // optimize it away. 12990 if (SingleSource.getValueType() != N->getValueType(0)) 12991 return SDValue(); 12992 } 12993 12994 unsigned IdentityIndex = i * PartNumElem; 12995 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12996 // The extract index must be constant. 12997 if (!CS) 12998 return SDValue(); 12999 13000 // Check that we are reading from the identity index. 13001 if (CS->getZExtValue() != IdentityIndex) 13002 return SDValue(); 13003 } 13004 13005 if (SingleSource.getNode()) 13006 return SingleSource; 13007 13008 return SDValue(); 13009 } 13010 13011 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13012 EVT NVT = N->getValueType(0); 13013 SDValue V = N->getOperand(0); 13014 13015 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13016 // Combine: 13017 // (extract_subvec (concat V1, V2, ...), i) 13018 // Into: 13019 // Vi if possible 13020 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13021 // type. 13022 if (V->getOperand(0).getValueType() != NVT) 13023 return SDValue(); 13024 unsigned Idx = N->getConstantOperandVal(1); 13025 unsigned NumElems = NVT.getVectorNumElements(); 13026 assert((Idx % NumElems) == 0 && 13027 "IDX in concat is not a multiple of the result vector length."); 13028 return V->getOperand(Idx / NumElems); 13029 } 13030 13031 // Skip bitcasting 13032 if (V->getOpcode() == ISD::BITCAST) 13033 V = V.getOperand(0); 13034 13035 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13036 SDLoc dl(N); 13037 // Handle only simple case where vector being inserted and vector 13038 // being extracted are of same type, and are half size of larger vectors. 13039 EVT BigVT = V->getOperand(0).getValueType(); 13040 EVT SmallVT = V->getOperand(1).getValueType(); 13041 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13042 return SDValue(); 13043 13044 // Only handle cases where both indexes are constants with the same type. 13045 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13046 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13047 13048 if (InsIdx && ExtIdx && 13049 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13050 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13051 // Combine: 13052 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13053 // Into: 13054 // indices are equal or bit offsets are equal => V1 13055 // otherwise => (extract_subvec V1, ExtIdx) 13056 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13057 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13058 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 13059 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 13060 DAG.getNode(ISD::BITCAST, dl, 13061 N->getOperand(0).getValueType(), 13062 V->getOperand(0)), N->getOperand(1)); 13063 } 13064 } 13065 13066 return SDValue(); 13067 } 13068 13069 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13070 SDValue V, SelectionDAG &DAG) { 13071 SDLoc DL(V); 13072 EVT VT = V.getValueType(); 13073 13074 switch (V.getOpcode()) { 13075 default: 13076 return V; 13077 13078 case ISD::CONCAT_VECTORS: { 13079 EVT OpVT = V->getOperand(0).getValueType(); 13080 int OpSize = OpVT.getVectorNumElements(); 13081 SmallBitVector OpUsedElements(OpSize, false); 13082 bool FoundSimplification = false; 13083 SmallVector<SDValue, 4> NewOps; 13084 NewOps.reserve(V->getNumOperands()); 13085 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13086 SDValue Op = V->getOperand(i); 13087 bool OpUsed = false; 13088 for (int j = 0; j < OpSize; ++j) 13089 if (UsedElements[i * OpSize + j]) { 13090 OpUsedElements[j] = true; 13091 OpUsed = true; 13092 } 13093 NewOps.push_back( 13094 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13095 : DAG.getUNDEF(OpVT)); 13096 FoundSimplification |= Op == NewOps.back(); 13097 OpUsedElements.reset(); 13098 } 13099 if (FoundSimplification) 13100 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13101 return V; 13102 } 13103 13104 case ISD::INSERT_SUBVECTOR: { 13105 SDValue BaseV = V->getOperand(0); 13106 SDValue SubV = V->getOperand(1); 13107 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13108 if (!IdxN) 13109 return V; 13110 13111 int SubSize = SubV.getValueType().getVectorNumElements(); 13112 int Idx = IdxN->getZExtValue(); 13113 bool SubVectorUsed = false; 13114 SmallBitVector SubUsedElements(SubSize, false); 13115 for (int i = 0; i < SubSize; ++i) 13116 if (UsedElements[i + Idx]) { 13117 SubVectorUsed = true; 13118 SubUsedElements[i] = true; 13119 UsedElements[i + Idx] = false; 13120 } 13121 13122 // Now recurse on both the base and sub vectors. 13123 SDValue SimplifiedSubV = 13124 SubVectorUsed 13125 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13126 : DAG.getUNDEF(SubV.getValueType()); 13127 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13128 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13129 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13130 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13131 return V; 13132 } 13133 } 13134 } 13135 13136 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13137 SDValue N1, SelectionDAG &DAG) { 13138 EVT VT = SVN->getValueType(0); 13139 int NumElts = VT.getVectorNumElements(); 13140 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13141 for (int M : SVN->getMask()) 13142 if (M >= 0 && M < NumElts) 13143 N0UsedElements[M] = true; 13144 else if (M >= NumElts) 13145 N1UsedElements[M - NumElts] = true; 13146 13147 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13148 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13149 if (S0 == N0 && S1 == N1) 13150 return SDValue(); 13151 13152 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13153 } 13154 13155 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13156 // or turn a shuffle of a single concat into simpler shuffle then concat. 13157 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13158 EVT VT = N->getValueType(0); 13159 unsigned NumElts = VT.getVectorNumElements(); 13160 13161 SDValue N0 = N->getOperand(0); 13162 SDValue N1 = N->getOperand(1); 13163 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13164 13165 SmallVector<SDValue, 4> Ops; 13166 EVT ConcatVT = N0.getOperand(0).getValueType(); 13167 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13168 unsigned NumConcats = NumElts / NumElemsPerConcat; 13169 13170 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13171 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13172 // half vector elements. 13173 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 13174 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13175 SVN->getMask().end(), [](int i) { return i == -1; })) { 13176 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13177 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13178 N1 = DAG.getUNDEF(ConcatVT); 13179 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13180 } 13181 13182 // Look at every vector that's inserted. We're looking for exact 13183 // subvector-sized copies from a concatenated vector 13184 for (unsigned I = 0; I != NumConcats; ++I) { 13185 // Make sure we're dealing with a copy. 13186 unsigned Begin = I * NumElemsPerConcat; 13187 bool AllUndef = true, NoUndef = true; 13188 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13189 if (SVN->getMaskElt(J) >= 0) 13190 AllUndef = false; 13191 else 13192 NoUndef = false; 13193 } 13194 13195 if (NoUndef) { 13196 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13197 return SDValue(); 13198 13199 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13200 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13201 return SDValue(); 13202 13203 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13204 if (FirstElt < N0.getNumOperands()) 13205 Ops.push_back(N0.getOperand(FirstElt)); 13206 else 13207 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13208 13209 } else if (AllUndef) { 13210 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13211 } else { // Mixed with general masks and undefs, can't do optimization. 13212 return SDValue(); 13213 } 13214 } 13215 13216 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13217 } 13218 13219 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13220 EVT VT = N->getValueType(0); 13221 unsigned NumElts = VT.getVectorNumElements(); 13222 13223 SDValue N0 = N->getOperand(0); 13224 SDValue N1 = N->getOperand(1); 13225 13226 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13227 13228 // Canonicalize shuffle undef, undef -> undef 13229 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 13230 return DAG.getUNDEF(VT); 13231 13232 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13233 13234 // Canonicalize shuffle v, v -> v, undef 13235 if (N0 == N1) { 13236 SmallVector<int, 8> NewMask; 13237 for (unsigned i = 0; i != NumElts; ++i) { 13238 int Idx = SVN->getMaskElt(i); 13239 if (Idx >= (int)NumElts) Idx -= NumElts; 13240 NewMask.push_back(Idx); 13241 } 13242 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 13243 &NewMask[0]); 13244 } 13245 13246 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13247 if (N0.getOpcode() == ISD::UNDEF) { 13248 SmallVector<int, 8> NewMask; 13249 for (unsigned i = 0; i != NumElts; ++i) { 13250 int Idx = SVN->getMaskElt(i); 13251 if (Idx >= 0) { 13252 if (Idx >= (int)NumElts) 13253 Idx -= NumElts; 13254 else 13255 Idx = -1; // remove reference to lhs 13256 } 13257 NewMask.push_back(Idx); 13258 } 13259 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 13260 &NewMask[0]); 13261 } 13262 13263 // Remove references to rhs if it is undef 13264 if (N1.getOpcode() == ISD::UNDEF) { 13265 bool Changed = false; 13266 SmallVector<int, 8> NewMask; 13267 for (unsigned i = 0; i != NumElts; ++i) { 13268 int Idx = SVN->getMaskElt(i); 13269 if (Idx >= (int)NumElts) { 13270 Idx = -1; 13271 Changed = true; 13272 } 13273 NewMask.push_back(Idx); 13274 } 13275 if (Changed) 13276 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 13277 } 13278 13279 // If it is a splat, check if the argument vector is another splat or a 13280 // build_vector. 13281 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13282 SDNode *V = N0.getNode(); 13283 13284 // If this is a bit convert that changes the element type of the vector but 13285 // not the number of vector elements, look through it. Be careful not to 13286 // look though conversions that change things like v4f32 to v2f64. 13287 if (V->getOpcode() == ISD::BITCAST) { 13288 SDValue ConvInput = V->getOperand(0); 13289 if (ConvInput.getValueType().isVector() && 13290 ConvInput.getValueType().getVectorNumElements() == NumElts) 13291 V = ConvInput.getNode(); 13292 } 13293 13294 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13295 assert(V->getNumOperands() == NumElts && 13296 "BUILD_VECTOR has wrong number of operands"); 13297 SDValue Base; 13298 bool AllSame = true; 13299 for (unsigned i = 0; i != NumElts; ++i) { 13300 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 13301 Base = V->getOperand(i); 13302 break; 13303 } 13304 } 13305 // Splat of <u, u, u, u>, return <u, u, u, u> 13306 if (!Base.getNode()) 13307 return N0; 13308 for (unsigned i = 0; i != NumElts; ++i) { 13309 if (V->getOperand(i) != Base) { 13310 AllSame = false; 13311 break; 13312 } 13313 } 13314 // Splat of <x, x, x, x>, return <x, x, x, x> 13315 if (AllSame) 13316 return N0; 13317 13318 // Canonicalize any other splat as a build_vector. 13319 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13320 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13321 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 13322 V->getValueType(0), Ops); 13323 13324 // We may have jumped through bitcasts, so the type of the 13325 // BUILD_VECTOR may not match the type of the shuffle. 13326 if (V->getValueType(0) != VT) 13327 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13328 return NewBV; 13329 } 13330 } 13331 13332 // There are various patterns used to build up a vector from smaller vectors, 13333 // subvectors, or elements. Scan chains of these and replace unused insertions 13334 // or components with undef. 13335 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13336 return S; 13337 13338 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13339 Level < AfterLegalizeVectorOps && 13340 (N1.getOpcode() == ISD::UNDEF || 13341 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13342 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13343 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13344 return V; 13345 } 13346 13347 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13348 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13349 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13350 SmallVector<SDValue, 8> Ops; 13351 for (int M : SVN->getMask()) { 13352 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13353 if (M >= 0) { 13354 int Idx = M % NumElts; 13355 SDValue &S = (M < (int)NumElts ? N0 : N1); 13356 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13357 Op = S.getOperand(Idx); 13358 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13359 if (Idx == 0) 13360 Op = S.getOperand(0); 13361 } else { 13362 // Operand can't be combined - bail out. 13363 break; 13364 } 13365 } 13366 Ops.push_back(Op); 13367 } 13368 if (Ops.size() == VT.getVectorNumElements()) { 13369 // BUILD_VECTOR requires all inputs to be of the same type, find the 13370 // maximum type and extend them all. 13371 EVT SVT = VT.getScalarType(); 13372 if (SVT.isInteger()) 13373 for (SDValue &Op : Ops) 13374 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13375 if (SVT != VT.getScalarType()) 13376 for (SDValue &Op : Ops) 13377 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13378 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13379 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13380 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 13381 } 13382 } 13383 13384 // If this shuffle only has a single input that is a bitcasted shuffle, 13385 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13386 // back to their original types. 13387 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13388 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 13389 TLI.isTypeLegal(VT)) { 13390 13391 // Peek through the bitcast only if there is one user. 13392 SDValue BC0 = N0; 13393 while (BC0.getOpcode() == ISD::BITCAST) { 13394 if (!BC0.hasOneUse()) 13395 break; 13396 BC0 = BC0.getOperand(0); 13397 } 13398 13399 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13400 if (Scale == 1) 13401 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13402 13403 SmallVector<int, 8> NewMask; 13404 for (int M : Mask) 13405 for (int s = 0; s != Scale; ++s) 13406 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13407 return NewMask; 13408 }; 13409 13410 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13411 EVT SVT = VT.getScalarType(); 13412 EVT InnerVT = BC0->getValueType(0); 13413 EVT InnerSVT = InnerVT.getScalarType(); 13414 13415 // Determine which shuffle works with the smaller scalar type. 13416 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13417 EVT ScaleSVT = ScaleVT.getScalarType(); 13418 13419 if (TLI.isTypeLegal(ScaleVT) && 13420 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13421 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13422 13423 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13424 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13425 13426 // Scale the shuffle masks to the smaller scalar type. 13427 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13428 SmallVector<int, 8> InnerMask = 13429 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13430 SmallVector<int, 8> OuterMask = 13431 ScaleShuffleMask(SVN->getMask(), OuterScale); 13432 13433 // Merge the shuffle masks. 13434 SmallVector<int, 8> NewMask; 13435 for (int M : OuterMask) 13436 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13437 13438 // Test for shuffle mask legality over both commutations. 13439 SDValue SV0 = BC0->getOperand(0); 13440 SDValue SV1 = BC0->getOperand(1); 13441 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13442 if (!LegalMask) { 13443 std::swap(SV0, SV1); 13444 ShuffleVectorSDNode::commuteMask(NewMask); 13445 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13446 } 13447 13448 if (LegalMask) { 13449 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13450 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13451 return DAG.getNode( 13452 ISD::BITCAST, SDLoc(N), VT, 13453 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13454 } 13455 } 13456 } 13457 } 13458 13459 // Canonicalize shuffles according to rules: 13460 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13461 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13462 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13463 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13464 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13465 TLI.isTypeLegal(VT)) { 13466 // The incoming shuffle must be of the same type as the result of the 13467 // current shuffle. 13468 assert(N1->getOperand(0).getValueType() == VT && 13469 "Shuffle types don't match"); 13470 13471 SDValue SV0 = N1->getOperand(0); 13472 SDValue SV1 = N1->getOperand(1); 13473 bool HasSameOp0 = N0 == SV0; 13474 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 13475 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13476 // Commute the operands of this shuffle so that next rule 13477 // will trigger. 13478 return DAG.getCommutedVectorShuffle(*SVN); 13479 } 13480 13481 // Try to fold according to rules: 13482 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13483 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13484 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13485 // Don't try to fold shuffles with illegal type. 13486 // Only fold if this shuffle is the only user of the other shuffle. 13487 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13488 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13489 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13490 13491 // The incoming shuffle must be of the same type as the result of the 13492 // current shuffle. 13493 assert(OtherSV->getOperand(0).getValueType() == VT && 13494 "Shuffle types don't match"); 13495 13496 SDValue SV0, SV1; 13497 SmallVector<int, 4> Mask; 13498 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13499 // operand, and SV1 as the second operand. 13500 for (unsigned i = 0; i != NumElts; ++i) { 13501 int Idx = SVN->getMaskElt(i); 13502 if (Idx < 0) { 13503 // Propagate Undef. 13504 Mask.push_back(Idx); 13505 continue; 13506 } 13507 13508 SDValue CurrentVec; 13509 if (Idx < (int)NumElts) { 13510 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13511 // shuffle mask to identify which vector is actually referenced. 13512 Idx = OtherSV->getMaskElt(Idx); 13513 if (Idx < 0) { 13514 // Propagate Undef. 13515 Mask.push_back(Idx); 13516 continue; 13517 } 13518 13519 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13520 : OtherSV->getOperand(1); 13521 } else { 13522 // This shuffle index references an element within N1. 13523 CurrentVec = N1; 13524 } 13525 13526 // Simple case where 'CurrentVec' is UNDEF. 13527 if (CurrentVec.getOpcode() == ISD::UNDEF) { 13528 Mask.push_back(-1); 13529 continue; 13530 } 13531 13532 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13533 // will be the first or second operand of the combined shuffle. 13534 Idx = Idx % NumElts; 13535 if (!SV0.getNode() || SV0 == CurrentVec) { 13536 // Ok. CurrentVec is the left hand side. 13537 // Update the mask accordingly. 13538 SV0 = CurrentVec; 13539 Mask.push_back(Idx); 13540 continue; 13541 } 13542 13543 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13544 if (SV1.getNode() && SV1 != CurrentVec) 13545 return SDValue(); 13546 13547 // Ok. CurrentVec is the right hand side. 13548 // Update the mask accordingly. 13549 SV1 = CurrentVec; 13550 Mask.push_back(Idx + NumElts); 13551 } 13552 13553 // Check if all indices in Mask are Undef. In case, propagate Undef. 13554 bool isUndefMask = true; 13555 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13556 isUndefMask &= Mask[i] < 0; 13557 13558 if (isUndefMask) 13559 return DAG.getUNDEF(VT); 13560 13561 if (!SV0.getNode()) 13562 SV0 = DAG.getUNDEF(VT); 13563 if (!SV1.getNode()) 13564 SV1 = DAG.getUNDEF(VT); 13565 13566 // Avoid introducing shuffles with illegal mask. 13567 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13568 ShuffleVectorSDNode::commuteMask(Mask); 13569 13570 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13571 return SDValue(); 13572 13573 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13574 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13575 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13576 std::swap(SV0, SV1); 13577 } 13578 13579 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13580 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13581 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13582 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13583 } 13584 13585 return SDValue(); 13586 } 13587 13588 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13589 SDValue InVal = N->getOperand(0); 13590 EVT VT = N->getValueType(0); 13591 13592 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13593 // with a VECTOR_SHUFFLE. 13594 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13595 SDValue InVec = InVal->getOperand(0); 13596 SDValue EltNo = InVal->getOperand(1); 13597 13598 // FIXME: We could support implicit truncation if the shuffle can be 13599 // scaled to a smaller vector scalar type. 13600 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13601 if (C0 && VT == InVec.getValueType() && 13602 VT.getScalarType() == InVal.getValueType()) { 13603 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13604 int Elt = C0->getZExtValue(); 13605 NewMask[0] = Elt; 13606 13607 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13608 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13609 NewMask); 13610 } 13611 } 13612 13613 return SDValue(); 13614 } 13615 13616 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13617 SDValue N0 = N->getOperand(0); 13618 SDValue N2 = N->getOperand(2); 13619 13620 // If the input vector is a concatenation, and the insert replaces 13621 // one of the halves, we can optimize into a single concat_vectors. 13622 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13623 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13624 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13625 EVT VT = N->getValueType(0); 13626 13627 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13628 // (concat_vectors Z, Y) 13629 if (InsIdx == 0) 13630 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13631 N->getOperand(1), N0.getOperand(1)); 13632 13633 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13634 // (concat_vectors X, Z) 13635 if (InsIdx == VT.getVectorNumElements()/2) 13636 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13637 N0.getOperand(0), N->getOperand(1)); 13638 } 13639 13640 return SDValue(); 13641 } 13642 13643 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13644 SDValue N0 = N->getOperand(0); 13645 13646 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13647 if (N0->getOpcode() == ISD::FP16_TO_FP) 13648 return N0->getOperand(0); 13649 13650 return SDValue(); 13651 } 13652 13653 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13654 SDValue N0 = N->getOperand(0); 13655 13656 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13657 if (N0->getOpcode() == ISD::AND) { 13658 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13659 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13660 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13661 N0.getOperand(0)); 13662 } 13663 } 13664 13665 return SDValue(); 13666 } 13667 13668 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13669 /// with the destination vector and a zero vector. 13670 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13671 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13672 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13673 EVT VT = N->getValueType(0); 13674 SDValue LHS = N->getOperand(0); 13675 SDValue RHS = N->getOperand(1); 13676 SDLoc dl(N); 13677 13678 // Make sure we're not running after operation legalization where it 13679 // may have custom lowered the vector shuffles. 13680 if (LegalOperations) 13681 return SDValue(); 13682 13683 if (N->getOpcode() != ISD::AND) 13684 return SDValue(); 13685 13686 if (RHS.getOpcode() == ISD::BITCAST) 13687 RHS = RHS.getOperand(0); 13688 13689 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13690 return SDValue(); 13691 13692 EVT RVT = RHS.getValueType(); 13693 unsigned NumElts = RHS.getNumOperands(); 13694 13695 // Attempt to create a valid clear mask, splitting the mask into 13696 // sub elements and checking to see if each is 13697 // all zeros or all ones - suitable for shuffle masking. 13698 auto BuildClearMask = [&](int Split) { 13699 int NumSubElts = NumElts * Split; 13700 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13701 13702 SmallVector<int, 8> Indices; 13703 for (int i = 0; i != NumSubElts; ++i) { 13704 int EltIdx = i / Split; 13705 int SubIdx = i % Split; 13706 SDValue Elt = RHS.getOperand(EltIdx); 13707 if (Elt.getOpcode() == ISD::UNDEF) { 13708 Indices.push_back(-1); 13709 continue; 13710 } 13711 13712 APInt Bits; 13713 if (isa<ConstantSDNode>(Elt)) 13714 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13715 else if (isa<ConstantFPSDNode>(Elt)) 13716 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13717 else 13718 return SDValue(); 13719 13720 // Extract the sub element from the constant bit mask. 13721 if (DAG.getDataLayout().isBigEndian()) { 13722 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13723 } else { 13724 Bits = Bits.lshr(SubIdx * NumSubBits); 13725 } 13726 13727 if (Split > 1) 13728 Bits = Bits.trunc(NumSubBits); 13729 13730 if (Bits.isAllOnesValue()) 13731 Indices.push_back(i); 13732 else if (Bits == 0) 13733 Indices.push_back(i + NumSubElts); 13734 else 13735 return SDValue(); 13736 } 13737 13738 // Let's see if the target supports this vector_shuffle. 13739 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13740 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13741 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13742 return SDValue(); 13743 13744 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13745 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13746 DAG.getBitcast(ClearVT, LHS), 13747 Zero, &Indices[0])); 13748 }; 13749 13750 // Determine maximum split level (byte level masking). 13751 int MaxSplit = 1; 13752 if (RVT.getScalarSizeInBits() % 8 == 0) 13753 MaxSplit = RVT.getScalarSizeInBits() / 8; 13754 13755 for (int Split = 1; Split <= MaxSplit; ++Split) 13756 if (RVT.getScalarSizeInBits() % Split == 0) 13757 if (SDValue S = BuildClearMask(Split)) 13758 return S; 13759 13760 return SDValue(); 13761 } 13762 13763 /// Visit a binary vector operation, like ADD. 13764 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13765 assert(N->getValueType(0).isVector() && 13766 "SimplifyVBinOp only works on vectors!"); 13767 13768 SDValue LHS = N->getOperand(0); 13769 SDValue RHS = N->getOperand(1); 13770 SDValue Ops[] = {LHS, RHS}; 13771 13772 // See if we can constant fold the vector operation. 13773 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13774 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13775 return Fold; 13776 13777 // Try to convert a constant mask AND into a shuffle clear mask. 13778 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13779 return Shuffle; 13780 13781 // Type legalization might introduce new shuffles in the DAG. 13782 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13783 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13784 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13785 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13786 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 13787 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 13788 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13789 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13790 13791 if (SVN0->getMask().equals(SVN1->getMask())) { 13792 EVT VT = N->getValueType(0); 13793 SDValue UndefVector = LHS.getOperand(1); 13794 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13795 LHS.getOperand(0), RHS.getOperand(0), 13796 N->getFlags()); 13797 AddUsersToWorklist(N); 13798 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13799 &SVN0->getMask()[0]); 13800 } 13801 } 13802 13803 return SDValue(); 13804 } 13805 13806 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13807 SDValue N1, SDValue N2){ 13808 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13809 13810 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13811 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13812 13813 // If we got a simplified select_cc node back from SimplifySelectCC, then 13814 // break it down into a new SETCC node, and a new SELECT node, and then return 13815 // the SELECT node, since we were called with a SELECT node. 13816 if (SCC.getNode()) { 13817 // Check to see if we got a select_cc back (to turn into setcc/select). 13818 // Otherwise, just return whatever node we got back, like fabs. 13819 if (SCC.getOpcode() == ISD::SELECT_CC) { 13820 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13821 N0.getValueType(), 13822 SCC.getOperand(0), SCC.getOperand(1), 13823 SCC.getOperand(4)); 13824 AddToWorklist(SETCC.getNode()); 13825 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13826 SCC.getOperand(2), SCC.getOperand(3)); 13827 } 13828 13829 return SCC; 13830 } 13831 return SDValue(); 13832 } 13833 13834 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13835 /// being selected between, see if we can simplify the select. Callers of this 13836 /// should assume that TheSelect is deleted if this returns true. As such, they 13837 /// should return the appropriate thing (e.g. the node) back to the top-level of 13838 /// the DAG combiner loop to avoid it being looked at. 13839 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13840 SDValue RHS) { 13841 13842 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 13843 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 13844 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13845 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13846 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13847 SDValue Sqrt = RHS; 13848 ISD::CondCode CC; 13849 SDValue CmpLHS; 13850 const ConstantFPSDNode *Zero = nullptr; 13851 13852 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13853 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13854 CmpLHS = TheSelect->getOperand(0); 13855 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13856 } else { 13857 // SELECT or VSELECT 13858 SDValue Cmp = TheSelect->getOperand(0); 13859 if (Cmp.getOpcode() == ISD::SETCC) { 13860 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13861 CmpLHS = Cmp.getOperand(0); 13862 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13863 } 13864 } 13865 if (Zero && Zero->isZero() && 13866 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13867 CC == ISD::SETULT || CC == ISD::SETLT)) { 13868 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 13869 CombineTo(TheSelect, Sqrt); 13870 return true; 13871 } 13872 } 13873 } 13874 // Cannot simplify select with vector condition 13875 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13876 13877 // If this is a select from two identical things, try to pull the operation 13878 // through the select. 13879 if (LHS.getOpcode() != RHS.getOpcode() || 13880 !LHS.hasOneUse() || !RHS.hasOneUse()) 13881 return false; 13882 13883 // If this is a load and the token chain is identical, replace the select 13884 // of two loads with a load through a select of the address to load from. 13885 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13886 // constants have been dropped into the constant pool. 13887 if (LHS.getOpcode() == ISD::LOAD) { 13888 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13889 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13890 13891 // Token chains must be identical. 13892 if (LHS.getOperand(0) != RHS.getOperand(0) || 13893 // Do not let this transformation reduce the number of volatile loads. 13894 LLD->isVolatile() || RLD->isVolatile() || 13895 // FIXME: If either is a pre/post inc/dec load, 13896 // we'd need to split out the address adjustment. 13897 LLD->isIndexed() || RLD->isIndexed() || 13898 // If this is an EXTLOAD, the VT's must match. 13899 LLD->getMemoryVT() != RLD->getMemoryVT() || 13900 // If this is an EXTLOAD, the kind of extension must match. 13901 (LLD->getExtensionType() != RLD->getExtensionType() && 13902 // The only exception is if one of the extensions is anyext. 13903 LLD->getExtensionType() != ISD::EXTLOAD && 13904 RLD->getExtensionType() != ISD::EXTLOAD) || 13905 // FIXME: this discards src value information. This is 13906 // over-conservative. It would be beneficial to be able to remember 13907 // both potential memory locations. Since we are discarding 13908 // src value info, don't do the transformation if the memory 13909 // locations are not in the default address space. 13910 LLD->getPointerInfo().getAddrSpace() != 0 || 13911 RLD->getPointerInfo().getAddrSpace() != 0 || 13912 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13913 LLD->getBasePtr().getValueType())) 13914 return false; 13915 13916 // Check that the select condition doesn't reach either load. If so, 13917 // folding this will induce a cycle into the DAG. If not, this is safe to 13918 // xform, so create a select of the addresses. 13919 SDValue Addr; 13920 if (TheSelect->getOpcode() == ISD::SELECT) { 13921 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13922 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13923 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13924 return false; 13925 // The loads must not depend on one another. 13926 if (LLD->isPredecessorOf(RLD) || 13927 RLD->isPredecessorOf(LLD)) 13928 return false; 13929 Addr = DAG.getSelect(SDLoc(TheSelect), 13930 LLD->getBasePtr().getValueType(), 13931 TheSelect->getOperand(0), LLD->getBasePtr(), 13932 RLD->getBasePtr()); 13933 } else { // Otherwise SELECT_CC 13934 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13935 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13936 13937 if ((LLD->hasAnyUseOfValue(1) && 13938 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13939 (RLD->hasAnyUseOfValue(1) && 13940 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13941 return false; 13942 13943 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13944 LLD->getBasePtr().getValueType(), 13945 TheSelect->getOperand(0), 13946 TheSelect->getOperand(1), 13947 LLD->getBasePtr(), RLD->getBasePtr(), 13948 TheSelect->getOperand(4)); 13949 } 13950 13951 SDValue Load; 13952 // It is safe to replace the two loads if they have different alignments, 13953 // but the new load must be the minimum (most restrictive) alignment of the 13954 // inputs. 13955 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13956 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13957 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13958 Load = DAG.getLoad(TheSelect->getValueType(0), 13959 SDLoc(TheSelect), 13960 // FIXME: Discards pointer and AA info. 13961 LLD->getChain(), Addr, MachinePointerInfo(), 13962 LLD->isVolatile(), LLD->isNonTemporal(), 13963 isInvariant, Alignment); 13964 } else { 13965 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13966 RLD->getExtensionType() : LLD->getExtensionType(), 13967 SDLoc(TheSelect), 13968 TheSelect->getValueType(0), 13969 // FIXME: Discards pointer and AA info. 13970 LLD->getChain(), Addr, MachinePointerInfo(), 13971 LLD->getMemoryVT(), LLD->isVolatile(), 13972 LLD->isNonTemporal(), isInvariant, Alignment); 13973 } 13974 13975 // Users of the select now use the result of the load. 13976 CombineTo(TheSelect, Load); 13977 13978 // Users of the old loads now use the new load's chain. We know the 13979 // old-load value is dead now. 13980 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13981 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13982 return true; 13983 } 13984 13985 return false; 13986 } 13987 13988 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13989 /// where 'cond' is the comparison specified by CC. 13990 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13991 SDValue N2, SDValue N3, 13992 ISD::CondCode CC, bool NotExtCompare) { 13993 // (x ? y : y) -> y. 13994 if (N2 == N3) return N2; 13995 13996 EVT VT = N2.getValueType(); 13997 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13998 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13999 14000 // Determine if the condition we're dealing with is constant 14001 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14002 N0, N1, CC, DL, false); 14003 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14004 14005 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14006 // fold select_cc true, x, y -> x 14007 // fold select_cc false, x, y -> y 14008 return !SCCC->isNullValue() ? N2 : N3; 14009 } 14010 14011 // Check to see if we can simplify the select into an fabs node 14012 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14013 // Allow either -0.0 or 0.0 14014 if (CFP->isZero()) { 14015 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14016 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14017 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14018 N2 == N3.getOperand(0)) 14019 return DAG.getNode(ISD::FABS, DL, VT, N0); 14020 14021 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14022 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14023 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14024 N2.getOperand(0) == N3) 14025 return DAG.getNode(ISD::FABS, DL, VT, N3); 14026 } 14027 } 14028 14029 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14030 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14031 // in it. This is a win when the constant is not otherwise available because 14032 // it replaces two constant pool loads with one. We only do this if the FP 14033 // type is known to be legal, because if it isn't, then we are before legalize 14034 // types an we want the other legalization to happen first (e.g. to avoid 14035 // messing with soft float) and if the ConstantFP is not legal, because if 14036 // it is legal, we may not need to store the FP constant in a constant pool. 14037 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14038 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14039 if (TLI.isTypeLegal(N2.getValueType()) && 14040 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14041 TargetLowering::Legal && 14042 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14043 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14044 // If both constants have multiple uses, then we won't need to do an 14045 // extra load, they are likely around in registers for other users. 14046 (TV->hasOneUse() || FV->hasOneUse())) { 14047 Constant *Elts[] = { 14048 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14049 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14050 }; 14051 Type *FPTy = Elts[0]->getType(); 14052 const DataLayout &TD = DAG.getDataLayout(); 14053 14054 // Create a ConstantArray of the two constants. 14055 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14056 SDValue CPIdx = 14057 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14058 TD.getPrefTypeAlignment(FPTy)); 14059 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14060 14061 // Get the offsets to the 0 and 1 element of the array so that we can 14062 // select between them. 14063 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14064 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14065 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14066 14067 SDValue Cond = DAG.getSetCC(DL, 14068 getSetCCResultType(N0.getValueType()), 14069 N0, N1, CC); 14070 AddToWorklist(Cond.getNode()); 14071 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14072 Cond, One, Zero); 14073 AddToWorklist(CstOffset.getNode()); 14074 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14075 CstOffset); 14076 AddToWorklist(CPIdx.getNode()); 14077 return DAG.getLoad( 14078 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14079 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14080 false, false, false, Alignment); 14081 } 14082 } 14083 14084 // Check to see if we can perform the "gzip trick", transforming 14085 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14086 if (isNullConstant(N3) && CC == ISD::SETLT && 14087 (isNullConstant(N1) || // (a < 0) ? b : 0 14088 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14089 EVT XType = N0.getValueType(); 14090 EVT AType = N2.getValueType(); 14091 if (XType.bitsGE(AType)) { 14092 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14093 // single-bit constant. 14094 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14095 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14096 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14097 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14098 getShiftAmountTy(N0.getValueType())); 14099 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14100 XType, N0, ShCt); 14101 AddToWorklist(Shift.getNode()); 14102 14103 if (XType.bitsGT(AType)) { 14104 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14105 AddToWorklist(Shift.getNode()); 14106 } 14107 14108 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14109 } 14110 14111 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14112 XType, N0, 14113 DAG.getConstant(XType.getSizeInBits() - 1, 14114 SDLoc(N0), 14115 getShiftAmountTy(N0.getValueType()))); 14116 AddToWorklist(Shift.getNode()); 14117 14118 if (XType.bitsGT(AType)) { 14119 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14120 AddToWorklist(Shift.getNode()); 14121 } 14122 14123 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14124 } 14125 } 14126 14127 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14128 // where y is has a single bit set. 14129 // A plaintext description would be, we can turn the SELECT_CC into an AND 14130 // when the condition can be materialized as an all-ones register. Any 14131 // single bit-test can be materialized as an all-ones register with 14132 // shift-left and shift-right-arith. 14133 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14134 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14135 SDValue AndLHS = N0->getOperand(0); 14136 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14137 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14138 // Shift the tested bit over the sign bit. 14139 APInt AndMask = ConstAndRHS->getAPIntValue(); 14140 SDValue ShlAmt = 14141 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14142 getShiftAmountTy(AndLHS.getValueType())); 14143 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14144 14145 // Now arithmetic right shift it all the way over, so the result is either 14146 // all-ones, or zero. 14147 SDValue ShrAmt = 14148 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14149 getShiftAmountTy(Shl.getValueType())); 14150 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14151 14152 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14153 } 14154 } 14155 14156 // fold select C, 16, 0 -> shl C, 4 14157 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14158 TLI.getBooleanContents(N0.getValueType()) == 14159 TargetLowering::ZeroOrOneBooleanContent) { 14160 14161 // If the caller doesn't want us to simplify this into a zext of a compare, 14162 // don't do it. 14163 if (NotExtCompare && N2C->isOne()) 14164 return SDValue(); 14165 14166 // Get a SetCC of the condition 14167 // NOTE: Don't create a SETCC if it's not legal on this target. 14168 if (!LegalOperations || 14169 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14170 SDValue Temp, SCC; 14171 // cast from setcc result type to select result type 14172 if (LegalTypes) { 14173 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14174 N0, N1, CC); 14175 if (N2.getValueType().bitsLT(SCC.getValueType())) 14176 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14177 N2.getValueType()); 14178 else 14179 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14180 N2.getValueType(), SCC); 14181 } else { 14182 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14183 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14184 N2.getValueType(), SCC); 14185 } 14186 14187 AddToWorklist(SCC.getNode()); 14188 AddToWorklist(Temp.getNode()); 14189 14190 if (N2C->isOne()) 14191 return Temp; 14192 14193 // shl setcc result by log2 n2c 14194 return DAG.getNode( 14195 ISD::SHL, DL, N2.getValueType(), Temp, 14196 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14197 getShiftAmountTy(Temp.getValueType()))); 14198 } 14199 } 14200 14201 // Check to see if this is an integer abs. 14202 // select_cc setg[te] X, 0, X, -X -> 14203 // select_cc setgt X, -1, X, -X -> 14204 // select_cc setl[te] X, 0, -X, X -> 14205 // select_cc setlt X, 1, -X, X -> 14206 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14207 if (N1C) { 14208 ConstantSDNode *SubC = nullptr; 14209 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14210 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14211 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14212 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14213 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14214 (N1C->isOne() && CC == ISD::SETLT)) && 14215 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14216 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14217 14218 EVT XType = N0.getValueType(); 14219 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14220 SDLoc DL(N0); 14221 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14222 N0, 14223 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14224 getShiftAmountTy(N0.getValueType()))); 14225 SDValue Add = DAG.getNode(ISD::ADD, DL, 14226 XType, N0, Shift); 14227 AddToWorklist(Shift.getNode()); 14228 AddToWorklist(Add.getNode()); 14229 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14230 } 14231 } 14232 14233 return SDValue(); 14234 } 14235 14236 /// This is a stub for TargetLowering::SimplifySetCC. 14237 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 14238 SDValue N1, ISD::CondCode Cond, 14239 SDLoc DL, bool foldBooleans) { 14240 TargetLowering::DAGCombinerInfo 14241 DagCombineInfo(DAG, Level, false, this); 14242 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14243 } 14244 14245 /// Given an ISD::SDIV node expressing a divide by constant, return 14246 /// a DAG expression to select that will generate the same value by multiplying 14247 /// by a magic number. 14248 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14249 SDValue DAGCombiner::BuildSDIV(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 = 14260 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14261 14262 for (SDNode *N : Built) 14263 AddToWorklist(N); 14264 return S; 14265 } 14266 14267 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14268 /// DAG expression that will generate the same value by right shifting. 14269 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14270 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14271 if (!C) 14272 return SDValue(); 14273 14274 // Avoid division by zero. 14275 if (C->isNullValue()) 14276 return SDValue(); 14277 14278 std::vector<SDNode *> Built; 14279 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14280 14281 for (SDNode *N : Built) 14282 AddToWorklist(N); 14283 return S; 14284 } 14285 14286 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14287 /// expression that will generate the same value by multiplying by a magic 14288 /// number. 14289 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14290 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14291 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14292 if (!C) 14293 return SDValue(); 14294 14295 // Avoid division by zero. 14296 if (C->isNullValue()) 14297 return SDValue(); 14298 14299 std::vector<SDNode*> Built; 14300 SDValue S = 14301 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14302 14303 for (SDNode *N : Built) 14304 AddToWorklist(N); 14305 return S; 14306 } 14307 14308 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14309 if (Level >= AfterLegalizeDAG) 14310 return SDValue(); 14311 14312 // Expose the DAG combiner to the target combiner implementations. 14313 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14314 14315 unsigned Iterations = 0; 14316 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14317 if (Iterations) { 14318 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14319 // For the reciprocal, we need to find the zero of the function: 14320 // F(X) = A X - 1 [which has a zero at X = 1/A] 14321 // => 14322 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14323 // does not require additional intermediate precision] 14324 EVT VT = Op.getValueType(); 14325 SDLoc DL(Op); 14326 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14327 14328 AddToWorklist(Est.getNode()); 14329 14330 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14331 for (unsigned i = 0; i < Iterations; ++i) { 14332 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14333 AddToWorklist(NewEst.getNode()); 14334 14335 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14336 AddToWorklist(NewEst.getNode()); 14337 14338 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14339 AddToWorklist(NewEst.getNode()); 14340 14341 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14342 AddToWorklist(Est.getNode()); 14343 } 14344 } 14345 return Est; 14346 } 14347 14348 return SDValue(); 14349 } 14350 14351 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14352 /// For the reciprocal sqrt, we need to find the zero of the function: 14353 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14354 /// => 14355 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14356 /// As a result, we precompute A/2 prior to the iteration loop. 14357 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14358 unsigned Iterations, 14359 SDNodeFlags *Flags) { 14360 EVT VT = Arg.getValueType(); 14361 SDLoc DL(Arg); 14362 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14363 14364 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14365 // this entire sequence requires only one FP constant. 14366 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14367 AddToWorklist(HalfArg.getNode()); 14368 14369 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14370 AddToWorklist(HalfArg.getNode()); 14371 14372 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14373 for (unsigned i = 0; i < Iterations; ++i) { 14374 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14375 AddToWorklist(NewEst.getNode()); 14376 14377 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14378 AddToWorklist(NewEst.getNode()); 14379 14380 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14381 AddToWorklist(NewEst.getNode()); 14382 14383 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14384 AddToWorklist(Est.getNode()); 14385 } 14386 return Est; 14387 } 14388 14389 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14390 /// For the reciprocal sqrt, we need to find the zero of the function: 14391 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14392 /// => 14393 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14394 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14395 unsigned Iterations, 14396 SDNodeFlags *Flags) { 14397 EVT VT = Arg.getValueType(); 14398 SDLoc DL(Arg); 14399 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14400 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14401 14402 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14403 for (unsigned i = 0; i < Iterations; ++i) { 14404 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14405 AddToWorklist(HalfEst.getNode()); 14406 14407 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14408 AddToWorklist(Est.getNode()); 14409 14410 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14411 AddToWorklist(Est.getNode()); 14412 14413 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14414 AddToWorklist(Est.getNode()); 14415 14416 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14417 AddToWorklist(Est.getNode()); 14418 } 14419 return Est; 14420 } 14421 14422 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14423 if (Level >= AfterLegalizeDAG) 14424 return SDValue(); 14425 14426 // Expose the DAG combiner to the target combiner implementations. 14427 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14428 unsigned Iterations = 0; 14429 bool UseOneConstNR = false; 14430 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14431 AddToWorklist(Est.getNode()); 14432 if (Iterations) { 14433 Est = UseOneConstNR ? 14434 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14435 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14436 } 14437 return Est; 14438 } 14439 14440 return SDValue(); 14441 } 14442 14443 /// Return true if base is a frame index, which is known not to alias with 14444 /// anything but itself. Provides base object and offset as results. 14445 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14446 const GlobalValue *&GV, const void *&CV) { 14447 // Assume it is a primitive operation. 14448 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14449 14450 // If it's an adding a simple constant then integrate the offset. 14451 if (Base.getOpcode() == ISD::ADD) { 14452 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14453 Base = Base.getOperand(0); 14454 Offset += C->getZExtValue(); 14455 } 14456 } 14457 14458 // Return the underlying GlobalValue, and update the Offset. Return false 14459 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14460 // by multiple nodes with different offsets. 14461 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14462 GV = G->getGlobal(); 14463 Offset += G->getOffset(); 14464 return false; 14465 } 14466 14467 // Return the underlying Constant value, and update the Offset. Return false 14468 // for ConstantSDNodes since the same constant pool entry may be represented 14469 // by multiple nodes with different offsets. 14470 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14471 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14472 : (const void *)C->getConstVal(); 14473 Offset += C->getOffset(); 14474 return false; 14475 } 14476 // If it's any of the following then it can't alias with anything but itself. 14477 return isa<FrameIndexSDNode>(Base); 14478 } 14479 14480 /// Return true if there is any possibility that the two addresses overlap. 14481 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14482 // If they are the same then they must be aliases. 14483 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14484 14485 // If they are both volatile then they cannot be reordered. 14486 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14487 14488 // If one operation reads from invariant memory, and the other may store, they 14489 // cannot alias. These should really be checking the equivalent of mayWrite, 14490 // but it only matters for memory nodes other than load /store. 14491 if (Op0->isInvariant() && Op1->writeMem()) 14492 return false; 14493 14494 if (Op1->isInvariant() && Op0->writeMem()) 14495 return false; 14496 14497 // Gather base node and offset information. 14498 SDValue Base1, Base2; 14499 int64_t Offset1, Offset2; 14500 const GlobalValue *GV1, *GV2; 14501 const void *CV1, *CV2; 14502 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14503 Base1, Offset1, GV1, CV1); 14504 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14505 Base2, Offset2, GV2, CV2); 14506 14507 // If they have a same base address then check to see if they overlap. 14508 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14509 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14510 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14511 14512 // It is possible for different frame indices to alias each other, mostly 14513 // when tail call optimization reuses return address slots for arguments. 14514 // To catch this case, look up the actual index of frame indices to compute 14515 // the real alias relationship. 14516 if (isFrameIndex1 && isFrameIndex2) { 14517 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14518 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14519 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14520 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14521 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14522 } 14523 14524 // Otherwise, if we know what the bases are, and they aren't identical, then 14525 // we know they cannot alias. 14526 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14527 return false; 14528 14529 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14530 // compared to the size and offset of the access, we may be able to prove they 14531 // do not alias. This check is conservative for now to catch cases created by 14532 // splitting vector types. 14533 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14534 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14535 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14536 Op1->getMemoryVT().getSizeInBits() >> 3) && 14537 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14538 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14539 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14540 14541 // There is no overlap between these relatively aligned accesses of similar 14542 // size, return no alias. 14543 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14544 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14545 return false; 14546 } 14547 14548 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14549 ? CombinerGlobalAA 14550 : DAG.getSubtarget().useAA(); 14551 #ifndef NDEBUG 14552 if (CombinerAAOnlyFunc.getNumOccurrences() && 14553 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14554 UseAA = false; 14555 #endif 14556 if (UseAA && 14557 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14558 // Use alias analysis information. 14559 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14560 Op1->getSrcValueOffset()); 14561 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14562 Op0->getSrcValueOffset() - MinOffset; 14563 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14564 Op1->getSrcValueOffset() - MinOffset; 14565 AliasResult AAResult = 14566 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14567 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14568 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14569 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14570 if (AAResult == NoAlias) 14571 return false; 14572 } 14573 14574 // Otherwise we have to assume they alias. 14575 return true; 14576 } 14577 14578 /// Walk up chain skipping non-aliasing memory nodes, 14579 /// looking for aliasing nodes and adding them to the Aliases vector. 14580 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14581 SmallVectorImpl<SDValue> &Aliases) { 14582 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14583 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14584 14585 // Get alias information for node. 14586 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14587 14588 // Starting off. 14589 Chains.push_back(OriginalChain); 14590 unsigned Depth = 0; 14591 14592 // Look at each chain and determine if it is an alias. If so, add it to the 14593 // aliases list. If not, then continue up the chain looking for the next 14594 // candidate. 14595 while (!Chains.empty()) { 14596 SDValue Chain = Chains.pop_back_val(); 14597 14598 // For TokenFactor nodes, look at each operand and only continue up the 14599 // chain until we reach the depth limit. 14600 // 14601 // FIXME: The depth check could be made to return the last non-aliasing 14602 // chain we found before we hit a tokenfactor rather than the original 14603 // chain. 14604 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14605 Aliases.clear(); 14606 Aliases.push_back(OriginalChain); 14607 return; 14608 } 14609 14610 // Don't bother if we've been before. 14611 if (!Visited.insert(Chain.getNode()).second) 14612 continue; 14613 14614 switch (Chain.getOpcode()) { 14615 case ISD::EntryToken: 14616 // Entry token is ideal chain operand, but handled in FindBetterChain. 14617 break; 14618 14619 case ISD::LOAD: 14620 case ISD::STORE: { 14621 // Get alias information for Chain. 14622 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14623 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14624 14625 // If chain is alias then stop here. 14626 if (!(IsLoad && IsOpLoad) && 14627 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14628 Aliases.push_back(Chain); 14629 } else { 14630 // Look further up the chain. 14631 Chains.push_back(Chain.getOperand(0)); 14632 ++Depth; 14633 } 14634 break; 14635 } 14636 14637 case ISD::TokenFactor: 14638 // We have to check each of the operands of the token factor for "small" 14639 // token factors, so we queue them up. Adding the operands to the queue 14640 // (stack) in reverse order maintains the original order and increases the 14641 // likelihood that getNode will find a matching token factor (CSE.) 14642 if (Chain.getNumOperands() > 16) { 14643 Aliases.push_back(Chain); 14644 break; 14645 } 14646 for (unsigned n = Chain.getNumOperands(); n;) 14647 Chains.push_back(Chain.getOperand(--n)); 14648 ++Depth; 14649 break; 14650 14651 default: 14652 // For all other instructions we will just have to take what we can get. 14653 Aliases.push_back(Chain); 14654 break; 14655 } 14656 } 14657 14658 // We need to be careful here to also search for aliases through the 14659 // value operand of a store, etc. Consider the following situation: 14660 // Token1 = ... 14661 // L1 = load Token1, %52 14662 // S1 = store Token1, L1, %51 14663 // L2 = load Token1, %52+8 14664 // S2 = store Token1, L2, %51+8 14665 // Token2 = Token(S1, S2) 14666 // L3 = load Token2, %53 14667 // S3 = store Token2, L3, %52 14668 // L4 = load Token2, %53+8 14669 // S4 = store Token2, L4, %52+8 14670 // If we search for aliases of S3 (which loads address %52), and we look 14671 // only through the chain, then we'll miss the trivial dependence on L1 14672 // (which also loads from %52). We then might change all loads and 14673 // stores to use Token1 as their chain operand, which could result in 14674 // copying %53 into %52 before copying %52 into %51 (which should 14675 // happen first). 14676 // 14677 // The problem is, however, that searching for such data dependencies 14678 // can become expensive, and the cost is not directly related to the 14679 // chain depth. Instead, we'll rule out such configurations here by 14680 // insisting that we've visited all chain users (except for users 14681 // of the original chain, which is not necessary). When doing this, 14682 // we need to look through nodes we don't care about (otherwise, things 14683 // like register copies will interfere with trivial cases). 14684 14685 SmallVector<const SDNode *, 16> Worklist; 14686 for (const SDNode *N : Visited) 14687 if (N != OriginalChain.getNode()) 14688 Worklist.push_back(N); 14689 14690 while (!Worklist.empty()) { 14691 const SDNode *M = Worklist.pop_back_val(); 14692 14693 // We have already visited M, and want to make sure we've visited any uses 14694 // of M that we care about. For uses that we've not visisted, and don't 14695 // care about, queue them to the worklist. 14696 14697 for (SDNode::use_iterator UI = M->use_begin(), 14698 UIE = M->use_end(); UI != UIE; ++UI) 14699 if (UI.getUse().getValueType() == MVT::Other && 14700 Visited.insert(*UI).second) { 14701 if (isa<MemSDNode>(*UI)) { 14702 // We've not visited this use, and we care about it (it could have an 14703 // ordering dependency with the original node). 14704 Aliases.clear(); 14705 Aliases.push_back(OriginalChain); 14706 return; 14707 } 14708 14709 // We've not visited this use, but we don't care about it. Mark it as 14710 // visited and enqueue it to the worklist. 14711 Worklist.push_back(*UI); 14712 } 14713 } 14714 } 14715 14716 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14717 /// (aliasing node.) 14718 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14719 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14720 14721 // Accumulate all the aliases to this node. 14722 GatherAllAliases(N, OldChain, Aliases); 14723 14724 // If no operands then chain to entry token. 14725 if (Aliases.size() == 0) 14726 return DAG.getEntryNode(); 14727 14728 // If a single operand then chain to it. We don't need to revisit it. 14729 if (Aliases.size() == 1) 14730 return Aliases[0]; 14731 14732 // Construct a custom tailored token factor. 14733 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14734 } 14735 14736 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14737 // This holds the base pointer, index, and the offset in bytes from the base 14738 // pointer. 14739 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14740 14741 // We must have a base and an offset. 14742 if (!BasePtr.Base.getNode()) 14743 return false; 14744 14745 // Do not handle stores to undef base pointers. 14746 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 14747 return false; 14748 14749 SmallVector<StoreSDNode *, 8> ChainedStores; 14750 ChainedStores.push_back(St); 14751 14752 // Walk up the chain and look for nodes with offsets from the same 14753 // base pointer. Stop when reaching an instruction with a different kind 14754 // or instruction which has a different base pointer. 14755 StoreSDNode *Index = St; 14756 while (Index) { 14757 // If the chain has more than one use, then we can't reorder the mem ops. 14758 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14759 break; 14760 14761 if (Index->isVolatile() || Index->isIndexed()) 14762 break; 14763 14764 // Find the base pointer and offset for this memory node. 14765 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 14766 14767 // Check that the base pointer is the same as the original one. 14768 if (!Ptr.equalBaseIndex(BasePtr)) 14769 break; 14770 14771 // Find the next memory operand in the chain. If the next operand in the 14772 // chain is a store then move up and continue the scan with the next 14773 // memory operand. If the next operand is a load save it and use alias 14774 // information to check if it interferes with anything. 14775 SDNode *NextInChain = Index->getChain().getNode(); 14776 while (true) { 14777 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14778 // We found a store node. Use it for the next iteration. 14779 if (STn->isVolatile() || STn->isIndexed()) { 14780 Index = nullptr; 14781 break; 14782 } 14783 ChainedStores.push_back(STn); 14784 Index = STn; 14785 break; 14786 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14787 NextInChain = Ldn->getChain().getNode(); 14788 continue; 14789 } else { 14790 Index = nullptr; 14791 break; 14792 } 14793 } 14794 } 14795 14796 bool MadeChange = false; 14797 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14798 14799 for (StoreSDNode *ChainedStore : ChainedStores) { 14800 SDValue Chain = ChainedStore->getChain(); 14801 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14802 14803 if (Chain != BetterChain) { 14804 MadeChange = true; 14805 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14806 } 14807 } 14808 14809 // Do all replacements after finding the replacements to make to avoid making 14810 // the chains more complicated by introducing new TokenFactors. 14811 for (auto Replacement : BetterChains) 14812 replaceStoreChain(Replacement.first, Replacement.second); 14813 14814 return MadeChange; 14815 } 14816 14817 /// This is the entry point for the file. 14818 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14819 CodeGenOpt::Level OptLevel) { 14820 /// This is the main entry point to this class. 14821 DAGCombiner(*this, AA, OptLevel).Run(Level); 14822 } 14823