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 visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 277 SDValue visitTRUNCATE(SDNode *N); 278 SDValue visitBITCAST(SDNode *N); 279 SDValue visitBUILD_PAIR(SDNode *N); 280 SDValue visitFADD(SDNode *N); 281 SDValue visitFSUB(SDNode *N); 282 SDValue visitFMUL(SDNode *N); 283 SDValue visitFMA(SDNode *N); 284 SDValue visitFDIV(SDNode *N); 285 SDValue visitFREM(SDNode *N); 286 SDValue visitFSQRT(SDNode *N); 287 SDValue visitFCOPYSIGN(SDNode *N); 288 SDValue visitSINT_TO_FP(SDNode *N); 289 SDValue visitUINT_TO_FP(SDNode *N); 290 SDValue visitFP_TO_SINT(SDNode *N); 291 SDValue visitFP_TO_UINT(SDNode *N); 292 SDValue visitFP_ROUND(SDNode *N); 293 SDValue visitFP_ROUND_INREG(SDNode *N); 294 SDValue visitFP_EXTEND(SDNode *N); 295 SDValue visitFNEG(SDNode *N); 296 SDValue visitFABS(SDNode *N); 297 SDValue visitFCEIL(SDNode *N); 298 SDValue visitFTRUNC(SDNode *N); 299 SDValue visitFFLOOR(SDNode *N); 300 SDValue visitFMINNUM(SDNode *N); 301 SDValue visitFMAXNUM(SDNode *N); 302 SDValue visitBRCOND(SDNode *N); 303 SDValue visitBR_CC(SDNode *N); 304 SDValue visitLOAD(SDNode *N); 305 306 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 307 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 308 309 SDValue visitSTORE(SDNode *N); 310 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 311 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 312 SDValue visitBUILD_VECTOR(SDNode *N); 313 SDValue visitCONCAT_VECTORS(SDNode *N); 314 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 315 SDValue visitVECTOR_SHUFFLE(SDNode *N); 316 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 317 SDValue visitINSERT_SUBVECTOR(SDNode *N); 318 SDValue visitMLOAD(SDNode *N); 319 SDValue visitMSTORE(SDNode *N); 320 SDValue visitMGATHER(SDNode *N); 321 SDValue visitMSCATTER(SDNode *N); 322 SDValue visitFP_TO_FP16(SDNode *N); 323 SDValue visitFP16_TO_FP(SDNode *N); 324 325 SDValue visitFADDForFMACombine(SDNode *N); 326 SDValue visitFSUBForFMACombine(SDNode *N); 327 SDValue visitFMULForFMACombine(SDNode *N); 328 329 SDValue XformToShuffleWithZero(SDNode *N); 330 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 331 332 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 333 334 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 335 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 336 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 337 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 338 SDValue N3, ISD::CondCode CC, 339 bool NotExtCompare = false); 340 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 341 SDLoc DL, bool foldBooleans = true); 342 343 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 344 SDValue &CC) const; 345 bool isOneUseSetCC(SDValue N) const; 346 347 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 348 unsigned HiOp); 349 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 350 SDValue CombineExtLoad(SDNode *N); 351 SDValue combineRepeatedFPDivisors(SDNode *N); 352 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 353 SDValue BuildSDIV(SDNode *N); 354 SDValue BuildSDIVPow2(SDNode *N); 355 SDValue BuildUDIV(SDNode *N); 356 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 357 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 358 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 359 SDNodeFlags *Flags); 360 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 361 SDNodeFlags *Flags); 362 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 363 bool DemandHighBits = true); 364 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 365 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 366 SDValue InnerPos, SDValue InnerNeg, 367 unsigned PosOpcode, unsigned NegOpcode, 368 SDLoc DL); 369 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 370 SDValue ReduceLoadWidth(SDNode *N); 371 SDValue ReduceLoadOpStoreWidth(SDNode *N); 372 SDValue TransformFPLoadStorePair(SDNode *N); 373 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 374 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 375 376 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 377 378 /// Walk up chain skipping non-aliasing memory nodes, 379 /// looking for aliasing nodes and adding them to the Aliases vector. 380 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 381 SmallVectorImpl<SDValue> &Aliases); 382 383 /// Return true if there is any possibility that the two addresses overlap. 384 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 385 386 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 387 /// chain (aliasing node.) 388 SDValue FindBetterChain(SDNode *N, SDValue Chain); 389 390 /// Do FindBetterChain for a store and any possibly adjacent stores on 391 /// consecutive chains. 392 bool findBetterNeighborChains(StoreSDNode *St); 393 394 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 395 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 396 397 /// Holds a pointer to an LSBaseSDNode as well as information on where it 398 /// is located in a sequence of memory operations connected by a chain. 399 struct MemOpLink { 400 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 401 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 402 // Ptr to the mem node. 403 LSBaseSDNode *MemNode; 404 // Offset from the base ptr. 405 int64_t OffsetFromBase; 406 // What is the sequence number of this mem node. 407 // Lowest mem operand in the DAG starts at zero. 408 unsigned SequenceNum; 409 }; 410 411 /// This is a helper function for visitMUL to check the profitability 412 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 413 /// MulNode is the original multiply, AddNode is (add x, c1), 414 /// and ConstNode is c2. 415 bool isMulAddWithConstProfitable(SDNode *MulNode, 416 SDValue &AddNode, 417 SDValue &ConstNode); 418 419 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 420 /// constant build_vector of the stored constant values in Stores. 421 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 422 SDLoc SL, 423 ArrayRef<MemOpLink> Stores, 424 SmallVectorImpl<SDValue> &Chains, 425 EVT Ty) const; 426 427 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 428 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 429 /// the type of the loaded value to be extended. LoadedVT returns the type 430 /// of the original loaded value. NarrowLoad returns whether the load would 431 /// need to be narrowed in order to match. 432 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 433 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 434 bool &NarrowLoad); 435 436 /// This is a helper function for MergeConsecutiveStores. When the source 437 /// elements of the consecutive stores are all constants or all extracted 438 /// vector elements, try to merge them into one larger store. 439 /// \return True if a merged store was created. 440 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 441 EVT MemVT, unsigned NumStores, 442 bool IsConstantSrc, bool UseVector); 443 444 /// This is a helper function for MergeConsecutiveStores. 445 /// Stores that may be merged are placed in StoreNodes. 446 /// Loads that may alias with those stores are placed in AliasLoadNodes. 447 void getStoreMergeAndAliasCandidates( 448 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 449 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 450 451 /// Helper function for MergeConsecutiveStores. Checks if 452 /// Candidate stores have indirect dependency through their 453 /// operands. \return True if safe to merge 454 bool checkMergeStoreCandidatesForDependencies( 455 SmallVectorImpl<MemOpLink> &StoreNodes); 456 457 /// Merge consecutive store operations into a wide store. 458 /// This optimization uses wide integers or vectors when possible. 459 /// \return True if some memory operations were changed. 460 bool MergeConsecutiveStores(StoreSDNode *N); 461 462 /// \brief Try to transform a truncation where C is a constant: 463 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 464 /// 465 /// \p N needs to be a truncation and its first operand an AND. Other 466 /// requirements are checked by the function (e.g. that trunc is 467 /// single-use) and if missed an empty SDValue is returned. 468 SDValue distributeTruncateThroughAnd(SDNode *N); 469 470 public: 471 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 472 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 473 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 474 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 475 } 476 477 /// Runs the dag combiner on all nodes in the work list 478 void Run(CombineLevel AtLevel); 479 480 SelectionDAG &getDAG() const { return DAG; } 481 482 /// Returns a type large enough to hold any valid shift amount - before type 483 /// legalization these can be huge. 484 EVT getShiftAmountTy(EVT LHSTy) { 485 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 486 if (LHSTy.isVector()) 487 return LHSTy; 488 auto &DL = DAG.getDataLayout(); 489 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 490 : TLI.getPointerTy(DL); 491 } 492 493 /// This method returns true if we are running before type legalization or 494 /// if the specified VT is legal. 495 bool isTypeLegal(const EVT &VT) { 496 if (!LegalTypes) return true; 497 return TLI.isTypeLegal(VT); 498 } 499 500 /// Convenience wrapper around TargetLowering::getSetCCResultType 501 EVT getSetCCResultType(EVT VT) const { 502 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 503 } 504 }; 505 } 506 507 508 namespace { 509 /// This class is a DAGUpdateListener that removes any deleted 510 /// nodes from the worklist. 511 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 512 DAGCombiner &DC; 513 public: 514 explicit WorklistRemover(DAGCombiner &dc) 515 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 516 517 void NodeDeleted(SDNode *N, SDNode *E) override { 518 DC.removeFromWorklist(N); 519 } 520 }; 521 } 522 523 //===----------------------------------------------------------------------===// 524 // TargetLowering::DAGCombinerInfo implementation 525 //===----------------------------------------------------------------------===// 526 527 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 528 ((DAGCombiner*)DC)->AddToWorklist(N); 529 } 530 531 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 532 ((DAGCombiner*)DC)->removeFromWorklist(N); 533 } 534 535 SDValue TargetLowering::DAGCombinerInfo:: 536 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 537 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 538 } 539 540 SDValue TargetLowering::DAGCombinerInfo:: 541 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 542 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 543 } 544 545 546 SDValue TargetLowering::DAGCombinerInfo:: 547 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 548 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 549 } 550 551 void TargetLowering::DAGCombinerInfo:: 552 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 553 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 554 } 555 556 //===----------------------------------------------------------------------===// 557 // Helper Functions 558 //===----------------------------------------------------------------------===// 559 560 void DAGCombiner::deleteAndRecombine(SDNode *N) { 561 removeFromWorklist(N); 562 563 // If the operands of this node are only used by the node, they will now be 564 // dead. Make sure to re-visit them and recursively delete dead nodes. 565 for (const SDValue &Op : N->ops()) 566 // For an operand generating multiple values, one of the values may 567 // become dead allowing further simplification (e.g. split index 568 // arithmetic from an indexed load). 569 if (Op->hasOneUse() || Op->getNumValues() > 1) 570 AddToWorklist(Op.getNode()); 571 572 DAG.DeleteNode(N); 573 } 574 575 /// Return 1 if we can compute the negated form of the specified expression for 576 /// the same cost as the expression itself, or 2 if we can compute the negated 577 /// form more cheaply than the expression itself. 578 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 579 const TargetLowering &TLI, 580 const TargetOptions *Options, 581 unsigned Depth = 0) { 582 // fneg is removable even if it has multiple uses. 583 if (Op.getOpcode() == ISD::FNEG) return 2; 584 585 // Don't allow anything with multiple uses. 586 if (!Op.hasOneUse()) return 0; 587 588 // Don't recurse exponentially. 589 if (Depth > 6) return 0; 590 591 switch (Op.getOpcode()) { 592 default: return false; 593 case ISD::ConstantFP: 594 // Don't invert constant FP values after legalize. The negated constant 595 // isn't necessarily legal. 596 return LegalOperations ? 0 : 1; 597 case ISD::FADD: 598 // FIXME: determine better conditions for this xform. 599 if (!Options->UnsafeFPMath) return 0; 600 601 // After operation legalization, it might not be legal to create new FSUBs. 602 if (LegalOperations && 603 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 604 return 0; 605 606 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 607 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 608 Options, Depth + 1)) 609 return V; 610 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 611 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 612 Depth + 1); 613 case ISD::FSUB: 614 // We can't turn -(A-B) into B-A when we honor signed zeros. 615 if (!Options->UnsafeFPMath) return 0; 616 617 // fold (fneg (fsub A, B)) -> (fsub B, A) 618 return 1; 619 620 case ISD::FMUL: 621 case ISD::FDIV: 622 if (Options->HonorSignDependentRoundingFPMath()) return 0; 623 624 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 625 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 626 Options, Depth + 1)) 627 return V; 628 629 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 630 Depth + 1); 631 632 case ISD::FP_EXTEND: 633 case ISD::FP_ROUND: 634 case ISD::FSIN: 635 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 636 Depth + 1); 637 } 638 } 639 640 /// If isNegatibleForFree returns true, return the newly negated expression. 641 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 642 bool LegalOperations, unsigned Depth = 0) { 643 const TargetOptions &Options = DAG.getTarget().Options; 644 // fneg is removable even if it has multiple uses. 645 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 646 647 // Don't allow anything with multiple uses. 648 assert(Op.hasOneUse() && "Unknown reuse!"); 649 650 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 651 652 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 653 654 switch (Op.getOpcode()) { 655 default: llvm_unreachable("Unknown code"); 656 case ISD::ConstantFP: { 657 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 658 V.changeSign(); 659 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 660 } 661 case ISD::FADD: 662 // FIXME: determine better conditions for this xform. 663 assert(Options.UnsafeFPMath); 664 665 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 666 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 667 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 668 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 669 GetNegatedExpression(Op.getOperand(0), DAG, 670 LegalOperations, Depth+1), 671 Op.getOperand(1), Flags); 672 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 673 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 674 GetNegatedExpression(Op.getOperand(1), DAG, 675 LegalOperations, Depth+1), 676 Op.getOperand(0), Flags); 677 case ISD::FSUB: 678 // We can't turn -(A-B) into B-A when we honor signed zeros. 679 assert(Options.UnsafeFPMath); 680 681 // fold (fneg (fsub 0, B)) -> B 682 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 683 if (N0CFP->isZero()) 684 return Op.getOperand(1); 685 686 // fold (fneg (fsub A, B)) -> (fsub B, A) 687 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 688 Op.getOperand(1), Op.getOperand(0), Flags); 689 690 case ISD::FMUL: 691 case ISD::FDIV: 692 assert(!Options.HonorSignDependentRoundingFPMath()); 693 694 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 695 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 696 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 697 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 698 GetNegatedExpression(Op.getOperand(0), DAG, 699 LegalOperations, Depth+1), 700 Op.getOperand(1), Flags); 701 702 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 703 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 704 Op.getOperand(0), 705 GetNegatedExpression(Op.getOperand(1), DAG, 706 LegalOperations, Depth+1), Flags); 707 708 case ISD::FP_EXTEND: 709 case ISD::FSIN: 710 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 711 GetNegatedExpression(Op.getOperand(0), DAG, 712 LegalOperations, Depth+1)); 713 case ISD::FP_ROUND: 714 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 715 GetNegatedExpression(Op.getOperand(0), DAG, 716 LegalOperations, Depth+1), 717 Op.getOperand(1)); 718 } 719 } 720 721 // Return true if this node is a setcc, or is a select_cc 722 // that selects between the target values used for true and false, making it 723 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 724 // the appropriate nodes based on the type of node we are checking. This 725 // simplifies life a bit for the callers. 726 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 727 SDValue &CC) const { 728 if (N.getOpcode() == ISD::SETCC) { 729 LHS = N.getOperand(0); 730 RHS = N.getOperand(1); 731 CC = N.getOperand(2); 732 return true; 733 } 734 735 if (N.getOpcode() != ISD::SELECT_CC || 736 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 737 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 738 return false; 739 740 if (TLI.getBooleanContents(N.getValueType()) == 741 TargetLowering::UndefinedBooleanContent) 742 return false; 743 744 LHS = N.getOperand(0); 745 RHS = N.getOperand(1); 746 CC = N.getOperand(4); 747 return true; 748 } 749 750 /// Return true if this is a SetCC-equivalent operation with only one use. 751 /// If this is true, it allows the users to invert the operation for free when 752 /// it is profitable to do so. 753 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 754 SDValue N0, N1, N2; 755 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 756 return true; 757 return false; 758 } 759 760 /// Returns true if N is a BUILD_VECTOR node whose 761 /// elements are all the same constant or undefined. 762 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 763 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 764 if (!C) 765 return false; 766 767 APInt SplatUndef; 768 unsigned SplatBitSize; 769 bool HasAnyUndefs; 770 EVT EltVT = N->getValueType(0).getVectorElementType(); 771 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 772 HasAnyUndefs) && 773 EltVT.getSizeInBits() >= SplatBitSize); 774 } 775 776 // \brief Returns the SDNode if it is a constant float BuildVector 777 // or constant float. 778 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 779 if (isa<ConstantFPSDNode>(N)) 780 return N.getNode(); 781 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 782 return N.getNode(); 783 return nullptr; 784 } 785 786 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 787 // int. 788 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 789 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 790 return CN; 791 792 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 793 BitVector UndefElements; 794 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 795 796 // BuildVectors can truncate their operands. Ignore that case here. 797 // FIXME: We blindly ignore splats which include undef which is overly 798 // pessimistic. 799 if (CN && UndefElements.none() && 800 CN->getValueType(0) == N.getValueType().getScalarType()) 801 return CN; 802 } 803 804 return nullptr; 805 } 806 807 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 808 // float. 809 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 810 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 811 return CN; 812 813 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 814 BitVector UndefElements; 815 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 816 817 if (CN && UndefElements.none()) 818 return CN; 819 } 820 821 return nullptr; 822 } 823 824 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 825 SDValue N0, SDValue N1) { 826 EVT VT = N0.getValueType(); 827 if (N0.getOpcode() == Opc) { 828 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 829 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 830 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 831 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 832 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 833 return SDValue(); 834 } 835 if (N0.hasOneUse()) { 836 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 837 // use 838 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 839 if (!OpNode.getNode()) 840 return SDValue(); 841 AddToWorklist(OpNode.getNode()); 842 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 843 } 844 } 845 } 846 847 if (N1.getOpcode() == Opc) { 848 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 849 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 850 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 851 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 852 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 853 return SDValue(); 854 } 855 if (N1.hasOneUse()) { 856 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 857 // use 858 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 859 if (!OpNode.getNode()) 860 return SDValue(); 861 AddToWorklist(OpNode.getNode()); 862 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 863 } 864 } 865 } 866 867 return SDValue(); 868 } 869 870 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 871 bool AddTo) { 872 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 873 ++NodesCombined; 874 DEBUG(dbgs() << "\nReplacing.1 "; 875 N->dump(&DAG); 876 dbgs() << "\nWith: "; 877 To[0].getNode()->dump(&DAG); 878 dbgs() << " and " << NumTo-1 << " other values\n"); 879 for (unsigned i = 0, e = NumTo; i != e; ++i) 880 assert((!To[i].getNode() || 881 N->getValueType(i) == To[i].getValueType()) && 882 "Cannot combine value to value of different type!"); 883 884 WorklistRemover DeadNodes(*this); 885 DAG.ReplaceAllUsesWith(N, To); 886 if (AddTo) { 887 // Push the new nodes and any users onto the worklist 888 for (unsigned i = 0, e = NumTo; i != e; ++i) { 889 if (To[i].getNode()) { 890 AddToWorklist(To[i].getNode()); 891 AddUsersToWorklist(To[i].getNode()); 892 } 893 } 894 } 895 896 // Finally, if the node is now dead, remove it from the graph. The node 897 // may not be dead if the replacement process recursively simplified to 898 // something else needing this node. 899 if (N->use_empty()) 900 deleteAndRecombine(N); 901 return SDValue(N, 0); 902 } 903 904 void DAGCombiner:: 905 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 906 // Replace all uses. If any nodes become isomorphic to other nodes and 907 // are deleted, make sure to remove them from our worklist. 908 WorklistRemover DeadNodes(*this); 909 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 910 911 // Push the new node and any (possibly new) users onto the worklist. 912 AddToWorklist(TLO.New.getNode()); 913 AddUsersToWorklist(TLO.New.getNode()); 914 915 // Finally, if the node is now dead, remove it from the graph. The node 916 // may not be dead if the replacement process recursively simplified to 917 // something else needing this node. 918 if (TLO.Old.getNode()->use_empty()) 919 deleteAndRecombine(TLO.Old.getNode()); 920 } 921 922 /// Check the specified integer node value to see if it can be simplified or if 923 /// things it uses can be simplified by bit propagation. If so, return true. 924 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 925 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 926 APInt KnownZero, KnownOne; 927 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 928 return false; 929 930 // Revisit the node. 931 AddToWorklist(Op.getNode()); 932 933 // Replace the old value with the new one. 934 ++NodesCombined; 935 DEBUG(dbgs() << "\nReplacing.2 "; 936 TLO.Old.getNode()->dump(&DAG); 937 dbgs() << "\nWith: "; 938 TLO.New.getNode()->dump(&DAG); 939 dbgs() << '\n'); 940 941 CommitTargetLoweringOpt(TLO); 942 return true; 943 } 944 945 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 946 SDLoc dl(Load); 947 EVT VT = Load->getValueType(0); 948 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 949 950 DEBUG(dbgs() << "\nReplacing.9 "; 951 Load->dump(&DAG); 952 dbgs() << "\nWith: "; 953 Trunc.getNode()->dump(&DAG); 954 dbgs() << '\n'); 955 WorklistRemover DeadNodes(*this); 956 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 957 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 958 deleteAndRecombine(Load); 959 AddToWorklist(Trunc.getNode()); 960 } 961 962 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 963 Replace = false; 964 SDLoc dl(Op); 965 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 966 EVT MemVT = LD->getMemoryVT(); 967 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 968 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 969 : ISD::EXTLOAD) 970 : LD->getExtensionType(); 971 Replace = true; 972 return DAG.getExtLoad(ExtType, dl, PVT, 973 LD->getChain(), LD->getBasePtr(), 974 MemVT, LD->getMemOperand()); 975 } 976 977 unsigned Opc = Op.getOpcode(); 978 switch (Opc) { 979 default: break; 980 case ISD::AssertSext: 981 return DAG.getNode(ISD::AssertSext, dl, PVT, 982 SExtPromoteOperand(Op.getOperand(0), PVT), 983 Op.getOperand(1)); 984 case ISD::AssertZext: 985 return DAG.getNode(ISD::AssertZext, dl, PVT, 986 ZExtPromoteOperand(Op.getOperand(0), PVT), 987 Op.getOperand(1)); 988 case ISD::Constant: { 989 unsigned ExtOpc = 990 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 991 return DAG.getNode(ExtOpc, dl, PVT, Op); 992 } 993 } 994 995 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 996 return SDValue(); 997 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 998 } 999 1000 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1001 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1002 return SDValue(); 1003 EVT OldVT = Op.getValueType(); 1004 SDLoc dl(Op); 1005 bool Replace = false; 1006 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1007 if (!NewOp.getNode()) 1008 return SDValue(); 1009 AddToWorklist(NewOp.getNode()); 1010 1011 if (Replace) 1012 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1013 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1014 DAG.getValueType(OldVT)); 1015 } 1016 1017 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1018 EVT OldVT = Op.getValueType(); 1019 SDLoc dl(Op); 1020 bool Replace = false; 1021 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1022 if (!NewOp.getNode()) 1023 return SDValue(); 1024 AddToWorklist(NewOp.getNode()); 1025 1026 if (Replace) 1027 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1028 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1029 } 1030 1031 /// Promote the specified integer binary operation if the target indicates it is 1032 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1033 /// i32 since i16 instructions are longer. 1034 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1035 if (!LegalOperations) 1036 return SDValue(); 1037 1038 EVT VT = Op.getValueType(); 1039 if (VT.isVector() || !VT.isInteger()) 1040 return SDValue(); 1041 1042 // If operation type is 'undesirable', e.g. i16 on x86, consider 1043 // promoting it. 1044 unsigned Opc = Op.getOpcode(); 1045 if (TLI.isTypeDesirableForOp(Opc, VT)) 1046 return SDValue(); 1047 1048 EVT PVT = VT; 1049 // Consult target whether it is a good idea to promote this operation and 1050 // what's the right type to promote it to. 1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1052 assert(PVT != VT && "Don't know what type to promote to!"); 1053 1054 bool Replace0 = false; 1055 SDValue N0 = Op.getOperand(0); 1056 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1057 if (!NN0.getNode()) 1058 return SDValue(); 1059 1060 bool Replace1 = false; 1061 SDValue N1 = Op.getOperand(1); 1062 SDValue NN1; 1063 if (N0 == N1) 1064 NN1 = NN0; 1065 else { 1066 NN1 = PromoteOperand(N1, PVT, Replace1); 1067 if (!NN1.getNode()) 1068 return SDValue(); 1069 } 1070 1071 AddToWorklist(NN0.getNode()); 1072 if (NN1.getNode()) 1073 AddToWorklist(NN1.getNode()); 1074 1075 if (Replace0) 1076 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1077 if (Replace1) 1078 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1079 1080 DEBUG(dbgs() << "\nPromoting "; 1081 Op.getNode()->dump(&DAG)); 1082 SDLoc dl(Op); 1083 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1084 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1085 } 1086 return SDValue(); 1087 } 1088 1089 /// Promote the specified integer shift operation if the target indicates it is 1090 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1091 /// i32 since i16 instructions are longer. 1092 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1093 if (!LegalOperations) 1094 return SDValue(); 1095 1096 EVT VT = Op.getValueType(); 1097 if (VT.isVector() || !VT.isInteger()) 1098 return SDValue(); 1099 1100 // If operation type is 'undesirable', e.g. i16 on x86, consider 1101 // promoting it. 1102 unsigned Opc = Op.getOpcode(); 1103 if (TLI.isTypeDesirableForOp(Opc, VT)) 1104 return SDValue(); 1105 1106 EVT PVT = VT; 1107 // Consult target whether it is a good idea to promote this operation and 1108 // what's the right type to promote it to. 1109 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1110 assert(PVT != VT && "Don't know what type to promote to!"); 1111 1112 bool Replace = false; 1113 SDValue N0 = Op.getOperand(0); 1114 if (Opc == ISD::SRA) 1115 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1116 else if (Opc == ISD::SRL) 1117 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1118 else 1119 N0 = PromoteOperand(N0, PVT, Replace); 1120 if (!N0.getNode()) 1121 return SDValue(); 1122 1123 AddToWorklist(N0.getNode()); 1124 if (Replace) 1125 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1126 1127 DEBUG(dbgs() << "\nPromoting "; 1128 Op.getNode()->dump(&DAG)); 1129 SDLoc dl(Op); 1130 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1131 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1132 } 1133 return SDValue(); 1134 } 1135 1136 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1137 if (!LegalOperations) 1138 return SDValue(); 1139 1140 EVT VT = Op.getValueType(); 1141 if (VT.isVector() || !VT.isInteger()) 1142 return SDValue(); 1143 1144 // If operation type is 'undesirable', e.g. i16 on x86, consider 1145 // promoting it. 1146 unsigned Opc = Op.getOpcode(); 1147 if (TLI.isTypeDesirableForOp(Opc, VT)) 1148 return SDValue(); 1149 1150 EVT PVT = VT; 1151 // Consult target whether it is a good idea to promote this operation and 1152 // what's the right type to promote it to. 1153 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1154 assert(PVT != VT && "Don't know what type to promote to!"); 1155 // fold (aext (aext x)) -> (aext x) 1156 // fold (aext (zext x)) -> (zext x) 1157 // fold (aext (sext x)) -> (sext x) 1158 DEBUG(dbgs() << "\nPromoting "; 1159 Op.getNode()->dump(&DAG)); 1160 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1161 } 1162 return SDValue(); 1163 } 1164 1165 bool DAGCombiner::PromoteLoad(SDValue Op) { 1166 if (!LegalOperations) 1167 return false; 1168 1169 EVT VT = Op.getValueType(); 1170 if (VT.isVector() || !VT.isInteger()) 1171 return false; 1172 1173 // If operation type is 'undesirable', e.g. i16 on x86, consider 1174 // promoting it. 1175 unsigned Opc = Op.getOpcode(); 1176 if (TLI.isTypeDesirableForOp(Opc, VT)) 1177 return false; 1178 1179 EVT PVT = VT; 1180 // Consult target whether it is a good idea to promote this operation and 1181 // what's the right type to promote it to. 1182 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1183 assert(PVT != VT && "Don't know what type to promote to!"); 1184 1185 SDLoc dl(Op); 1186 SDNode *N = Op.getNode(); 1187 LoadSDNode *LD = cast<LoadSDNode>(N); 1188 EVT MemVT = LD->getMemoryVT(); 1189 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1190 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1191 : ISD::EXTLOAD) 1192 : LD->getExtensionType(); 1193 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1194 LD->getChain(), LD->getBasePtr(), 1195 MemVT, LD->getMemOperand()); 1196 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1197 1198 DEBUG(dbgs() << "\nPromoting "; 1199 N->dump(&DAG); 1200 dbgs() << "\nTo: "; 1201 Result.getNode()->dump(&DAG); 1202 dbgs() << '\n'); 1203 WorklistRemover DeadNodes(*this); 1204 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1205 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1206 deleteAndRecombine(N); 1207 AddToWorklist(Result.getNode()); 1208 return true; 1209 } 1210 return false; 1211 } 1212 1213 /// \brief Recursively delete a node which has no uses and any operands for 1214 /// which it is the only use. 1215 /// 1216 /// Note that this both deletes the nodes and removes them from the worklist. 1217 /// It also adds any nodes who have had a user deleted to the worklist as they 1218 /// may now have only one use and subject to other combines. 1219 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1220 if (!N->use_empty()) 1221 return false; 1222 1223 SmallSetVector<SDNode *, 16> Nodes; 1224 Nodes.insert(N); 1225 do { 1226 N = Nodes.pop_back_val(); 1227 if (!N) 1228 continue; 1229 1230 if (N->use_empty()) { 1231 for (const SDValue &ChildN : N->op_values()) 1232 Nodes.insert(ChildN.getNode()); 1233 1234 removeFromWorklist(N); 1235 DAG.DeleteNode(N); 1236 } else { 1237 AddToWorklist(N); 1238 } 1239 } while (!Nodes.empty()); 1240 return true; 1241 } 1242 1243 //===----------------------------------------------------------------------===// 1244 // Main DAG Combiner implementation 1245 //===----------------------------------------------------------------------===// 1246 1247 void DAGCombiner::Run(CombineLevel AtLevel) { 1248 // set the instance variables, so that the various visit routines may use it. 1249 Level = AtLevel; 1250 LegalOperations = Level >= AfterLegalizeVectorOps; 1251 LegalTypes = Level >= AfterLegalizeTypes; 1252 1253 // Add all the dag nodes to the worklist. 1254 for (SDNode &Node : DAG.allnodes()) 1255 AddToWorklist(&Node); 1256 1257 // Create a dummy node (which is not added to allnodes), that adds a reference 1258 // to the root node, preventing it from being deleted, and tracking any 1259 // changes of the root. 1260 HandleSDNode Dummy(DAG.getRoot()); 1261 1262 // While the worklist isn't empty, find a node and try to combine it. 1263 while (!WorklistMap.empty()) { 1264 SDNode *N; 1265 // The Worklist holds the SDNodes in order, but it may contain null entries. 1266 do { 1267 N = Worklist.pop_back_val(); 1268 } while (!N); 1269 1270 bool GoodWorklistEntry = WorklistMap.erase(N); 1271 (void)GoodWorklistEntry; 1272 assert(GoodWorklistEntry && 1273 "Found a worklist entry without a corresponding map entry!"); 1274 1275 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1276 // N is deleted from the DAG, since they too may now be dead or may have a 1277 // reduced number of uses, allowing other xforms. 1278 if (recursivelyDeleteUnusedNodes(N)) 1279 continue; 1280 1281 WorklistRemover DeadNodes(*this); 1282 1283 // If this combine is running after legalizing the DAG, re-legalize any 1284 // nodes pulled off the worklist. 1285 if (Level == AfterLegalizeDAG) { 1286 SmallSetVector<SDNode *, 16> UpdatedNodes; 1287 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1288 1289 for (SDNode *LN : UpdatedNodes) { 1290 AddToWorklist(LN); 1291 AddUsersToWorklist(LN); 1292 } 1293 if (!NIsValid) 1294 continue; 1295 } 1296 1297 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1298 1299 // Add any operands of the new node which have not yet been combined to the 1300 // worklist as well. Because the worklist uniques things already, this 1301 // won't repeatedly process the same operand. 1302 CombinedNodes.insert(N); 1303 for (const SDValue &ChildN : N->op_values()) 1304 if (!CombinedNodes.count(ChildN.getNode())) 1305 AddToWorklist(ChildN.getNode()); 1306 1307 SDValue RV = combine(N); 1308 1309 if (!RV.getNode()) 1310 continue; 1311 1312 ++NodesCombined; 1313 1314 // If we get back the same node we passed in, rather than a new node or 1315 // zero, we know that the node must have defined multiple values and 1316 // CombineTo was used. Since CombineTo takes care of the worklist 1317 // mechanics for us, we have no work to do in this case. 1318 if (RV.getNode() == N) 1319 continue; 1320 1321 assert(N->getOpcode() != ISD::DELETED_NODE && 1322 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1323 "Node was deleted but visit returned new node!"); 1324 1325 DEBUG(dbgs() << " ... into: "; 1326 RV.getNode()->dump(&DAG)); 1327 1328 // Transfer debug value. 1329 DAG.TransferDbgValues(SDValue(N, 0), RV); 1330 if (N->getNumValues() == RV.getNode()->getNumValues()) 1331 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1332 else { 1333 assert(N->getValueType(0) == RV.getValueType() && 1334 N->getNumValues() == 1 && "Type mismatch"); 1335 SDValue OpV = RV; 1336 DAG.ReplaceAllUsesWith(N, &OpV); 1337 } 1338 1339 // Push the new node and any users onto the worklist 1340 AddToWorklist(RV.getNode()); 1341 AddUsersToWorklist(RV.getNode()); 1342 1343 // Finally, if the node is now dead, remove it from the graph. The node 1344 // may not be dead if the replacement process recursively simplified to 1345 // something else needing this node. This will also take care of adding any 1346 // operands which have lost a user to the worklist. 1347 recursivelyDeleteUnusedNodes(N); 1348 } 1349 1350 // If the root changed (e.g. it was a dead load, update the root). 1351 DAG.setRoot(Dummy.getValue()); 1352 DAG.RemoveDeadNodes(); 1353 } 1354 1355 SDValue DAGCombiner::visit(SDNode *N) { 1356 switch (N->getOpcode()) { 1357 default: break; 1358 case ISD::TokenFactor: return visitTokenFactor(N); 1359 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1360 case ISD::ADD: return visitADD(N); 1361 case ISD::SUB: return visitSUB(N); 1362 case ISD::ADDC: return visitADDC(N); 1363 case ISD::SUBC: return visitSUBC(N); 1364 case ISD::ADDE: return visitADDE(N); 1365 case ISD::SUBE: return visitSUBE(N); 1366 case ISD::MUL: return visitMUL(N); 1367 case ISD::SDIV: return visitSDIV(N); 1368 case ISD::UDIV: return visitUDIV(N); 1369 case ISD::SREM: 1370 case ISD::UREM: return visitREM(N); 1371 case ISD::MULHU: return visitMULHU(N); 1372 case ISD::MULHS: return visitMULHS(N); 1373 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1374 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1375 case ISD::SMULO: return visitSMULO(N); 1376 case ISD::UMULO: return visitUMULO(N); 1377 case ISD::SMIN: 1378 case ISD::SMAX: 1379 case ISD::UMIN: 1380 case ISD::UMAX: return visitIMINMAX(N); 1381 case ISD::AND: return visitAND(N); 1382 case ISD::OR: return visitOR(N); 1383 case ISD::XOR: return visitXOR(N); 1384 case ISD::SHL: return visitSHL(N); 1385 case ISD::SRA: return visitSRA(N); 1386 case ISD::SRL: return visitSRL(N); 1387 case ISD::ROTR: 1388 case ISD::ROTL: return visitRotate(N); 1389 case ISD::BSWAP: return visitBSWAP(N); 1390 case ISD::CTLZ: return visitCTLZ(N); 1391 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1392 case ISD::CTTZ: return visitCTTZ(N); 1393 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1394 case ISD::CTPOP: return visitCTPOP(N); 1395 case ISD::SELECT: return visitSELECT(N); 1396 case ISD::VSELECT: return visitVSELECT(N); 1397 case ISD::SELECT_CC: return visitSELECT_CC(N); 1398 case ISD::SETCC: return visitSETCC(N); 1399 case ISD::SETCCE: return visitSETCCE(N); 1400 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1401 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1402 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1403 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1404 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1405 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1406 case ISD::TRUNCATE: return visitTRUNCATE(N); 1407 case ISD::BITCAST: return visitBITCAST(N); 1408 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1409 case ISD::FADD: return visitFADD(N); 1410 case ISD::FSUB: return visitFSUB(N); 1411 case ISD::FMUL: return visitFMUL(N); 1412 case ISD::FMA: return visitFMA(N); 1413 case ISD::FDIV: return visitFDIV(N); 1414 case ISD::FREM: return visitFREM(N); 1415 case ISD::FSQRT: return visitFSQRT(N); 1416 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1417 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1418 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1419 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1420 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1421 case ISD::FP_ROUND: return visitFP_ROUND(N); 1422 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1423 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1424 case ISD::FNEG: return visitFNEG(N); 1425 case ISD::FABS: return visitFABS(N); 1426 case ISD::FFLOOR: return visitFFLOOR(N); 1427 case ISD::FMINNUM: return visitFMINNUM(N); 1428 case ISD::FMAXNUM: return visitFMAXNUM(N); 1429 case ISD::FCEIL: return visitFCEIL(N); 1430 case ISD::FTRUNC: return visitFTRUNC(N); 1431 case ISD::BRCOND: return visitBRCOND(N); 1432 case ISD::BR_CC: return visitBR_CC(N); 1433 case ISD::LOAD: return visitLOAD(N); 1434 case ISD::STORE: return visitSTORE(N); 1435 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1436 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1437 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1438 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1439 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1440 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1441 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1442 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1443 case ISD::MGATHER: return visitMGATHER(N); 1444 case ISD::MLOAD: return visitMLOAD(N); 1445 case ISD::MSCATTER: return visitMSCATTER(N); 1446 case ISD::MSTORE: return visitMSTORE(N); 1447 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1448 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1449 } 1450 return SDValue(); 1451 } 1452 1453 SDValue DAGCombiner::combine(SDNode *N) { 1454 SDValue RV = visit(N); 1455 1456 // If nothing happened, try a target-specific DAG combine. 1457 if (!RV.getNode()) { 1458 assert(N->getOpcode() != ISD::DELETED_NODE && 1459 "Node was deleted but visit returned NULL!"); 1460 1461 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1462 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1463 1464 // Expose the DAG combiner to the target combiner impls. 1465 TargetLowering::DAGCombinerInfo 1466 DagCombineInfo(DAG, Level, false, this); 1467 1468 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1469 } 1470 } 1471 1472 // If nothing happened still, try promoting the operation. 1473 if (!RV.getNode()) { 1474 switch (N->getOpcode()) { 1475 default: break; 1476 case ISD::ADD: 1477 case ISD::SUB: 1478 case ISD::MUL: 1479 case ISD::AND: 1480 case ISD::OR: 1481 case ISD::XOR: 1482 RV = PromoteIntBinOp(SDValue(N, 0)); 1483 break; 1484 case ISD::SHL: 1485 case ISD::SRA: 1486 case ISD::SRL: 1487 RV = PromoteIntShiftOp(SDValue(N, 0)); 1488 break; 1489 case ISD::SIGN_EXTEND: 1490 case ISD::ZERO_EXTEND: 1491 case ISD::ANY_EXTEND: 1492 RV = PromoteExtend(SDValue(N, 0)); 1493 break; 1494 case ISD::LOAD: 1495 if (PromoteLoad(SDValue(N, 0))) 1496 RV = SDValue(N, 0); 1497 break; 1498 } 1499 } 1500 1501 // If N is a commutative binary node, try commuting it to enable more 1502 // sdisel CSE. 1503 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1504 N->getNumValues() == 1) { 1505 SDValue N0 = N->getOperand(0); 1506 SDValue N1 = N->getOperand(1); 1507 1508 // Constant operands are canonicalized to RHS. 1509 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1510 SDValue Ops[] = {N1, N0}; 1511 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1512 N->getFlags()); 1513 if (CSENode) 1514 return SDValue(CSENode, 0); 1515 } 1516 } 1517 1518 return RV; 1519 } 1520 1521 /// Given a node, return its input chain if it has one, otherwise return a null 1522 /// sd operand. 1523 static SDValue getInputChainForNode(SDNode *N) { 1524 if (unsigned NumOps = N->getNumOperands()) { 1525 if (N->getOperand(0).getValueType() == MVT::Other) 1526 return N->getOperand(0); 1527 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1528 return N->getOperand(NumOps-1); 1529 for (unsigned i = 1; i < NumOps-1; ++i) 1530 if (N->getOperand(i).getValueType() == MVT::Other) 1531 return N->getOperand(i); 1532 } 1533 return SDValue(); 1534 } 1535 1536 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1537 // If N has two operands, where one has an input chain equal to the other, 1538 // the 'other' chain is redundant. 1539 if (N->getNumOperands() == 2) { 1540 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1541 return N->getOperand(0); 1542 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1543 return N->getOperand(1); 1544 } 1545 1546 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1547 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1548 SmallPtrSet<SDNode*, 16> SeenOps; 1549 bool Changed = false; // If we should replace this token factor. 1550 1551 // Start out with this token factor. 1552 TFs.push_back(N); 1553 1554 // Iterate through token factors. The TFs grows when new token factors are 1555 // encountered. 1556 for (unsigned i = 0; i < TFs.size(); ++i) { 1557 SDNode *TF = TFs[i]; 1558 1559 // Check each of the operands. 1560 for (const SDValue &Op : TF->op_values()) { 1561 1562 switch (Op.getOpcode()) { 1563 case ISD::EntryToken: 1564 // Entry tokens don't need to be added to the list. They are 1565 // redundant. 1566 Changed = true; 1567 break; 1568 1569 case ISD::TokenFactor: 1570 if (Op.hasOneUse() && 1571 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1572 // Queue up for processing. 1573 TFs.push_back(Op.getNode()); 1574 // Clean up in case the token factor is removed. 1575 AddToWorklist(Op.getNode()); 1576 Changed = true; 1577 break; 1578 } 1579 // Fall thru 1580 1581 default: 1582 // Only add if it isn't already in the list. 1583 if (SeenOps.insert(Op.getNode()).second) 1584 Ops.push_back(Op); 1585 else 1586 Changed = true; 1587 break; 1588 } 1589 } 1590 } 1591 1592 SDValue Result; 1593 1594 // If we've changed things around then replace token factor. 1595 if (Changed) { 1596 if (Ops.empty()) { 1597 // The entry token is the only possible outcome. 1598 Result = DAG.getEntryNode(); 1599 } else { 1600 // New and improved token factor. 1601 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1602 } 1603 1604 // Add users to worklist if AA is enabled, since it may introduce 1605 // a lot of new chained token factors while removing memory deps. 1606 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1607 : DAG.getSubtarget().useAA(); 1608 return CombineTo(N, Result, UseAA /*add to worklist*/); 1609 } 1610 1611 return Result; 1612 } 1613 1614 /// MERGE_VALUES can always be eliminated. 1615 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1616 WorklistRemover DeadNodes(*this); 1617 // Replacing results may cause a different MERGE_VALUES to suddenly 1618 // be CSE'd with N, and carry its uses with it. Iterate until no 1619 // uses remain, to ensure that the node can be safely deleted. 1620 // First add the users of this node to the work list so that they 1621 // can be tried again once they have new operands. 1622 AddUsersToWorklist(N); 1623 do { 1624 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1625 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1626 } while (!N->use_empty()); 1627 deleteAndRecombine(N); 1628 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1629 } 1630 1631 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1632 /// ConstantSDNode pointer else nullptr. 1633 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1634 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1635 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1636 } 1637 1638 SDValue DAGCombiner::visitADD(SDNode *N) { 1639 SDValue N0 = N->getOperand(0); 1640 SDValue N1 = N->getOperand(1); 1641 EVT VT = N0.getValueType(); 1642 1643 // fold vector ops 1644 if (VT.isVector()) { 1645 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1646 return FoldedVOp; 1647 1648 // fold (add x, 0) -> x, vector edition 1649 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1650 return N0; 1651 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1652 return N1; 1653 } 1654 1655 // fold (add x, undef) -> undef 1656 if (N0.isUndef()) 1657 return N0; 1658 if (N1.isUndef()) 1659 return N1; 1660 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1661 // canonicalize constant to RHS 1662 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1663 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1664 // fold (add c1, c2) -> c1+c2 1665 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1666 N0.getNode(), N1.getNode()); 1667 } 1668 // fold (add x, 0) -> x 1669 if (isNullConstant(N1)) 1670 return N0; 1671 // fold ((c1-A)+c2) -> (c1+c2)-A 1672 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1673 if (N0.getOpcode() == ISD::SUB) 1674 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1675 SDLoc DL(N); 1676 return DAG.getNode(ISD::SUB, DL, VT, 1677 DAG.getConstant(N1C->getAPIntValue()+ 1678 N0C->getAPIntValue(), DL, VT), 1679 N0.getOperand(1)); 1680 } 1681 } 1682 // reassociate add 1683 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1684 return RADD; 1685 // fold ((0-A) + B) -> B-A 1686 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1688 // fold (A + (0-B)) -> A-B 1689 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1690 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1691 // fold (A+(B-A)) -> B 1692 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1693 return N1.getOperand(0); 1694 // fold ((B-A)+A) -> B 1695 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1696 return N0.getOperand(0); 1697 // fold (A+(B-(A+C))) to (B-C) 1698 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1699 N0 == N1.getOperand(1).getOperand(0)) 1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1701 N1.getOperand(1).getOperand(1)); 1702 // fold (A+(B-(C+A))) to (B-C) 1703 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1704 N0 == N1.getOperand(1).getOperand(1)) 1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1706 N1.getOperand(1).getOperand(0)); 1707 // fold (A+((B-A)+or-C)) to (B+or-C) 1708 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1709 N1.getOperand(0).getOpcode() == ISD::SUB && 1710 N0 == N1.getOperand(0).getOperand(1)) 1711 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1712 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1713 1714 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1715 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1716 SDValue N00 = N0.getOperand(0); 1717 SDValue N01 = N0.getOperand(1); 1718 SDValue N10 = N1.getOperand(0); 1719 SDValue N11 = N1.getOperand(1); 1720 1721 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1722 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1723 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1724 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1725 } 1726 1727 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1728 return SDValue(N, 0); 1729 1730 // fold (a+b) -> (a|b) iff a and b share no bits. 1731 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::OR, VT)) && 1732 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1733 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1734 1735 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1736 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1737 isNullConstant(N1.getOperand(0).getOperand(0))) 1738 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1739 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1740 N1.getOperand(0).getOperand(1), 1741 N1.getOperand(1))); 1742 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1743 isNullConstant(N0.getOperand(0).getOperand(0))) 1744 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1745 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1746 N0.getOperand(0).getOperand(1), 1747 N0.getOperand(1))); 1748 1749 if (N1.getOpcode() == ISD::AND) { 1750 SDValue AndOp0 = N1.getOperand(0); 1751 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1752 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1753 1754 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1755 // and similar xforms where the inner op is either ~0 or 0. 1756 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1757 SDLoc DL(N); 1758 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1759 } 1760 } 1761 1762 // add (sext i1), X -> sub X, (zext i1) 1763 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1764 N0.getOperand(0).getValueType() == MVT::i1 && 1765 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1766 SDLoc DL(N); 1767 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1768 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1769 } 1770 1771 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1772 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1773 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1774 if (TN->getVT() == MVT::i1) { 1775 SDLoc DL(N); 1776 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1777 DAG.getConstant(1, DL, VT)); 1778 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1779 } 1780 } 1781 1782 return SDValue(); 1783 } 1784 1785 SDValue DAGCombiner::visitADDC(SDNode *N) { 1786 SDValue N0 = N->getOperand(0); 1787 SDValue N1 = N->getOperand(1); 1788 EVT VT = N0.getValueType(); 1789 1790 // If the flag result is dead, turn this into an ADD. 1791 if (!N->hasAnyUseOfValue(1)) 1792 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1793 DAG.getNode(ISD::CARRY_FALSE, 1794 SDLoc(N), MVT::Glue)); 1795 1796 // canonicalize constant to RHS. 1797 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1798 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1799 if (N0C && !N1C) 1800 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1801 1802 // fold (addc x, 0) -> x + no carry out 1803 if (isNullConstant(N1)) 1804 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1805 SDLoc(N), MVT::Glue)); 1806 1807 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1808 APInt LHSZero, LHSOne; 1809 APInt RHSZero, RHSOne; 1810 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1811 1812 if (LHSZero.getBoolValue()) { 1813 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1814 1815 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1816 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1817 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1818 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1819 DAG.getNode(ISD::CARRY_FALSE, 1820 SDLoc(N), MVT::Glue)); 1821 } 1822 1823 return SDValue(); 1824 } 1825 1826 SDValue DAGCombiner::visitADDE(SDNode *N) { 1827 SDValue N0 = N->getOperand(0); 1828 SDValue N1 = N->getOperand(1); 1829 SDValue CarryIn = N->getOperand(2); 1830 1831 // canonicalize constant to RHS 1832 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1833 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1834 if (N0C && !N1C) 1835 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1836 N1, N0, CarryIn); 1837 1838 // fold (adde x, y, false) -> (addc x, y) 1839 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1840 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1841 1842 return SDValue(); 1843 } 1844 1845 // Since it may not be valid to emit a fold to zero for vector initializers 1846 // check if we can before folding. 1847 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1848 SelectionDAG &DAG, 1849 bool LegalOperations, bool LegalTypes) { 1850 if (!VT.isVector()) 1851 return DAG.getConstant(0, DL, VT); 1852 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1853 return DAG.getConstant(0, DL, VT); 1854 return SDValue(); 1855 } 1856 1857 SDValue DAGCombiner::visitSUB(SDNode *N) { 1858 SDValue N0 = N->getOperand(0); 1859 SDValue N1 = N->getOperand(1); 1860 EVT VT = N0.getValueType(); 1861 1862 // fold vector ops 1863 if (VT.isVector()) { 1864 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1865 return FoldedVOp; 1866 1867 // fold (sub x, 0) -> x, vector edition 1868 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1869 return N0; 1870 } 1871 1872 // fold (sub x, x) -> 0 1873 // FIXME: Refactor this and xor and other similar operations together. 1874 if (N0 == N1) 1875 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1876 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1877 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1878 // fold (sub c1, c2) -> c1-c2 1879 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1880 N0.getNode(), N1.getNode()); 1881 } 1882 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1883 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1884 // fold (sub x, c) -> (add x, -c) 1885 if (N1C) { 1886 SDLoc DL(N); 1887 return DAG.getNode(ISD::ADD, DL, VT, N0, 1888 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1889 } 1890 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1891 if (isAllOnesConstant(N0)) 1892 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1893 // fold A-(A-B) -> B 1894 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1895 return N1.getOperand(1); 1896 // fold (A+B)-A -> B 1897 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1898 return N0.getOperand(1); 1899 // fold (A+B)-B -> A 1900 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1901 return N0.getOperand(0); 1902 // fold C2-(A+C1) -> (C2-C1)-A 1903 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1904 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1905 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1906 SDLoc DL(N); 1907 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1908 DL, VT); 1909 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1910 N1.getOperand(0)); 1911 } 1912 // fold ((A+(B+or-C))-B) -> A+or-C 1913 if (N0.getOpcode() == ISD::ADD && 1914 (N0.getOperand(1).getOpcode() == ISD::SUB || 1915 N0.getOperand(1).getOpcode() == ISD::ADD) && 1916 N0.getOperand(1).getOperand(0) == N1) 1917 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1918 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1919 // fold ((A+(C+B))-B) -> A+C 1920 if (N0.getOpcode() == ISD::ADD && 1921 N0.getOperand(1).getOpcode() == ISD::ADD && 1922 N0.getOperand(1).getOperand(1) == N1) 1923 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1924 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1925 // fold ((A-(B-C))-C) -> A-B 1926 if (N0.getOpcode() == ISD::SUB && 1927 N0.getOperand(1).getOpcode() == ISD::SUB && 1928 N0.getOperand(1).getOperand(1) == N1) 1929 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1930 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1931 1932 // If either operand of a sub is undef, the result is undef 1933 if (N0.isUndef()) 1934 return N0; 1935 if (N1.isUndef()) 1936 return N1; 1937 1938 // If the relocation model supports it, consider symbol offsets. 1939 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1940 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1941 // fold (sub Sym, c) -> Sym-c 1942 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1943 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1944 GA->getOffset() - 1945 (uint64_t)N1C->getSExtValue()); 1946 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1947 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1948 if (GA->getGlobal() == GB->getGlobal()) 1949 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1950 SDLoc(N), VT); 1951 } 1952 1953 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1954 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1955 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1956 if (TN->getVT() == MVT::i1) { 1957 SDLoc DL(N); 1958 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1959 DAG.getConstant(1, DL, VT)); 1960 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1961 } 1962 } 1963 1964 return SDValue(); 1965 } 1966 1967 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1968 SDValue N0 = N->getOperand(0); 1969 SDValue N1 = N->getOperand(1); 1970 EVT VT = N0.getValueType(); 1971 SDLoc DL(N); 1972 1973 // If the flag result is dead, turn this into an SUB. 1974 if (!N->hasAnyUseOfValue(1)) 1975 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1976 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1977 1978 // fold (subc x, x) -> 0 + no borrow 1979 if (N0 == N1) 1980 return CombineTo(N, DAG.getConstant(0, DL, VT), 1981 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1982 1983 // fold (subc x, 0) -> x + no borrow 1984 if (isNullConstant(N1)) 1985 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1986 1987 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1988 if (isAllOnesConstant(N0)) 1989 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1990 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1991 1992 return SDValue(); 1993 } 1994 1995 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1996 SDValue N0 = N->getOperand(0); 1997 SDValue N1 = N->getOperand(1); 1998 SDValue CarryIn = N->getOperand(2); 1999 2000 // fold (sube x, y, false) -> (subc x, y) 2001 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2002 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2003 2004 return SDValue(); 2005 } 2006 2007 SDValue DAGCombiner::visitMUL(SDNode *N) { 2008 SDValue N0 = N->getOperand(0); 2009 SDValue N1 = N->getOperand(1); 2010 EVT VT = N0.getValueType(); 2011 2012 // fold (mul x, undef) -> 0 2013 if (N0.isUndef() || N1.isUndef()) 2014 return DAG.getConstant(0, SDLoc(N), VT); 2015 2016 bool N0IsConst = false; 2017 bool N1IsConst = false; 2018 bool N1IsOpaqueConst = false; 2019 bool N0IsOpaqueConst = false; 2020 APInt ConstValue0, ConstValue1; 2021 // fold vector ops 2022 if (VT.isVector()) { 2023 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2024 return FoldedVOp; 2025 2026 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2027 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2028 } else { 2029 N0IsConst = isa<ConstantSDNode>(N0); 2030 if (N0IsConst) { 2031 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2032 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2033 } 2034 N1IsConst = isa<ConstantSDNode>(N1); 2035 if (N1IsConst) { 2036 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2037 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2038 } 2039 } 2040 2041 // fold (mul c1, c2) -> c1*c2 2042 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2043 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2044 N0.getNode(), N1.getNode()); 2045 2046 // canonicalize constant to RHS (vector doesn't have to splat) 2047 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2048 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2049 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2050 // fold (mul x, 0) -> 0 2051 if (N1IsConst && ConstValue1 == 0) 2052 return N1; 2053 // We require a splat of the entire scalar bit width for non-contiguous 2054 // bit patterns. 2055 bool IsFullSplat = 2056 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2057 // fold (mul x, 1) -> x 2058 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2059 return N0; 2060 // fold (mul x, -1) -> 0-x 2061 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2062 SDLoc DL(N); 2063 return DAG.getNode(ISD::SUB, DL, VT, 2064 DAG.getConstant(0, DL, VT), N0); 2065 } 2066 // fold (mul x, (1 << c)) -> x << c 2067 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2068 IsFullSplat) { 2069 SDLoc DL(N); 2070 return DAG.getNode(ISD::SHL, DL, VT, N0, 2071 DAG.getConstant(ConstValue1.logBase2(), DL, 2072 getShiftAmountTy(N0.getValueType()))); 2073 } 2074 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2075 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2076 IsFullSplat) { 2077 unsigned Log2Val = (-ConstValue1).logBase2(); 2078 SDLoc DL(N); 2079 // FIXME: If the input is something that is easily negated (e.g. a 2080 // single-use add), we should put the negate there. 2081 return DAG.getNode(ISD::SUB, DL, VT, 2082 DAG.getConstant(0, DL, VT), 2083 DAG.getNode(ISD::SHL, DL, VT, N0, 2084 DAG.getConstant(Log2Val, DL, 2085 getShiftAmountTy(N0.getValueType())))); 2086 } 2087 2088 APInt Val; 2089 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2090 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2091 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2092 isa<ConstantSDNode>(N0.getOperand(1)))) { 2093 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2094 N1, N0.getOperand(1)); 2095 AddToWorklist(C3.getNode()); 2096 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2097 N0.getOperand(0), C3); 2098 } 2099 2100 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2101 // use. 2102 { 2103 SDValue Sh(nullptr,0), Y(nullptr,0); 2104 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2105 if (N0.getOpcode() == ISD::SHL && 2106 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2107 isa<ConstantSDNode>(N0.getOperand(1))) && 2108 N0.getNode()->hasOneUse()) { 2109 Sh = N0; Y = N1; 2110 } else if (N1.getOpcode() == ISD::SHL && 2111 isa<ConstantSDNode>(N1.getOperand(1)) && 2112 N1.getNode()->hasOneUse()) { 2113 Sh = N1; Y = N0; 2114 } 2115 2116 if (Sh.getNode()) { 2117 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2118 Sh.getOperand(0), Y); 2119 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2120 Mul, Sh.getOperand(1)); 2121 } 2122 } 2123 2124 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2125 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2126 N0.getOpcode() == ISD::ADD && 2127 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2128 isMulAddWithConstProfitable(N, N0, N1)) 2129 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2130 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2131 N0.getOperand(0), N1), 2132 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2133 N0.getOperand(1), N1)); 2134 2135 // reassociate mul 2136 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2137 return RMUL; 2138 2139 return SDValue(); 2140 } 2141 2142 /// Return true if divmod libcall is available. 2143 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2144 const TargetLowering &TLI) { 2145 RTLIB::Libcall LC; 2146 EVT NodeType = Node->getValueType(0); 2147 if (!NodeType.isSimple()) 2148 return false; 2149 switch (NodeType.getSimpleVT().SimpleTy) { 2150 default: return false; // No libcall for vector types. 2151 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2152 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2153 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2154 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2155 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2156 } 2157 2158 return TLI.getLibcallName(LC) != nullptr; 2159 } 2160 2161 /// Issue divrem if both quotient and remainder are needed. 2162 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2163 if (Node->use_empty()) 2164 return SDValue(); // This is a dead node, leave it alone. 2165 2166 unsigned Opcode = Node->getOpcode(); 2167 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2168 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2169 2170 // DivMod lib calls can still work on non-legal types if using lib-calls. 2171 EVT VT = Node->getValueType(0); 2172 if (VT.isVector() || !VT.isInteger()) 2173 return SDValue(); 2174 2175 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2176 return SDValue(); 2177 2178 // If DIVREM is going to get expanded into a libcall, 2179 // but there is no libcall available, then don't combine. 2180 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2181 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2182 return SDValue(); 2183 2184 // If div is legal, it's better to do the normal expansion 2185 unsigned OtherOpcode = 0; 2186 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2187 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2188 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2189 return SDValue(); 2190 } else { 2191 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2192 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2193 return SDValue(); 2194 } 2195 2196 SDValue Op0 = Node->getOperand(0); 2197 SDValue Op1 = Node->getOperand(1); 2198 SDValue combined; 2199 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2200 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2201 SDNode *User = *UI; 2202 if (User == Node || User->use_empty()) 2203 continue; 2204 // Convert the other matching node(s), too; 2205 // otherwise, the DIVREM may get target-legalized into something 2206 // target-specific that we won't be able to recognize. 2207 unsigned UserOpc = User->getOpcode(); 2208 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2209 User->getOperand(0) == Op0 && 2210 User->getOperand(1) == Op1) { 2211 if (!combined) { 2212 if (UserOpc == OtherOpcode) { 2213 SDVTList VTs = DAG.getVTList(VT, VT); 2214 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2215 } else if (UserOpc == DivRemOpc) { 2216 combined = SDValue(User, 0); 2217 } else { 2218 assert(UserOpc == Opcode); 2219 continue; 2220 } 2221 } 2222 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2223 CombineTo(User, combined); 2224 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2225 CombineTo(User, combined.getValue(1)); 2226 } 2227 } 2228 return combined; 2229 } 2230 2231 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2232 SDValue N0 = N->getOperand(0); 2233 SDValue N1 = N->getOperand(1); 2234 EVT VT = N->getValueType(0); 2235 2236 // fold vector ops 2237 if (VT.isVector()) 2238 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2239 return FoldedVOp; 2240 2241 SDLoc DL(N); 2242 2243 // fold (sdiv c1, c2) -> c1/c2 2244 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2245 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2246 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2247 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2248 // fold (sdiv X, 1) -> X 2249 if (N1C && N1C->isOne()) 2250 return N0; 2251 // fold (sdiv X, -1) -> 0-X 2252 if (N1C && N1C->isAllOnesValue()) 2253 return DAG.getNode(ISD::SUB, DL, VT, 2254 DAG.getConstant(0, DL, VT), N0); 2255 2256 // If we know the sign bits of both operands are zero, strength reduce to a 2257 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2258 if (!VT.isVector()) { 2259 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2260 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2261 } 2262 2263 // fold (sdiv X, pow2) -> simple ops after legalize 2264 // FIXME: We check for the exact bit here because the generic lowering gives 2265 // better results in that case. The target-specific lowering should learn how 2266 // to handle exact sdivs efficiently. 2267 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2268 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2269 (N1C->getAPIntValue().isPowerOf2() || 2270 (-N1C->getAPIntValue()).isPowerOf2())) { 2271 // Target-specific implementation of sdiv x, pow2. 2272 if (SDValue Res = BuildSDIVPow2(N)) 2273 return Res; 2274 2275 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2276 2277 // Splat the sign bit into the register 2278 SDValue SGN = 2279 DAG.getNode(ISD::SRA, DL, VT, N0, 2280 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2281 getShiftAmountTy(N0.getValueType()))); 2282 AddToWorklist(SGN.getNode()); 2283 2284 // Add (N0 < 0) ? abs2 - 1 : 0; 2285 SDValue SRL = 2286 DAG.getNode(ISD::SRL, DL, VT, SGN, 2287 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2288 getShiftAmountTy(SGN.getValueType()))); 2289 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2290 AddToWorklist(SRL.getNode()); 2291 AddToWorklist(ADD.getNode()); // Divide by pow2 2292 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2293 DAG.getConstant(lg2, DL, 2294 getShiftAmountTy(ADD.getValueType()))); 2295 2296 // If we're dividing by a positive value, we're done. Otherwise, we must 2297 // negate the result. 2298 if (N1C->getAPIntValue().isNonNegative()) 2299 return SRA; 2300 2301 AddToWorklist(SRA.getNode()); 2302 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2303 } 2304 2305 // If integer divide is expensive and we satisfy the requirements, emit an 2306 // alternate sequence. Targets may check function attributes for size/speed 2307 // trade-offs. 2308 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2309 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2310 if (SDValue Op = BuildSDIV(N)) 2311 return Op; 2312 2313 // sdiv, srem -> sdivrem 2314 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2315 // Otherwise, we break the simplification logic in visitREM(). 2316 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2317 if (SDValue DivRem = useDivRem(N)) 2318 return DivRem; 2319 2320 // undef / X -> 0 2321 if (N0.isUndef()) 2322 return DAG.getConstant(0, DL, VT); 2323 // X / undef -> undef 2324 if (N1.isUndef()) 2325 return N1; 2326 2327 return SDValue(); 2328 } 2329 2330 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2331 SDValue N0 = N->getOperand(0); 2332 SDValue N1 = N->getOperand(1); 2333 EVT VT = N->getValueType(0); 2334 2335 // fold vector ops 2336 if (VT.isVector()) 2337 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2338 return FoldedVOp; 2339 2340 SDLoc DL(N); 2341 2342 // fold (udiv c1, c2) -> c1/c2 2343 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2344 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2345 if (N0C && N1C) 2346 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2347 N0C, N1C)) 2348 return Folded; 2349 // fold (udiv x, (1 << c)) -> x >>u c 2350 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2351 return DAG.getNode(ISD::SRL, DL, VT, N0, 2352 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2353 getShiftAmountTy(N0.getValueType()))); 2354 2355 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2356 if (N1.getOpcode() == ISD::SHL) { 2357 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2358 if (SHC->getAPIntValue().isPowerOf2()) { 2359 EVT ADDVT = N1.getOperand(1).getValueType(); 2360 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2361 N1.getOperand(1), 2362 DAG.getConstant(SHC->getAPIntValue() 2363 .logBase2(), 2364 DL, ADDVT)); 2365 AddToWorklist(Add.getNode()); 2366 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2367 } 2368 } 2369 } 2370 2371 // fold (udiv x, c) -> alternate 2372 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2373 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2374 if (SDValue Op = BuildUDIV(N)) 2375 return Op; 2376 2377 // sdiv, srem -> sdivrem 2378 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2379 // Otherwise, we break the simplification logic in visitREM(). 2380 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2381 if (SDValue DivRem = useDivRem(N)) 2382 return DivRem; 2383 2384 // undef / X -> 0 2385 if (N0.isUndef()) 2386 return DAG.getConstant(0, DL, VT); 2387 // X / undef -> undef 2388 if (N1.isUndef()) 2389 return N1; 2390 2391 return SDValue(); 2392 } 2393 2394 // handles ISD::SREM and ISD::UREM 2395 SDValue DAGCombiner::visitREM(SDNode *N) { 2396 unsigned Opcode = N->getOpcode(); 2397 SDValue N0 = N->getOperand(0); 2398 SDValue N1 = N->getOperand(1); 2399 EVT VT = N->getValueType(0); 2400 bool isSigned = (Opcode == ISD::SREM); 2401 SDLoc DL(N); 2402 2403 // fold (rem c1, c2) -> c1%c2 2404 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2405 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2406 if (N0C && N1C) 2407 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2408 return Folded; 2409 2410 if (isSigned) { 2411 // If we know the sign bits of both operands are zero, strength reduce to a 2412 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2413 if (!VT.isVector()) { 2414 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2415 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2416 } 2417 } else { 2418 // fold (urem x, pow2) -> (and x, pow2-1) 2419 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2420 N1C->getAPIntValue().isPowerOf2()) { 2421 return DAG.getNode(ISD::AND, DL, VT, N0, 2422 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2423 } 2424 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2425 if (N1.getOpcode() == ISD::SHL) { 2426 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2427 if (SHC->getAPIntValue().isPowerOf2()) { 2428 SDValue Add = 2429 DAG.getNode(ISD::ADD, DL, VT, N1, 2430 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2431 VT)); 2432 AddToWorklist(Add.getNode()); 2433 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2434 } 2435 } 2436 } 2437 } 2438 2439 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2440 2441 // If X/C can be simplified by the division-by-constant logic, lower 2442 // X%C to the equivalent of X-X/C*C. 2443 // To avoid mangling nodes, this simplification requires that the combine() 2444 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2445 // against this by skipping the simplification if isIntDivCheap(). When 2446 // div is not cheap, combine will not return a DIVREM. Regardless, 2447 // checking cheapness here makes sense since the simplification results in 2448 // fatter code. 2449 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2450 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2451 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2452 AddToWorklist(Div.getNode()); 2453 SDValue OptimizedDiv = combine(Div.getNode()); 2454 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2455 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2456 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2457 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2458 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2459 AddToWorklist(Mul.getNode()); 2460 return Sub; 2461 } 2462 } 2463 2464 // sdiv, srem -> sdivrem 2465 if (SDValue DivRem = useDivRem(N)) 2466 return DivRem.getValue(1); 2467 2468 // undef % X -> 0 2469 if (N0.isUndef()) 2470 return DAG.getConstant(0, DL, VT); 2471 // X % undef -> undef 2472 if (N1.isUndef()) 2473 return N1; 2474 2475 return SDValue(); 2476 } 2477 2478 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2479 SDValue N0 = N->getOperand(0); 2480 SDValue N1 = N->getOperand(1); 2481 EVT VT = N->getValueType(0); 2482 SDLoc DL(N); 2483 2484 // fold (mulhs x, 0) -> 0 2485 if (isNullConstant(N1)) 2486 return N1; 2487 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2488 if (isOneConstant(N1)) { 2489 SDLoc DL(N); 2490 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2491 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2492 DL, 2493 getShiftAmountTy(N0.getValueType()))); 2494 } 2495 // fold (mulhs x, undef) -> 0 2496 if (N0.isUndef() || N1.isUndef()) 2497 return DAG.getConstant(0, SDLoc(N), VT); 2498 2499 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2500 // plus a shift. 2501 if (VT.isSimple() && !VT.isVector()) { 2502 MVT Simple = VT.getSimpleVT(); 2503 unsigned SimpleSize = Simple.getSizeInBits(); 2504 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2505 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2506 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2507 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2508 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2509 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2510 DAG.getConstant(SimpleSize, DL, 2511 getShiftAmountTy(N1.getValueType()))); 2512 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2513 } 2514 } 2515 2516 return SDValue(); 2517 } 2518 2519 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2520 SDValue N0 = N->getOperand(0); 2521 SDValue N1 = N->getOperand(1); 2522 EVT VT = N->getValueType(0); 2523 SDLoc DL(N); 2524 2525 // fold (mulhu x, 0) -> 0 2526 if (isNullConstant(N1)) 2527 return N1; 2528 // fold (mulhu x, 1) -> 0 2529 if (isOneConstant(N1)) 2530 return DAG.getConstant(0, DL, N0.getValueType()); 2531 // fold (mulhu x, undef) -> 0 2532 if (N0.isUndef() || N1.isUndef()) 2533 return DAG.getConstant(0, DL, VT); 2534 2535 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2536 // plus a shift. 2537 if (VT.isSimple() && !VT.isVector()) { 2538 MVT Simple = VT.getSimpleVT(); 2539 unsigned SimpleSize = Simple.getSizeInBits(); 2540 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2541 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2542 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2543 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2544 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2545 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2546 DAG.getConstant(SimpleSize, DL, 2547 getShiftAmountTy(N1.getValueType()))); 2548 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2549 } 2550 } 2551 2552 return SDValue(); 2553 } 2554 2555 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2556 /// give the opcodes for the two computations that are being performed. Return 2557 /// true if a simplification was made. 2558 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2559 unsigned HiOp) { 2560 // If the high half is not needed, just compute the low half. 2561 bool HiExists = N->hasAnyUseOfValue(1); 2562 if (!HiExists && 2563 (!LegalOperations || 2564 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2565 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2566 return CombineTo(N, Res, Res); 2567 } 2568 2569 // If the low half is not needed, just compute the high half. 2570 bool LoExists = N->hasAnyUseOfValue(0); 2571 if (!LoExists && 2572 (!LegalOperations || 2573 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2574 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2575 return CombineTo(N, Res, Res); 2576 } 2577 2578 // If both halves are used, return as it is. 2579 if (LoExists && HiExists) 2580 return SDValue(); 2581 2582 // If the two computed results can be simplified separately, separate them. 2583 if (LoExists) { 2584 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2585 AddToWorklist(Lo.getNode()); 2586 SDValue LoOpt = combine(Lo.getNode()); 2587 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2588 (!LegalOperations || 2589 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2590 return CombineTo(N, LoOpt, LoOpt); 2591 } 2592 2593 if (HiExists) { 2594 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2595 AddToWorklist(Hi.getNode()); 2596 SDValue HiOpt = combine(Hi.getNode()); 2597 if (HiOpt.getNode() && HiOpt != Hi && 2598 (!LegalOperations || 2599 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2600 return CombineTo(N, HiOpt, HiOpt); 2601 } 2602 2603 return SDValue(); 2604 } 2605 2606 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2607 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2608 return Res; 2609 2610 EVT VT = N->getValueType(0); 2611 SDLoc DL(N); 2612 2613 // If the type is twice as wide is legal, transform the mulhu to a wider 2614 // multiply plus a shift. 2615 if (VT.isSimple() && !VT.isVector()) { 2616 MVT Simple = VT.getSimpleVT(); 2617 unsigned SimpleSize = Simple.getSizeInBits(); 2618 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2619 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2620 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2621 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2622 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2623 // Compute the high part as N1. 2624 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2625 DAG.getConstant(SimpleSize, DL, 2626 getShiftAmountTy(Lo.getValueType()))); 2627 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2628 // Compute the low part as N0. 2629 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2630 return CombineTo(N, Lo, Hi); 2631 } 2632 } 2633 2634 return SDValue(); 2635 } 2636 2637 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2638 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2639 return Res; 2640 2641 EVT VT = N->getValueType(0); 2642 SDLoc DL(N); 2643 2644 // If the type is twice as wide is legal, transform the mulhu to a wider 2645 // multiply plus a shift. 2646 if (VT.isSimple() && !VT.isVector()) { 2647 MVT Simple = VT.getSimpleVT(); 2648 unsigned SimpleSize = Simple.getSizeInBits(); 2649 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2650 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2651 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2652 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2653 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2654 // Compute the high part as N1. 2655 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2656 DAG.getConstant(SimpleSize, DL, 2657 getShiftAmountTy(Lo.getValueType()))); 2658 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2659 // Compute the low part as N0. 2660 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2661 return CombineTo(N, Lo, Hi); 2662 } 2663 } 2664 2665 return SDValue(); 2666 } 2667 2668 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2669 // (smulo x, 2) -> (saddo x, x) 2670 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2671 if (C2->getAPIntValue() == 2) 2672 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2673 N->getOperand(0), N->getOperand(0)); 2674 2675 return SDValue(); 2676 } 2677 2678 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2679 // (umulo x, 2) -> (uaddo x, x) 2680 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2681 if (C2->getAPIntValue() == 2) 2682 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2683 N->getOperand(0), N->getOperand(0)); 2684 2685 return SDValue(); 2686 } 2687 2688 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2689 SDValue N0 = N->getOperand(0); 2690 SDValue N1 = N->getOperand(1); 2691 EVT VT = N0.getValueType(); 2692 2693 // fold vector ops 2694 if (VT.isVector()) 2695 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2696 return FoldedVOp; 2697 2698 // fold (add c1, c2) -> c1+c2 2699 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2700 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2701 if (N0C && N1C) 2702 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2703 2704 // canonicalize constant to RHS 2705 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2706 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2707 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2708 2709 return SDValue(); 2710 } 2711 2712 /// If this is a binary operator with two operands of the same opcode, try to 2713 /// simplify it. 2714 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2715 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2716 EVT VT = N0.getValueType(); 2717 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2718 2719 // Bail early if none of these transforms apply. 2720 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2721 2722 // For each of OP in AND/OR/XOR: 2723 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2724 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2725 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2726 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2727 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2728 // 2729 // do not sink logical op inside of a vector extend, since it may combine 2730 // into a vsetcc. 2731 EVT Op0VT = N0.getOperand(0).getValueType(); 2732 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2733 N0.getOpcode() == ISD::SIGN_EXTEND || 2734 N0.getOpcode() == ISD::BSWAP || 2735 // Avoid infinite looping with PromoteIntBinOp. 2736 (N0.getOpcode() == ISD::ANY_EXTEND && 2737 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2738 (N0.getOpcode() == ISD::TRUNCATE && 2739 (!TLI.isZExtFree(VT, Op0VT) || 2740 !TLI.isTruncateFree(Op0VT, VT)) && 2741 TLI.isTypeLegal(Op0VT))) && 2742 !VT.isVector() && 2743 Op0VT == N1.getOperand(0).getValueType() && 2744 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2745 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2746 N0.getOperand(0).getValueType(), 2747 N0.getOperand(0), N1.getOperand(0)); 2748 AddToWorklist(ORNode.getNode()); 2749 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2750 } 2751 2752 // For each of OP in SHL/SRL/SRA/AND... 2753 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2754 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2755 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2756 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2757 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2758 N0.getOperand(1) == N1.getOperand(1)) { 2759 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2760 N0.getOperand(0).getValueType(), 2761 N0.getOperand(0), N1.getOperand(0)); 2762 AddToWorklist(ORNode.getNode()); 2763 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2764 ORNode, N0.getOperand(1)); 2765 } 2766 2767 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2768 // Only perform this optimization up until type legalization, before 2769 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2770 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2771 // we don't want to undo this promotion. 2772 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2773 // on scalars. 2774 if ((N0.getOpcode() == ISD::BITCAST || 2775 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2776 Level <= AfterLegalizeTypes) { 2777 SDValue In0 = N0.getOperand(0); 2778 SDValue In1 = N1.getOperand(0); 2779 EVT In0Ty = In0.getValueType(); 2780 EVT In1Ty = In1.getValueType(); 2781 SDLoc DL(N); 2782 // If both incoming values are integers, and the original types are the 2783 // same. 2784 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2785 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2786 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2787 AddToWorklist(Op.getNode()); 2788 return BC; 2789 } 2790 } 2791 2792 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2793 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2794 // If both shuffles use the same mask, and both shuffle within a single 2795 // vector, then it is worthwhile to move the swizzle after the operation. 2796 // The type-legalizer generates this pattern when loading illegal 2797 // vector types from memory. In many cases this allows additional shuffle 2798 // optimizations. 2799 // There are other cases where moving the shuffle after the xor/and/or 2800 // is profitable even if shuffles don't perform a swizzle. 2801 // If both shuffles use the same mask, and both shuffles have the same first 2802 // or second operand, then it might still be profitable to move the shuffle 2803 // after the xor/and/or operation. 2804 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2805 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2806 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2807 2808 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2809 "Inputs to shuffles are not the same type"); 2810 2811 // Check that both shuffles use the same mask. The masks are known to be of 2812 // the same length because the result vector type is the same. 2813 // Check also that shuffles have only one use to avoid introducing extra 2814 // instructions. 2815 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2816 SVN0->getMask().equals(SVN1->getMask())) { 2817 SDValue ShOp = N0->getOperand(1); 2818 2819 // Don't try to fold this node if it requires introducing a 2820 // build vector of all zeros that might be illegal at this stage. 2821 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2822 if (!LegalTypes) 2823 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2824 else 2825 ShOp = SDValue(); 2826 } 2827 2828 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2829 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2830 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2831 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2832 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2833 N0->getOperand(0), N1->getOperand(0)); 2834 AddToWorklist(NewNode.getNode()); 2835 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2836 &SVN0->getMask()[0]); 2837 } 2838 2839 // Don't try to fold this node if it requires introducing a 2840 // build vector of all zeros that might be illegal at this stage. 2841 ShOp = N0->getOperand(0); 2842 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2843 if (!LegalTypes) 2844 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2845 else 2846 ShOp = SDValue(); 2847 } 2848 2849 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2850 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2851 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2852 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2853 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2854 N0->getOperand(1), N1->getOperand(1)); 2855 AddToWorklist(NewNode.getNode()); 2856 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2857 &SVN0->getMask()[0]); 2858 } 2859 } 2860 } 2861 2862 return SDValue(); 2863 } 2864 2865 /// This contains all DAGCombine rules which reduce two values combined by 2866 /// an And operation to a single value. This makes them reusable in the context 2867 /// of visitSELECT(). Rules involving constants are not included as 2868 /// visitSELECT() already handles those cases. 2869 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2870 SDNode *LocReference) { 2871 EVT VT = N1.getValueType(); 2872 2873 // fold (and x, undef) -> 0 2874 if (N0.isUndef() || N1.isUndef()) 2875 return DAG.getConstant(0, SDLoc(LocReference), VT); 2876 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2877 SDValue LL, LR, RL, RR, CC0, CC1; 2878 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2879 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2880 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2881 2882 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2883 LL.getValueType().isInteger()) { 2884 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2885 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2886 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2887 LR.getValueType(), LL, RL); 2888 AddToWorklist(ORNode.getNode()); 2889 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2890 } 2891 if (isAllOnesConstant(LR)) { 2892 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2893 if (Op1 == ISD::SETEQ) { 2894 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2895 LR.getValueType(), LL, RL); 2896 AddToWorklist(ANDNode.getNode()); 2897 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2898 } 2899 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2900 if (Op1 == ISD::SETGT) { 2901 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2902 LR.getValueType(), LL, RL); 2903 AddToWorklist(ORNode.getNode()); 2904 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2905 } 2906 } 2907 } 2908 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2909 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2910 Op0 == Op1 && LL.getValueType().isInteger() && 2911 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2912 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2913 SDLoc DL(N0); 2914 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2915 LL, DAG.getConstant(1, DL, 2916 LL.getValueType())); 2917 AddToWorklist(ADDNode.getNode()); 2918 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2919 DAG.getConstant(2, DL, LL.getValueType()), 2920 ISD::SETUGE); 2921 } 2922 // canonicalize equivalent to ll == rl 2923 if (LL == RR && LR == RL) { 2924 Op1 = ISD::getSetCCSwappedOperands(Op1); 2925 std::swap(RL, RR); 2926 } 2927 if (LL == RL && LR == RR) { 2928 bool isInteger = LL.getValueType().isInteger(); 2929 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2930 if (Result != ISD::SETCC_INVALID && 2931 (!LegalOperations || 2932 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2933 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2934 EVT CCVT = getSetCCResultType(LL.getValueType()); 2935 if (N0.getValueType() == CCVT || 2936 (!LegalOperations && N0.getValueType() == MVT::i1)) 2937 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2938 LL, LR, Result); 2939 } 2940 } 2941 } 2942 2943 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2944 VT.getSizeInBits() <= 64) { 2945 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2946 APInt ADDC = ADDI->getAPIntValue(); 2947 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2948 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2949 // immediate for an add, but it is legal if its top c2 bits are set, 2950 // transform the ADD so the immediate doesn't need to be materialized 2951 // in a register. 2952 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2953 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2954 SRLI->getZExtValue()); 2955 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2956 ADDC |= Mask; 2957 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2958 SDLoc DL(N0); 2959 SDValue NewAdd = 2960 DAG.getNode(ISD::ADD, DL, VT, 2961 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2962 CombineTo(N0.getNode(), NewAdd); 2963 // Return N so it doesn't get rechecked! 2964 return SDValue(LocReference, 0); 2965 } 2966 } 2967 } 2968 } 2969 } 2970 } 2971 2972 return SDValue(); 2973 } 2974 2975 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 2976 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 2977 bool &NarrowLoad) { 2978 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 2979 2980 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 2981 return false; 2982 2983 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2984 LoadedVT = LoadN->getMemoryVT(); 2985 2986 if (ExtVT == LoadedVT && 2987 (!LegalOperations || 2988 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 2989 // ZEXTLOAD will match without needing to change the size of the value being 2990 // loaded. 2991 NarrowLoad = false; 2992 return true; 2993 } 2994 2995 // Do not change the width of a volatile load. 2996 if (LoadN->isVolatile()) 2997 return false; 2998 2999 // Do not generate loads of non-round integer types since these can 3000 // be expensive (and would be wrong if the type is not byte sized). 3001 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3002 return false; 3003 3004 if (LegalOperations && 3005 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3006 return false; 3007 3008 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3009 return false; 3010 3011 NarrowLoad = true; 3012 return true; 3013 } 3014 3015 SDValue DAGCombiner::visitAND(SDNode *N) { 3016 SDValue N0 = N->getOperand(0); 3017 SDValue N1 = N->getOperand(1); 3018 EVT VT = N1.getValueType(); 3019 3020 // fold vector ops 3021 if (VT.isVector()) { 3022 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3023 return FoldedVOp; 3024 3025 // fold (and x, 0) -> 0, vector edition 3026 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3027 // do not return N0, because undef node may exist in N0 3028 return DAG.getConstant( 3029 APInt::getNullValue( 3030 N0.getValueType().getScalarType().getSizeInBits()), 3031 SDLoc(N), N0.getValueType()); 3032 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3033 // do not return N1, because undef node may exist in N1 3034 return DAG.getConstant( 3035 APInt::getNullValue( 3036 N1.getValueType().getScalarType().getSizeInBits()), 3037 SDLoc(N), N1.getValueType()); 3038 3039 // fold (and x, -1) -> x, vector edition 3040 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3041 return N1; 3042 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3043 return N0; 3044 } 3045 3046 // fold (and c1, c2) -> c1&c2 3047 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3048 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3049 if (N0C && N1C && !N1C->isOpaque()) 3050 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3051 // canonicalize constant to RHS 3052 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3053 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3054 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3055 // fold (and x, -1) -> x 3056 if (isAllOnesConstant(N1)) 3057 return N0; 3058 // if (and x, c) is known to be zero, return 0 3059 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3060 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3061 APInt::getAllOnesValue(BitWidth))) 3062 return DAG.getConstant(0, SDLoc(N), VT); 3063 // reassociate and 3064 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3065 return RAND; 3066 // fold (and (or x, C), D) -> D if (C & D) == D 3067 if (N1C && N0.getOpcode() == ISD::OR) 3068 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3069 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3070 return N1; 3071 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3072 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3073 SDValue N0Op0 = N0.getOperand(0); 3074 APInt Mask = ~N1C->getAPIntValue(); 3075 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3076 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3077 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3078 N0.getValueType(), N0Op0); 3079 3080 // Replace uses of the AND with uses of the Zero extend node. 3081 CombineTo(N, Zext); 3082 3083 // We actually want to replace all uses of the any_extend with the 3084 // zero_extend, to avoid duplicating things. This will later cause this 3085 // AND to be folded. 3086 CombineTo(N0.getNode(), Zext); 3087 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3088 } 3089 } 3090 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3091 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3092 // already be zero by virtue of the width of the base type of the load. 3093 // 3094 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3095 // more cases. 3096 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3097 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3098 N0.getOperand(0).getOpcode() == ISD::LOAD) || 3099 N0.getOpcode() == ISD::LOAD) { 3100 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3101 N0 : N0.getOperand(0) ); 3102 3103 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3104 // This can be a pure constant or a vector splat, in which case we treat the 3105 // vector as a scalar and use the splat value. 3106 APInt Constant = APInt::getNullValue(1); 3107 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3108 Constant = C->getAPIntValue(); 3109 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3110 APInt SplatValue, SplatUndef; 3111 unsigned SplatBitSize; 3112 bool HasAnyUndefs; 3113 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3114 SplatBitSize, HasAnyUndefs); 3115 if (IsSplat) { 3116 // Undef bits can contribute to a possible optimisation if set, so 3117 // set them. 3118 SplatValue |= SplatUndef; 3119 3120 // The splat value may be something like "0x00FFFFFF", which means 0 for 3121 // the first vector value and FF for the rest, repeating. We need a mask 3122 // that will apply equally to all members of the vector, so AND all the 3123 // lanes of the constant together. 3124 EVT VT = Vector->getValueType(0); 3125 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3126 3127 // If the splat value has been compressed to a bitlength lower 3128 // than the size of the vector lane, we need to re-expand it to 3129 // the lane size. 3130 if (BitWidth > SplatBitSize) 3131 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3132 SplatBitSize < BitWidth; 3133 SplatBitSize = SplatBitSize * 2) 3134 SplatValue |= SplatValue.shl(SplatBitSize); 3135 3136 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3137 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3138 if (SplatBitSize % BitWidth == 0) { 3139 Constant = APInt::getAllOnesValue(BitWidth); 3140 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3141 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3142 } 3143 } 3144 } 3145 3146 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3147 // actually legal and isn't going to get expanded, else this is a false 3148 // optimisation. 3149 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3150 Load->getValueType(0), 3151 Load->getMemoryVT()); 3152 3153 // Resize the constant to the same size as the original memory access before 3154 // extension. If it is still the AllOnesValue then this AND is completely 3155 // unneeded. 3156 Constant = 3157 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3158 3159 bool B; 3160 switch (Load->getExtensionType()) { 3161 default: B = false; break; 3162 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3163 case ISD::ZEXTLOAD: 3164 case ISD::NON_EXTLOAD: B = true; break; 3165 } 3166 3167 if (B && Constant.isAllOnesValue()) { 3168 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3169 // preserve semantics once we get rid of the AND. 3170 SDValue NewLoad(Load, 0); 3171 if (Load->getExtensionType() == ISD::EXTLOAD) { 3172 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3173 Load->getValueType(0), SDLoc(Load), 3174 Load->getChain(), Load->getBasePtr(), 3175 Load->getOffset(), Load->getMemoryVT(), 3176 Load->getMemOperand()); 3177 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3178 if (Load->getNumValues() == 3) { 3179 // PRE/POST_INC loads have 3 values. 3180 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3181 NewLoad.getValue(2) }; 3182 CombineTo(Load, To, 3, true); 3183 } else { 3184 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3185 } 3186 } 3187 3188 // Fold the AND away, taking care not to fold to the old load node if we 3189 // replaced it. 3190 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3191 3192 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3193 } 3194 } 3195 3196 // fold (and (load x), 255) -> (zextload x, i8) 3197 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3198 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3199 if (N1C && (N0.getOpcode() == ISD::LOAD || 3200 (N0.getOpcode() == ISD::ANY_EXTEND && 3201 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3202 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3203 LoadSDNode *LN0 = HasAnyExt 3204 ? cast<LoadSDNode>(N0.getOperand(0)) 3205 : cast<LoadSDNode>(N0); 3206 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3207 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3208 auto NarrowLoad = false; 3209 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3210 EVT ExtVT, LoadedVT; 3211 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3212 NarrowLoad)) { 3213 if (!NarrowLoad) { 3214 SDValue NewLoad = 3215 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3216 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3217 LN0->getMemOperand()); 3218 AddToWorklist(N); 3219 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3220 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3221 } else { 3222 EVT PtrType = LN0->getOperand(1).getValueType(); 3223 3224 unsigned Alignment = LN0->getAlignment(); 3225 SDValue NewPtr = LN0->getBasePtr(); 3226 3227 // For big endian targets, we need to add an offset to the pointer 3228 // to load the correct bytes. For little endian systems, we merely 3229 // need to read fewer bytes from the same pointer. 3230 if (DAG.getDataLayout().isBigEndian()) { 3231 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3232 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3233 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3234 SDLoc DL(LN0); 3235 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3236 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3237 Alignment = MinAlign(Alignment, PtrOff); 3238 } 3239 3240 AddToWorklist(NewPtr.getNode()); 3241 3242 SDValue Load = 3243 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3244 LN0->getChain(), NewPtr, 3245 LN0->getPointerInfo(), 3246 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3247 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3248 AddToWorklist(N); 3249 CombineTo(LN0, Load, Load.getValue(1)); 3250 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3251 } 3252 } 3253 } 3254 } 3255 3256 if (SDValue Combined = visitANDLike(N0, N1, N)) 3257 return Combined; 3258 3259 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3260 if (N0.getOpcode() == N1.getOpcode()) 3261 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3262 return Tmp; 3263 3264 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3265 // fold (and (sra)) -> (and (srl)) when possible. 3266 if (!VT.isVector() && 3267 SimplifyDemandedBits(SDValue(N, 0))) 3268 return SDValue(N, 0); 3269 3270 // fold (zext_inreg (extload x)) -> (zextload x) 3271 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3272 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3273 EVT MemVT = LN0->getMemoryVT(); 3274 // If we zero all the possible extended bits, then we can turn this into 3275 // a zextload if we are running before legalize or the operation is legal. 3276 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3277 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3278 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3279 ((!LegalOperations && !LN0->isVolatile()) || 3280 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3281 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3282 LN0->getChain(), LN0->getBasePtr(), 3283 MemVT, LN0->getMemOperand()); 3284 AddToWorklist(N); 3285 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3286 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3287 } 3288 } 3289 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3290 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3291 N0.hasOneUse()) { 3292 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3293 EVT MemVT = LN0->getMemoryVT(); 3294 // If we zero all the possible extended bits, then we can turn this into 3295 // a zextload if we are running before legalize or the operation is legal. 3296 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3297 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3298 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3299 ((!LegalOperations && !LN0->isVolatile()) || 3300 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3301 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3302 LN0->getChain(), LN0->getBasePtr(), 3303 MemVT, LN0->getMemOperand()); 3304 AddToWorklist(N); 3305 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3306 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3307 } 3308 } 3309 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3310 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3311 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3312 N0.getOperand(1), false)) 3313 return BSwap; 3314 } 3315 3316 return SDValue(); 3317 } 3318 3319 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3320 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3321 bool DemandHighBits) { 3322 if (!LegalOperations) 3323 return SDValue(); 3324 3325 EVT VT = N->getValueType(0); 3326 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3327 return SDValue(); 3328 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3329 return SDValue(); 3330 3331 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3332 bool LookPassAnd0 = false; 3333 bool LookPassAnd1 = false; 3334 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3335 std::swap(N0, N1); 3336 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3337 std::swap(N0, N1); 3338 if (N0.getOpcode() == ISD::AND) { 3339 if (!N0.getNode()->hasOneUse()) 3340 return SDValue(); 3341 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3342 if (!N01C || N01C->getZExtValue() != 0xFF00) 3343 return SDValue(); 3344 N0 = N0.getOperand(0); 3345 LookPassAnd0 = true; 3346 } 3347 3348 if (N1.getOpcode() == ISD::AND) { 3349 if (!N1.getNode()->hasOneUse()) 3350 return SDValue(); 3351 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3352 if (!N11C || N11C->getZExtValue() != 0xFF) 3353 return SDValue(); 3354 N1 = N1.getOperand(0); 3355 LookPassAnd1 = true; 3356 } 3357 3358 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3359 std::swap(N0, N1); 3360 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3361 return SDValue(); 3362 if (!N0.getNode()->hasOneUse() || 3363 !N1.getNode()->hasOneUse()) 3364 return SDValue(); 3365 3366 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3367 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3368 if (!N01C || !N11C) 3369 return SDValue(); 3370 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3371 return SDValue(); 3372 3373 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3374 SDValue N00 = N0->getOperand(0); 3375 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3376 if (!N00.getNode()->hasOneUse()) 3377 return SDValue(); 3378 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3379 if (!N001C || N001C->getZExtValue() != 0xFF) 3380 return SDValue(); 3381 N00 = N00.getOperand(0); 3382 LookPassAnd0 = true; 3383 } 3384 3385 SDValue N10 = N1->getOperand(0); 3386 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3387 if (!N10.getNode()->hasOneUse()) 3388 return SDValue(); 3389 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3390 if (!N101C || N101C->getZExtValue() != 0xFF00) 3391 return SDValue(); 3392 N10 = N10.getOperand(0); 3393 LookPassAnd1 = true; 3394 } 3395 3396 if (N00 != N10) 3397 return SDValue(); 3398 3399 // Make sure everything beyond the low halfword gets set to zero since the SRL 3400 // 16 will clear the top bits. 3401 unsigned OpSizeInBits = VT.getSizeInBits(); 3402 if (DemandHighBits && OpSizeInBits > 16) { 3403 // If the left-shift isn't masked out then the only way this is a bswap is 3404 // if all bits beyond the low 8 are 0. In that case the entire pattern 3405 // reduces to a left shift anyway: leave it for other parts of the combiner. 3406 if (!LookPassAnd0) 3407 return SDValue(); 3408 3409 // However, if the right shift isn't masked out then it might be because 3410 // it's not needed. See if we can spot that too. 3411 if (!LookPassAnd1 && 3412 !DAG.MaskedValueIsZero( 3413 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3414 return SDValue(); 3415 } 3416 3417 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3418 if (OpSizeInBits > 16) { 3419 SDLoc DL(N); 3420 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3421 DAG.getConstant(OpSizeInBits - 16, DL, 3422 getShiftAmountTy(VT))); 3423 } 3424 return Res; 3425 } 3426 3427 /// Return true if the specified node is an element that makes up a 32-bit 3428 /// packed halfword byteswap. 3429 /// ((x & 0x000000ff) << 8) | 3430 /// ((x & 0x0000ff00) >> 8) | 3431 /// ((x & 0x00ff0000) << 8) | 3432 /// ((x & 0xff000000) >> 8) 3433 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3434 if (!N.getNode()->hasOneUse()) 3435 return false; 3436 3437 unsigned Opc = N.getOpcode(); 3438 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3439 return false; 3440 3441 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3442 if (!N1C) 3443 return false; 3444 3445 unsigned Num; 3446 switch (N1C->getZExtValue()) { 3447 default: 3448 return false; 3449 case 0xFF: Num = 0; break; 3450 case 0xFF00: Num = 1; break; 3451 case 0xFF0000: Num = 2; break; 3452 case 0xFF000000: Num = 3; break; 3453 } 3454 3455 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3456 SDValue N0 = N.getOperand(0); 3457 if (Opc == ISD::AND) { 3458 if (Num == 0 || Num == 2) { 3459 // (x >> 8) & 0xff 3460 // (x >> 8) & 0xff0000 3461 if (N0.getOpcode() != ISD::SRL) 3462 return false; 3463 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3464 if (!C || C->getZExtValue() != 8) 3465 return false; 3466 } else { 3467 // (x << 8) & 0xff00 3468 // (x << 8) & 0xff000000 3469 if (N0.getOpcode() != ISD::SHL) 3470 return false; 3471 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3472 if (!C || C->getZExtValue() != 8) 3473 return false; 3474 } 3475 } else if (Opc == ISD::SHL) { 3476 // (x & 0xff) << 8 3477 // (x & 0xff0000) << 8 3478 if (Num != 0 && Num != 2) 3479 return false; 3480 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3481 if (!C || C->getZExtValue() != 8) 3482 return false; 3483 } else { // Opc == ISD::SRL 3484 // (x & 0xff00) >> 8 3485 // (x & 0xff000000) >> 8 3486 if (Num != 1 && Num != 3) 3487 return false; 3488 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3489 if (!C || C->getZExtValue() != 8) 3490 return false; 3491 } 3492 3493 if (Parts[Num]) 3494 return false; 3495 3496 Parts[Num] = N0.getOperand(0).getNode(); 3497 return true; 3498 } 3499 3500 /// Match a 32-bit packed halfword bswap. That is 3501 /// ((x & 0x000000ff) << 8) | 3502 /// ((x & 0x0000ff00) >> 8) | 3503 /// ((x & 0x00ff0000) << 8) | 3504 /// ((x & 0xff000000) >> 8) 3505 /// => (rotl (bswap x), 16) 3506 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3507 if (!LegalOperations) 3508 return SDValue(); 3509 3510 EVT VT = N->getValueType(0); 3511 if (VT != MVT::i32) 3512 return SDValue(); 3513 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3514 return SDValue(); 3515 3516 // Look for either 3517 // (or (or (and), (and)), (or (and), (and))) 3518 // (or (or (or (and), (and)), (and)), (and)) 3519 if (N0.getOpcode() != ISD::OR) 3520 return SDValue(); 3521 SDValue N00 = N0.getOperand(0); 3522 SDValue N01 = N0.getOperand(1); 3523 SDNode *Parts[4] = {}; 3524 3525 if (N1.getOpcode() == ISD::OR && 3526 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3527 // (or (or (and), (and)), (or (and), (and))) 3528 SDValue N000 = N00.getOperand(0); 3529 if (!isBSwapHWordElement(N000, Parts)) 3530 return SDValue(); 3531 3532 SDValue N001 = N00.getOperand(1); 3533 if (!isBSwapHWordElement(N001, Parts)) 3534 return SDValue(); 3535 SDValue N010 = N01.getOperand(0); 3536 if (!isBSwapHWordElement(N010, Parts)) 3537 return SDValue(); 3538 SDValue N011 = N01.getOperand(1); 3539 if (!isBSwapHWordElement(N011, Parts)) 3540 return SDValue(); 3541 } else { 3542 // (or (or (or (and), (and)), (and)), (and)) 3543 if (!isBSwapHWordElement(N1, Parts)) 3544 return SDValue(); 3545 if (!isBSwapHWordElement(N01, Parts)) 3546 return SDValue(); 3547 if (N00.getOpcode() != ISD::OR) 3548 return SDValue(); 3549 SDValue N000 = N00.getOperand(0); 3550 if (!isBSwapHWordElement(N000, Parts)) 3551 return SDValue(); 3552 SDValue N001 = N00.getOperand(1); 3553 if (!isBSwapHWordElement(N001, Parts)) 3554 return SDValue(); 3555 } 3556 3557 // Make sure the parts are all coming from the same node. 3558 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3559 return SDValue(); 3560 3561 SDLoc DL(N); 3562 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3563 SDValue(Parts[0], 0)); 3564 3565 // Result of the bswap should be rotated by 16. If it's not legal, then 3566 // do (x << 16) | (x >> 16). 3567 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3568 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3569 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3570 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3571 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3572 return DAG.getNode(ISD::OR, DL, VT, 3573 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3574 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3575 } 3576 3577 /// This contains all DAGCombine rules which reduce two values combined by 3578 /// an Or operation to a single value \see visitANDLike(). 3579 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3580 EVT VT = N1.getValueType(); 3581 // fold (or x, undef) -> -1 3582 if (!LegalOperations && 3583 (N0.isUndef() || N1.isUndef())) { 3584 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3585 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3586 SDLoc(LocReference), VT); 3587 } 3588 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3589 SDValue LL, LR, RL, RR, CC0, CC1; 3590 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3591 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3592 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3593 3594 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3595 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3596 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3597 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3598 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3599 LR.getValueType(), LL, RL); 3600 AddToWorklist(ORNode.getNode()); 3601 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3602 } 3603 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3604 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3605 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3606 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3607 LR.getValueType(), LL, RL); 3608 AddToWorklist(ANDNode.getNode()); 3609 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3610 } 3611 } 3612 // canonicalize equivalent to ll == rl 3613 if (LL == RR && LR == RL) { 3614 Op1 = ISD::getSetCCSwappedOperands(Op1); 3615 std::swap(RL, RR); 3616 } 3617 if (LL == RL && LR == RR) { 3618 bool isInteger = LL.getValueType().isInteger(); 3619 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3620 if (Result != ISD::SETCC_INVALID && 3621 (!LegalOperations || 3622 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3623 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3624 EVT CCVT = getSetCCResultType(LL.getValueType()); 3625 if (N0.getValueType() == CCVT || 3626 (!LegalOperations && N0.getValueType() == MVT::i1)) 3627 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3628 LL, LR, Result); 3629 } 3630 } 3631 } 3632 3633 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3634 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3635 // Don't increase # computations. 3636 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3637 // We can only do this xform if we know that bits from X that are set in C2 3638 // but not in C1 are already zero. Likewise for Y. 3639 if (const ConstantSDNode *N0O1C = 3640 getAsNonOpaqueConstant(N0.getOperand(1))) { 3641 if (const ConstantSDNode *N1O1C = 3642 getAsNonOpaqueConstant(N1.getOperand(1))) { 3643 // We can only do this xform if we know that bits from X that are set in 3644 // C2 but not in C1 are already zero. Likewise for Y. 3645 const APInt &LHSMask = N0O1C->getAPIntValue(); 3646 const APInt &RHSMask = N1O1C->getAPIntValue(); 3647 3648 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3649 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3650 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3651 N0.getOperand(0), N1.getOperand(0)); 3652 SDLoc DL(LocReference); 3653 return DAG.getNode(ISD::AND, DL, VT, X, 3654 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3655 } 3656 } 3657 } 3658 } 3659 3660 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3661 if (N0.getOpcode() == ISD::AND && 3662 N1.getOpcode() == ISD::AND && 3663 N0.getOperand(0) == N1.getOperand(0) && 3664 // Don't increase # computations. 3665 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3666 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3667 N0.getOperand(1), N1.getOperand(1)); 3668 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3669 } 3670 3671 return SDValue(); 3672 } 3673 3674 SDValue DAGCombiner::visitOR(SDNode *N) { 3675 SDValue N0 = N->getOperand(0); 3676 SDValue N1 = N->getOperand(1); 3677 EVT VT = N1.getValueType(); 3678 3679 // fold vector ops 3680 if (VT.isVector()) { 3681 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3682 return FoldedVOp; 3683 3684 // fold (or x, 0) -> x, vector edition 3685 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3686 return N1; 3687 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3688 return N0; 3689 3690 // fold (or x, -1) -> -1, vector edition 3691 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3692 // do not return N0, because undef node may exist in N0 3693 return DAG.getConstant( 3694 APInt::getAllOnesValue( 3695 N0.getValueType().getScalarType().getSizeInBits()), 3696 SDLoc(N), N0.getValueType()); 3697 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3698 // do not return N1, because undef node may exist in N1 3699 return DAG.getConstant( 3700 APInt::getAllOnesValue( 3701 N1.getValueType().getScalarType().getSizeInBits()), 3702 SDLoc(N), N1.getValueType()); 3703 3704 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3705 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3706 // Do this only if the resulting shuffle is legal. 3707 if (isa<ShuffleVectorSDNode>(N0) && 3708 isa<ShuffleVectorSDNode>(N1) && 3709 // Avoid folding a node with illegal type. 3710 TLI.isTypeLegal(VT) && 3711 N0->getOperand(1) == N1->getOperand(1) && 3712 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3713 bool CanFold = true; 3714 unsigned NumElts = VT.getVectorNumElements(); 3715 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3716 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3717 // We construct two shuffle masks: 3718 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3719 // and N1 as the second operand. 3720 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3721 // and N0 as the second operand. 3722 // We do this because OR is commutable and therefore there might be 3723 // two ways to fold this node into a shuffle. 3724 SmallVector<int,4> Mask1; 3725 SmallVector<int,4> Mask2; 3726 3727 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3728 int M0 = SV0->getMaskElt(i); 3729 int M1 = SV1->getMaskElt(i); 3730 3731 // Both shuffle indexes are undef. Propagate Undef. 3732 if (M0 < 0 && M1 < 0) { 3733 Mask1.push_back(M0); 3734 Mask2.push_back(M0); 3735 continue; 3736 } 3737 3738 if (M0 < 0 || M1 < 0 || 3739 (M0 < (int)NumElts && M1 < (int)NumElts) || 3740 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3741 CanFold = false; 3742 break; 3743 } 3744 3745 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3746 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3747 } 3748 3749 if (CanFold) { 3750 // Fold this sequence only if the resulting shuffle is 'legal'. 3751 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3752 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3753 N1->getOperand(0), &Mask1[0]); 3754 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3755 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3756 N0->getOperand(0), &Mask2[0]); 3757 } 3758 } 3759 } 3760 3761 // fold (or c1, c2) -> c1|c2 3762 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3764 if (N0C && N1C && !N1C->isOpaque()) 3765 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3766 // canonicalize constant to RHS 3767 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3768 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3769 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3770 // fold (or x, 0) -> x 3771 if (isNullConstant(N1)) 3772 return N0; 3773 // fold (or x, -1) -> -1 3774 if (isAllOnesConstant(N1)) 3775 return N1; 3776 // fold (or x, c) -> c iff (x & ~c) == 0 3777 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3778 return N1; 3779 3780 if (SDValue Combined = visitORLike(N0, N1, N)) 3781 return Combined; 3782 3783 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3784 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3785 return BSwap; 3786 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3787 return BSwap; 3788 3789 // reassociate or 3790 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3791 return ROR; 3792 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3793 // iff (c1 & c2) == 0. 3794 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3795 isa<ConstantSDNode>(N0.getOperand(1))) { 3796 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3797 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3798 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3799 N1C, C1)) 3800 return DAG.getNode( 3801 ISD::AND, SDLoc(N), VT, 3802 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3803 return SDValue(); 3804 } 3805 } 3806 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3807 if (N0.getOpcode() == N1.getOpcode()) 3808 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3809 return Tmp; 3810 3811 // See if this is some rotate idiom. 3812 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3813 return SDValue(Rot, 0); 3814 3815 // Simplify the operands using demanded-bits information. 3816 if (!VT.isVector() && 3817 SimplifyDemandedBits(SDValue(N, 0))) 3818 return SDValue(N, 0); 3819 3820 return SDValue(); 3821 } 3822 3823 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3824 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3825 if (Op.getOpcode() == ISD::AND) { 3826 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3827 Mask = Op.getOperand(1); 3828 Op = Op.getOperand(0); 3829 } else { 3830 return false; 3831 } 3832 } 3833 3834 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3835 Shift = Op; 3836 return true; 3837 } 3838 3839 return false; 3840 } 3841 3842 // Return true if we can prove that, whenever Neg and Pos are both in the 3843 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3844 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3845 // 3846 // (or (shift1 X, Neg), (shift2 X, Pos)) 3847 // 3848 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3849 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3850 // to consider shift amounts with defined behavior. 3851 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3852 // If EltSize is a power of 2 then: 3853 // 3854 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3855 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3856 // 3857 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3858 // for the stronger condition: 3859 // 3860 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3861 // 3862 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3863 // we can just replace Neg with Neg' for the rest of the function. 3864 // 3865 // In other cases we check for the even stronger condition: 3866 // 3867 // Neg == EltSize - Pos [B] 3868 // 3869 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3870 // behavior if Pos == 0 (and consequently Neg == EltSize). 3871 // 3872 // We could actually use [A] whenever EltSize is a power of 2, but the 3873 // only extra cases that it would match are those uninteresting ones 3874 // where Neg and Pos are never in range at the same time. E.g. for 3875 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3876 // as well as (sub 32, Pos), but: 3877 // 3878 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3879 // 3880 // always invokes undefined behavior for 32-bit X. 3881 // 3882 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3883 unsigned MaskLoBits = 0; 3884 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3885 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3886 if (NegC->getAPIntValue() == EltSize - 1) { 3887 Neg = Neg.getOperand(0); 3888 MaskLoBits = Log2_64(EltSize); 3889 } 3890 } 3891 } 3892 3893 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3894 if (Neg.getOpcode() != ISD::SUB) 3895 return false; 3896 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3897 if (!NegC) 3898 return false; 3899 SDValue NegOp1 = Neg.getOperand(1); 3900 3901 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3902 // Pos'. The truncation is redundant for the purpose of the equality. 3903 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3904 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3905 if (PosC->getAPIntValue() == EltSize - 1) 3906 Pos = Pos.getOperand(0); 3907 3908 // The condition we need is now: 3909 // 3910 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3911 // 3912 // If NegOp1 == Pos then we need: 3913 // 3914 // EltSize & Mask == NegC & Mask 3915 // 3916 // (because "x & Mask" is a truncation and distributes through subtraction). 3917 APInt Width; 3918 if (Pos == NegOp1) 3919 Width = NegC->getAPIntValue(); 3920 3921 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3922 // Then the condition we want to prove becomes: 3923 // 3924 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3925 // 3926 // which, again because "x & Mask" is a truncation, becomes: 3927 // 3928 // NegC & Mask == (EltSize - PosC) & Mask 3929 // EltSize & Mask == (NegC + PosC) & Mask 3930 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3931 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3932 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3933 else 3934 return false; 3935 } else 3936 return false; 3937 3938 // Now we just need to check that EltSize & Mask == Width & Mask. 3939 if (MaskLoBits) 3940 // EltSize & Mask is 0 since Mask is EltSize - 1. 3941 return Width.getLoBits(MaskLoBits) == 0; 3942 return Width == EltSize; 3943 } 3944 3945 // A subroutine of MatchRotate used once we have found an OR of two opposite 3946 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3947 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3948 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3949 // Neg with outer conversions stripped away. 3950 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3951 SDValue Neg, SDValue InnerPos, 3952 SDValue InnerNeg, unsigned PosOpcode, 3953 unsigned NegOpcode, SDLoc DL) { 3954 // fold (or (shl x, (*ext y)), 3955 // (srl x, (*ext (sub 32, y)))) -> 3956 // (rotl x, y) or (rotr x, (sub 32, y)) 3957 // 3958 // fold (or (shl x, (*ext (sub 32, y))), 3959 // (srl x, (*ext y))) -> 3960 // (rotr x, y) or (rotl x, (sub 32, y)) 3961 EVT VT = Shifted.getValueType(); 3962 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 3963 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3964 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3965 HasPos ? Pos : Neg).getNode(); 3966 } 3967 3968 return nullptr; 3969 } 3970 3971 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3972 // idioms for rotate, and if the target supports rotation instructions, generate 3973 // a rot[lr]. 3974 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3975 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3976 EVT VT = LHS.getValueType(); 3977 if (!TLI.isTypeLegal(VT)) return nullptr; 3978 3979 // The target must have at least one rotate flavor. 3980 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3981 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3982 if (!HasROTL && !HasROTR) return nullptr; 3983 3984 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3985 SDValue LHSShift; // The shift. 3986 SDValue LHSMask; // AND value if any. 3987 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3988 return nullptr; // Not part of a rotate. 3989 3990 SDValue RHSShift; // The shift. 3991 SDValue RHSMask; // AND value if any. 3992 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3993 return nullptr; // Not part of a rotate. 3994 3995 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3996 return nullptr; // Not shifting the same value. 3997 3998 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3999 return nullptr; // Shifts must disagree. 4000 4001 // Canonicalize shl to left side in a shl/srl pair. 4002 if (RHSShift.getOpcode() == ISD::SHL) { 4003 std::swap(LHS, RHS); 4004 std::swap(LHSShift, RHSShift); 4005 std::swap(LHSMask, RHSMask); 4006 } 4007 4008 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4009 SDValue LHSShiftArg = LHSShift.getOperand(0); 4010 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4011 SDValue RHSShiftArg = RHSShift.getOperand(0); 4012 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4013 4014 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4015 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4016 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4017 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4018 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4019 if ((LShVal + RShVal) != EltSizeInBits) 4020 return nullptr; 4021 4022 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4023 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4024 4025 // If there is an AND of either shifted operand, apply it to the result. 4026 if (LHSMask.getNode() || RHSMask.getNode()) { 4027 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4028 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4029 4030 if (LHSMask.getNode()) { 4031 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4032 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4033 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4034 DAG.getConstant(RHSBits, DL, VT))); 4035 } 4036 if (RHSMask.getNode()) { 4037 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4038 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4039 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4040 DAG.getConstant(LHSBits, DL, VT))); 4041 } 4042 4043 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4044 } 4045 4046 return Rot.getNode(); 4047 } 4048 4049 // If there is a mask here, and we have a variable shift, we can't be sure 4050 // that we're masking out the right stuff. 4051 if (LHSMask.getNode() || RHSMask.getNode()) 4052 return nullptr; 4053 4054 // If the shift amount is sign/zext/any-extended just peel it off. 4055 SDValue LExtOp0 = LHSShiftAmt; 4056 SDValue RExtOp0 = RHSShiftAmt; 4057 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4058 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4059 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4060 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4061 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4062 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4063 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4064 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4065 LExtOp0 = LHSShiftAmt.getOperand(0); 4066 RExtOp0 = RHSShiftAmt.getOperand(0); 4067 } 4068 4069 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4070 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4071 if (TryL) 4072 return TryL; 4073 4074 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4075 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4076 if (TryR) 4077 return TryR; 4078 4079 return nullptr; 4080 } 4081 4082 SDValue DAGCombiner::visitXOR(SDNode *N) { 4083 SDValue N0 = N->getOperand(0); 4084 SDValue N1 = N->getOperand(1); 4085 EVT VT = N0.getValueType(); 4086 4087 // fold vector ops 4088 if (VT.isVector()) { 4089 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4090 return FoldedVOp; 4091 4092 // fold (xor x, 0) -> x, vector edition 4093 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4094 return N1; 4095 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4096 return N0; 4097 } 4098 4099 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4100 if (N0.isUndef() && N1.isUndef()) 4101 return DAG.getConstant(0, SDLoc(N), VT); 4102 // fold (xor x, undef) -> undef 4103 if (N0.isUndef()) 4104 return N0; 4105 if (N1.isUndef()) 4106 return N1; 4107 // fold (xor c1, c2) -> c1^c2 4108 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4109 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4110 if (N0C && N1C) 4111 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4112 // canonicalize constant to RHS 4113 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4114 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4115 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4116 // fold (xor x, 0) -> x 4117 if (isNullConstant(N1)) 4118 return N0; 4119 // reassociate xor 4120 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4121 return RXOR; 4122 4123 // fold !(x cc y) -> (x !cc y) 4124 SDValue LHS, RHS, CC; 4125 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4126 bool isInt = LHS.getValueType().isInteger(); 4127 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4128 isInt); 4129 4130 if (!LegalOperations || 4131 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4132 switch (N0.getOpcode()) { 4133 default: 4134 llvm_unreachable("Unhandled SetCC Equivalent!"); 4135 case ISD::SETCC: 4136 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4137 case ISD::SELECT_CC: 4138 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4139 N0.getOperand(3), NotCC); 4140 } 4141 } 4142 } 4143 4144 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4145 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4146 N0.getNode()->hasOneUse() && 4147 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4148 SDValue V = N0.getOperand(0); 4149 SDLoc DL(N0); 4150 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4151 DAG.getConstant(1, DL, V.getValueType())); 4152 AddToWorklist(V.getNode()); 4153 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4154 } 4155 4156 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4157 if (isOneConstant(N1) && VT == MVT::i1 && 4158 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4159 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4160 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4161 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4162 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4163 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4164 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4165 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4166 } 4167 } 4168 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4169 if (isAllOnesConstant(N1) && 4170 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4171 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4172 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4173 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4174 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4175 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4176 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4177 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4178 } 4179 } 4180 // fold (xor (and x, y), y) -> (and (not x), y) 4181 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4182 N0->getOperand(1) == N1) { 4183 SDValue X = N0->getOperand(0); 4184 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4185 AddToWorklist(NotX.getNode()); 4186 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4187 } 4188 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4189 if (N1C && N0.getOpcode() == ISD::XOR) { 4190 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4191 SDLoc DL(N); 4192 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4193 DAG.getConstant(N1C->getAPIntValue() ^ 4194 N00C->getAPIntValue(), DL, VT)); 4195 } 4196 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4197 SDLoc DL(N); 4198 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4199 DAG.getConstant(N1C->getAPIntValue() ^ 4200 N01C->getAPIntValue(), DL, VT)); 4201 } 4202 } 4203 // fold (xor x, x) -> 0 4204 if (N0 == N1) 4205 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4206 4207 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4208 // Here is a concrete example of this equivalence: 4209 // i16 x == 14 4210 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4211 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4212 // 4213 // => 4214 // 4215 // i16 ~1 == 0b1111111111111110 4216 // i16 rol(~1, 14) == 0b1011111111111111 4217 // 4218 // Some additional tips to help conceptualize this transform: 4219 // - Try to see the operation as placing a single zero in a value of all ones. 4220 // - There exists no value for x which would allow the result to contain zero. 4221 // - Values of x larger than the bitwidth are undefined and do not require a 4222 // consistent result. 4223 // - Pushing the zero left requires shifting one bits in from the right. 4224 // A rotate left of ~1 is a nice way of achieving the desired result. 4225 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4226 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4227 SDLoc DL(N); 4228 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4229 N0.getOperand(1)); 4230 } 4231 4232 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4233 if (N0.getOpcode() == N1.getOpcode()) 4234 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4235 return Tmp; 4236 4237 // Simplify the expression using non-local knowledge. 4238 if (!VT.isVector() && 4239 SimplifyDemandedBits(SDValue(N, 0))) 4240 return SDValue(N, 0); 4241 4242 return SDValue(); 4243 } 4244 4245 /// Handle transforms common to the three shifts, when the shift amount is a 4246 /// constant. 4247 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4248 SDNode *LHS = N->getOperand(0).getNode(); 4249 if (!LHS->hasOneUse()) return SDValue(); 4250 4251 // We want to pull some binops through shifts, so that we have (and (shift)) 4252 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4253 // thing happens with address calculations, so it's important to canonicalize 4254 // it. 4255 bool HighBitSet = false; // Can we transform this if the high bit is set? 4256 4257 switch (LHS->getOpcode()) { 4258 default: return SDValue(); 4259 case ISD::OR: 4260 case ISD::XOR: 4261 HighBitSet = false; // We can only transform sra if the high bit is clear. 4262 break; 4263 case ISD::AND: 4264 HighBitSet = true; // We can only transform sra if the high bit is set. 4265 break; 4266 case ISD::ADD: 4267 if (N->getOpcode() != ISD::SHL) 4268 return SDValue(); // only shl(add) not sr[al](add). 4269 HighBitSet = false; // We can only transform sra if the high bit is clear. 4270 break; 4271 } 4272 4273 // We require the RHS of the binop to be a constant and not opaque as well. 4274 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4275 if (!BinOpCst) return SDValue(); 4276 4277 // FIXME: disable this unless the input to the binop is a shift by a constant. 4278 // If it is not a shift, it pessimizes some common cases like: 4279 // 4280 // void foo(int *X, int i) { X[i & 1235] = 1; } 4281 // int bar(int *X, int i) { return X[i & 255]; } 4282 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4283 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4284 BinOpLHSVal->getOpcode() != ISD::SRA && 4285 BinOpLHSVal->getOpcode() != ISD::SRL) || 4286 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4287 return SDValue(); 4288 4289 EVT VT = N->getValueType(0); 4290 4291 // If this is a signed shift right, and the high bit is modified by the 4292 // logical operation, do not perform the transformation. The highBitSet 4293 // boolean indicates the value of the high bit of the constant which would 4294 // cause it to be modified for this operation. 4295 if (N->getOpcode() == ISD::SRA) { 4296 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4297 if (BinOpRHSSignSet != HighBitSet) 4298 return SDValue(); 4299 } 4300 4301 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4302 return SDValue(); 4303 4304 // Fold the constants, shifting the binop RHS by the shift amount. 4305 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4306 N->getValueType(0), 4307 LHS->getOperand(1), N->getOperand(1)); 4308 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4309 4310 // Create the new shift. 4311 SDValue NewShift = DAG.getNode(N->getOpcode(), 4312 SDLoc(LHS->getOperand(0)), 4313 VT, LHS->getOperand(0), N->getOperand(1)); 4314 4315 // Create the new binop. 4316 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4317 } 4318 4319 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4320 assert(N->getOpcode() == ISD::TRUNCATE); 4321 assert(N->getOperand(0).getOpcode() == ISD::AND); 4322 4323 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4324 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4325 SDValue N01 = N->getOperand(0).getOperand(1); 4326 4327 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4328 if (!N01C->isOpaque()) { 4329 EVT TruncVT = N->getValueType(0); 4330 SDValue N00 = N->getOperand(0).getOperand(0); 4331 APInt TruncC = N01C->getAPIntValue(); 4332 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4333 SDLoc DL(N); 4334 4335 return DAG.getNode(ISD::AND, DL, TruncVT, 4336 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4337 DAG.getConstant(TruncC, DL, TruncVT)); 4338 } 4339 } 4340 } 4341 4342 return SDValue(); 4343 } 4344 4345 SDValue DAGCombiner::visitRotate(SDNode *N) { 4346 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4347 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4348 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4349 if (SDValue NewOp1 = 4350 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4351 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4352 N->getOperand(0), NewOp1); 4353 } 4354 return SDValue(); 4355 } 4356 4357 SDValue DAGCombiner::visitSHL(SDNode *N) { 4358 SDValue N0 = N->getOperand(0); 4359 SDValue N1 = N->getOperand(1); 4360 EVT VT = N0.getValueType(); 4361 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4362 4363 // fold vector ops 4364 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4365 if (VT.isVector()) { 4366 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4367 return FoldedVOp; 4368 4369 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4370 // If setcc produces all-one true value then: 4371 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4372 if (N1CV && N1CV->isConstant()) { 4373 if (N0.getOpcode() == ISD::AND) { 4374 SDValue N00 = N0->getOperand(0); 4375 SDValue N01 = N0->getOperand(1); 4376 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4377 4378 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4379 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4380 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4381 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4382 N01CV, N1CV)) 4383 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4384 } 4385 } else { 4386 N1C = isConstOrConstSplat(N1); 4387 } 4388 } 4389 } 4390 4391 // fold (shl c1, c2) -> c1<<c2 4392 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4393 if (N0C && N1C && !N1C->isOpaque()) 4394 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4395 // fold (shl 0, x) -> 0 4396 if (isNullConstant(N0)) 4397 return N0; 4398 // fold (shl x, c >= size(x)) -> undef 4399 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4400 return DAG.getUNDEF(VT); 4401 // fold (shl x, 0) -> x 4402 if (N1C && N1C->isNullValue()) 4403 return N0; 4404 // fold (shl undef, x) -> 0 4405 if (N0.isUndef()) 4406 return DAG.getConstant(0, SDLoc(N), VT); 4407 // if (shl x, c) is known to be zero, return 0 4408 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4409 APInt::getAllOnesValue(OpSizeInBits))) 4410 return DAG.getConstant(0, SDLoc(N), VT); 4411 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4412 if (N1.getOpcode() == ISD::TRUNCATE && 4413 N1.getOperand(0).getOpcode() == ISD::AND) { 4414 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4415 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4416 } 4417 4418 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4419 return SDValue(N, 0); 4420 4421 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4422 if (N1C && N0.getOpcode() == ISD::SHL) { 4423 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4424 uint64_t c1 = N0C1->getZExtValue(); 4425 uint64_t c2 = N1C->getZExtValue(); 4426 SDLoc DL(N); 4427 if (c1 + c2 >= OpSizeInBits) 4428 return DAG.getConstant(0, DL, VT); 4429 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4430 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4431 } 4432 } 4433 4434 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4435 // For this to be valid, the second form must not preserve any of the bits 4436 // that are shifted out by the inner shift in the first form. This means 4437 // the outer shift size must be >= the number of bits added by the ext. 4438 // As a corollary, we don't care what kind of ext it is. 4439 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4440 N0.getOpcode() == ISD::ANY_EXTEND || 4441 N0.getOpcode() == ISD::SIGN_EXTEND) && 4442 N0.getOperand(0).getOpcode() == ISD::SHL) { 4443 SDValue N0Op0 = N0.getOperand(0); 4444 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4445 uint64_t c1 = N0Op0C1->getZExtValue(); 4446 uint64_t c2 = N1C->getZExtValue(); 4447 EVT InnerShiftVT = N0Op0.getValueType(); 4448 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4449 if (c2 >= OpSizeInBits - InnerShiftSize) { 4450 SDLoc DL(N0); 4451 if (c1 + c2 >= OpSizeInBits) 4452 return DAG.getConstant(0, DL, VT); 4453 return DAG.getNode(ISD::SHL, DL, VT, 4454 DAG.getNode(N0.getOpcode(), DL, VT, 4455 N0Op0->getOperand(0)), 4456 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4457 } 4458 } 4459 } 4460 4461 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4462 // Only fold this if the inner zext has no other uses to avoid increasing 4463 // the total number of instructions. 4464 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4465 N0.getOperand(0).getOpcode() == ISD::SRL) { 4466 SDValue N0Op0 = N0.getOperand(0); 4467 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4468 uint64_t c1 = N0Op0C1->getZExtValue(); 4469 if (c1 < VT.getScalarSizeInBits()) { 4470 uint64_t c2 = N1C->getZExtValue(); 4471 if (c1 == c2) { 4472 SDValue NewOp0 = N0.getOperand(0); 4473 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4474 SDLoc DL(N); 4475 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4476 NewOp0, 4477 DAG.getConstant(c2, DL, CountVT)); 4478 AddToWorklist(NewSHL.getNode()); 4479 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4480 } 4481 } 4482 } 4483 } 4484 4485 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4486 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4487 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4488 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4489 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4490 uint64_t C1 = N0C1->getZExtValue(); 4491 uint64_t C2 = N1C->getZExtValue(); 4492 SDLoc DL(N); 4493 if (C1 <= C2) 4494 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4495 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4496 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4497 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4498 } 4499 } 4500 4501 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4502 // (and (srl x, (sub c1, c2), MASK) 4503 // Only fold this if the inner shift has no other uses -- if it does, folding 4504 // this will increase the total number of instructions. 4505 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4506 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4507 uint64_t c1 = N0C1->getZExtValue(); 4508 if (c1 < OpSizeInBits) { 4509 uint64_t c2 = N1C->getZExtValue(); 4510 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4511 SDValue Shift; 4512 if (c2 > c1) { 4513 Mask = Mask.shl(c2 - c1); 4514 SDLoc DL(N); 4515 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4516 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4517 } else { 4518 Mask = Mask.lshr(c1 - c2); 4519 SDLoc DL(N); 4520 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4521 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4522 } 4523 SDLoc DL(N0); 4524 return DAG.getNode(ISD::AND, DL, VT, Shift, 4525 DAG.getConstant(Mask, DL, VT)); 4526 } 4527 } 4528 } 4529 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4530 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4531 unsigned BitSize = VT.getScalarSizeInBits(); 4532 SDLoc DL(N); 4533 SDValue HiBitsMask = 4534 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4535 BitSize - N1C->getZExtValue()), 4536 DL, VT); 4537 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4538 HiBitsMask); 4539 } 4540 4541 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4542 // Variant of version done on multiply, except mul by a power of 2 is turned 4543 // into a shift. 4544 APInt Val; 4545 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4546 (isa<ConstantSDNode>(N0.getOperand(1)) || 4547 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4548 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4549 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4550 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4551 } 4552 4553 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4554 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4555 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4556 if (SDValue Folded = 4557 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4558 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4559 } 4560 } 4561 4562 if (N1C && !N1C->isOpaque()) 4563 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4564 return NewSHL; 4565 4566 return SDValue(); 4567 } 4568 4569 SDValue DAGCombiner::visitSRA(SDNode *N) { 4570 SDValue N0 = N->getOperand(0); 4571 SDValue N1 = N->getOperand(1); 4572 EVT VT = N0.getValueType(); 4573 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4574 4575 // fold vector ops 4576 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4577 if (VT.isVector()) { 4578 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4579 return FoldedVOp; 4580 4581 N1C = isConstOrConstSplat(N1); 4582 } 4583 4584 // fold (sra c1, c2) -> (sra c1, c2) 4585 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4586 if (N0C && N1C && !N1C->isOpaque()) 4587 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4588 // fold (sra 0, x) -> 0 4589 if (isNullConstant(N0)) 4590 return N0; 4591 // fold (sra -1, x) -> -1 4592 if (isAllOnesConstant(N0)) 4593 return N0; 4594 // fold (sra x, (setge c, size(x))) -> undef 4595 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4596 return DAG.getUNDEF(VT); 4597 // fold (sra x, 0) -> x 4598 if (N1C && N1C->isNullValue()) 4599 return N0; 4600 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4601 // sext_inreg. 4602 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4603 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4604 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4605 if (VT.isVector()) 4606 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4607 ExtVT, VT.getVectorNumElements()); 4608 if ((!LegalOperations || 4609 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4610 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4611 N0.getOperand(0), DAG.getValueType(ExtVT)); 4612 } 4613 4614 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4615 if (N1C && N0.getOpcode() == ISD::SRA) { 4616 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4617 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4618 if (Sum >= OpSizeInBits) 4619 Sum = OpSizeInBits - 1; 4620 SDLoc DL(N); 4621 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4622 DAG.getConstant(Sum, DL, N1.getValueType())); 4623 } 4624 } 4625 4626 // fold (sra (shl X, m), (sub result_size, n)) 4627 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4628 // result_size - n != m. 4629 // If truncate is free for the target sext(shl) is likely to result in better 4630 // code. 4631 if (N0.getOpcode() == ISD::SHL && N1C) { 4632 // Get the two constanst of the shifts, CN0 = m, CN = n. 4633 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4634 if (N01C) { 4635 LLVMContext &Ctx = *DAG.getContext(); 4636 // Determine what the truncate's result bitsize and type would be. 4637 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4638 4639 if (VT.isVector()) 4640 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4641 4642 // Determine the residual right-shift amount. 4643 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4644 4645 // If the shift is not a no-op (in which case this should be just a sign 4646 // extend already), the truncated to type is legal, sign_extend is legal 4647 // on that type, and the truncate to that type is both legal and free, 4648 // perform the transform. 4649 if ((ShiftAmt > 0) && 4650 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4651 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4652 TLI.isTruncateFree(VT, TruncVT)) { 4653 4654 SDLoc DL(N); 4655 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4656 getShiftAmountTy(N0.getOperand(0).getValueType())); 4657 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4658 N0.getOperand(0), Amt); 4659 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4660 Shift); 4661 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4662 N->getValueType(0), Trunc); 4663 } 4664 } 4665 } 4666 4667 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4668 if (N1.getOpcode() == ISD::TRUNCATE && 4669 N1.getOperand(0).getOpcode() == ISD::AND) { 4670 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4671 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4672 } 4673 4674 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4675 // if c1 is equal to the number of bits the trunc removes 4676 if (N0.getOpcode() == ISD::TRUNCATE && 4677 (N0.getOperand(0).getOpcode() == ISD::SRL || 4678 N0.getOperand(0).getOpcode() == ISD::SRA) && 4679 N0.getOperand(0).hasOneUse() && 4680 N0.getOperand(0).getOperand(1).hasOneUse() && 4681 N1C) { 4682 SDValue N0Op0 = N0.getOperand(0); 4683 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4684 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4685 EVT LargeVT = N0Op0.getValueType(); 4686 4687 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4688 SDLoc DL(N); 4689 SDValue Amt = 4690 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4691 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4692 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4693 N0Op0.getOperand(0), Amt); 4694 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4695 } 4696 } 4697 } 4698 4699 // Simplify, based on bits shifted out of the LHS. 4700 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4701 return SDValue(N, 0); 4702 4703 4704 // If the sign bit is known to be zero, switch this to a SRL. 4705 if (DAG.SignBitIsZero(N0)) 4706 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4707 4708 if (N1C && !N1C->isOpaque()) 4709 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4710 return NewSRA; 4711 4712 return SDValue(); 4713 } 4714 4715 SDValue DAGCombiner::visitSRL(SDNode *N) { 4716 SDValue N0 = N->getOperand(0); 4717 SDValue N1 = N->getOperand(1); 4718 EVT VT = N0.getValueType(); 4719 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4720 4721 // fold vector ops 4722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4723 if (VT.isVector()) { 4724 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4725 return FoldedVOp; 4726 4727 N1C = isConstOrConstSplat(N1); 4728 } 4729 4730 // fold (srl c1, c2) -> c1 >>u c2 4731 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4732 if (N0C && N1C && !N1C->isOpaque()) 4733 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4734 // fold (srl 0, x) -> 0 4735 if (isNullConstant(N0)) 4736 return N0; 4737 // fold (srl x, c >= size(x)) -> undef 4738 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4739 return DAG.getUNDEF(VT); 4740 // fold (srl x, 0) -> x 4741 if (N1C && N1C->isNullValue()) 4742 return N0; 4743 // if (srl x, c) is known to be zero, return 0 4744 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4745 APInt::getAllOnesValue(OpSizeInBits))) 4746 return DAG.getConstant(0, SDLoc(N), VT); 4747 4748 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4749 if (N1C && N0.getOpcode() == ISD::SRL) { 4750 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4751 uint64_t c1 = N01C->getZExtValue(); 4752 uint64_t c2 = N1C->getZExtValue(); 4753 SDLoc DL(N); 4754 if (c1 + c2 >= OpSizeInBits) 4755 return DAG.getConstant(0, DL, VT); 4756 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4757 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4758 } 4759 } 4760 4761 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4762 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4763 N0.getOperand(0).getOpcode() == ISD::SRL && 4764 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4765 uint64_t c1 = 4766 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4767 uint64_t c2 = N1C->getZExtValue(); 4768 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4769 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4770 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4771 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4772 if (c1 + OpSizeInBits == InnerShiftSize) { 4773 SDLoc DL(N0); 4774 if (c1 + c2 >= InnerShiftSize) 4775 return DAG.getConstant(0, DL, VT); 4776 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4777 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4778 N0.getOperand(0)->getOperand(0), 4779 DAG.getConstant(c1 + c2, DL, 4780 ShiftCountVT))); 4781 } 4782 } 4783 4784 // fold (srl (shl x, c), c) -> (and x, cst2) 4785 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4786 unsigned BitSize = N0.getScalarValueSizeInBits(); 4787 if (BitSize <= 64) { 4788 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4789 SDLoc DL(N); 4790 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4791 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4792 } 4793 } 4794 4795 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4796 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4797 // Shifting in all undef bits? 4798 EVT SmallVT = N0.getOperand(0).getValueType(); 4799 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4800 if (N1C->getZExtValue() >= BitSize) 4801 return DAG.getUNDEF(VT); 4802 4803 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4804 uint64_t ShiftAmt = N1C->getZExtValue(); 4805 SDLoc DL0(N0); 4806 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4807 N0.getOperand(0), 4808 DAG.getConstant(ShiftAmt, DL0, 4809 getShiftAmountTy(SmallVT))); 4810 AddToWorklist(SmallShift.getNode()); 4811 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4812 SDLoc DL(N); 4813 return DAG.getNode(ISD::AND, DL, VT, 4814 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4815 DAG.getConstant(Mask, DL, VT)); 4816 } 4817 } 4818 4819 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4820 // bit, which is unmodified by sra. 4821 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4822 if (N0.getOpcode() == ISD::SRA) 4823 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4824 } 4825 4826 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4827 if (N1C && N0.getOpcode() == ISD::CTLZ && 4828 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4829 APInt KnownZero, KnownOne; 4830 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4831 4832 // If any of the input bits are KnownOne, then the input couldn't be all 4833 // zeros, thus the result of the srl will always be zero. 4834 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4835 4836 // If all of the bits input the to ctlz node are known to be zero, then 4837 // the result of the ctlz is "32" and the result of the shift is one. 4838 APInt UnknownBits = ~KnownZero; 4839 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4840 4841 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4842 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4843 // Okay, we know that only that the single bit specified by UnknownBits 4844 // could be set on input to the CTLZ node. If this bit is set, the SRL 4845 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4846 // to an SRL/XOR pair, which is likely to simplify more. 4847 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4848 SDValue Op = N0.getOperand(0); 4849 4850 if (ShAmt) { 4851 SDLoc DL(N0); 4852 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4853 DAG.getConstant(ShAmt, DL, 4854 getShiftAmountTy(Op.getValueType()))); 4855 AddToWorklist(Op.getNode()); 4856 } 4857 4858 SDLoc DL(N); 4859 return DAG.getNode(ISD::XOR, DL, VT, 4860 Op, DAG.getConstant(1, DL, VT)); 4861 } 4862 } 4863 4864 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4865 if (N1.getOpcode() == ISD::TRUNCATE && 4866 N1.getOperand(0).getOpcode() == ISD::AND) { 4867 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4868 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4869 } 4870 4871 // fold operands of srl based on knowledge that the low bits are not 4872 // demanded. 4873 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4874 return SDValue(N, 0); 4875 4876 if (N1C && !N1C->isOpaque()) 4877 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4878 return NewSRL; 4879 4880 // Attempt to convert a srl of a load into a narrower zero-extending load. 4881 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4882 return NarrowLoad; 4883 4884 // Here is a common situation. We want to optimize: 4885 // 4886 // %a = ... 4887 // %b = and i32 %a, 2 4888 // %c = srl i32 %b, 1 4889 // brcond i32 %c ... 4890 // 4891 // into 4892 // 4893 // %a = ... 4894 // %b = and %a, 2 4895 // %c = setcc eq %b, 0 4896 // brcond %c ... 4897 // 4898 // However when after the source operand of SRL is optimized into AND, the SRL 4899 // itself may not be optimized further. Look for it and add the BRCOND into 4900 // the worklist. 4901 if (N->hasOneUse()) { 4902 SDNode *Use = *N->use_begin(); 4903 if (Use->getOpcode() == ISD::BRCOND) 4904 AddToWorklist(Use); 4905 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4906 // Also look pass the truncate. 4907 Use = *Use->use_begin(); 4908 if (Use->getOpcode() == ISD::BRCOND) 4909 AddToWorklist(Use); 4910 } 4911 } 4912 4913 return SDValue(); 4914 } 4915 4916 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4917 SDValue N0 = N->getOperand(0); 4918 EVT VT = N->getValueType(0); 4919 4920 // fold (bswap c1) -> c2 4921 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4922 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4923 // fold (bswap (bswap x)) -> x 4924 if (N0.getOpcode() == ISD::BSWAP) 4925 return N0->getOperand(0); 4926 return SDValue(); 4927 } 4928 4929 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4930 SDValue N0 = N->getOperand(0); 4931 EVT VT = N->getValueType(0); 4932 4933 // fold (ctlz c1) -> c2 4934 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4935 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4936 return SDValue(); 4937 } 4938 4939 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4940 SDValue N0 = N->getOperand(0); 4941 EVT VT = N->getValueType(0); 4942 4943 // fold (ctlz_zero_undef c1) -> c2 4944 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4945 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4946 return SDValue(); 4947 } 4948 4949 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4950 SDValue N0 = N->getOperand(0); 4951 EVT VT = N->getValueType(0); 4952 4953 // fold (cttz c1) -> c2 4954 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4955 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4956 return SDValue(); 4957 } 4958 4959 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4960 SDValue N0 = N->getOperand(0); 4961 EVT VT = N->getValueType(0); 4962 4963 // fold (cttz_zero_undef c1) -> c2 4964 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4965 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4966 return SDValue(); 4967 } 4968 4969 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4970 SDValue N0 = N->getOperand(0); 4971 EVT VT = N->getValueType(0); 4972 4973 // fold (ctpop c1) -> c2 4974 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4975 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4976 return SDValue(); 4977 } 4978 4979 4980 /// \brief Generate Min/Max node 4981 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4982 SDValue True, SDValue False, 4983 ISD::CondCode CC, const TargetLowering &TLI, 4984 SelectionDAG &DAG) { 4985 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4986 return SDValue(); 4987 4988 switch (CC) { 4989 case ISD::SETOLT: 4990 case ISD::SETOLE: 4991 case ISD::SETLT: 4992 case ISD::SETLE: 4993 case ISD::SETULT: 4994 case ISD::SETULE: { 4995 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4996 if (TLI.isOperationLegal(Opcode, VT)) 4997 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4998 return SDValue(); 4999 } 5000 case ISD::SETOGT: 5001 case ISD::SETOGE: 5002 case ISD::SETGT: 5003 case ISD::SETGE: 5004 case ISD::SETUGT: 5005 case ISD::SETUGE: { 5006 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5007 if (TLI.isOperationLegal(Opcode, VT)) 5008 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5009 return SDValue(); 5010 } 5011 default: 5012 return SDValue(); 5013 } 5014 } 5015 5016 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5017 SDValue N0 = N->getOperand(0); 5018 SDValue N1 = N->getOperand(1); 5019 SDValue N2 = N->getOperand(2); 5020 EVT VT = N->getValueType(0); 5021 EVT VT0 = N0.getValueType(); 5022 5023 // fold (select C, X, X) -> X 5024 if (N1 == N2) 5025 return N1; 5026 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5027 // fold (select true, X, Y) -> X 5028 // fold (select false, X, Y) -> Y 5029 return !N0C->isNullValue() ? N1 : N2; 5030 } 5031 // fold (select C, 1, X) -> (or C, X) 5032 if (VT == MVT::i1 && isOneConstant(N1)) 5033 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5034 // fold (select C, 0, 1) -> (xor C, 1) 5035 // We can't do this reliably if integer based booleans have different contents 5036 // to floating point based booleans. This is because we can't tell whether we 5037 // have an integer-based boolean or a floating-point-based boolean unless we 5038 // can find the SETCC that produced it and inspect its operands. This is 5039 // fairly easy if C is the SETCC node, but it can potentially be 5040 // undiscoverable (or not reasonably discoverable). For example, it could be 5041 // in another basic block or it could require searching a complicated 5042 // expression. 5043 if (VT.isInteger() && 5044 (VT0 == MVT::i1 || (VT0.isInteger() && 5045 TLI.getBooleanContents(false, false) == 5046 TLI.getBooleanContents(false, true) && 5047 TLI.getBooleanContents(false, false) == 5048 TargetLowering::ZeroOrOneBooleanContent)) && 5049 isNullConstant(N1) && isOneConstant(N2)) { 5050 SDValue XORNode; 5051 if (VT == VT0) { 5052 SDLoc DL(N); 5053 return DAG.getNode(ISD::XOR, DL, VT0, 5054 N0, DAG.getConstant(1, DL, VT0)); 5055 } 5056 SDLoc DL0(N0); 5057 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5058 N0, DAG.getConstant(1, DL0, VT0)); 5059 AddToWorklist(XORNode.getNode()); 5060 if (VT.bitsGT(VT0)) 5061 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5062 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5063 } 5064 // fold (select C, 0, X) -> (and (not C), X) 5065 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5066 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5067 AddToWorklist(NOTNode.getNode()); 5068 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5069 } 5070 // fold (select C, X, 1) -> (or (not C), X) 5071 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5072 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5073 AddToWorklist(NOTNode.getNode()); 5074 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5075 } 5076 // fold (select C, X, 0) -> (and C, X) 5077 if (VT == MVT::i1 && isNullConstant(N2)) 5078 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5079 // fold (select X, X, Y) -> (or X, Y) 5080 // fold (select X, 1, Y) -> (or X, Y) 5081 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5082 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5083 // fold (select X, Y, X) -> (and X, Y) 5084 // fold (select X, Y, 0) -> (and X, Y) 5085 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5086 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5087 5088 // If we can fold this based on the true/false value, do so. 5089 if (SimplifySelectOps(N, N1, N2)) 5090 return SDValue(N, 0); // Don't revisit N. 5091 5092 if (VT0 == MVT::i1) { 5093 // The code in this block deals with the following 2 equivalences: 5094 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5095 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5096 // The target can specify its prefered form with the 5097 // shouldNormalizeToSelectSequence() callback. However we always transform 5098 // to the right anyway if we find the inner select exists in the DAG anyway 5099 // and we always transform to the left side if we know that we can further 5100 // optimize the combination of the conditions. 5101 bool normalizeToSequence 5102 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5103 // select (and Cond0, Cond1), X, Y 5104 // -> select Cond0, (select Cond1, X, Y), Y 5105 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5106 SDValue Cond0 = N0->getOperand(0); 5107 SDValue Cond1 = N0->getOperand(1); 5108 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5109 N1.getValueType(), Cond1, N1, N2); 5110 if (normalizeToSequence || !InnerSelect.use_empty()) 5111 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5112 InnerSelect, N2); 5113 } 5114 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5115 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5116 SDValue Cond0 = N0->getOperand(0); 5117 SDValue Cond1 = N0->getOperand(1); 5118 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5119 N1.getValueType(), Cond1, N1, N2); 5120 if (normalizeToSequence || !InnerSelect.use_empty()) 5121 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5122 InnerSelect); 5123 } 5124 5125 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5126 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5127 SDValue N1_0 = N1->getOperand(0); 5128 SDValue N1_1 = N1->getOperand(1); 5129 SDValue N1_2 = N1->getOperand(2); 5130 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5131 // Create the actual and node if we can generate good code for it. 5132 if (!normalizeToSequence) { 5133 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5134 N0, N1_0); 5135 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5136 N1_1, N2); 5137 } 5138 // Otherwise see if we can optimize the "and" to a better pattern. 5139 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5140 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5141 N1_1, N2); 5142 } 5143 } 5144 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5145 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5146 SDValue N2_0 = N2->getOperand(0); 5147 SDValue N2_1 = N2->getOperand(1); 5148 SDValue N2_2 = N2->getOperand(2); 5149 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5150 // Create the actual or node if we can generate good code for it. 5151 if (!normalizeToSequence) { 5152 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5153 N0, N2_0); 5154 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5155 N1, N2_2); 5156 } 5157 // Otherwise see if we can optimize to a better pattern. 5158 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5159 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5160 N1, N2_2); 5161 } 5162 } 5163 } 5164 5165 // fold selects based on a setcc into other things, such as min/max/abs 5166 if (N0.getOpcode() == ISD::SETCC) { 5167 // select x, y (fcmp lt x, y) -> fminnum x, y 5168 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5169 // 5170 // This is OK if we don't care about what happens if either operand is a 5171 // NaN. 5172 // 5173 5174 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5175 // no signed zeros as well as no nans. 5176 const TargetOptions &Options = DAG.getTarget().Options; 5177 if (Options.UnsafeFPMath && 5178 VT.isFloatingPoint() && N0.hasOneUse() && 5179 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5180 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5181 5182 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5183 N0.getOperand(1), N1, N2, CC, 5184 TLI, DAG)) 5185 return FMinMax; 5186 } 5187 5188 if ((!LegalOperations && 5189 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5190 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5191 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5192 N0.getOperand(0), N0.getOperand(1), 5193 N1, N2, N0.getOperand(2)); 5194 return SimplifySelect(SDLoc(N), N0, N1, N2); 5195 } 5196 5197 return SDValue(); 5198 } 5199 5200 static 5201 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5202 SDLoc DL(N); 5203 EVT LoVT, HiVT; 5204 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5205 5206 // Split the inputs. 5207 SDValue Lo, Hi, LL, LH, RL, RH; 5208 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5209 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5210 5211 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5212 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5213 5214 return std::make_pair(Lo, Hi); 5215 } 5216 5217 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5218 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5219 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5220 SDLoc dl(N); 5221 SDValue Cond = N->getOperand(0); 5222 SDValue LHS = N->getOperand(1); 5223 SDValue RHS = N->getOperand(2); 5224 EVT VT = N->getValueType(0); 5225 int NumElems = VT.getVectorNumElements(); 5226 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5227 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5228 Cond.getOpcode() == ISD::BUILD_VECTOR); 5229 5230 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5231 // binary ones here. 5232 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5233 return SDValue(); 5234 5235 // We're sure we have an even number of elements due to the 5236 // concat_vectors we have as arguments to vselect. 5237 // Skip BV elements until we find one that's not an UNDEF 5238 // After we find an UNDEF element, keep looping until we get to half the 5239 // length of the BV and see if all the non-undef nodes are the same. 5240 ConstantSDNode *BottomHalf = nullptr; 5241 for (int i = 0; i < NumElems / 2; ++i) { 5242 if (Cond->getOperand(i)->isUndef()) 5243 continue; 5244 5245 if (BottomHalf == nullptr) 5246 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5247 else if (Cond->getOperand(i).getNode() != BottomHalf) 5248 return SDValue(); 5249 } 5250 5251 // Do the same for the second half of the BuildVector 5252 ConstantSDNode *TopHalf = nullptr; 5253 for (int i = NumElems / 2; i < NumElems; ++i) { 5254 if (Cond->getOperand(i)->isUndef()) 5255 continue; 5256 5257 if (TopHalf == nullptr) 5258 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5259 else if (Cond->getOperand(i).getNode() != TopHalf) 5260 return SDValue(); 5261 } 5262 5263 assert(TopHalf && BottomHalf && 5264 "One half of the selector was all UNDEFs and the other was all the " 5265 "same value. This should have been addressed before this function."); 5266 return DAG.getNode( 5267 ISD::CONCAT_VECTORS, dl, VT, 5268 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5269 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5270 } 5271 5272 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5273 5274 if (Level >= AfterLegalizeTypes) 5275 return SDValue(); 5276 5277 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5278 SDValue Mask = MSC->getMask(); 5279 SDValue Data = MSC->getValue(); 5280 SDLoc DL(N); 5281 5282 // If the MSCATTER data type requires splitting and the mask is provided by a 5283 // SETCC, then split both nodes and its operands before legalization. This 5284 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5285 // and enables future optimizations (e.g. min/max pattern matching on X86). 5286 if (Mask.getOpcode() != ISD::SETCC) 5287 return SDValue(); 5288 5289 // Check if any splitting is required. 5290 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5291 TargetLowering::TypeSplitVector) 5292 return SDValue(); 5293 SDValue MaskLo, MaskHi, Lo, Hi; 5294 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5295 5296 EVT LoVT, HiVT; 5297 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5298 5299 SDValue Chain = MSC->getChain(); 5300 5301 EVT MemoryVT = MSC->getMemoryVT(); 5302 unsigned Alignment = MSC->getOriginalAlignment(); 5303 5304 EVT LoMemVT, HiMemVT; 5305 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5306 5307 SDValue DataLo, DataHi; 5308 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5309 5310 SDValue BasePtr = MSC->getBasePtr(); 5311 SDValue IndexLo, IndexHi; 5312 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5313 5314 MachineMemOperand *MMO = DAG.getMachineFunction(). 5315 getMachineMemOperand(MSC->getPointerInfo(), 5316 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5317 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5318 5319 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5320 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5321 DL, OpsLo, MMO); 5322 5323 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5324 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5325 DL, OpsHi, MMO); 5326 5327 AddToWorklist(Lo.getNode()); 5328 AddToWorklist(Hi.getNode()); 5329 5330 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5331 } 5332 5333 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5334 5335 if (Level >= AfterLegalizeTypes) 5336 return SDValue(); 5337 5338 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5339 SDValue Mask = MST->getMask(); 5340 SDValue Data = MST->getValue(); 5341 SDLoc DL(N); 5342 5343 // If the MSTORE data type requires splitting and the mask is provided by a 5344 // SETCC, then split both nodes and its operands before legalization. This 5345 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5346 // and enables future optimizations (e.g. min/max pattern matching on X86). 5347 if (Mask.getOpcode() == ISD::SETCC) { 5348 5349 // Check if any splitting is required. 5350 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5351 TargetLowering::TypeSplitVector) 5352 return SDValue(); 5353 5354 SDValue MaskLo, MaskHi, Lo, Hi; 5355 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5356 5357 EVT LoVT, HiVT; 5358 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5359 5360 SDValue Chain = MST->getChain(); 5361 SDValue Ptr = MST->getBasePtr(); 5362 5363 EVT MemoryVT = MST->getMemoryVT(); 5364 unsigned Alignment = MST->getOriginalAlignment(); 5365 5366 // if Alignment is equal to the vector size, 5367 // take the half of it for the second part 5368 unsigned SecondHalfAlignment = 5369 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5370 Alignment/2 : Alignment; 5371 5372 EVT LoMemVT, HiMemVT; 5373 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5374 5375 SDValue DataLo, DataHi; 5376 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5377 5378 MachineMemOperand *MMO = DAG.getMachineFunction(). 5379 getMachineMemOperand(MST->getPointerInfo(), 5380 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5381 Alignment, MST->getAAInfo(), MST->getRanges()); 5382 5383 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5384 MST->isTruncatingStore()); 5385 5386 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5387 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5388 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5389 5390 MMO = DAG.getMachineFunction(). 5391 getMachineMemOperand(MST->getPointerInfo(), 5392 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5393 SecondHalfAlignment, MST->getAAInfo(), 5394 MST->getRanges()); 5395 5396 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5397 MST->isTruncatingStore()); 5398 5399 AddToWorklist(Lo.getNode()); 5400 AddToWorklist(Hi.getNode()); 5401 5402 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5403 } 5404 return SDValue(); 5405 } 5406 5407 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5408 5409 if (Level >= AfterLegalizeTypes) 5410 return SDValue(); 5411 5412 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5413 SDValue Mask = MGT->getMask(); 5414 SDLoc DL(N); 5415 5416 // If the MGATHER result requires splitting and the mask is provided by a 5417 // SETCC, then split both nodes and its operands before legalization. This 5418 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5419 // and enables future optimizations (e.g. min/max pattern matching on X86). 5420 5421 if (Mask.getOpcode() != ISD::SETCC) 5422 return SDValue(); 5423 5424 EVT VT = N->getValueType(0); 5425 5426 // Check if any splitting is required. 5427 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5428 TargetLowering::TypeSplitVector) 5429 return SDValue(); 5430 5431 SDValue MaskLo, MaskHi, Lo, Hi; 5432 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5433 5434 SDValue Src0 = MGT->getValue(); 5435 SDValue Src0Lo, Src0Hi; 5436 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5437 5438 EVT LoVT, HiVT; 5439 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5440 5441 SDValue Chain = MGT->getChain(); 5442 EVT MemoryVT = MGT->getMemoryVT(); 5443 unsigned Alignment = MGT->getOriginalAlignment(); 5444 5445 EVT LoMemVT, HiMemVT; 5446 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5447 5448 SDValue BasePtr = MGT->getBasePtr(); 5449 SDValue Index = MGT->getIndex(); 5450 SDValue IndexLo, IndexHi; 5451 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5452 5453 MachineMemOperand *MMO = DAG.getMachineFunction(). 5454 getMachineMemOperand(MGT->getPointerInfo(), 5455 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5456 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5457 5458 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5459 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5460 MMO); 5461 5462 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5463 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5464 MMO); 5465 5466 AddToWorklist(Lo.getNode()); 5467 AddToWorklist(Hi.getNode()); 5468 5469 // Build a factor node to remember that this load is independent of the 5470 // other one. 5471 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5472 Hi.getValue(1)); 5473 5474 // Legalized the chain result - switch anything that used the old chain to 5475 // use the new one. 5476 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5477 5478 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5479 5480 SDValue RetOps[] = { GatherRes, Chain }; 5481 return DAG.getMergeValues(RetOps, DL); 5482 } 5483 5484 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5485 5486 if (Level >= AfterLegalizeTypes) 5487 return SDValue(); 5488 5489 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5490 SDValue Mask = MLD->getMask(); 5491 SDLoc DL(N); 5492 5493 // If the MLOAD result requires splitting and the mask is provided by a 5494 // SETCC, then split both nodes and its operands before legalization. This 5495 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5496 // and enables future optimizations (e.g. min/max pattern matching on X86). 5497 5498 if (Mask.getOpcode() == ISD::SETCC) { 5499 EVT VT = N->getValueType(0); 5500 5501 // Check if any splitting is required. 5502 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5503 TargetLowering::TypeSplitVector) 5504 return SDValue(); 5505 5506 SDValue MaskLo, MaskHi, Lo, Hi; 5507 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5508 5509 SDValue Src0 = MLD->getSrc0(); 5510 SDValue Src0Lo, Src0Hi; 5511 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5512 5513 EVT LoVT, HiVT; 5514 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5515 5516 SDValue Chain = MLD->getChain(); 5517 SDValue Ptr = MLD->getBasePtr(); 5518 EVT MemoryVT = MLD->getMemoryVT(); 5519 unsigned Alignment = MLD->getOriginalAlignment(); 5520 5521 // if Alignment is equal to the vector size, 5522 // take the half of it for the second part 5523 unsigned SecondHalfAlignment = 5524 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5525 Alignment/2 : Alignment; 5526 5527 EVT LoMemVT, HiMemVT; 5528 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5529 5530 MachineMemOperand *MMO = DAG.getMachineFunction(). 5531 getMachineMemOperand(MLD->getPointerInfo(), 5532 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5533 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5534 5535 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5536 ISD::NON_EXTLOAD); 5537 5538 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5539 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5540 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5541 5542 MMO = DAG.getMachineFunction(). 5543 getMachineMemOperand(MLD->getPointerInfo(), 5544 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5545 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5546 5547 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5548 ISD::NON_EXTLOAD); 5549 5550 AddToWorklist(Lo.getNode()); 5551 AddToWorklist(Hi.getNode()); 5552 5553 // Build a factor node to remember that this load is independent of the 5554 // other one. 5555 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5556 Hi.getValue(1)); 5557 5558 // Legalized the chain result - switch anything that used the old chain to 5559 // use the new one. 5560 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5561 5562 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5563 5564 SDValue RetOps[] = { LoadRes, Chain }; 5565 return DAG.getMergeValues(RetOps, DL); 5566 } 5567 return SDValue(); 5568 } 5569 5570 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5571 SDValue N0 = N->getOperand(0); 5572 SDValue N1 = N->getOperand(1); 5573 SDValue N2 = N->getOperand(2); 5574 SDLoc DL(N); 5575 5576 // Canonicalize integer abs. 5577 // vselect (setg[te] X, 0), X, -X -> 5578 // vselect (setgt X, -1), X, -X -> 5579 // vselect (setl[te] X, 0), -X, X -> 5580 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5581 if (N0.getOpcode() == ISD::SETCC) { 5582 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5583 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5584 bool isAbs = false; 5585 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5586 5587 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5588 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5589 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5590 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5591 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5592 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5593 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5594 5595 if (isAbs) { 5596 EVT VT = LHS.getValueType(); 5597 SDValue Shift = DAG.getNode( 5598 ISD::SRA, DL, VT, LHS, 5599 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5600 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5601 AddToWorklist(Shift.getNode()); 5602 AddToWorklist(Add.getNode()); 5603 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5604 } 5605 } 5606 5607 if (SimplifySelectOps(N, N1, N2)) 5608 return SDValue(N, 0); // Don't revisit N. 5609 5610 // If the VSELECT result requires splitting and the mask is provided by a 5611 // SETCC, then split both nodes and its operands before legalization. This 5612 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5613 // and enables future optimizations (e.g. min/max pattern matching on X86). 5614 if (N0.getOpcode() == ISD::SETCC) { 5615 EVT VT = N->getValueType(0); 5616 5617 // Check if any splitting is required. 5618 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5619 TargetLowering::TypeSplitVector) 5620 return SDValue(); 5621 5622 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5623 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5624 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5625 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5626 5627 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5628 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5629 5630 // Add the new VSELECT nodes to the work list in case they need to be split 5631 // again. 5632 AddToWorklist(Lo.getNode()); 5633 AddToWorklist(Hi.getNode()); 5634 5635 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5636 } 5637 5638 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5639 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5640 return N1; 5641 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5642 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5643 return N2; 5644 5645 // The ConvertSelectToConcatVector function is assuming both the above 5646 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5647 // and addressed. 5648 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5649 N2.getOpcode() == ISD::CONCAT_VECTORS && 5650 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5651 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5652 return CV; 5653 } 5654 5655 return SDValue(); 5656 } 5657 5658 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5659 SDValue N0 = N->getOperand(0); 5660 SDValue N1 = N->getOperand(1); 5661 SDValue N2 = N->getOperand(2); 5662 SDValue N3 = N->getOperand(3); 5663 SDValue N4 = N->getOperand(4); 5664 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5665 5666 // fold select_cc lhs, rhs, x, x, cc -> x 5667 if (N2 == N3) 5668 return N2; 5669 5670 // Determine if the condition we're dealing with is constant 5671 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5672 CC, SDLoc(N), false)) { 5673 AddToWorklist(SCC.getNode()); 5674 5675 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5676 if (!SCCC->isNullValue()) 5677 return N2; // cond always true -> true val 5678 else 5679 return N3; // cond always false -> false val 5680 } else if (SCC->isUndef()) { 5681 // When the condition is UNDEF, just return the first operand. This is 5682 // coherent the DAG creation, no setcc node is created in this case 5683 return N2; 5684 } else if (SCC.getOpcode() == ISD::SETCC) { 5685 // Fold to a simpler select_cc 5686 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5687 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5688 SCC.getOperand(2)); 5689 } 5690 } 5691 5692 // If we can fold this based on the true/false value, do so. 5693 if (SimplifySelectOps(N, N2, N3)) 5694 return SDValue(N, 0); // Don't revisit N. 5695 5696 // fold select_cc into other things, such as min/max/abs 5697 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5698 } 5699 5700 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5701 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5702 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5703 SDLoc(N)); 5704 } 5705 5706 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5707 SDValue LHS = N->getOperand(0); 5708 SDValue RHS = N->getOperand(1); 5709 SDValue Carry = N->getOperand(2); 5710 SDValue Cond = N->getOperand(3); 5711 5712 // If Carry is false, fold to a regular SETCC. 5713 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5714 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5715 5716 return SDValue(); 5717 } 5718 5719 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5720 /// a build_vector of constants. 5721 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5722 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5723 /// Vector extends are not folded if operations are legal; this is to 5724 /// avoid introducing illegal build_vector dag nodes. 5725 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5726 SelectionDAG &DAG, bool LegalTypes, 5727 bool LegalOperations) { 5728 unsigned Opcode = N->getOpcode(); 5729 SDValue N0 = N->getOperand(0); 5730 EVT VT = N->getValueType(0); 5731 5732 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5733 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5734 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5735 && "Expected EXTEND dag node in input!"); 5736 5737 // fold (sext c1) -> c1 5738 // fold (zext c1) -> c1 5739 // fold (aext c1) -> c1 5740 if (isa<ConstantSDNode>(N0)) 5741 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5742 5743 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5744 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5745 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5746 EVT SVT = VT.getScalarType(); 5747 if (!(VT.isVector() && 5748 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5749 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5750 return nullptr; 5751 5752 // We can fold this node into a build_vector. 5753 unsigned VTBits = SVT.getSizeInBits(); 5754 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5755 SmallVector<SDValue, 8> Elts; 5756 unsigned NumElts = VT.getVectorNumElements(); 5757 SDLoc DL(N); 5758 5759 for (unsigned i=0; i != NumElts; ++i) { 5760 SDValue Op = N0->getOperand(i); 5761 if (Op->isUndef()) { 5762 Elts.push_back(DAG.getUNDEF(SVT)); 5763 continue; 5764 } 5765 5766 SDLoc DL(Op); 5767 // Get the constant value and if needed trunc it to the size of the type. 5768 // Nodes like build_vector might have constants wider than the scalar type. 5769 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5770 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5771 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5772 else 5773 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5774 } 5775 5776 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5777 } 5778 5779 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5780 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5781 // transformation. Returns true if extension are possible and the above 5782 // mentioned transformation is profitable. 5783 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5784 unsigned ExtOpc, 5785 SmallVectorImpl<SDNode *> &ExtendNodes, 5786 const TargetLowering &TLI) { 5787 bool HasCopyToRegUses = false; 5788 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5789 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5790 UE = N0.getNode()->use_end(); 5791 UI != UE; ++UI) { 5792 SDNode *User = *UI; 5793 if (User == N) 5794 continue; 5795 if (UI.getUse().getResNo() != N0.getResNo()) 5796 continue; 5797 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5798 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5799 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5800 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5801 // Sign bits will be lost after a zext. 5802 return false; 5803 bool Add = false; 5804 for (unsigned i = 0; i != 2; ++i) { 5805 SDValue UseOp = User->getOperand(i); 5806 if (UseOp == N0) 5807 continue; 5808 if (!isa<ConstantSDNode>(UseOp)) 5809 return false; 5810 Add = true; 5811 } 5812 if (Add) 5813 ExtendNodes.push_back(User); 5814 continue; 5815 } 5816 // If truncates aren't free and there are users we can't 5817 // extend, it isn't worthwhile. 5818 if (!isTruncFree) 5819 return false; 5820 // Remember if this value is live-out. 5821 if (User->getOpcode() == ISD::CopyToReg) 5822 HasCopyToRegUses = true; 5823 } 5824 5825 if (HasCopyToRegUses) { 5826 bool BothLiveOut = false; 5827 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5828 UI != UE; ++UI) { 5829 SDUse &Use = UI.getUse(); 5830 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5831 BothLiveOut = true; 5832 break; 5833 } 5834 } 5835 if (BothLiveOut) 5836 // Both unextended and extended values are live out. There had better be 5837 // a good reason for the transformation. 5838 return ExtendNodes.size(); 5839 } 5840 return true; 5841 } 5842 5843 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5844 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5845 ISD::NodeType ExtType) { 5846 // Extend SetCC uses if necessary. 5847 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5848 SDNode *SetCC = SetCCs[i]; 5849 SmallVector<SDValue, 4> Ops; 5850 5851 for (unsigned j = 0; j != 2; ++j) { 5852 SDValue SOp = SetCC->getOperand(j); 5853 if (SOp == Trunc) 5854 Ops.push_back(ExtLoad); 5855 else 5856 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5857 } 5858 5859 Ops.push_back(SetCC->getOperand(2)); 5860 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5861 } 5862 } 5863 5864 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5865 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5866 SDValue N0 = N->getOperand(0); 5867 EVT DstVT = N->getValueType(0); 5868 EVT SrcVT = N0.getValueType(); 5869 5870 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5871 N->getOpcode() == ISD::ZERO_EXTEND) && 5872 "Unexpected node type (not an extend)!"); 5873 5874 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5875 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5876 // (v8i32 (sext (v8i16 (load x)))) 5877 // into: 5878 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5879 // (v4i32 (sextload (x + 16))))) 5880 // Where uses of the original load, i.e.: 5881 // (v8i16 (load x)) 5882 // are replaced with: 5883 // (v8i16 (truncate 5884 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5885 // (v4i32 (sextload (x + 16))))))) 5886 // 5887 // This combine is only applicable to illegal, but splittable, vectors. 5888 // All legal types, and illegal non-vector types, are handled elsewhere. 5889 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5890 // 5891 if (N0->getOpcode() != ISD::LOAD) 5892 return SDValue(); 5893 5894 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5895 5896 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5897 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5898 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5899 return SDValue(); 5900 5901 SmallVector<SDNode *, 4> SetCCs; 5902 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5903 return SDValue(); 5904 5905 ISD::LoadExtType ExtType = 5906 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5907 5908 // Try to split the vector types to get down to legal types. 5909 EVT SplitSrcVT = SrcVT; 5910 EVT SplitDstVT = DstVT; 5911 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5912 SplitSrcVT.getVectorNumElements() > 1) { 5913 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5914 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5915 } 5916 5917 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5918 return SDValue(); 5919 5920 SDLoc DL(N); 5921 const unsigned NumSplits = 5922 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5923 const unsigned Stride = SplitSrcVT.getStoreSize(); 5924 SmallVector<SDValue, 4> Loads; 5925 SmallVector<SDValue, 4> Chains; 5926 5927 SDValue BasePtr = LN0->getBasePtr(); 5928 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5929 const unsigned Offset = Idx * Stride; 5930 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5931 5932 SDValue SplitLoad = DAG.getExtLoad( 5933 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5934 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5935 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5936 Align, LN0->getAAInfo()); 5937 5938 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5939 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5940 5941 Loads.push_back(SplitLoad.getValue(0)); 5942 Chains.push_back(SplitLoad.getValue(1)); 5943 } 5944 5945 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5946 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5947 5948 CombineTo(N, NewValue); 5949 5950 // Replace uses of the original load (before extension) 5951 // with a truncate of the concatenated sextloaded vectors. 5952 SDValue Trunc = 5953 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5954 CombineTo(N0.getNode(), Trunc, NewChain); 5955 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5956 (ISD::NodeType)N->getOpcode()); 5957 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5958 } 5959 5960 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5961 SDValue N0 = N->getOperand(0); 5962 EVT VT = N->getValueType(0); 5963 5964 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5965 LegalOperations)) 5966 return SDValue(Res, 0); 5967 5968 // fold (sext (sext x)) -> (sext x) 5969 // fold (sext (aext x)) -> (sext x) 5970 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5971 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5972 N0.getOperand(0)); 5973 5974 if (N0.getOpcode() == ISD::TRUNCATE) { 5975 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5976 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5977 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5978 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5979 if (NarrowLoad.getNode() != N0.getNode()) { 5980 CombineTo(N0.getNode(), NarrowLoad); 5981 // CombineTo deleted the truncate, if needed, but not what's under it. 5982 AddToWorklist(oye); 5983 } 5984 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5985 } 5986 5987 // See if the value being truncated is already sign extended. If so, just 5988 // eliminate the trunc/sext pair. 5989 SDValue Op = N0.getOperand(0); 5990 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5991 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5992 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5993 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5994 5995 if (OpBits == DestBits) { 5996 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5997 // bits, it is already ready. 5998 if (NumSignBits > DestBits-MidBits) 5999 return Op; 6000 } else if (OpBits < DestBits) { 6001 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6002 // bits, just sext from i32. 6003 if (NumSignBits > OpBits-MidBits) 6004 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6005 } else { 6006 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6007 // bits, just truncate to i32. 6008 if (NumSignBits > OpBits-MidBits) 6009 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6010 } 6011 6012 // fold (sext (truncate x)) -> (sextinreg x). 6013 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6014 N0.getValueType())) { 6015 if (OpBits < DestBits) 6016 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6017 else if (OpBits > DestBits) 6018 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6019 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6020 DAG.getValueType(N0.getValueType())); 6021 } 6022 } 6023 6024 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6025 // Only generate vector extloads when 1) they're legal, and 2) they are 6026 // deemed desirable by the target. 6027 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6028 ((!LegalOperations && !VT.isVector() && 6029 !cast<LoadSDNode>(N0)->isVolatile()) || 6030 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6031 bool DoXform = true; 6032 SmallVector<SDNode*, 4> SetCCs; 6033 if (!N0.hasOneUse()) 6034 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6035 if (VT.isVector()) 6036 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6037 if (DoXform) { 6038 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6039 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6040 LN0->getChain(), 6041 LN0->getBasePtr(), N0.getValueType(), 6042 LN0->getMemOperand()); 6043 CombineTo(N, ExtLoad); 6044 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6045 N0.getValueType(), ExtLoad); 6046 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6047 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6048 ISD::SIGN_EXTEND); 6049 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6050 } 6051 } 6052 6053 // fold (sext (load x)) to multiple smaller sextloads. 6054 // Only on illegal but splittable vectors. 6055 if (SDValue ExtLoad = CombineExtLoad(N)) 6056 return ExtLoad; 6057 6058 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6059 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6060 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6061 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6062 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6063 EVT MemVT = LN0->getMemoryVT(); 6064 if ((!LegalOperations && !LN0->isVolatile()) || 6065 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6066 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6067 LN0->getChain(), 6068 LN0->getBasePtr(), MemVT, 6069 LN0->getMemOperand()); 6070 CombineTo(N, ExtLoad); 6071 CombineTo(N0.getNode(), 6072 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6073 N0.getValueType(), ExtLoad), 6074 ExtLoad.getValue(1)); 6075 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6076 } 6077 } 6078 6079 // fold (sext (and/or/xor (load x), cst)) -> 6080 // (and/or/xor (sextload x), (sext cst)) 6081 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6082 N0.getOpcode() == ISD::XOR) && 6083 isa<LoadSDNode>(N0.getOperand(0)) && 6084 N0.getOperand(1).getOpcode() == ISD::Constant && 6085 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6086 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6087 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6088 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6089 bool DoXform = true; 6090 SmallVector<SDNode*, 4> SetCCs; 6091 if (!N0.hasOneUse()) 6092 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6093 SetCCs, TLI); 6094 if (DoXform) { 6095 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6096 LN0->getChain(), LN0->getBasePtr(), 6097 LN0->getMemoryVT(), 6098 LN0->getMemOperand()); 6099 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6100 Mask = Mask.sext(VT.getSizeInBits()); 6101 SDLoc DL(N); 6102 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6103 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6104 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6105 SDLoc(N0.getOperand(0)), 6106 N0.getOperand(0).getValueType(), ExtLoad); 6107 CombineTo(N, And); 6108 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6109 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6110 ISD::SIGN_EXTEND); 6111 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6112 } 6113 } 6114 } 6115 6116 if (N0.getOpcode() == ISD::SETCC) { 6117 EVT N0VT = N0.getOperand(0).getValueType(); 6118 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6119 // Only do this before legalize for now. 6120 if (VT.isVector() && !LegalOperations && 6121 TLI.getBooleanContents(N0VT) == 6122 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6123 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6124 // of the same size as the compared operands. Only optimize sext(setcc()) 6125 // if this is the case. 6126 EVT SVT = getSetCCResultType(N0VT); 6127 6128 // We know that the # elements of the results is the same as the 6129 // # elements of the compare (and the # elements of the compare result 6130 // for that matter). Check to see that they are the same size. If so, 6131 // we know that the element size of the sext'd result matches the 6132 // element size of the compare operands. 6133 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6134 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6135 N0.getOperand(1), 6136 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6137 6138 // If the desired elements are smaller or larger than the source 6139 // elements we can use a matching integer vector type and then 6140 // truncate/sign extend 6141 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6142 if (SVT == MatchingVectorType) { 6143 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6144 N0.getOperand(0), N0.getOperand(1), 6145 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6146 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6147 } 6148 } 6149 6150 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6151 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6152 SDLoc DL(N); 6153 SDValue NegOne = 6154 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6155 if (SDValue SCC = SimplifySelectCC( 6156 DL, N0.getOperand(0), N0.getOperand(1), NegOne, 6157 DAG.getConstant(0, DL, VT), 6158 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6159 return SCC; 6160 6161 if (!VT.isVector()) { 6162 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6163 if (!LegalOperations || 6164 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6165 SDLoc DL(N); 6166 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6167 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6168 N0.getOperand(0), N0.getOperand(1), CC); 6169 return DAG.getSelect(DL, VT, SetCC, 6170 NegOne, DAG.getConstant(0, DL, VT)); 6171 } 6172 } 6173 } 6174 6175 // fold (sext x) -> (zext x) if the sign bit is known zero. 6176 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6177 DAG.SignBitIsZero(N0)) 6178 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6179 6180 return SDValue(); 6181 } 6182 6183 // isTruncateOf - If N is a truncate of some other value, return true, record 6184 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6185 // This function computes KnownZero to avoid a duplicated call to 6186 // computeKnownBits in the caller. 6187 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6188 APInt &KnownZero) { 6189 APInt KnownOne; 6190 if (N->getOpcode() == ISD::TRUNCATE) { 6191 Op = N->getOperand(0); 6192 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6193 return true; 6194 } 6195 6196 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6197 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6198 return false; 6199 6200 SDValue Op0 = N->getOperand(0); 6201 SDValue Op1 = N->getOperand(1); 6202 assert(Op0.getValueType() == Op1.getValueType()); 6203 6204 if (isNullConstant(Op0)) 6205 Op = Op1; 6206 else if (isNullConstant(Op1)) 6207 Op = Op0; 6208 else 6209 return false; 6210 6211 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6212 6213 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6214 return false; 6215 6216 return true; 6217 } 6218 6219 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6220 SDValue N0 = N->getOperand(0); 6221 EVT VT = N->getValueType(0); 6222 6223 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6224 LegalOperations)) 6225 return SDValue(Res, 0); 6226 6227 // fold (zext (zext x)) -> (zext x) 6228 // fold (zext (aext x)) -> (zext x) 6229 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6230 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6231 N0.getOperand(0)); 6232 6233 // fold (zext (truncate x)) -> (zext x) or 6234 // (zext (truncate x)) -> (truncate x) 6235 // This is valid when the truncated bits of x are already zero. 6236 // FIXME: We should extend this to work for vectors too. 6237 SDValue Op; 6238 APInt KnownZero; 6239 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6240 APInt TruncatedBits = 6241 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6242 APInt(Op.getValueSizeInBits(), 0) : 6243 APInt::getBitsSet(Op.getValueSizeInBits(), 6244 N0.getValueSizeInBits(), 6245 std::min(Op.getValueSizeInBits(), 6246 VT.getSizeInBits())); 6247 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6248 if (VT.bitsGT(Op.getValueType())) 6249 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6250 if (VT.bitsLT(Op.getValueType())) 6251 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6252 6253 return Op; 6254 } 6255 } 6256 6257 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6258 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6259 if (N0.getOpcode() == ISD::TRUNCATE) { 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 6271 // fold (zext (truncate x)) -> (and x, mask) 6272 if (N0.getOpcode() == ISD::TRUNCATE) { 6273 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6274 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6275 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6276 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6277 if (NarrowLoad.getNode() != N0.getNode()) { 6278 CombineTo(N0.getNode(), NarrowLoad); 6279 // CombineTo deleted the truncate, if needed, but not what's under it. 6280 AddToWorklist(oye); 6281 } 6282 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6283 } 6284 6285 EVT SrcVT = N0.getOperand(0).getValueType(); 6286 EVT MinVT = N0.getValueType(); 6287 6288 // Try to mask before the extension to avoid having to generate a larger mask, 6289 // possibly over several sub-vectors. 6290 if (SrcVT.bitsLT(VT)) { 6291 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6292 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6293 SDValue Op = N0.getOperand(0); 6294 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6295 AddToWorklist(Op.getNode()); 6296 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6297 } 6298 } 6299 6300 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6301 SDValue Op = N0.getOperand(0); 6302 if (SrcVT.bitsLT(VT)) { 6303 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6304 AddToWorklist(Op.getNode()); 6305 } else if (SrcVT.bitsGT(VT)) { 6306 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6307 AddToWorklist(Op.getNode()); 6308 } 6309 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6310 } 6311 } 6312 6313 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6314 // if either of the casts is not free. 6315 if (N0.getOpcode() == ISD::AND && 6316 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6317 N0.getOperand(1).getOpcode() == ISD::Constant && 6318 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6319 N0.getValueType()) || 6320 !TLI.isZExtFree(N0.getValueType(), VT))) { 6321 SDValue X = N0.getOperand(0).getOperand(0); 6322 if (X.getValueType().bitsLT(VT)) { 6323 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6324 } else if (X.getValueType().bitsGT(VT)) { 6325 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6326 } 6327 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6328 Mask = Mask.zext(VT.getSizeInBits()); 6329 SDLoc DL(N); 6330 return DAG.getNode(ISD::AND, DL, VT, 6331 X, DAG.getConstant(Mask, DL, VT)); 6332 } 6333 6334 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6335 // Only generate vector extloads when 1) they're legal, and 2) they are 6336 // deemed desirable by the target. 6337 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6338 ((!LegalOperations && !VT.isVector() && 6339 !cast<LoadSDNode>(N0)->isVolatile()) || 6340 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6341 bool DoXform = true; 6342 SmallVector<SDNode*, 4> SetCCs; 6343 if (!N0.hasOneUse()) 6344 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6345 if (VT.isVector()) 6346 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6347 if (DoXform) { 6348 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6349 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6350 LN0->getChain(), 6351 LN0->getBasePtr(), N0.getValueType(), 6352 LN0->getMemOperand()); 6353 CombineTo(N, ExtLoad); 6354 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6355 N0.getValueType(), ExtLoad); 6356 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6357 6358 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6359 ISD::ZERO_EXTEND); 6360 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6361 } 6362 } 6363 6364 // fold (zext (load x)) to multiple smaller zextloads. 6365 // Only on illegal but splittable vectors. 6366 if (SDValue ExtLoad = CombineExtLoad(N)) 6367 return ExtLoad; 6368 6369 // fold (zext (and/or/xor (load x), cst)) -> 6370 // (and/or/xor (zextload x), (zext cst)) 6371 // Unless (and (load x) cst) will match as a zextload already and has 6372 // additional users. 6373 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6374 N0.getOpcode() == ISD::XOR) && 6375 isa<LoadSDNode>(N0.getOperand(0)) && 6376 N0.getOperand(1).getOpcode() == ISD::Constant && 6377 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6378 (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) { 6379 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6380 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6381 bool DoXform = true; 6382 SmallVector<SDNode*, 4> SetCCs; 6383 if (!N0.hasOneUse()) { 6384 if (N0.getOpcode() == ISD::AND) { 6385 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6386 auto NarrowLoad = false; 6387 EVT LoadResultTy = AndC->getValueType(0); 6388 EVT ExtVT, LoadedVT; 6389 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6390 NarrowLoad)) 6391 DoXform = false; 6392 } 6393 if (DoXform) 6394 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6395 ISD::ZERO_EXTEND, SetCCs, TLI); 6396 } 6397 if (DoXform) { 6398 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6399 LN0->getChain(), LN0->getBasePtr(), 6400 LN0->getMemoryVT(), 6401 LN0->getMemOperand()); 6402 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6403 Mask = Mask.zext(VT.getSizeInBits()); 6404 SDLoc DL(N); 6405 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6406 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6407 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6408 SDLoc(N0.getOperand(0)), 6409 N0.getOperand(0).getValueType(), ExtLoad); 6410 CombineTo(N, And); 6411 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6412 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6413 ISD::ZERO_EXTEND); 6414 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6415 } 6416 } 6417 } 6418 6419 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6420 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6421 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6422 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6423 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6424 EVT MemVT = LN0->getMemoryVT(); 6425 if ((!LegalOperations && !LN0->isVolatile()) || 6426 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6427 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6428 LN0->getChain(), 6429 LN0->getBasePtr(), MemVT, 6430 LN0->getMemOperand()); 6431 CombineTo(N, ExtLoad); 6432 CombineTo(N0.getNode(), 6433 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6434 ExtLoad), 6435 ExtLoad.getValue(1)); 6436 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6437 } 6438 } 6439 6440 if (N0.getOpcode() == ISD::SETCC) { 6441 if (!LegalOperations && VT.isVector() && 6442 N0.getValueType().getVectorElementType() == MVT::i1) { 6443 EVT N0VT = N0.getOperand(0).getValueType(); 6444 if (getSetCCResultType(N0VT) == N0.getValueType()) 6445 return SDValue(); 6446 6447 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6448 // Only do this before legalize for now. 6449 SDLoc DL(N); 6450 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6451 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6452 // We know that the # elements of the results is the same as the 6453 // # elements of the compare (and the # elements of the compare result 6454 // for that matter). Check to see that they are the same size. If so, 6455 // we know that the element size of the sext'd result matches the 6456 // element size of the compare operands. 6457 return DAG.getNode(ISD::AND, DL, VT, 6458 DAG.getSetCC(DL, VT, N0.getOperand(0), 6459 N0.getOperand(1), 6460 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6461 VecOnes); 6462 6463 // If the desired elements are smaller or larger than the source 6464 // elements we can use a matching integer vector type and then 6465 // truncate/sign extend 6466 EVT MatchingElementType = 6467 EVT::getIntegerVT(*DAG.getContext(), 6468 N0VT.getScalarType().getSizeInBits()); 6469 EVT MatchingVectorType = 6470 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6471 N0VT.getVectorNumElements()); 6472 SDValue VsetCC = 6473 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6474 N0.getOperand(1), 6475 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6476 return DAG.getNode(ISD::AND, DL, VT, 6477 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6478 VecOnes); 6479 } 6480 6481 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6482 SDLoc DL(N); 6483 if (SDValue SCC = SimplifySelectCC( 6484 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6485 DAG.getConstant(0, DL, VT), 6486 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6487 return SCC; 6488 } 6489 6490 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6491 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6492 isa<ConstantSDNode>(N0.getOperand(1)) && 6493 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6494 N0.hasOneUse()) { 6495 SDValue ShAmt = N0.getOperand(1); 6496 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6497 if (N0.getOpcode() == ISD::SHL) { 6498 SDValue InnerZExt = N0.getOperand(0); 6499 // If the original shl may be shifting out bits, do not perform this 6500 // transformation. 6501 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6502 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6503 if (ShAmtVal > KnownZeroBits) 6504 return SDValue(); 6505 } 6506 6507 SDLoc DL(N); 6508 6509 // Ensure that the shift amount is wide enough for the shifted value. 6510 if (VT.getSizeInBits() >= 256) 6511 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6512 6513 return DAG.getNode(N0.getOpcode(), DL, VT, 6514 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6515 ShAmt); 6516 } 6517 6518 return SDValue(); 6519 } 6520 6521 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6522 SDValue N0 = N->getOperand(0); 6523 EVT VT = N->getValueType(0); 6524 6525 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6526 LegalOperations)) 6527 return SDValue(Res, 0); 6528 6529 // fold (aext (aext x)) -> (aext x) 6530 // fold (aext (zext x)) -> (zext x) 6531 // fold (aext (sext x)) -> (sext x) 6532 if (N0.getOpcode() == ISD::ANY_EXTEND || 6533 N0.getOpcode() == ISD::ZERO_EXTEND || 6534 N0.getOpcode() == ISD::SIGN_EXTEND) 6535 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6536 6537 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6538 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6539 if (N0.getOpcode() == ISD::TRUNCATE) { 6540 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6541 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6542 if (NarrowLoad.getNode() != N0.getNode()) { 6543 CombineTo(N0.getNode(), NarrowLoad); 6544 // CombineTo deleted the truncate, if needed, but not what's under it. 6545 AddToWorklist(oye); 6546 } 6547 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6548 } 6549 } 6550 6551 // fold (aext (truncate x)) 6552 if (N0.getOpcode() == ISD::TRUNCATE) { 6553 SDValue TruncOp = N0.getOperand(0); 6554 if (TruncOp.getValueType() == VT) 6555 return TruncOp; // x iff x size == zext size. 6556 if (TruncOp.getValueType().bitsGT(VT)) 6557 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6558 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6559 } 6560 6561 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6562 // if the trunc is not free. 6563 if (N0.getOpcode() == ISD::AND && 6564 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6565 N0.getOperand(1).getOpcode() == ISD::Constant && 6566 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6567 N0.getValueType())) { 6568 SDValue X = N0.getOperand(0).getOperand(0); 6569 if (X.getValueType().bitsLT(VT)) { 6570 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6571 } else if (X.getValueType().bitsGT(VT)) { 6572 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6573 } 6574 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6575 Mask = Mask.zext(VT.getSizeInBits()); 6576 SDLoc DL(N); 6577 return DAG.getNode(ISD::AND, DL, VT, 6578 X, DAG.getConstant(Mask, DL, VT)); 6579 } 6580 6581 // fold (aext (load x)) -> (aext (truncate (extload x))) 6582 // None of the supported targets knows how to perform load and any_ext 6583 // on vectors in one instruction. We only perform this transformation on 6584 // scalars. 6585 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6586 ISD::isUNINDEXEDLoad(N0.getNode()) && 6587 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6588 bool DoXform = true; 6589 SmallVector<SDNode*, 4> SetCCs; 6590 if (!N0.hasOneUse()) 6591 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6592 if (DoXform) { 6593 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6594 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6595 LN0->getChain(), 6596 LN0->getBasePtr(), N0.getValueType(), 6597 LN0->getMemOperand()); 6598 CombineTo(N, ExtLoad); 6599 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6600 N0.getValueType(), ExtLoad); 6601 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6602 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6603 ISD::ANY_EXTEND); 6604 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6605 } 6606 } 6607 6608 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6609 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6610 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6611 if (N0.getOpcode() == ISD::LOAD && 6612 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6613 N0.hasOneUse()) { 6614 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6615 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6616 EVT MemVT = LN0->getMemoryVT(); 6617 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6618 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6619 VT, LN0->getChain(), LN0->getBasePtr(), 6620 MemVT, LN0->getMemOperand()); 6621 CombineTo(N, ExtLoad); 6622 CombineTo(N0.getNode(), 6623 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6624 N0.getValueType(), ExtLoad), 6625 ExtLoad.getValue(1)); 6626 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6627 } 6628 } 6629 6630 if (N0.getOpcode() == ISD::SETCC) { 6631 // For vectors: 6632 // aext(setcc) -> vsetcc 6633 // aext(setcc) -> truncate(vsetcc) 6634 // aext(setcc) -> aext(vsetcc) 6635 // Only do this before legalize for now. 6636 if (VT.isVector() && !LegalOperations) { 6637 EVT N0VT = N0.getOperand(0).getValueType(); 6638 // We know that the # elements of the results is the same as the 6639 // # elements of the compare (and the # elements of the compare result 6640 // for that matter). Check to see that they are the same size. If so, 6641 // we know that the element size of the sext'd result matches the 6642 // element size of the compare operands. 6643 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6644 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6645 N0.getOperand(1), 6646 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6647 // If the desired elements are smaller or larger than the source 6648 // elements we can use a matching integer vector type and then 6649 // truncate/any extend 6650 else { 6651 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6652 SDValue VsetCC = 6653 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6654 N0.getOperand(1), 6655 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6656 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6657 } 6658 } 6659 6660 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6661 SDLoc DL(N); 6662 if (SDValue SCC = SimplifySelectCC( 6663 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6664 DAG.getConstant(0, DL, VT), 6665 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6666 return SCC; 6667 } 6668 6669 return SDValue(); 6670 } 6671 6672 /// See if the specified operand can be simplified with the knowledge that only 6673 /// the bits specified by Mask are used. If so, return the simpler operand, 6674 /// otherwise return a null SDValue. 6675 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6676 switch (V.getOpcode()) { 6677 default: break; 6678 case ISD::Constant: { 6679 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6680 assert(CV && "Const value should be ConstSDNode."); 6681 const APInt &CVal = CV->getAPIntValue(); 6682 APInt NewVal = CVal & Mask; 6683 if (NewVal != CVal) 6684 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6685 break; 6686 } 6687 case ISD::OR: 6688 case ISD::XOR: 6689 // If the LHS or RHS don't contribute bits to the or, drop them. 6690 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6691 return V.getOperand(1); 6692 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6693 return V.getOperand(0); 6694 break; 6695 case ISD::SRL: 6696 // Only look at single-use SRLs. 6697 if (!V.getNode()->hasOneUse()) 6698 break; 6699 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6700 // See if we can recursively simplify the LHS. 6701 unsigned Amt = RHSC->getZExtValue(); 6702 6703 // Watch out for shift count overflow though. 6704 if (Amt >= Mask.getBitWidth()) break; 6705 APInt NewMask = Mask << Amt; 6706 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6707 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6708 SimplifyLHS, V.getOperand(1)); 6709 } 6710 } 6711 return SDValue(); 6712 } 6713 6714 /// If the result of a wider load is shifted to right of N bits and then 6715 /// truncated to a narrower type and where N is a multiple of number of bits of 6716 /// the narrower type, transform it to a narrower load from address + N / num of 6717 /// bits of new type. If the result is to be extended, also fold the extension 6718 /// to form a extending load. 6719 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6720 unsigned Opc = N->getOpcode(); 6721 6722 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6723 SDValue N0 = N->getOperand(0); 6724 EVT VT = N->getValueType(0); 6725 EVT ExtVT = VT; 6726 6727 // This transformation isn't valid for vector loads. 6728 if (VT.isVector()) 6729 return SDValue(); 6730 6731 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6732 // extended to VT. 6733 if (Opc == ISD::SIGN_EXTEND_INREG) { 6734 ExtType = ISD::SEXTLOAD; 6735 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6736 } else if (Opc == ISD::SRL) { 6737 // Another special-case: SRL is basically zero-extending a narrower value. 6738 ExtType = ISD::ZEXTLOAD; 6739 N0 = SDValue(N, 0); 6740 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6741 if (!N01) return SDValue(); 6742 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6743 VT.getSizeInBits() - N01->getZExtValue()); 6744 } 6745 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6746 return SDValue(); 6747 6748 unsigned EVTBits = ExtVT.getSizeInBits(); 6749 6750 // Do not generate loads of non-round integer types since these can 6751 // be expensive (and would be wrong if the type is not byte sized). 6752 if (!ExtVT.isRound()) 6753 return SDValue(); 6754 6755 unsigned ShAmt = 0; 6756 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6757 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6758 ShAmt = N01->getZExtValue(); 6759 // Is the shift amount a multiple of size of VT? 6760 if ((ShAmt & (EVTBits-1)) == 0) { 6761 N0 = N0.getOperand(0); 6762 // Is the load width a multiple of size of VT? 6763 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6764 return SDValue(); 6765 } 6766 6767 // At this point, we must have a load or else we can't do the transform. 6768 if (!isa<LoadSDNode>(N0)) return SDValue(); 6769 6770 // Because a SRL must be assumed to *need* to zero-extend the high bits 6771 // (as opposed to anyext the high bits), we can't combine the zextload 6772 // lowering of SRL and an sextload. 6773 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6774 return SDValue(); 6775 6776 // If the shift amount is larger than the input type then we're not 6777 // accessing any of the loaded bytes. If the load was a zextload/extload 6778 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6779 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6780 return SDValue(); 6781 } 6782 } 6783 6784 // If the load is shifted left (and the result isn't shifted back right), 6785 // we can fold the truncate through the shift. 6786 unsigned ShLeftAmt = 0; 6787 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6788 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6789 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6790 ShLeftAmt = N01->getZExtValue(); 6791 N0 = N0.getOperand(0); 6792 } 6793 } 6794 6795 // If we haven't found a load, we can't narrow it. Don't transform one with 6796 // multiple uses, this would require adding a new load. 6797 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6798 return SDValue(); 6799 6800 // Don't change the width of a volatile load. 6801 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6802 if (LN0->isVolatile()) 6803 return SDValue(); 6804 6805 // Verify that we are actually reducing a load width here. 6806 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6807 return SDValue(); 6808 6809 // For the transform to be legal, the load must produce only two values 6810 // (the value loaded and the chain). Don't transform a pre-increment 6811 // load, for example, which produces an extra value. Otherwise the 6812 // transformation is not equivalent, and the downstream logic to replace 6813 // uses gets things wrong. 6814 if (LN0->getNumValues() > 2) 6815 return SDValue(); 6816 6817 // If the load that we're shrinking is an extload and we're not just 6818 // discarding the extension we can't simply shrink the load. Bail. 6819 // TODO: It would be possible to merge the extensions in some cases. 6820 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6821 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6822 return SDValue(); 6823 6824 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6825 return SDValue(); 6826 6827 EVT PtrType = N0.getOperand(1).getValueType(); 6828 6829 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6830 // It's not possible to generate a constant of extended or untyped type. 6831 return SDValue(); 6832 6833 // For big endian targets, we need to adjust the offset to the pointer to 6834 // load the correct bytes. 6835 if (DAG.getDataLayout().isBigEndian()) { 6836 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6837 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6838 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6839 } 6840 6841 uint64_t PtrOff = ShAmt / 8; 6842 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6843 SDLoc DL(LN0); 6844 // The original load itself didn't wrap, so an offset within it doesn't. 6845 SDNodeFlags Flags; 6846 Flags.setNoUnsignedWrap(true); 6847 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6848 PtrType, LN0->getBasePtr(), 6849 DAG.getConstant(PtrOff, DL, PtrType), 6850 &Flags); 6851 AddToWorklist(NewPtr.getNode()); 6852 6853 SDValue Load; 6854 if (ExtType == ISD::NON_EXTLOAD) 6855 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6856 LN0->getPointerInfo().getWithOffset(PtrOff), 6857 LN0->isVolatile(), LN0->isNonTemporal(), 6858 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6859 else 6860 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6861 LN0->getPointerInfo().getWithOffset(PtrOff), 6862 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6863 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6864 6865 // Replace the old load's chain with the new load's chain. 6866 WorklistRemover DeadNodes(*this); 6867 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6868 6869 // Shift the result left, if we've swallowed a left shift. 6870 SDValue Result = Load; 6871 if (ShLeftAmt != 0) { 6872 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6873 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6874 ShImmTy = VT; 6875 // If the shift amount is as large as the result size (but, presumably, 6876 // no larger than the source) then the useful bits of the result are 6877 // zero; we can't simply return the shortened shift, because the result 6878 // of that operation is undefined. 6879 SDLoc DL(N0); 6880 if (ShLeftAmt >= VT.getSizeInBits()) 6881 Result = DAG.getConstant(0, DL, VT); 6882 else 6883 Result = DAG.getNode(ISD::SHL, DL, VT, 6884 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6885 } 6886 6887 // Return the new loaded value. 6888 return Result; 6889 } 6890 6891 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6892 SDValue N0 = N->getOperand(0); 6893 SDValue N1 = N->getOperand(1); 6894 EVT VT = N->getValueType(0); 6895 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6896 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6897 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6898 6899 if (N0.isUndef()) 6900 return DAG.getUNDEF(VT); 6901 6902 // fold (sext_in_reg c1) -> c1 6903 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6904 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6905 6906 // If the input is already sign extended, just drop the extension. 6907 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6908 return N0; 6909 6910 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6911 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6912 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6913 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6914 N0.getOperand(0), N1); 6915 6916 // fold (sext_in_reg (sext x)) -> (sext x) 6917 // fold (sext_in_reg (aext x)) -> (sext x) 6918 // if x is small enough. 6919 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6920 SDValue N00 = N0.getOperand(0); 6921 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6922 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6923 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6924 } 6925 6926 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6927 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6928 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6929 6930 // fold operands of sext_in_reg based on knowledge that the top bits are not 6931 // demanded. 6932 if (SimplifyDemandedBits(SDValue(N, 0))) 6933 return SDValue(N, 0); 6934 6935 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6936 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6937 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6938 return NarrowLoad; 6939 6940 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6941 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6942 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6943 if (N0.getOpcode() == ISD::SRL) { 6944 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6945 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6946 // We can turn this into an SRA iff the input to the SRL is already sign 6947 // extended enough. 6948 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6949 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6950 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6951 N0.getOperand(0), N0.getOperand(1)); 6952 } 6953 } 6954 6955 // fold (sext_inreg (extload x)) -> (sextload x) 6956 if (ISD::isEXTLoad(N0.getNode()) && 6957 ISD::isUNINDEXEDLoad(N0.getNode()) && 6958 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6959 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6960 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6961 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6962 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6963 LN0->getChain(), 6964 LN0->getBasePtr(), EVT, 6965 LN0->getMemOperand()); 6966 CombineTo(N, ExtLoad); 6967 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6968 AddToWorklist(ExtLoad.getNode()); 6969 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6970 } 6971 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6972 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6973 N0.hasOneUse() && 6974 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6975 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6976 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6977 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6978 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6979 LN0->getChain(), 6980 LN0->getBasePtr(), EVT, 6981 LN0->getMemOperand()); 6982 CombineTo(N, ExtLoad); 6983 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6984 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6985 } 6986 6987 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6988 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6989 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6990 N0.getOperand(1), false)) 6991 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6992 BSwap, N1); 6993 } 6994 6995 return SDValue(); 6996 } 6997 6998 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 6999 SDValue N0 = N->getOperand(0); 7000 EVT VT = N->getValueType(0); 7001 7002 if (N0.isUndef()) 7003 return DAG.getUNDEF(VT); 7004 7005 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7006 LegalOperations)) 7007 return SDValue(Res, 0); 7008 7009 return SDValue(); 7010 } 7011 7012 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7013 SDValue N0 = N->getOperand(0); 7014 EVT VT = N->getValueType(0); 7015 7016 if (N0.isUndef()) 7017 return DAG.getUNDEF(VT); 7018 7019 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7020 LegalOperations)) 7021 return SDValue(Res, 0); 7022 7023 return SDValue(); 7024 } 7025 7026 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7027 SDValue N0 = N->getOperand(0); 7028 EVT VT = N->getValueType(0); 7029 bool isLE = DAG.getDataLayout().isLittleEndian(); 7030 7031 // noop truncate 7032 if (N0.getValueType() == N->getValueType(0)) 7033 return N0; 7034 // fold (truncate c1) -> c1 7035 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7036 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7037 // fold (truncate (truncate x)) -> (truncate x) 7038 if (N0.getOpcode() == ISD::TRUNCATE) 7039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7040 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7041 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7042 N0.getOpcode() == ISD::SIGN_EXTEND || 7043 N0.getOpcode() == ISD::ANY_EXTEND) { 7044 // if the source is smaller than the dest, we still need an extend. 7045 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7046 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7047 // if the source is larger than the dest, than we just need the truncate. 7048 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7049 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7050 // if the source and dest are the same type, we can drop both the extend 7051 // and the truncate. 7052 return N0.getOperand(0); 7053 } 7054 7055 // Fold extract-and-trunc into a narrow extract. For example: 7056 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7057 // i32 y = TRUNCATE(i64 x) 7058 // -- becomes -- 7059 // v16i8 b = BITCAST (v2i64 val) 7060 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7061 // 7062 // Note: We only run this optimization after type legalization (which often 7063 // creates this pattern) and before operation legalization after which 7064 // we need to be more careful about the vector instructions that we generate. 7065 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7066 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7067 7068 EVT VecTy = N0.getOperand(0).getValueType(); 7069 EVT ExTy = N0.getValueType(); 7070 EVT TrTy = N->getValueType(0); 7071 7072 unsigned NumElem = VecTy.getVectorNumElements(); 7073 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7074 7075 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7076 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7077 7078 SDValue EltNo = N0->getOperand(1); 7079 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7080 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7081 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7082 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7083 7084 SDLoc DL(N); 7085 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7086 DAG.getBitcast(NVT, N0.getOperand(0)), 7087 DAG.getConstant(Index, DL, IndexTy)); 7088 } 7089 } 7090 7091 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7092 if (N0.getOpcode() == ISD::SELECT) { 7093 EVT SrcVT = N0.getValueType(); 7094 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7095 TLI.isTruncateFree(SrcVT, VT)) { 7096 SDLoc SL(N0); 7097 SDValue Cond = N0.getOperand(0); 7098 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7099 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7100 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7101 } 7102 } 7103 7104 // Fold a series of buildvector, bitcast, and truncate if possible. 7105 // For example fold 7106 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7107 // (2xi32 (buildvector x, y)). 7108 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7109 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7110 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7111 N0.getOperand(0).hasOneUse()) { 7112 7113 SDValue BuildVect = N0.getOperand(0); 7114 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7115 EVT TruncVecEltTy = VT.getVectorElementType(); 7116 7117 // Check that the element types match. 7118 if (BuildVectEltTy == TruncVecEltTy) { 7119 // Now we only need to compute the offset of the truncated elements. 7120 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7121 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7122 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7123 7124 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7125 "Invalid number of elements"); 7126 7127 SmallVector<SDValue, 8> Opnds; 7128 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7129 Opnds.push_back(BuildVect.getOperand(i)); 7130 7131 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 7132 } 7133 } 7134 7135 // See if we can simplify the input to this truncate through knowledge that 7136 // only the low bits are being used. 7137 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7138 // Currently we only perform this optimization on scalars because vectors 7139 // may have different active low bits. 7140 if (!VT.isVector()) { 7141 if (SDValue Shorter = 7142 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7143 VT.getSizeInBits()))) 7144 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7145 } 7146 // fold (truncate (load x)) -> (smaller load x) 7147 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7148 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7149 if (SDValue Reduced = ReduceLoadWidth(N)) 7150 return Reduced; 7151 7152 // Handle the case where the load remains an extending load even 7153 // after truncation. 7154 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7155 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7156 if (!LN0->isVolatile() && 7157 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7158 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7159 VT, LN0->getChain(), LN0->getBasePtr(), 7160 LN0->getMemoryVT(), 7161 LN0->getMemOperand()); 7162 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7163 return NewLoad; 7164 } 7165 } 7166 } 7167 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7168 // where ... are all 'undef'. 7169 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7170 SmallVector<EVT, 8> VTs; 7171 SDValue V; 7172 unsigned Idx = 0; 7173 unsigned NumDefs = 0; 7174 7175 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7176 SDValue X = N0.getOperand(i); 7177 if (!X.isUndef()) { 7178 V = X; 7179 Idx = i; 7180 NumDefs++; 7181 } 7182 // Stop if more than one members are non-undef. 7183 if (NumDefs > 1) 7184 break; 7185 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7186 VT.getVectorElementType(), 7187 X.getValueType().getVectorNumElements())); 7188 } 7189 7190 if (NumDefs == 0) 7191 return DAG.getUNDEF(VT); 7192 7193 if (NumDefs == 1) { 7194 assert(V.getNode() && "The single defined operand is empty!"); 7195 SmallVector<SDValue, 8> Opnds; 7196 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7197 if (i != Idx) { 7198 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7199 continue; 7200 } 7201 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7202 AddToWorklist(NV.getNode()); 7203 Opnds.push_back(NV); 7204 } 7205 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7206 } 7207 } 7208 7209 // Fold truncate of a bitcast of a vector to an extract of the low vector 7210 // element. 7211 // 7212 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7213 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7214 SDValue VecSrc = N0.getOperand(0); 7215 EVT SrcVT = VecSrc.getValueType(); 7216 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7217 (!LegalOperations || 7218 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7219 SDLoc SL(N); 7220 7221 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7222 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7223 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7224 } 7225 } 7226 7227 // Simplify the operands using demanded-bits information. 7228 if (!VT.isVector() && 7229 SimplifyDemandedBits(SDValue(N, 0))) 7230 return SDValue(N, 0); 7231 7232 return SDValue(); 7233 } 7234 7235 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7236 SDValue Elt = N->getOperand(i); 7237 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7238 return Elt.getNode(); 7239 return Elt.getOperand(Elt.getResNo()).getNode(); 7240 } 7241 7242 /// build_pair (load, load) -> load 7243 /// if load locations are consecutive. 7244 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7245 assert(N->getOpcode() == ISD::BUILD_PAIR); 7246 7247 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7248 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7249 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7250 LD1->getAddressSpace() != LD2->getAddressSpace()) 7251 return SDValue(); 7252 EVT LD1VT = LD1->getValueType(0); 7253 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7254 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7255 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7256 unsigned Align = LD1->getAlignment(); 7257 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7258 VT.getTypeForEVT(*DAG.getContext())); 7259 7260 if (NewAlign <= Align && 7261 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7262 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7263 LD1->getBasePtr(), LD1->getPointerInfo(), 7264 false, false, false, Align); 7265 } 7266 7267 return SDValue(); 7268 } 7269 7270 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7271 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7272 // and Lo parts; on big-endian machines it doesn't. 7273 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7274 } 7275 7276 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7277 SDValue N0 = N->getOperand(0); 7278 EVT VT = N->getValueType(0); 7279 7280 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7281 // Only do this before legalize, since afterward the target may be depending 7282 // on the bitconvert. 7283 // First check to see if this is all constant. 7284 if (!LegalTypes && 7285 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7286 VT.isVector()) { 7287 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7288 7289 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7290 assert(!DestEltVT.isVector() && 7291 "Element type of vector ValueType must not be vector!"); 7292 if (isSimple) 7293 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7294 } 7295 7296 // If the input is a constant, let getNode fold it. 7297 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7298 // If we can't allow illegal operations, we need to check that this is just 7299 // a fp -> int or int -> conversion and that the resulting operation will 7300 // be legal. 7301 if (!LegalOperations || 7302 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7303 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7304 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7305 TLI.isOperationLegal(ISD::Constant, VT))) 7306 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7307 } 7308 7309 // (conv (conv x, t1), t2) -> (conv x, t2) 7310 if (N0.getOpcode() == ISD::BITCAST) 7311 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7312 N0.getOperand(0)); 7313 7314 // fold (conv (load x)) -> (load (conv*)x) 7315 // If the resultant load doesn't need a higher alignment than the original! 7316 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7317 // Do not change the width of a volatile load. 7318 !cast<LoadSDNode>(N0)->isVolatile() && 7319 // Do not remove the cast if the types differ in endian layout. 7320 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7321 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7322 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7323 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7324 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7325 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7326 VT.getTypeForEVT(*DAG.getContext())); 7327 unsigned OrigAlign = LN0->getAlignment(); 7328 7329 if (Align <= OrigAlign) { 7330 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7331 LN0->getBasePtr(), LN0->getPointerInfo(), 7332 LN0->isVolatile(), LN0->isNonTemporal(), 7333 LN0->isInvariant(), OrigAlign, 7334 LN0->getAAInfo()); 7335 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7336 return Load; 7337 } 7338 } 7339 7340 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7341 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7342 // 7343 // For ppc_fp128: 7344 // fold (bitcast (fneg x)) -> 7345 // flipbit = signbit 7346 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7347 // 7348 // fold (bitcast (fabs x)) -> 7349 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7350 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7351 // This often reduces constant pool loads. 7352 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7353 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7354 N0.getNode()->hasOneUse() && VT.isInteger() && 7355 !VT.isVector() && !N0.getValueType().isVector()) { 7356 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7357 N0.getOperand(0)); 7358 AddToWorklist(NewConv.getNode()); 7359 7360 SDLoc DL(N); 7361 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7362 assert(VT.getSizeInBits() == 128); 7363 SDValue SignBit = DAG.getConstant( 7364 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7365 SDValue FlipBit; 7366 if (N0.getOpcode() == ISD::FNEG) { 7367 FlipBit = SignBit; 7368 AddToWorklist(FlipBit.getNode()); 7369 } else { 7370 assert(N0.getOpcode() == ISD::FABS); 7371 SDValue Hi = 7372 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7373 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7374 SDLoc(NewConv))); 7375 AddToWorklist(Hi.getNode()); 7376 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7377 AddToWorklist(FlipBit.getNode()); 7378 } 7379 SDValue FlipBits = 7380 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7381 AddToWorklist(FlipBits.getNode()); 7382 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7383 } 7384 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7385 if (N0.getOpcode() == ISD::FNEG) 7386 return DAG.getNode(ISD::XOR, DL, VT, 7387 NewConv, DAG.getConstant(SignBit, DL, VT)); 7388 assert(N0.getOpcode() == ISD::FABS); 7389 return DAG.getNode(ISD::AND, DL, VT, 7390 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7391 } 7392 7393 // fold (bitconvert (fcopysign cst, x)) -> 7394 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7395 // Note that we don't handle (copysign x, cst) because this can always be 7396 // folded to an fneg or fabs. 7397 // 7398 // For ppc_fp128: 7399 // fold (bitcast (fcopysign cst, x)) -> 7400 // flipbit = (and (extract_element 7401 // (xor (bitcast cst), (bitcast x)), 0), 7402 // signbit) 7403 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7404 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7405 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7406 VT.isInteger() && !VT.isVector()) { 7407 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7408 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7409 if (isTypeLegal(IntXVT)) { 7410 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7411 IntXVT, N0.getOperand(1)); 7412 AddToWorklist(X.getNode()); 7413 7414 // If X has a different width than the result/lhs, sext it or truncate it. 7415 unsigned VTWidth = VT.getSizeInBits(); 7416 if (OrigXWidth < VTWidth) { 7417 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7418 AddToWorklist(X.getNode()); 7419 } else if (OrigXWidth > VTWidth) { 7420 // To get the sign bit in the right place, we have to shift it right 7421 // before truncating. 7422 SDLoc DL(X); 7423 X = DAG.getNode(ISD::SRL, DL, 7424 X.getValueType(), X, 7425 DAG.getConstant(OrigXWidth-VTWidth, DL, 7426 X.getValueType())); 7427 AddToWorklist(X.getNode()); 7428 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7429 AddToWorklist(X.getNode()); 7430 } 7431 7432 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7433 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7434 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7435 AddToWorklist(Cst.getNode()); 7436 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7437 AddToWorklist(X.getNode()); 7438 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7439 AddToWorklist(XorResult.getNode()); 7440 SDValue XorResult64 = DAG.getNode( 7441 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7442 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7443 SDLoc(XorResult))); 7444 AddToWorklist(XorResult64.getNode()); 7445 SDValue FlipBit = 7446 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7447 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7448 AddToWorklist(FlipBit.getNode()); 7449 SDValue FlipBits = 7450 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7451 AddToWorklist(FlipBits.getNode()); 7452 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7453 } 7454 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7455 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7456 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7457 AddToWorklist(X.getNode()); 7458 7459 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7460 VT, N0.getOperand(0)); 7461 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7462 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7463 AddToWorklist(Cst.getNode()); 7464 7465 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7466 } 7467 } 7468 7469 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7470 if (N0.getOpcode() == ISD::BUILD_PAIR) 7471 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7472 return CombineLD; 7473 7474 // Remove double bitcasts from shuffles - this is often a legacy of 7475 // XformToShuffleWithZero being used to combine bitmaskings (of 7476 // float vectors bitcast to integer vectors) into shuffles. 7477 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7478 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7479 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7480 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7481 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7482 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7483 7484 // If operands are a bitcast, peek through if it casts the original VT. 7485 // If operands are a constant, just bitcast back to original VT. 7486 auto PeekThroughBitcast = [&](SDValue Op) { 7487 if (Op.getOpcode() == ISD::BITCAST && 7488 Op.getOperand(0).getValueType() == VT) 7489 return SDValue(Op.getOperand(0)); 7490 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7491 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7492 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7493 return SDValue(); 7494 }; 7495 7496 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7497 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7498 if (!(SV0 && SV1)) 7499 return SDValue(); 7500 7501 int MaskScale = 7502 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7503 SmallVector<int, 8> NewMask; 7504 for (int M : SVN->getMask()) 7505 for (int i = 0; i != MaskScale; ++i) 7506 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7507 7508 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7509 if (!LegalMask) { 7510 std::swap(SV0, SV1); 7511 ShuffleVectorSDNode::commuteMask(NewMask); 7512 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7513 } 7514 7515 if (LegalMask) 7516 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7517 } 7518 7519 return SDValue(); 7520 } 7521 7522 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7523 EVT VT = N->getValueType(0); 7524 return CombineConsecutiveLoads(N, VT); 7525 } 7526 7527 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7528 /// operands. DstEltVT indicates the destination element value type. 7529 SDValue DAGCombiner:: 7530 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7531 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7532 7533 // If this is already the right type, we're done. 7534 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7535 7536 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7537 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7538 7539 // If this is a conversion of N elements of one type to N elements of another 7540 // type, convert each element. This handles FP<->INT cases. 7541 if (SrcBitSize == DstBitSize) { 7542 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7543 BV->getValueType(0).getVectorNumElements()); 7544 7545 // Due to the FP element handling below calling this routine recursively, 7546 // we can end up with a scalar-to-vector node here. 7547 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7548 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7549 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7550 DstEltVT, BV->getOperand(0))); 7551 7552 SmallVector<SDValue, 8> Ops; 7553 for (SDValue Op : BV->op_values()) { 7554 // If the vector element type is not legal, the BUILD_VECTOR operands 7555 // are promoted and implicitly truncated. Make that explicit here. 7556 if (Op.getValueType() != SrcEltVT) 7557 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7558 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7559 DstEltVT, Op)); 7560 AddToWorklist(Ops.back().getNode()); 7561 } 7562 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7563 } 7564 7565 // Otherwise, we're growing or shrinking the elements. To avoid having to 7566 // handle annoying details of growing/shrinking FP values, we convert them to 7567 // int first. 7568 if (SrcEltVT.isFloatingPoint()) { 7569 // Convert the input float vector to a int vector where the elements are the 7570 // same sizes. 7571 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7572 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7573 SrcEltVT = IntVT; 7574 } 7575 7576 // Now we know the input is an integer vector. If the output is a FP type, 7577 // convert to integer first, then to FP of the right size. 7578 if (DstEltVT.isFloatingPoint()) { 7579 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7580 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7581 7582 // Next, convert to FP elements of the same size. 7583 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7584 } 7585 7586 SDLoc DL(BV); 7587 7588 // Okay, we know the src/dst types are both integers of differing types. 7589 // Handling growing first. 7590 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7591 if (SrcBitSize < DstBitSize) { 7592 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7593 7594 SmallVector<SDValue, 8> Ops; 7595 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7596 i += NumInputsPerOutput) { 7597 bool isLE = DAG.getDataLayout().isLittleEndian(); 7598 APInt NewBits = APInt(DstBitSize, 0); 7599 bool EltIsUndef = true; 7600 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7601 // Shift the previously computed bits over. 7602 NewBits <<= SrcBitSize; 7603 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7604 if (Op.isUndef()) continue; 7605 EltIsUndef = false; 7606 7607 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7608 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7609 } 7610 7611 if (EltIsUndef) 7612 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7613 else 7614 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7615 } 7616 7617 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7618 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7619 } 7620 7621 // Finally, this must be the case where we are shrinking elements: each input 7622 // turns into multiple outputs. 7623 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7624 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7625 NumOutputsPerInput*BV->getNumOperands()); 7626 SmallVector<SDValue, 8> Ops; 7627 7628 for (const SDValue &Op : BV->op_values()) { 7629 if (Op.isUndef()) { 7630 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7631 continue; 7632 } 7633 7634 APInt OpVal = cast<ConstantSDNode>(Op)-> 7635 getAPIntValue().zextOrTrunc(SrcBitSize); 7636 7637 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7638 APInt ThisVal = OpVal.trunc(DstBitSize); 7639 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7640 OpVal = OpVal.lshr(DstBitSize); 7641 } 7642 7643 // For big endian targets, swap the order of the pieces of each element. 7644 if (DAG.getDataLayout().isBigEndian()) 7645 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7646 } 7647 7648 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7649 } 7650 7651 /// Try to perform FMA combining on a given FADD node. 7652 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7653 SDValue N0 = N->getOperand(0); 7654 SDValue N1 = N->getOperand(1); 7655 EVT VT = N->getValueType(0); 7656 SDLoc SL(N); 7657 7658 const TargetOptions &Options = DAG.getTarget().Options; 7659 bool AllowFusion = 7660 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7661 7662 // Floating-point multiply-add with intermediate rounding. 7663 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7664 7665 // Floating-point multiply-add without intermediate rounding. 7666 bool HasFMA = 7667 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7668 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7669 7670 // No valid opcode, do not combine. 7671 if (!HasFMAD && !HasFMA) 7672 return SDValue(); 7673 7674 // Always prefer FMAD to FMA for precision. 7675 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7676 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7677 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7678 7679 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7680 // prefer to fold the multiply with fewer uses. 7681 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7682 N1.getOpcode() == ISD::FMUL) { 7683 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7684 std::swap(N0, N1); 7685 } 7686 7687 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7688 if (N0.getOpcode() == ISD::FMUL && 7689 (Aggressive || N0->hasOneUse())) { 7690 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7691 N0.getOperand(0), N0.getOperand(1), N1); 7692 } 7693 7694 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7695 // Note: Commutes FADD operands. 7696 if (N1.getOpcode() == ISD::FMUL && 7697 (Aggressive || N1->hasOneUse())) { 7698 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7699 N1.getOperand(0), N1.getOperand(1), N0); 7700 } 7701 7702 // Look through FP_EXTEND nodes to do more combining. 7703 if (AllowFusion && LookThroughFPExt) { 7704 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7705 if (N0.getOpcode() == ISD::FP_EXTEND) { 7706 SDValue N00 = N0.getOperand(0); 7707 if (N00.getOpcode() == ISD::FMUL) 7708 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7709 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7710 N00.getOperand(0)), 7711 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7712 N00.getOperand(1)), N1); 7713 } 7714 7715 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7716 // Note: Commutes FADD operands. 7717 if (N1.getOpcode() == ISD::FP_EXTEND) { 7718 SDValue N10 = N1.getOperand(0); 7719 if (N10.getOpcode() == ISD::FMUL) 7720 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7721 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7722 N10.getOperand(0)), 7723 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7724 N10.getOperand(1)), N0); 7725 } 7726 } 7727 7728 // More folding opportunities when target permits. 7729 if ((AllowFusion || HasFMAD) && Aggressive) { 7730 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7731 if (N0.getOpcode() == PreferredFusedOpcode && 7732 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7733 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7734 N0.getOperand(0), N0.getOperand(1), 7735 DAG.getNode(PreferredFusedOpcode, SL, VT, 7736 N0.getOperand(2).getOperand(0), 7737 N0.getOperand(2).getOperand(1), 7738 N1)); 7739 } 7740 7741 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7742 if (N1->getOpcode() == PreferredFusedOpcode && 7743 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7744 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7745 N1.getOperand(0), N1.getOperand(1), 7746 DAG.getNode(PreferredFusedOpcode, SL, VT, 7747 N1.getOperand(2).getOperand(0), 7748 N1.getOperand(2).getOperand(1), 7749 N0)); 7750 } 7751 7752 if (AllowFusion && LookThroughFPExt) { 7753 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7754 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7755 auto FoldFAddFMAFPExtFMul = [&] ( 7756 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7757 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, 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() == PreferredFusedOpcode) { 7764 SDValue N02 = N0.getOperand(2); 7765 if (N02.getOpcode() == ISD::FP_EXTEND) { 7766 SDValue N020 = N02.getOperand(0); 7767 if (N020.getOpcode() == ISD::FMUL) 7768 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7769 N020.getOperand(0), N020.getOperand(1), 7770 N1); 7771 } 7772 } 7773 7774 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7775 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7776 // FIXME: This turns two single-precision and one double-precision 7777 // operation into two double-precision operations, which might not be 7778 // interesting for all targets, especially GPUs. 7779 auto FoldFAddFPExtFMAFMul = [&] ( 7780 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7781 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7782 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7783 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7784 DAG.getNode(PreferredFusedOpcode, SL, VT, 7785 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7786 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7787 Z)); 7788 }; 7789 if (N0.getOpcode() == ISD::FP_EXTEND) { 7790 SDValue N00 = N0.getOperand(0); 7791 if (N00.getOpcode() == PreferredFusedOpcode) { 7792 SDValue N002 = N00.getOperand(2); 7793 if (N002.getOpcode() == ISD::FMUL) 7794 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7795 N002.getOperand(0), N002.getOperand(1), 7796 N1); 7797 } 7798 } 7799 7800 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7801 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7802 if (N1.getOpcode() == PreferredFusedOpcode) { 7803 SDValue N12 = N1.getOperand(2); 7804 if (N12.getOpcode() == ISD::FP_EXTEND) { 7805 SDValue N120 = N12.getOperand(0); 7806 if (N120.getOpcode() == ISD::FMUL) 7807 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7808 N120.getOperand(0), N120.getOperand(1), 7809 N0); 7810 } 7811 } 7812 7813 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7814 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7815 // FIXME: This turns two single-precision and one double-precision 7816 // operation into two double-precision operations, which might not be 7817 // interesting for all targets, especially GPUs. 7818 if (N1.getOpcode() == ISD::FP_EXTEND) { 7819 SDValue N10 = N1.getOperand(0); 7820 if (N10.getOpcode() == PreferredFusedOpcode) { 7821 SDValue N102 = N10.getOperand(2); 7822 if (N102.getOpcode() == ISD::FMUL) 7823 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7824 N102.getOperand(0), N102.getOperand(1), 7825 N0); 7826 } 7827 } 7828 } 7829 } 7830 7831 return SDValue(); 7832 } 7833 7834 /// Try to perform FMA combining on a given FSUB node. 7835 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7836 SDValue N0 = N->getOperand(0); 7837 SDValue N1 = N->getOperand(1); 7838 EVT VT = N->getValueType(0); 7839 SDLoc SL(N); 7840 7841 const TargetOptions &Options = DAG.getTarget().Options; 7842 bool AllowFusion = 7843 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7844 7845 // Floating-point multiply-add with intermediate rounding. 7846 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7847 7848 // Floating-point multiply-add without intermediate rounding. 7849 bool HasFMA = 7850 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7851 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7852 7853 // No valid opcode, do not combine. 7854 if (!HasFMAD && !HasFMA) 7855 return SDValue(); 7856 7857 // Always prefer FMAD to FMA for precision. 7858 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7859 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7860 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7861 7862 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7863 if (N0.getOpcode() == ISD::FMUL && 7864 (Aggressive || N0->hasOneUse())) { 7865 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7866 N0.getOperand(0), N0.getOperand(1), 7867 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7868 } 7869 7870 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7871 // Note: Commutes FSUB operands. 7872 if (N1.getOpcode() == ISD::FMUL && 7873 (Aggressive || N1->hasOneUse())) 7874 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7875 DAG.getNode(ISD::FNEG, SL, VT, 7876 N1.getOperand(0)), 7877 N1.getOperand(1), N0); 7878 7879 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7880 if (N0.getOpcode() == ISD::FNEG && 7881 N0.getOperand(0).getOpcode() == ISD::FMUL && 7882 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7883 SDValue N00 = N0.getOperand(0).getOperand(0); 7884 SDValue N01 = N0.getOperand(0).getOperand(1); 7885 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7886 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7887 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7888 } 7889 7890 // Look through FP_EXTEND nodes to do more combining. 7891 if (AllowFusion && LookThroughFPExt) { 7892 // fold (fsub (fpext (fmul x, y)), z) 7893 // -> (fma (fpext x), (fpext y), (fneg z)) 7894 if (N0.getOpcode() == ISD::FP_EXTEND) { 7895 SDValue N00 = N0.getOperand(0); 7896 if (N00.getOpcode() == ISD::FMUL) 7897 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7898 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7899 N00.getOperand(0)), 7900 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7901 N00.getOperand(1)), 7902 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7903 } 7904 7905 // fold (fsub x, (fpext (fmul y, z))) 7906 // -> (fma (fneg (fpext y)), (fpext z), x) 7907 // Note: Commutes FSUB operands. 7908 if (N1.getOpcode() == ISD::FP_EXTEND) { 7909 SDValue N10 = N1.getOperand(0); 7910 if (N10.getOpcode() == ISD::FMUL) 7911 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7912 DAG.getNode(ISD::FNEG, SL, VT, 7913 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7914 N10.getOperand(0))), 7915 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7916 N10.getOperand(1)), 7917 N0); 7918 } 7919 7920 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7921 // -> (fneg (fma (fpext x), (fpext y), z)) 7922 // Note: This could be removed with appropriate canonicalization of the 7923 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7924 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7925 // from implementing the canonicalization in visitFSUB. 7926 if (N0.getOpcode() == ISD::FP_EXTEND) { 7927 SDValue N00 = N0.getOperand(0); 7928 if (N00.getOpcode() == ISD::FNEG) { 7929 SDValue N000 = N00.getOperand(0); 7930 if (N000.getOpcode() == ISD::FMUL) { 7931 return DAG.getNode(ISD::FNEG, SL, VT, 7932 DAG.getNode(PreferredFusedOpcode, SL, VT, 7933 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7934 N000.getOperand(0)), 7935 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7936 N000.getOperand(1)), 7937 N1)); 7938 } 7939 } 7940 } 7941 7942 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7943 // -> (fneg (fma (fpext x)), (fpext y), z) 7944 // Note: This could be removed with appropriate canonicalization of the 7945 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7946 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7947 // from implementing the canonicalization in visitFSUB. 7948 if (N0.getOpcode() == ISD::FNEG) { 7949 SDValue N00 = N0.getOperand(0); 7950 if (N00.getOpcode() == ISD::FP_EXTEND) { 7951 SDValue N000 = N00.getOperand(0); 7952 if (N000.getOpcode() == ISD::FMUL) { 7953 return DAG.getNode(ISD::FNEG, SL, VT, 7954 DAG.getNode(PreferredFusedOpcode, SL, VT, 7955 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7956 N000.getOperand(0)), 7957 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7958 N000.getOperand(1)), 7959 N1)); 7960 } 7961 } 7962 } 7963 7964 } 7965 7966 // More folding opportunities when target permits. 7967 if ((AllowFusion || HasFMAD) && Aggressive) { 7968 // fold (fsub (fma x, y, (fmul u, v)), z) 7969 // -> (fma x, y (fma u, v, (fneg z))) 7970 if (N0.getOpcode() == PreferredFusedOpcode && 7971 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7972 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7973 N0.getOperand(0), N0.getOperand(1), 7974 DAG.getNode(PreferredFusedOpcode, SL, VT, 7975 N0.getOperand(2).getOperand(0), 7976 N0.getOperand(2).getOperand(1), 7977 DAG.getNode(ISD::FNEG, SL, VT, 7978 N1))); 7979 } 7980 7981 // fold (fsub x, (fma y, z, (fmul u, v))) 7982 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7983 if (N1.getOpcode() == PreferredFusedOpcode && 7984 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7985 SDValue N20 = N1.getOperand(2).getOperand(0); 7986 SDValue N21 = N1.getOperand(2).getOperand(1); 7987 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7988 DAG.getNode(ISD::FNEG, SL, VT, 7989 N1.getOperand(0)), 7990 N1.getOperand(1), 7991 DAG.getNode(PreferredFusedOpcode, SL, VT, 7992 DAG.getNode(ISD::FNEG, SL, VT, N20), 7993 7994 N21, N0)); 7995 } 7996 7997 if (AllowFusion && LookThroughFPExt) { 7998 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7999 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8000 if (N0.getOpcode() == PreferredFusedOpcode) { 8001 SDValue N02 = N0.getOperand(2); 8002 if (N02.getOpcode() == ISD::FP_EXTEND) { 8003 SDValue N020 = N02.getOperand(0); 8004 if (N020.getOpcode() == ISD::FMUL) 8005 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8006 N0.getOperand(0), N0.getOperand(1), 8007 DAG.getNode(PreferredFusedOpcode, SL, VT, 8008 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8009 N020.getOperand(0)), 8010 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8011 N020.getOperand(1)), 8012 DAG.getNode(ISD::FNEG, SL, VT, 8013 N1))); 8014 } 8015 } 8016 8017 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8018 // -> (fma (fpext x), (fpext y), 8019 // (fma (fpext u), (fpext v), (fneg z))) 8020 // FIXME: This turns two single-precision and one double-precision 8021 // operation into two double-precision operations, which might not be 8022 // interesting for all targets, especially GPUs. 8023 if (N0.getOpcode() == ISD::FP_EXTEND) { 8024 SDValue N00 = N0.getOperand(0); 8025 if (N00.getOpcode() == PreferredFusedOpcode) { 8026 SDValue N002 = N00.getOperand(2); 8027 if (N002.getOpcode() == ISD::FMUL) 8028 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8029 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8030 N00.getOperand(0)), 8031 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8032 N00.getOperand(1)), 8033 DAG.getNode(PreferredFusedOpcode, SL, VT, 8034 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8035 N002.getOperand(0)), 8036 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8037 N002.getOperand(1)), 8038 DAG.getNode(ISD::FNEG, SL, VT, 8039 N1))); 8040 } 8041 } 8042 8043 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8044 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8045 if (N1.getOpcode() == PreferredFusedOpcode && 8046 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8047 SDValue N120 = N1.getOperand(2).getOperand(0); 8048 if (N120.getOpcode() == ISD::FMUL) { 8049 SDValue N1200 = N120.getOperand(0); 8050 SDValue N1201 = N120.getOperand(1); 8051 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8052 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8053 N1.getOperand(1), 8054 DAG.getNode(PreferredFusedOpcode, SL, VT, 8055 DAG.getNode(ISD::FNEG, SL, VT, 8056 DAG.getNode(ISD::FP_EXTEND, SL, 8057 VT, N1200)), 8058 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8059 N1201), 8060 N0)); 8061 } 8062 } 8063 8064 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8065 // -> (fma (fneg (fpext y)), (fpext z), 8066 // (fma (fneg (fpext u)), (fpext v), x)) 8067 // FIXME: This turns two single-precision and one double-precision 8068 // operation into two double-precision operations, which might not be 8069 // interesting for all targets, especially GPUs. 8070 if (N1.getOpcode() == ISD::FP_EXTEND && 8071 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8072 SDValue N100 = N1.getOperand(0).getOperand(0); 8073 SDValue N101 = N1.getOperand(0).getOperand(1); 8074 SDValue N102 = N1.getOperand(0).getOperand(2); 8075 if (N102.getOpcode() == ISD::FMUL) { 8076 SDValue N1020 = N102.getOperand(0); 8077 SDValue N1021 = N102.getOperand(1); 8078 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8079 DAG.getNode(ISD::FNEG, SL, VT, 8080 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8081 N100)), 8082 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8083 DAG.getNode(PreferredFusedOpcode, SL, VT, 8084 DAG.getNode(ISD::FNEG, SL, VT, 8085 DAG.getNode(ISD::FP_EXTEND, SL, 8086 VT, N1020)), 8087 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8088 N1021), 8089 N0)); 8090 } 8091 } 8092 } 8093 } 8094 8095 return SDValue(); 8096 } 8097 8098 /// Try to perform FMA combining on a given FMUL node. 8099 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8100 SDValue N0 = N->getOperand(0); 8101 SDValue N1 = N->getOperand(1); 8102 EVT VT = N->getValueType(0); 8103 SDLoc SL(N); 8104 8105 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8106 8107 const TargetOptions &Options = DAG.getTarget().Options; 8108 bool AllowFusion = 8109 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8110 8111 // Floating-point multiply-add with intermediate rounding. 8112 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8113 8114 // Floating-point multiply-add without intermediate rounding. 8115 bool HasFMA = 8116 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8117 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8118 8119 // No valid opcode, do not combine. 8120 if (!HasFMAD && !HasFMA) 8121 return SDValue(); 8122 8123 // Always prefer FMAD to FMA for precision. 8124 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8125 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8126 8127 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8128 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8129 auto FuseFADD = [&](SDValue X, SDValue Y) { 8130 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8131 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8132 if (XC1 && XC1->isExactlyValue(+1.0)) 8133 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8134 if (XC1 && XC1->isExactlyValue(-1.0)) 8135 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8136 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8137 } 8138 return SDValue(); 8139 }; 8140 8141 if (SDValue FMA = FuseFADD(N0, N1)) 8142 return FMA; 8143 if (SDValue FMA = FuseFADD(N1, N0)) 8144 return FMA; 8145 8146 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8147 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8148 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8149 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8150 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8151 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8152 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8153 if (XC0 && XC0->isExactlyValue(+1.0)) 8154 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8155 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8156 Y); 8157 if (XC0 && XC0->isExactlyValue(-1.0)) 8158 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8159 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8160 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8161 8162 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8163 if (XC1 && XC1->isExactlyValue(+1.0)) 8164 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8165 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8166 if (XC1 && XC1->isExactlyValue(-1.0)) 8167 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8168 } 8169 return SDValue(); 8170 }; 8171 8172 if (SDValue FMA = FuseFSUB(N0, N1)) 8173 return FMA; 8174 if (SDValue FMA = FuseFSUB(N1, N0)) 8175 return FMA; 8176 8177 return SDValue(); 8178 } 8179 8180 SDValue DAGCombiner::visitFADD(SDNode *N) { 8181 SDValue N0 = N->getOperand(0); 8182 SDValue N1 = N->getOperand(1); 8183 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8184 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8185 EVT VT = N->getValueType(0); 8186 SDLoc DL(N); 8187 const TargetOptions &Options = DAG.getTarget().Options; 8188 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8189 8190 // fold vector ops 8191 if (VT.isVector()) 8192 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8193 return FoldedVOp; 8194 8195 // fold (fadd c1, c2) -> c1 + c2 8196 if (N0CFP && N1CFP) 8197 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8198 8199 // canonicalize constant to RHS 8200 if (N0CFP && !N1CFP) 8201 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8202 8203 // fold (fadd A, (fneg B)) -> (fsub A, B) 8204 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8205 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8206 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8207 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8208 8209 // fold (fadd (fneg A), B) -> (fsub B, A) 8210 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8211 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8212 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8213 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8214 8215 // If 'unsafe math' is enabled, fold lots of things. 8216 if (Options.UnsafeFPMath) { 8217 // No FP constant should be created after legalization as Instruction 8218 // Selection pass has a hard time dealing with FP constants. 8219 bool AllowNewConst = (Level < AfterLegalizeDAG); 8220 8221 // fold (fadd A, 0) -> A 8222 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8223 if (N1C->isZero()) 8224 return N0; 8225 8226 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8227 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8228 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8229 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8230 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8231 Flags), 8232 Flags); 8233 8234 // If allowed, fold (fadd (fneg x), x) -> 0.0 8235 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8236 return DAG.getConstantFP(0.0, DL, VT); 8237 8238 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8239 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8240 return DAG.getConstantFP(0.0, DL, VT); 8241 8242 // We can fold chains of FADD's of the same value into multiplications. 8243 // This transform is not safe in general because we are reducing the number 8244 // of rounding steps. 8245 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8246 if (N0.getOpcode() == ISD::FMUL) { 8247 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8248 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8249 8250 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8251 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8252 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8253 DAG.getConstantFP(1.0, DL, VT), Flags); 8254 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8255 } 8256 8257 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8258 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8259 N1.getOperand(0) == N1.getOperand(1) && 8260 N0.getOperand(0) == N1.getOperand(0)) { 8261 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8262 DAG.getConstantFP(2.0, DL, VT), Flags); 8263 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8264 } 8265 } 8266 8267 if (N1.getOpcode() == ISD::FMUL) { 8268 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8269 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8270 8271 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8272 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8273 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8274 DAG.getConstantFP(1.0, DL, VT), Flags); 8275 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8276 } 8277 8278 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8279 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8280 N0.getOperand(0) == N0.getOperand(1) && 8281 N1.getOperand(0) == N0.getOperand(0)) { 8282 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8283 DAG.getConstantFP(2.0, DL, VT), Flags); 8284 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8285 } 8286 } 8287 8288 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8289 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8290 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8291 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8292 (N0.getOperand(0) == N1)) { 8293 return DAG.getNode(ISD::FMUL, DL, VT, 8294 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8295 } 8296 } 8297 8298 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8299 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8300 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8301 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8302 N1.getOperand(0) == N0) { 8303 return DAG.getNode(ISD::FMUL, DL, VT, 8304 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8305 } 8306 } 8307 8308 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8309 if (AllowNewConst && 8310 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8311 N0.getOperand(0) == N0.getOperand(1) && 8312 N1.getOperand(0) == N1.getOperand(1) && 8313 N0.getOperand(0) == N1.getOperand(0)) { 8314 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8315 DAG.getConstantFP(4.0, DL, VT), Flags); 8316 } 8317 } 8318 } // enable-unsafe-fp-math 8319 8320 // FADD -> FMA combines: 8321 if (SDValue Fused = visitFADDForFMACombine(N)) { 8322 AddToWorklist(Fused.getNode()); 8323 return Fused; 8324 } 8325 8326 return SDValue(); 8327 } 8328 8329 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8330 SDValue N0 = N->getOperand(0); 8331 SDValue N1 = N->getOperand(1); 8332 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8333 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8334 EVT VT = N->getValueType(0); 8335 SDLoc dl(N); 8336 const TargetOptions &Options = DAG.getTarget().Options; 8337 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8338 8339 // fold vector ops 8340 if (VT.isVector()) 8341 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8342 return FoldedVOp; 8343 8344 // fold (fsub c1, c2) -> c1-c2 8345 if (N0CFP && N1CFP) 8346 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8347 8348 // fold (fsub A, (fneg B)) -> (fadd A, B) 8349 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8350 return DAG.getNode(ISD::FADD, dl, VT, N0, 8351 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8352 8353 // If 'unsafe math' is enabled, fold lots of things. 8354 if (Options.UnsafeFPMath) { 8355 // (fsub A, 0) -> A 8356 if (N1CFP && N1CFP->isZero()) 8357 return N0; 8358 8359 // (fsub 0, B) -> -B 8360 if (N0CFP && N0CFP->isZero()) { 8361 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8362 return GetNegatedExpression(N1, DAG, LegalOperations); 8363 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8364 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8365 } 8366 8367 // (fsub x, x) -> 0.0 8368 if (N0 == N1) 8369 return DAG.getConstantFP(0.0f, dl, VT); 8370 8371 // (fsub x, (fadd x, y)) -> (fneg y) 8372 // (fsub x, (fadd y, x)) -> (fneg y) 8373 if (N1.getOpcode() == ISD::FADD) { 8374 SDValue N10 = N1->getOperand(0); 8375 SDValue N11 = N1->getOperand(1); 8376 8377 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8378 return GetNegatedExpression(N11, DAG, LegalOperations); 8379 8380 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8381 return GetNegatedExpression(N10, DAG, LegalOperations); 8382 } 8383 } 8384 8385 // FSUB -> FMA combines: 8386 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8387 AddToWorklist(Fused.getNode()); 8388 return Fused; 8389 } 8390 8391 return SDValue(); 8392 } 8393 8394 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8395 SDValue N0 = N->getOperand(0); 8396 SDValue N1 = N->getOperand(1); 8397 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8398 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8399 EVT VT = N->getValueType(0); 8400 SDLoc DL(N); 8401 const TargetOptions &Options = DAG.getTarget().Options; 8402 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8403 8404 // fold vector ops 8405 if (VT.isVector()) { 8406 // This just handles C1 * C2 for vectors. Other vector folds are below. 8407 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8408 return FoldedVOp; 8409 } 8410 8411 // fold (fmul c1, c2) -> c1*c2 8412 if (N0CFP && N1CFP) 8413 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8414 8415 // canonicalize constant to RHS 8416 if (isConstantFPBuildVectorOrConstantFP(N0) && 8417 !isConstantFPBuildVectorOrConstantFP(N1)) 8418 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8419 8420 // fold (fmul A, 1.0) -> A 8421 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8422 return N0; 8423 8424 if (Options.UnsafeFPMath) { 8425 // fold (fmul A, 0) -> 0 8426 if (N1CFP && N1CFP->isZero()) 8427 return N1; 8428 8429 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8430 if (N0.getOpcode() == ISD::FMUL) { 8431 // Fold scalars or any vector constants (not just splats). 8432 // This fold is done in general by InstCombine, but extra fmul insts 8433 // may have been generated during lowering. 8434 SDValue N00 = N0.getOperand(0); 8435 SDValue N01 = N0.getOperand(1); 8436 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8437 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8438 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8439 8440 // Check 1: Make sure that the first operand of the inner multiply is NOT 8441 // a constant. Otherwise, we may induce infinite looping. 8442 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8443 // Check 2: Make sure that the second operand of the inner multiply and 8444 // the second operand of the outer multiply are constants. 8445 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8446 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8447 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8448 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8449 } 8450 } 8451 } 8452 8453 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8454 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8455 // during an early run of DAGCombiner can prevent folding with fmuls 8456 // inserted during lowering. 8457 if (N0.getOpcode() == ISD::FADD && 8458 (N0.getOperand(0) == N0.getOperand(1)) && 8459 N0.hasOneUse()) { 8460 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8461 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8462 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8463 } 8464 } 8465 8466 // fold (fmul X, 2.0) -> (fadd X, X) 8467 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8468 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8469 8470 // fold (fmul X, -1.0) -> (fneg X) 8471 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8472 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8473 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8474 8475 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8476 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8477 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8478 // Both can be negated for free, check to see if at least one is cheaper 8479 // negated. 8480 if (LHSNeg == 2 || RHSNeg == 2) 8481 return DAG.getNode(ISD::FMUL, DL, VT, 8482 GetNegatedExpression(N0, DAG, LegalOperations), 8483 GetNegatedExpression(N1, DAG, LegalOperations), 8484 Flags); 8485 } 8486 } 8487 8488 // FMUL -> FMA combines: 8489 if (SDValue Fused = visitFMULForFMACombine(N)) { 8490 AddToWorklist(Fused.getNode()); 8491 return Fused; 8492 } 8493 8494 return SDValue(); 8495 } 8496 8497 SDValue DAGCombiner::visitFMA(SDNode *N) { 8498 SDValue N0 = N->getOperand(0); 8499 SDValue N1 = N->getOperand(1); 8500 SDValue N2 = N->getOperand(2); 8501 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8502 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8503 EVT VT = N->getValueType(0); 8504 SDLoc dl(N); 8505 const TargetOptions &Options = DAG.getTarget().Options; 8506 8507 // Constant fold FMA. 8508 if (isa<ConstantFPSDNode>(N0) && 8509 isa<ConstantFPSDNode>(N1) && 8510 isa<ConstantFPSDNode>(N2)) { 8511 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8512 } 8513 8514 if (Options.UnsafeFPMath) { 8515 if (N0CFP && N0CFP->isZero()) 8516 return N2; 8517 if (N1CFP && N1CFP->isZero()) 8518 return N2; 8519 } 8520 // TODO: The FMA node should have flags that propagate to these nodes. 8521 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8522 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8523 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8524 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8525 8526 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8527 if (isConstantFPBuildVectorOrConstantFP(N0) && 8528 !isConstantFPBuildVectorOrConstantFP(N1)) 8529 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8530 8531 // TODO: FMA nodes should have flags that propagate to the created nodes. 8532 // For now, create a Flags object for use with all unsafe math transforms. 8533 SDNodeFlags Flags; 8534 Flags.setUnsafeAlgebra(true); 8535 8536 if (Options.UnsafeFPMath) { 8537 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8538 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8539 isConstantFPBuildVectorOrConstantFP(N1) && 8540 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8541 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8542 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8543 &Flags), &Flags); 8544 } 8545 8546 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8547 if (N0.getOpcode() == ISD::FMUL && 8548 isConstantFPBuildVectorOrConstantFP(N1) && 8549 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8550 return DAG.getNode(ISD::FMA, dl, VT, 8551 N0.getOperand(0), 8552 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8553 &Flags), 8554 N2); 8555 } 8556 } 8557 8558 // (fma x, 1, y) -> (fadd x, y) 8559 // (fma x, -1, y) -> (fadd (fneg x), y) 8560 if (N1CFP) { 8561 if (N1CFP->isExactlyValue(1.0)) 8562 // TODO: The FMA node should have flags that propagate to this node. 8563 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8564 8565 if (N1CFP->isExactlyValue(-1.0) && 8566 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8567 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8568 AddToWorklist(RHSNeg.getNode()); 8569 // TODO: The FMA node should have flags that propagate to this node. 8570 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8571 } 8572 } 8573 8574 if (Options.UnsafeFPMath) { 8575 // (fma x, c, x) -> (fmul x, (c+1)) 8576 if (N1CFP && N0 == N2) { 8577 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8578 DAG.getNode(ISD::FADD, dl, VT, 8579 N1, DAG.getConstantFP(1.0, dl, VT), 8580 &Flags), &Flags); 8581 } 8582 8583 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8584 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8585 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8586 DAG.getNode(ISD::FADD, dl, VT, 8587 N1, DAG.getConstantFP(-1.0, dl, VT), 8588 &Flags), &Flags); 8589 } 8590 } 8591 8592 return SDValue(); 8593 } 8594 8595 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8596 // reciprocal. 8597 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8598 // Notice that this is not always beneficial. One reason is different target 8599 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8600 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8601 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8602 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8603 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8604 const SDNodeFlags *Flags = N->getFlags(); 8605 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8606 return SDValue(); 8607 8608 // Skip if current node is a reciprocal. 8609 SDValue N0 = N->getOperand(0); 8610 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8611 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8612 return SDValue(); 8613 8614 // Exit early if the target does not want this transform or if there can't 8615 // possibly be enough uses of the divisor to make the transform worthwhile. 8616 SDValue N1 = N->getOperand(1); 8617 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8618 if (!MinUses || N1->use_size() < MinUses) 8619 return SDValue(); 8620 8621 // Find all FDIV users of the same divisor. 8622 // Use a set because duplicates may be present in the user list. 8623 SetVector<SDNode *> Users; 8624 for (auto *U : N1->uses()) { 8625 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8626 // This division is eligible for optimization only if global unsafe math 8627 // is enabled or if this division allows reciprocal formation. 8628 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8629 Users.insert(U); 8630 } 8631 } 8632 8633 // Now that we have the actual number of divisor uses, make sure it meets 8634 // the minimum threshold specified by the target. 8635 if (Users.size() < MinUses) 8636 return SDValue(); 8637 8638 EVT VT = N->getValueType(0); 8639 SDLoc DL(N); 8640 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8641 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8642 8643 // Dividend / Divisor -> Dividend * Reciprocal 8644 for (auto *U : Users) { 8645 SDValue Dividend = U->getOperand(0); 8646 if (Dividend != FPOne) { 8647 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8648 Reciprocal, Flags); 8649 CombineTo(U, NewNode); 8650 } else if (U != Reciprocal.getNode()) { 8651 // In the absence of fast-math-flags, this user node is always the 8652 // same node as Reciprocal, but with FMF they may be different nodes. 8653 CombineTo(U, Reciprocal); 8654 } 8655 } 8656 return SDValue(N, 0); // N was replaced. 8657 } 8658 8659 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8660 SDValue N0 = N->getOperand(0); 8661 SDValue N1 = N->getOperand(1); 8662 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8663 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8664 EVT VT = N->getValueType(0); 8665 SDLoc DL(N); 8666 const TargetOptions &Options = DAG.getTarget().Options; 8667 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8668 8669 // fold vector ops 8670 if (VT.isVector()) 8671 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8672 return FoldedVOp; 8673 8674 // fold (fdiv c1, c2) -> c1/c2 8675 if (N0CFP && N1CFP) 8676 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8677 8678 if (Options.UnsafeFPMath) { 8679 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8680 if (N1CFP) { 8681 // Compute the reciprocal 1.0 / c2. 8682 APFloat N1APF = N1CFP->getValueAPF(); 8683 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8684 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8685 // Only do the transform if the reciprocal is a legal fp immediate that 8686 // isn't too nasty (eg NaN, denormal, ...). 8687 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8688 (!LegalOperations || 8689 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8690 // backend)... we should handle this gracefully after Legalize. 8691 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8692 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8693 TLI.isFPImmLegal(Recip, VT))) 8694 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8695 DAG.getConstantFP(Recip, DL, VT), Flags); 8696 } 8697 8698 // If this FDIV is part of a reciprocal square root, it may be folded 8699 // into a target-specific square root estimate instruction. 8700 if (N1.getOpcode() == ISD::FSQRT) { 8701 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8702 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8703 } 8704 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8705 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8706 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8707 Flags)) { 8708 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8709 AddToWorklist(RV.getNode()); 8710 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8711 } 8712 } else if (N1.getOpcode() == ISD::FP_ROUND && 8713 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8714 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8715 Flags)) { 8716 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8717 AddToWorklist(RV.getNode()); 8718 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8719 } 8720 } else if (N1.getOpcode() == ISD::FMUL) { 8721 // Look through an FMUL. Even though this won't remove the FDIV directly, 8722 // it's still worthwhile to get rid of the FSQRT if possible. 8723 SDValue SqrtOp; 8724 SDValue OtherOp; 8725 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8726 SqrtOp = N1.getOperand(0); 8727 OtherOp = N1.getOperand(1); 8728 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8729 SqrtOp = N1.getOperand(1); 8730 OtherOp = N1.getOperand(0); 8731 } 8732 if (SqrtOp.getNode()) { 8733 // We found a FSQRT, so try to make this fold: 8734 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8735 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8736 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8737 AddToWorklist(RV.getNode()); 8738 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8739 } 8740 } 8741 } 8742 8743 // Fold into a reciprocal estimate and multiply instead of a real divide. 8744 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8745 AddToWorklist(RV.getNode()); 8746 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8747 } 8748 } 8749 8750 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8751 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8752 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8753 // Both can be negated for free, check to see if at least one is cheaper 8754 // negated. 8755 if (LHSNeg == 2 || RHSNeg == 2) 8756 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8757 GetNegatedExpression(N0, DAG, LegalOperations), 8758 GetNegatedExpression(N1, DAG, LegalOperations), 8759 Flags); 8760 } 8761 } 8762 8763 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8764 return CombineRepeatedDivisors; 8765 8766 return SDValue(); 8767 } 8768 8769 SDValue DAGCombiner::visitFREM(SDNode *N) { 8770 SDValue N0 = N->getOperand(0); 8771 SDValue N1 = N->getOperand(1); 8772 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8773 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8774 EVT VT = N->getValueType(0); 8775 8776 // fold (frem c1, c2) -> fmod(c1,c2) 8777 if (N0CFP && N1CFP) 8778 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8779 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8780 8781 return SDValue(); 8782 } 8783 8784 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8785 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8786 return SDValue(); 8787 8788 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8789 // For now, create a Flags object for use with all unsafe math transforms. 8790 SDNodeFlags Flags; 8791 Flags.setUnsafeAlgebra(true); 8792 8793 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8794 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8795 if (!RV) 8796 return SDValue(); 8797 8798 EVT VT = RV.getValueType(); 8799 SDLoc DL(N); 8800 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8801 AddToWorklist(RV.getNode()); 8802 8803 // Unfortunately, RV is now NaN if the input was exactly 0. 8804 // Select out this case and force the answer to 0. 8805 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8806 EVT CCVT = getSetCCResultType(VT); 8807 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8808 AddToWorklist(ZeroCmp.getNode()); 8809 AddToWorklist(RV.getNode()); 8810 8811 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8812 ZeroCmp, Zero, RV); 8813 } 8814 8815 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8816 /// copysign(x, fp_round(y)) -> copysign(x, y) 8817 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8818 SDValue N1 = N->getOperand(1); 8819 if ((N1.getOpcode() == ISD::FP_EXTEND || 8820 N1.getOpcode() == ISD::FP_ROUND)) { 8821 // Do not optimize out type conversion of f128 type yet. 8822 // For some targets like x86_64, configuration is changed to keep one f128 8823 // value in one SSE register, but instruction selection cannot handle 8824 // FCOPYSIGN on SSE registers yet. 8825 EVT N1VT = N1->getValueType(0); 8826 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8827 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8828 } 8829 return false; 8830 } 8831 8832 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8833 SDValue N0 = N->getOperand(0); 8834 SDValue N1 = N->getOperand(1); 8835 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8836 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8837 EVT VT = N->getValueType(0); 8838 8839 if (N0CFP && N1CFP) // Constant fold 8840 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8841 8842 if (N1CFP) { 8843 const APFloat& V = N1CFP->getValueAPF(); 8844 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8845 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8846 if (!V.isNegative()) { 8847 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8848 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8849 } else { 8850 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8851 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8852 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8853 } 8854 } 8855 8856 // copysign(fabs(x), y) -> copysign(x, y) 8857 // copysign(fneg(x), y) -> copysign(x, y) 8858 // copysign(copysign(x,z), y) -> copysign(x, y) 8859 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8860 N0.getOpcode() == ISD::FCOPYSIGN) 8861 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8862 N0.getOperand(0), N1); 8863 8864 // copysign(x, abs(y)) -> abs(x) 8865 if (N1.getOpcode() == ISD::FABS) 8866 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8867 8868 // copysign(x, copysign(y,z)) -> copysign(x, z) 8869 if (N1.getOpcode() == ISD::FCOPYSIGN) 8870 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8871 N0, N1.getOperand(1)); 8872 8873 // copysign(x, fp_extend(y)) -> copysign(x, y) 8874 // copysign(x, fp_round(y)) -> copysign(x, y) 8875 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 8876 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8877 N0, N1.getOperand(0)); 8878 8879 return SDValue(); 8880 } 8881 8882 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8883 SDValue N0 = N->getOperand(0); 8884 EVT VT = N->getValueType(0); 8885 EVT OpVT = N0.getValueType(); 8886 8887 // fold (sint_to_fp c1) -> c1fp 8888 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8889 // ...but only if the target supports immediate floating-point values 8890 (!LegalOperations || 8891 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8892 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8893 8894 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8895 // but UINT_TO_FP is legal on this target, try to convert. 8896 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8897 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8898 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8899 if (DAG.SignBitIsZero(N0)) 8900 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8901 } 8902 8903 // The next optimizations are desirable only if SELECT_CC can be lowered. 8904 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8905 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8906 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8907 !VT.isVector() && 8908 (!LegalOperations || 8909 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8910 SDLoc DL(N); 8911 SDValue Ops[] = 8912 { N0.getOperand(0), N0.getOperand(1), 8913 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8914 N0.getOperand(2) }; 8915 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8916 } 8917 8918 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8919 // (select_cc x, y, 1.0, 0.0,, cc) 8920 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8921 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8922 (!LegalOperations || 8923 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8924 SDLoc DL(N); 8925 SDValue Ops[] = 8926 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8927 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8928 N0.getOperand(0).getOperand(2) }; 8929 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8930 } 8931 } 8932 8933 return SDValue(); 8934 } 8935 8936 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8937 SDValue N0 = N->getOperand(0); 8938 EVT VT = N->getValueType(0); 8939 EVT OpVT = N0.getValueType(); 8940 8941 // fold (uint_to_fp c1) -> c1fp 8942 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8943 // ...but only if the target supports immediate floating-point values 8944 (!LegalOperations || 8945 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8946 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8947 8948 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8949 // but SINT_TO_FP is legal on this target, try to convert. 8950 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8951 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8952 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8953 if (DAG.SignBitIsZero(N0)) 8954 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8955 } 8956 8957 // The next optimizations are desirable only if SELECT_CC can be lowered. 8958 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8959 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8960 8961 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8962 (!LegalOperations || 8963 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8964 SDLoc DL(N); 8965 SDValue Ops[] = 8966 { N0.getOperand(0), N0.getOperand(1), 8967 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8968 N0.getOperand(2) }; 8969 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8970 } 8971 } 8972 8973 return SDValue(); 8974 } 8975 8976 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8977 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8978 SDValue N0 = N->getOperand(0); 8979 EVT VT = N->getValueType(0); 8980 8981 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8982 return SDValue(); 8983 8984 SDValue Src = N0.getOperand(0); 8985 EVT SrcVT = Src.getValueType(); 8986 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8987 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8988 8989 // We can safely assume the conversion won't overflow the output range, 8990 // because (for example) (uint8_t)18293.f is undefined behavior. 8991 8992 // Since we can assume the conversion won't overflow, our decision as to 8993 // whether the input will fit in the float should depend on the minimum 8994 // of the input range and output range. 8995 8996 // This means this is also safe for a signed input and unsigned output, since 8997 // a negative input would lead to undefined behavior. 8998 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8999 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9000 unsigned ActualSize = std::min(InputSize, OutputSize); 9001 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9002 9003 // We can only fold away the float conversion if the input range can be 9004 // represented exactly in the float range. 9005 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9006 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9007 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9008 : ISD::ZERO_EXTEND; 9009 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9010 } 9011 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9012 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9013 return DAG.getBitcast(VT, Src); 9014 } 9015 return SDValue(); 9016 } 9017 9018 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9019 SDValue N0 = N->getOperand(0); 9020 EVT VT = N->getValueType(0); 9021 9022 // fold (fp_to_sint c1fp) -> c1 9023 if (isConstantFPBuildVectorOrConstantFP(N0)) 9024 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9025 9026 return FoldIntToFPToInt(N, DAG); 9027 } 9028 9029 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9030 SDValue N0 = N->getOperand(0); 9031 EVT VT = N->getValueType(0); 9032 9033 // fold (fp_to_uint c1fp) -> c1 9034 if (isConstantFPBuildVectorOrConstantFP(N0)) 9035 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9036 9037 return FoldIntToFPToInt(N, DAG); 9038 } 9039 9040 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9041 SDValue N0 = N->getOperand(0); 9042 SDValue N1 = N->getOperand(1); 9043 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9044 EVT VT = N->getValueType(0); 9045 9046 // fold (fp_round c1fp) -> c1fp 9047 if (N0CFP) 9048 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9049 9050 // fold (fp_round (fp_extend x)) -> x 9051 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9052 return N0.getOperand(0); 9053 9054 // fold (fp_round (fp_round x)) -> (fp_round x) 9055 if (N0.getOpcode() == ISD::FP_ROUND) { 9056 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9057 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9058 9059 // Skip this folding if it results in an fp_round from f80 to f16. 9060 // 9061 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9062 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9063 // instructions from f32 or f64. Moreover, the first (value-preserving) 9064 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9065 // x86. 9066 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9067 return SDValue(); 9068 9069 // If the first fp_round isn't a value preserving truncation, it might 9070 // introduce a tie in the second fp_round, that wouldn't occur in the 9071 // single-step fp_round we want to fold to. 9072 // In other words, double rounding isn't the same as rounding. 9073 // Also, this is a value preserving truncation iff both fp_round's are. 9074 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9075 SDLoc DL(N); 9076 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9077 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9078 } 9079 } 9080 9081 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9082 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9083 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9084 N0.getOperand(0), N1); 9085 AddToWorklist(Tmp.getNode()); 9086 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9087 Tmp, N0.getOperand(1)); 9088 } 9089 9090 return SDValue(); 9091 } 9092 9093 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9094 SDValue N0 = N->getOperand(0); 9095 EVT VT = N->getValueType(0); 9096 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9097 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9098 9099 // fold (fp_round_inreg c1fp) -> c1fp 9100 if (N0CFP && isTypeLegal(EVT)) { 9101 SDLoc DL(N); 9102 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9103 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9104 } 9105 9106 return SDValue(); 9107 } 9108 9109 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9110 SDValue N0 = N->getOperand(0); 9111 EVT VT = N->getValueType(0); 9112 9113 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9114 if (N->hasOneUse() && 9115 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9116 return SDValue(); 9117 9118 // fold (fp_extend c1fp) -> c1fp 9119 if (isConstantFPBuildVectorOrConstantFP(N0)) 9120 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9121 9122 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9123 if (N0.getOpcode() == ISD::FP16_TO_FP && 9124 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9125 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9126 9127 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9128 // value of X. 9129 if (N0.getOpcode() == ISD::FP_ROUND 9130 && N0.getNode()->getConstantOperandVal(1) == 1) { 9131 SDValue In = N0.getOperand(0); 9132 if (In.getValueType() == VT) return In; 9133 if (VT.bitsLT(In.getValueType())) 9134 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9135 In, N0.getOperand(1)); 9136 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9137 } 9138 9139 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9140 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9141 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9142 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9143 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9144 LN0->getChain(), 9145 LN0->getBasePtr(), N0.getValueType(), 9146 LN0->getMemOperand()); 9147 CombineTo(N, ExtLoad); 9148 CombineTo(N0.getNode(), 9149 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9150 N0.getValueType(), ExtLoad, 9151 DAG.getIntPtrConstant(1, SDLoc(N0))), 9152 ExtLoad.getValue(1)); 9153 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9154 } 9155 9156 return SDValue(); 9157 } 9158 9159 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9160 SDValue N0 = N->getOperand(0); 9161 EVT VT = N->getValueType(0); 9162 9163 // fold (fceil c1) -> fceil(c1) 9164 if (isConstantFPBuildVectorOrConstantFP(N0)) 9165 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9166 9167 return SDValue(); 9168 } 9169 9170 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9171 SDValue N0 = N->getOperand(0); 9172 EVT VT = N->getValueType(0); 9173 9174 // fold (ftrunc c1) -> ftrunc(c1) 9175 if (isConstantFPBuildVectorOrConstantFP(N0)) 9176 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9177 9178 return SDValue(); 9179 } 9180 9181 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9182 SDValue N0 = N->getOperand(0); 9183 EVT VT = N->getValueType(0); 9184 9185 // fold (ffloor c1) -> ffloor(c1) 9186 if (isConstantFPBuildVectorOrConstantFP(N0)) 9187 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9188 9189 return SDValue(); 9190 } 9191 9192 // FIXME: FNEG and FABS have a lot in common; refactor. 9193 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9194 SDValue N0 = N->getOperand(0); 9195 EVT VT = N->getValueType(0); 9196 9197 // Constant fold FNEG. 9198 if (isConstantFPBuildVectorOrConstantFP(N0)) 9199 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9200 9201 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9202 &DAG.getTarget().Options)) 9203 return GetNegatedExpression(N0, DAG, LegalOperations); 9204 9205 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9206 // constant pool values. 9207 if (!TLI.isFNegFree(VT) && 9208 N0.getOpcode() == ISD::BITCAST && 9209 N0.getNode()->hasOneUse()) { 9210 SDValue Int = N0.getOperand(0); 9211 EVT IntVT = Int.getValueType(); 9212 if (IntVT.isInteger() && !IntVT.isVector()) { 9213 APInt SignMask; 9214 if (N0.getValueType().isVector()) { 9215 // For a vector, get a mask such as 0x80... per scalar element 9216 // and splat it. 9217 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9218 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9219 } else { 9220 // For a scalar, just generate 0x80... 9221 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9222 } 9223 SDLoc DL0(N0); 9224 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9225 DAG.getConstant(SignMask, DL0, IntVT)); 9226 AddToWorklist(Int.getNode()); 9227 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9228 } 9229 } 9230 9231 // (fneg (fmul c, x)) -> (fmul -c, x) 9232 if (N0.getOpcode() == ISD::FMUL && 9233 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9234 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9235 if (CFP1) { 9236 APFloat CVal = CFP1->getValueAPF(); 9237 CVal.changeSign(); 9238 if (Level >= AfterLegalizeDAG && 9239 (TLI.isFPImmLegal(CVal, VT) || 9240 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9241 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9242 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9243 N0.getOperand(1)), 9244 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9245 } 9246 } 9247 9248 return SDValue(); 9249 } 9250 9251 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9252 SDValue N0 = N->getOperand(0); 9253 SDValue N1 = N->getOperand(1); 9254 EVT VT = N->getValueType(0); 9255 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9256 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9257 9258 if (N0CFP && N1CFP) { 9259 const APFloat &C0 = N0CFP->getValueAPF(); 9260 const APFloat &C1 = N1CFP->getValueAPF(); 9261 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9262 } 9263 9264 // Canonicalize to constant on RHS. 9265 if (isConstantFPBuildVectorOrConstantFP(N0) && 9266 !isConstantFPBuildVectorOrConstantFP(N1)) 9267 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9268 9269 return SDValue(); 9270 } 9271 9272 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9273 SDValue N0 = N->getOperand(0); 9274 SDValue N1 = N->getOperand(1); 9275 EVT VT = N->getValueType(0); 9276 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9277 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9278 9279 if (N0CFP && N1CFP) { 9280 const APFloat &C0 = N0CFP->getValueAPF(); 9281 const APFloat &C1 = N1CFP->getValueAPF(); 9282 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9283 } 9284 9285 // Canonicalize to constant on RHS. 9286 if (isConstantFPBuildVectorOrConstantFP(N0) && 9287 !isConstantFPBuildVectorOrConstantFP(N1)) 9288 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9289 9290 return SDValue(); 9291 } 9292 9293 SDValue DAGCombiner::visitFABS(SDNode *N) { 9294 SDValue N0 = N->getOperand(0); 9295 EVT VT = N->getValueType(0); 9296 9297 // fold (fabs c1) -> fabs(c1) 9298 if (isConstantFPBuildVectorOrConstantFP(N0)) 9299 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9300 9301 // fold (fabs (fabs x)) -> (fabs x) 9302 if (N0.getOpcode() == ISD::FABS) 9303 return N->getOperand(0); 9304 9305 // fold (fabs (fneg x)) -> (fabs x) 9306 // fold (fabs (fcopysign x, y)) -> (fabs x) 9307 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9308 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9309 9310 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9311 // constant pool values. 9312 if (!TLI.isFAbsFree(VT) && 9313 N0.getOpcode() == ISD::BITCAST && 9314 N0.getNode()->hasOneUse()) { 9315 SDValue Int = N0.getOperand(0); 9316 EVT IntVT = Int.getValueType(); 9317 if (IntVT.isInteger() && !IntVT.isVector()) { 9318 APInt SignMask; 9319 if (N0.getValueType().isVector()) { 9320 // For a vector, get a mask such as 0x7f... per scalar element 9321 // and splat it. 9322 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9323 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9324 } else { 9325 // For a scalar, just generate 0x7f... 9326 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9327 } 9328 SDLoc DL(N0); 9329 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9330 DAG.getConstant(SignMask, DL, IntVT)); 9331 AddToWorklist(Int.getNode()); 9332 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9333 } 9334 } 9335 9336 return SDValue(); 9337 } 9338 9339 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9340 SDValue Chain = N->getOperand(0); 9341 SDValue N1 = N->getOperand(1); 9342 SDValue N2 = N->getOperand(2); 9343 9344 // If N is a constant we could fold this into a fallthrough or unconditional 9345 // branch. However that doesn't happen very often in normal code, because 9346 // Instcombine/SimplifyCFG should have handled the available opportunities. 9347 // If we did this folding here, it would be necessary to update the 9348 // MachineBasicBlock CFG, which is awkward. 9349 9350 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9351 // on the target. 9352 if (N1.getOpcode() == ISD::SETCC && 9353 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9354 N1.getOperand(0).getValueType())) { 9355 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9356 Chain, N1.getOperand(2), 9357 N1.getOperand(0), N1.getOperand(1), N2); 9358 } 9359 9360 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9361 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9362 (N1.getOperand(0).hasOneUse() && 9363 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9364 SDNode *Trunc = nullptr; 9365 if (N1.getOpcode() == ISD::TRUNCATE) { 9366 // Look pass the truncate. 9367 Trunc = N1.getNode(); 9368 N1 = N1.getOperand(0); 9369 } 9370 9371 // Match this pattern so that we can generate simpler code: 9372 // 9373 // %a = ... 9374 // %b = and i32 %a, 2 9375 // %c = srl i32 %b, 1 9376 // brcond i32 %c ... 9377 // 9378 // into 9379 // 9380 // %a = ... 9381 // %b = and i32 %a, 2 9382 // %c = setcc eq %b, 0 9383 // brcond %c ... 9384 // 9385 // This applies only when the AND constant value has one bit set and the 9386 // SRL constant is equal to the log2 of the AND constant. The back-end is 9387 // smart enough to convert the result into a TEST/JMP sequence. 9388 SDValue Op0 = N1.getOperand(0); 9389 SDValue Op1 = N1.getOperand(1); 9390 9391 if (Op0.getOpcode() == ISD::AND && 9392 Op1.getOpcode() == ISD::Constant) { 9393 SDValue AndOp1 = Op0.getOperand(1); 9394 9395 if (AndOp1.getOpcode() == ISD::Constant) { 9396 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9397 9398 if (AndConst.isPowerOf2() && 9399 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9400 SDLoc DL(N); 9401 SDValue SetCC = 9402 DAG.getSetCC(DL, 9403 getSetCCResultType(Op0.getValueType()), 9404 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9405 ISD::SETNE); 9406 9407 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9408 MVT::Other, Chain, SetCC, N2); 9409 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9410 // will convert it back to (X & C1) >> C2. 9411 CombineTo(N, NewBRCond, false); 9412 // Truncate is dead. 9413 if (Trunc) 9414 deleteAndRecombine(Trunc); 9415 // Replace the uses of SRL with SETCC 9416 WorklistRemover DeadNodes(*this); 9417 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9418 deleteAndRecombine(N1.getNode()); 9419 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9420 } 9421 } 9422 } 9423 9424 if (Trunc) 9425 // Restore N1 if the above transformation doesn't match. 9426 N1 = N->getOperand(1); 9427 } 9428 9429 // Transform br(xor(x, y)) -> br(x != y) 9430 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9431 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9432 SDNode *TheXor = N1.getNode(); 9433 SDValue Op0 = TheXor->getOperand(0); 9434 SDValue Op1 = TheXor->getOperand(1); 9435 if (Op0.getOpcode() == Op1.getOpcode()) { 9436 // Avoid missing important xor optimizations. 9437 if (SDValue Tmp = visitXOR(TheXor)) { 9438 if (Tmp.getNode() != TheXor) { 9439 DEBUG(dbgs() << "\nReplacing.8 "; 9440 TheXor->dump(&DAG); 9441 dbgs() << "\nWith: "; 9442 Tmp.getNode()->dump(&DAG); 9443 dbgs() << '\n'); 9444 WorklistRemover DeadNodes(*this); 9445 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9446 deleteAndRecombine(TheXor); 9447 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9448 MVT::Other, Chain, Tmp, N2); 9449 } 9450 9451 // visitXOR has changed XOR's operands or replaced the XOR completely, 9452 // bail out. 9453 return SDValue(N, 0); 9454 } 9455 } 9456 9457 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9458 bool Equal = false; 9459 if (isOneConstant(Op0) && Op0.hasOneUse() && 9460 Op0.getOpcode() == ISD::XOR) { 9461 TheXor = Op0.getNode(); 9462 Equal = true; 9463 } 9464 9465 EVT SetCCVT = N1.getValueType(); 9466 if (LegalTypes) 9467 SetCCVT = getSetCCResultType(SetCCVT); 9468 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9469 SetCCVT, 9470 Op0, Op1, 9471 Equal ? ISD::SETEQ : ISD::SETNE); 9472 // Replace the uses of XOR with SETCC 9473 WorklistRemover DeadNodes(*this); 9474 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9475 deleteAndRecombine(N1.getNode()); 9476 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9477 MVT::Other, Chain, SetCC, N2); 9478 } 9479 } 9480 9481 return SDValue(); 9482 } 9483 9484 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9485 // 9486 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9487 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9488 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9489 9490 // If N is a constant we could fold this into a fallthrough or unconditional 9491 // branch. However that doesn't happen very often in normal code, because 9492 // Instcombine/SimplifyCFG should have handled the available opportunities. 9493 // If we did this folding here, it would be necessary to update the 9494 // MachineBasicBlock CFG, which is awkward. 9495 9496 // Use SimplifySetCC to simplify SETCC's. 9497 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9498 CondLHS, CondRHS, CC->get(), SDLoc(N), 9499 false); 9500 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9501 9502 // fold to a simpler setcc 9503 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9504 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9505 N->getOperand(0), Simp.getOperand(2), 9506 Simp.getOperand(0), Simp.getOperand(1), 9507 N->getOperand(4)); 9508 9509 return SDValue(); 9510 } 9511 9512 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9513 /// and that N may be folded in the load / store addressing mode. 9514 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9515 SelectionDAG &DAG, 9516 const TargetLowering &TLI) { 9517 EVT VT; 9518 unsigned AS; 9519 9520 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9521 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9522 return false; 9523 VT = LD->getMemoryVT(); 9524 AS = LD->getAddressSpace(); 9525 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9526 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9527 return false; 9528 VT = ST->getMemoryVT(); 9529 AS = ST->getAddressSpace(); 9530 } else 9531 return false; 9532 9533 TargetLowering::AddrMode AM; 9534 if (N->getOpcode() == ISD::ADD) { 9535 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9536 if (Offset) 9537 // [reg +/- imm] 9538 AM.BaseOffs = Offset->getSExtValue(); 9539 else 9540 // [reg +/- reg] 9541 AM.Scale = 1; 9542 } else if (N->getOpcode() == ISD::SUB) { 9543 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9544 if (Offset) 9545 // [reg +/- imm] 9546 AM.BaseOffs = -Offset->getSExtValue(); 9547 else 9548 // [reg +/- reg] 9549 AM.Scale = 1; 9550 } else 9551 return false; 9552 9553 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9554 VT.getTypeForEVT(*DAG.getContext()), AS); 9555 } 9556 9557 /// Try turning a load/store into a pre-indexed load/store when the base 9558 /// pointer is an add or subtract and it has other uses besides the load/store. 9559 /// After the transformation, the new indexed load/store has effectively folded 9560 /// the add/subtract in and all of its other uses are redirected to the 9561 /// new load/store. 9562 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9563 if (Level < AfterLegalizeDAG) 9564 return false; 9565 9566 bool isLoad = true; 9567 SDValue Ptr; 9568 EVT VT; 9569 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9570 if (LD->isIndexed()) 9571 return false; 9572 VT = LD->getMemoryVT(); 9573 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9574 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9575 return false; 9576 Ptr = LD->getBasePtr(); 9577 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9578 if (ST->isIndexed()) 9579 return false; 9580 VT = ST->getMemoryVT(); 9581 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9582 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9583 return false; 9584 Ptr = ST->getBasePtr(); 9585 isLoad = false; 9586 } else { 9587 return false; 9588 } 9589 9590 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9591 // out. There is no reason to make this a preinc/predec. 9592 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9593 Ptr.getNode()->hasOneUse()) 9594 return false; 9595 9596 // Ask the target to do addressing mode selection. 9597 SDValue BasePtr; 9598 SDValue Offset; 9599 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9600 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9601 return false; 9602 9603 // Backends without true r+i pre-indexed forms may need to pass a 9604 // constant base with a variable offset so that constant coercion 9605 // will work with the patterns in canonical form. 9606 bool Swapped = false; 9607 if (isa<ConstantSDNode>(BasePtr)) { 9608 std::swap(BasePtr, Offset); 9609 Swapped = true; 9610 } 9611 9612 // Don't create a indexed load / store with zero offset. 9613 if (isNullConstant(Offset)) 9614 return false; 9615 9616 // Try turning it into a pre-indexed load / store except when: 9617 // 1) The new base ptr is a frame index. 9618 // 2) If N is a store and the new base ptr is either the same as or is a 9619 // predecessor of the value being stored. 9620 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9621 // that would create a cycle. 9622 // 4) All uses are load / store ops that use it as old base ptr. 9623 9624 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9625 // (plus the implicit offset) to a register to preinc anyway. 9626 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9627 return false; 9628 9629 // Check #2. 9630 if (!isLoad) { 9631 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9632 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9633 return false; 9634 } 9635 9636 // Caches for hasPredecessorHelper. 9637 SmallPtrSet<const SDNode *, 32> Visited; 9638 SmallVector<const SDNode *, 16> Worklist; 9639 Worklist.push_back(N); 9640 9641 // If the offset is a constant, there may be other adds of constants that 9642 // can be folded with this one. We should do this to avoid having to keep 9643 // a copy of the original base pointer. 9644 SmallVector<SDNode *, 16> OtherUses; 9645 if (isa<ConstantSDNode>(Offset)) 9646 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9647 UE = BasePtr.getNode()->use_end(); 9648 UI != UE; ++UI) { 9649 SDUse &Use = UI.getUse(); 9650 // Skip the use that is Ptr and uses of other results from BasePtr's 9651 // node (important for nodes that return multiple results). 9652 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9653 continue; 9654 9655 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9656 continue; 9657 9658 if (Use.getUser()->getOpcode() != ISD::ADD && 9659 Use.getUser()->getOpcode() != ISD::SUB) { 9660 OtherUses.clear(); 9661 break; 9662 } 9663 9664 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9665 if (!isa<ConstantSDNode>(Op1)) { 9666 OtherUses.clear(); 9667 break; 9668 } 9669 9670 // FIXME: In some cases, we can be smarter about this. 9671 if (Op1.getValueType() != Offset.getValueType()) { 9672 OtherUses.clear(); 9673 break; 9674 } 9675 9676 OtherUses.push_back(Use.getUser()); 9677 } 9678 9679 if (Swapped) 9680 std::swap(BasePtr, Offset); 9681 9682 // Now check for #3 and #4. 9683 bool RealUse = false; 9684 9685 for (SDNode *Use : Ptr.getNode()->uses()) { 9686 if (Use == N) 9687 continue; 9688 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9689 return false; 9690 9691 // If Ptr may be folded in addressing mode of other use, then it's 9692 // not profitable to do this transformation. 9693 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9694 RealUse = true; 9695 } 9696 9697 if (!RealUse) 9698 return false; 9699 9700 SDValue Result; 9701 if (isLoad) 9702 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9703 BasePtr, Offset, AM); 9704 else 9705 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9706 BasePtr, Offset, AM); 9707 ++PreIndexedNodes; 9708 ++NodesCombined; 9709 DEBUG(dbgs() << "\nReplacing.4 "; 9710 N->dump(&DAG); 9711 dbgs() << "\nWith: "; 9712 Result.getNode()->dump(&DAG); 9713 dbgs() << '\n'); 9714 WorklistRemover DeadNodes(*this); 9715 if (isLoad) { 9716 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9717 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9718 } else { 9719 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9720 } 9721 9722 // Finally, since the node is now dead, remove it from the graph. 9723 deleteAndRecombine(N); 9724 9725 if (Swapped) 9726 std::swap(BasePtr, Offset); 9727 9728 // Replace other uses of BasePtr that can be updated to use Ptr 9729 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9730 unsigned OffsetIdx = 1; 9731 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9732 OffsetIdx = 0; 9733 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9734 BasePtr.getNode() && "Expected BasePtr operand"); 9735 9736 // We need to replace ptr0 in the following expression: 9737 // x0 * offset0 + y0 * ptr0 = t0 9738 // knowing that 9739 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9740 // 9741 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9742 // indexed load/store and the expresion that needs to be re-written. 9743 // 9744 // Therefore, we have: 9745 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9746 9747 ConstantSDNode *CN = 9748 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9749 int X0, X1, Y0, Y1; 9750 APInt Offset0 = CN->getAPIntValue(); 9751 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9752 9753 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9754 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9755 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9756 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9757 9758 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9759 9760 APInt CNV = Offset0; 9761 if (X0 < 0) CNV = -CNV; 9762 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9763 else CNV = CNV - Offset1; 9764 9765 SDLoc DL(OtherUses[i]); 9766 9767 // We can now generate the new expression. 9768 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9769 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9770 9771 SDValue NewUse = DAG.getNode(Opcode, 9772 DL, 9773 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9774 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9775 deleteAndRecombine(OtherUses[i]); 9776 } 9777 9778 // Replace the uses of Ptr with uses of the updated base value. 9779 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9780 deleteAndRecombine(Ptr.getNode()); 9781 9782 return true; 9783 } 9784 9785 /// Try to combine a load/store with a add/sub of the base pointer node into a 9786 /// post-indexed load/store. The transformation folded the add/subtract into the 9787 /// new indexed load/store effectively and all of its uses are redirected to the 9788 /// new load/store. 9789 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9790 if (Level < AfterLegalizeDAG) 9791 return false; 9792 9793 bool isLoad = true; 9794 SDValue Ptr; 9795 EVT VT; 9796 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9797 if (LD->isIndexed()) 9798 return false; 9799 VT = LD->getMemoryVT(); 9800 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9801 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9802 return false; 9803 Ptr = LD->getBasePtr(); 9804 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9805 if (ST->isIndexed()) 9806 return false; 9807 VT = ST->getMemoryVT(); 9808 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9809 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9810 return false; 9811 Ptr = ST->getBasePtr(); 9812 isLoad = false; 9813 } else { 9814 return false; 9815 } 9816 9817 if (Ptr.getNode()->hasOneUse()) 9818 return false; 9819 9820 for (SDNode *Op : Ptr.getNode()->uses()) { 9821 if (Op == N || 9822 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9823 continue; 9824 9825 SDValue BasePtr; 9826 SDValue Offset; 9827 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9828 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9829 // Don't create a indexed load / store with zero offset. 9830 if (isNullConstant(Offset)) 9831 continue; 9832 9833 // Try turning it into a post-indexed load / store except when 9834 // 1) All uses are load / store ops that use it as base ptr (and 9835 // it may be folded as addressing mmode). 9836 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9837 // nor a successor of N. Otherwise, if Op is folded that would 9838 // create a cycle. 9839 9840 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9841 continue; 9842 9843 // Check for #1. 9844 bool TryNext = false; 9845 for (SDNode *Use : BasePtr.getNode()->uses()) { 9846 if (Use == Ptr.getNode()) 9847 continue; 9848 9849 // If all the uses are load / store addresses, then don't do the 9850 // transformation. 9851 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9852 bool RealUse = false; 9853 for (SDNode *UseUse : Use->uses()) { 9854 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9855 RealUse = true; 9856 } 9857 9858 if (!RealUse) { 9859 TryNext = true; 9860 break; 9861 } 9862 } 9863 } 9864 9865 if (TryNext) 9866 continue; 9867 9868 // Check for #2 9869 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9870 SDValue Result = isLoad 9871 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9872 BasePtr, Offset, AM) 9873 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9874 BasePtr, Offset, AM); 9875 ++PostIndexedNodes; 9876 ++NodesCombined; 9877 DEBUG(dbgs() << "\nReplacing.5 "; 9878 N->dump(&DAG); 9879 dbgs() << "\nWith: "; 9880 Result.getNode()->dump(&DAG); 9881 dbgs() << '\n'); 9882 WorklistRemover DeadNodes(*this); 9883 if (isLoad) { 9884 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9885 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9886 } else { 9887 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9888 } 9889 9890 // Finally, since the node is now dead, remove it from the graph. 9891 deleteAndRecombine(N); 9892 9893 // Replace the uses of Use with uses of the updated base value. 9894 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9895 Result.getValue(isLoad ? 1 : 0)); 9896 deleteAndRecombine(Op); 9897 return true; 9898 } 9899 } 9900 } 9901 9902 return false; 9903 } 9904 9905 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9906 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9907 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9908 assert(AM != ISD::UNINDEXED); 9909 SDValue BP = LD->getOperand(1); 9910 SDValue Inc = LD->getOperand(2); 9911 9912 // Some backends use TargetConstants for load offsets, but don't expect 9913 // TargetConstants in general ADD nodes. We can convert these constants into 9914 // regular Constants (if the constant is not opaque). 9915 assert((Inc.getOpcode() != ISD::TargetConstant || 9916 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9917 "Cannot split out indexing using opaque target constants"); 9918 if (Inc.getOpcode() == ISD::TargetConstant) { 9919 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9920 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9921 ConstInc->getValueType(0)); 9922 } 9923 9924 unsigned Opc = 9925 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9926 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9927 } 9928 9929 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9930 LoadSDNode *LD = cast<LoadSDNode>(N); 9931 SDValue Chain = LD->getChain(); 9932 SDValue Ptr = LD->getBasePtr(); 9933 9934 // If load is not volatile and there are no uses of the loaded value (and 9935 // the updated indexed value in case of indexed loads), change uses of the 9936 // chain value into uses of the chain input (i.e. delete the dead load). 9937 if (!LD->isVolatile()) { 9938 if (N->getValueType(1) == MVT::Other) { 9939 // Unindexed loads. 9940 if (!N->hasAnyUseOfValue(0)) { 9941 // It's not safe to use the two value CombineTo variant here. e.g. 9942 // v1, chain2 = load chain1, loc 9943 // v2, chain3 = load chain2, loc 9944 // v3 = add v2, c 9945 // Now we replace use of chain2 with chain1. This makes the second load 9946 // isomorphic to the one we are deleting, and thus makes this load live. 9947 DEBUG(dbgs() << "\nReplacing.6 "; 9948 N->dump(&DAG); 9949 dbgs() << "\nWith chain: "; 9950 Chain.getNode()->dump(&DAG); 9951 dbgs() << "\n"); 9952 WorklistRemover DeadNodes(*this); 9953 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9954 9955 if (N->use_empty()) 9956 deleteAndRecombine(N); 9957 9958 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9959 } 9960 } else { 9961 // Indexed loads. 9962 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9963 9964 // If this load has an opaque TargetConstant offset, then we cannot split 9965 // the indexing into an add/sub directly (that TargetConstant may not be 9966 // valid for a different type of node, and we cannot convert an opaque 9967 // target constant into a regular constant). 9968 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9969 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9970 9971 if (!N->hasAnyUseOfValue(0) && 9972 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9973 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9974 SDValue Index; 9975 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9976 Index = SplitIndexingFromLoad(LD); 9977 // Try to fold the base pointer arithmetic into subsequent loads and 9978 // stores. 9979 AddUsersToWorklist(N); 9980 } else 9981 Index = DAG.getUNDEF(N->getValueType(1)); 9982 DEBUG(dbgs() << "\nReplacing.7 "; 9983 N->dump(&DAG); 9984 dbgs() << "\nWith: "; 9985 Undef.getNode()->dump(&DAG); 9986 dbgs() << " and 2 other values\n"); 9987 WorklistRemover DeadNodes(*this); 9988 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9989 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9990 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9991 deleteAndRecombine(N); 9992 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9993 } 9994 } 9995 } 9996 9997 // If this load is directly stored, replace the load value with the stored 9998 // value. 9999 // TODO: Handle store large -> read small portion. 10000 // TODO: Handle TRUNCSTORE/LOADEXT 10001 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 10002 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10003 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10004 if (PrevST->getBasePtr() == Ptr && 10005 PrevST->getValue().getValueType() == N->getValueType(0)) 10006 return CombineTo(N, Chain.getOperand(1), Chain); 10007 } 10008 } 10009 10010 // Try to infer better alignment information than the load already has. 10011 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10012 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10013 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10014 SDValue NewLoad = 10015 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 10016 LD->getValueType(0), 10017 Chain, Ptr, LD->getPointerInfo(), 10018 LD->getMemoryVT(), 10019 LD->isVolatile(), LD->isNonTemporal(), 10020 LD->isInvariant(), Align, LD->getAAInfo()); 10021 if (NewLoad.getNode() != N) 10022 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10023 } 10024 } 10025 } 10026 10027 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10028 : DAG.getSubtarget().useAA(); 10029 #ifndef NDEBUG 10030 if (CombinerAAOnlyFunc.getNumOccurrences() && 10031 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10032 UseAA = false; 10033 #endif 10034 if (UseAA && LD->isUnindexed()) { 10035 // Walk up chain skipping non-aliasing memory nodes. 10036 SDValue BetterChain = FindBetterChain(N, Chain); 10037 10038 // If there is a better chain. 10039 if (Chain != BetterChain) { 10040 SDValue ReplLoad; 10041 10042 // Replace the chain to void dependency. 10043 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10044 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10045 BetterChain, Ptr, LD->getMemOperand()); 10046 } else { 10047 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10048 LD->getValueType(0), 10049 BetterChain, Ptr, LD->getMemoryVT(), 10050 LD->getMemOperand()); 10051 } 10052 10053 // Create token factor to keep old chain connected. 10054 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10055 MVT::Other, Chain, ReplLoad.getValue(1)); 10056 10057 // Make sure the new and old chains are cleaned up. 10058 AddToWorklist(Token.getNode()); 10059 10060 // Replace uses with load result and token factor. Don't add users 10061 // to work list. 10062 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10063 } 10064 } 10065 10066 // Try transforming N to an indexed load. 10067 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10068 return SDValue(N, 0); 10069 10070 // Try to slice up N to more direct loads if the slices are mapped to 10071 // different register banks or pairing can take place. 10072 if (SliceUpLoad(N)) 10073 return SDValue(N, 0); 10074 10075 return SDValue(); 10076 } 10077 10078 namespace { 10079 /// \brief Helper structure used to slice a load in smaller loads. 10080 /// Basically a slice is obtained from the following sequence: 10081 /// Origin = load Ty1, Base 10082 /// Shift = srl Ty1 Origin, CstTy Amount 10083 /// Inst = trunc Shift to Ty2 10084 /// 10085 /// Then, it will be rewriten into: 10086 /// Slice = load SliceTy, Base + SliceOffset 10087 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10088 /// 10089 /// SliceTy is deduced from the number of bits that are actually used to 10090 /// build Inst. 10091 struct LoadedSlice { 10092 /// \brief Helper structure used to compute the cost of a slice. 10093 struct Cost { 10094 /// Are we optimizing for code size. 10095 bool ForCodeSize; 10096 /// Various cost. 10097 unsigned Loads; 10098 unsigned Truncates; 10099 unsigned CrossRegisterBanksCopies; 10100 unsigned ZExts; 10101 unsigned Shift; 10102 10103 Cost(bool ForCodeSize = false) 10104 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10105 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10106 10107 /// \brief Get the cost of one isolated slice. 10108 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10109 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10110 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10111 EVT TruncType = LS.Inst->getValueType(0); 10112 EVT LoadedType = LS.getLoadedType(); 10113 if (TruncType != LoadedType && 10114 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10115 ZExts = 1; 10116 } 10117 10118 /// \brief Account for slicing gain in the current cost. 10119 /// Slicing provide a few gains like removing a shift or a 10120 /// truncate. This method allows to grow the cost of the original 10121 /// load with the gain from this slice. 10122 void addSliceGain(const LoadedSlice &LS) { 10123 // Each slice saves a truncate. 10124 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10125 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10126 LS.Inst->getValueType(0))) 10127 ++Truncates; 10128 // If there is a shift amount, this slice gets rid of it. 10129 if (LS.Shift) 10130 ++Shift; 10131 // If this slice can merge a cross register bank copy, account for it. 10132 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10133 ++CrossRegisterBanksCopies; 10134 } 10135 10136 Cost &operator+=(const Cost &RHS) { 10137 Loads += RHS.Loads; 10138 Truncates += RHS.Truncates; 10139 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10140 ZExts += RHS.ZExts; 10141 Shift += RHS.Shift; 10142 return *this; 10143 } 10144 10145 bool operator==(const Cost &RHS) const { 10146 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10147 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10148 ZExts == RHS.ZExts && Shift == RHS.Shift; 10149 } 10150 10151 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10152 10153 bool operator<(const Cost &RHS) const { 10154 // Assume cross register banks copies are as expensive as loads. 10155 // FIXME: Do we want some more target hooks? 10156 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10157 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10158 // Unless we are optimizing for code size, consider the 10159 // expensive operation first. 10160 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10161 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10162 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10163 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10164 } 10165 10166 bool operator>(const Cost &RHS) const { return RHS < *this; } 10167 10168 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10169 10170 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10171 }; 10172 // The last instruction that represent the slice. This should be a 10173 // truncate instruction. 10174 SDNode *Inst; 10175 // The original load instruction. 10176 LoadSDNode *Origin; 10177 // The right shift amount in bits from the original load. 10178 unsigned Shift; 10179 // The DAG from which Origin came from. 10180 // This is used to get some contextual information about legal types, etc. 10181 SelectionDAG *DAG; 10182 10183 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10184 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10185 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10186 10187 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10188 /// \return Result is \p BitWidth and has used bits set to 1 and 10189 /// not used bits set to 0. 10190 APInt getUsedBits() const { 10191 // Reproduce the trunc(lshr) sequence: 10192 // - Start from the truncated value. 10193 // - Zero extend to the desired bit width. 10194 // - Shift left. 10195 assert(Origin && "No original load to compare against."); 10196 unsigned BitWidth = Origin->getValueSizeInBits(0); 10197 assert(Inst && "This slice is not bound to an instruction"); 10198 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10199 "Extracted slice is bigger than the whole type!"); 10200 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10201 UsedBits.setAllBits(); 10202 UsedBits = UsedBits.zext(BitWidth); 10203 UsedBits <<= Shift; 10204 return UsedBits; 10205 } 10206 10207 /// \brief Get the size of the slice to be loaded in bytes. 10208 unsigned getLoadedSize() const { 10209 unsigned SliceSize = getUsedBits().countPopulation(); 10210 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10211 return SliceSize / 8; 10212 } 10213 10214 /// \brief Get the type that will be loaded for this slice. 10215 /// Note: This may not be the final type for the slice. 10216 EVT getLoadedType() const { 10217 assert(DAG && "Missing context"); 10218 LLVMContext &Ctxt = *DAG->getContext(); 10219 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10220 } 10221 10222 /// \brief Get the alignment of the load used for this slice. 10223 unsigned getAlignment() const { 10224 unsigned Alignment = Origin->getAlignment(); 10225 unsigned Offset = getOffsetFromBase(); 10226 if (Offset != 0) 10227 Alignment = MinAlign(Alignment, Alignment + Offset); 10228 return Alignment; 10229 } 10230 10231 /// \brief Check if this slice can be rewritten with legal operations. 10232 bool isLegal() const { 10233 // An invalid slice is not legal. 10234 if (!Origin || !Inst || !DAG) 10235 return false; 10236 10237 // Offsets are for indexed load only, we do not handle that. 10238 if (!Origin->getOffset().isUndef()) 10239 return false; 10240 10241 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10242 10243 // Check that the type is legal. 10244 EVT SliceType = getLoadedType(); 10245 if (!TLI.isTypeLegal(SliceType)) 10246 return false; 10247 10248 // Check that the load is legal for this type. 10249 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10250 return false; 10251 10252 // Check that the offset can be computed. 10253 // 1. Check its type. 10254 EVT PtrType = Origin->getBasePtr().getValueType(); 10255 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10256 return false; 10257 10258 // 2. Check that it fits in the immediate. 10259 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10260 return false; 10261 10262 // 3. Check that the computation is legal. 10263 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10264 return false; 10265 10266 // Check that the zext is legal if it needs one. 10267 EVT TruncateType = Inst->getValueType(0); 10268 if (TruncateType != SliceType && 10269 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10270 return false; 10271 10272 return true; 10273 } 10274 10275 /// \brief Get the offset in bytes of this slice in the original chunk of 10276 /// bits. 10277 /// \pre DAG != nullptr. 10278 uint64_t getOffsetFromBase() const { 10279 assert(DAG && "Missing context."); 10280 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10281 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10282 uint64_t Offset = Shift / 8; 10283 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10284 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10285 "The size of the original loaded type is not a multiple of a" 10286 " byte."); 10287 // If Offset is bigger than TySizeInBytes, it means we are loading all 10288 // zeros. This should have been optimized before in the process. 10289 assert(TySizeInBytes > Offset && 10290 "Invalid shift amount for given loaded size"); 10291 if (IsBigEndian) 10292 Offset = TySizeInBytes - Offset - getLoadedSize(); 10293 return Offset; 10294 } 10295 10296 /// \brief Generate the sequence of instructions to load the slice 10297 /// represented by this object and redirect the uses of this slice to 10298 /// this new sequence of instructions. 10299 /// \pre this->Inst && this->Origin are valid Instructions and this 10300 /// object passed the legal check: LoadedSlice::isLegal returned true. 10301 /// \return The last instruction of the sequence used to load the slice. 10302 SDValue loadSlice() const { 10303 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10304 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10305 SDValue BaseAddr = OldBaseAddr; 10306 // Get the offset in that chunk of bytes w.r.t. the endianess. 10307 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10308 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10309 if (Offset) { 10310 // BaseAddr = BaseAddr + Offset. 10311 EVT ArithType = BaseAddr.getValueType(); 10312 SDLoc DL(Origin); 10313 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10314 DAG->getConstant(Offset, DL, ArithType)); 10315 } 10316 10317 // Create the type of the loaded slice according to its size. 10318 EVT SliceType = getLoadedType(); 10319 10320 // Create the load for the slice. 10321 SDValue LastInst = DAG->getLoad( 10322 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10323 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10324 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10325 // If the final type is not the same as the loaded type, this means that 10326 // we have to pad with zero. Create a zero extend for that. 10327 EVT FinalType = Inst->getValueType(0); 10328 if (SliceType != FinalType) 10329 LastInst = 10330 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10331 return LastInst; 10332 } 10333 10334 /// \brief Check if this slice can be merged with an expensive cross register 10335 /// bank copy. E.g., 10336 /// i = load i32 10337 /// f = bitcast i32 i to float 10338 bool canMergeExpensiveCrossRegisterBankCopy() const { 10339 if (!Inst || !Inst->hasOneUse()) 10340 return false; 10341 SDNode *Use = *Inst->use_begin(); 10342 if (Use->getOpcode() != ISD::BITCAST) 10343 return false; 10344 assert(DAG && "Missing context"); 10345 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10346 EVT ResVT = Use->getValueType(0); 10347 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10348 const TargetRegisterClass *ArgRC = 10349 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10350 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10351 return false; 10352 10353 // At this point, we know that we perform a cross-register-bank copy. 10354 // Check if it is expensive. 10355 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10356 // Assume bitcasts are cheap, unless both register classes do not 10357 // explicitly share a common sub class. 10358 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10359 return false; 10360 10361 // Check if it will be merged with the load. 10362 // 1. Check the alignment constraint. 10363 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10364 ResVT.getTypeForEVT(*DAG->getContext())); 10365 10366 if (RequiredAlignment > getAlignment()) 10367 return false; 10368 10369 // 2. Check that the load is a legal operation for that type. 10370 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10371 return false; 10372 10373 // 3. Check that we do not have a zext in the way. 10374 if (Inst->getValueType(0) != getLoadedType()) 10375 return false; 10376 10377 return true; 10378 } 10379 }; 10380 } 10381 10382 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10383 /// \p UsedBits looks like 0..0 1..1 0..0. 10384 static bool areUsedBitsDense(const APInt &UsedBits) { 10385 // If all the bits are one, this is dense! 10386 if (UsedBits.isAllOnesValue()) 10387 return true; 10388 10389 // Get rid of the unused bits on the right. 10390 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10391 // Get rid of the unused bits on the left. 10392 if (NarrowedUsedBits.countLeadingZeros()) 10393 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10394 // Check that the chunk of bits is completely used. 10395 return NarrowedUsedBits.isAllOnesValue(); 10396 } 10397 10398 /// \brief Check whether or not \p First and \p Second are next to each other 10399 /// in memory. This means that there is no hole between the bits loaded 10400 /// by \p First and the bits loaded by \p Second. 10401 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10402 const LoadedSlice &Second) { 10403 assert(First.Origin == Second.Origin && First.Origin && 10404 "Unable to match different memory origins."); 10405 APInt UsedBits = First.getUsedBits(); 10406 assert((UsedBits & Second.getUsedBits()) == 0 && 10407 "Slices are not supposed to overlap."); 10408 UsedBits |= Second.getUsedBits(); 10409 return areUsedBitsDense(UsedBits); 10410 } 10411 10412 /// \brief Adjust the \p GlobalLSCost according to the target 10413 /// paring capabilities and the layout of the slices. 10414 /// \pre \p GlobalLSCost should account for at least as many loads as 10415 /// there is in the slices in \p LoadedSlices. 10416 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10417 LoadedSlice::Cost &GlobalLSCost) { 10418 unsigned NumberOfSlices = LoadedSlices.size(); 10419 // If there is less than 2 elements, no pairing is possible. 10420 if (NumberOfSlices < 2) 10421 return; 10422 10423 // Sort the slices so that elements that are likely to be next to each 10424 // other in memory are next to each other in the list. 10425 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10426 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10427 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10428 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10429 }); 10430 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10431 // First (resp. Second) is the first (resp. Second) potentially candidate 10432 // to be placed in a paired load. 10433 const LoadedSlice *First = nullptr; 10434 const LoadedSlice *Second = nullptr; 10435 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10436 // Set the beginning of the pair. 10437 First = Second) { 10438 10439 Second = &LoadedSlices[CurrSlice]; 10440 10441 // If First is NULL, it means we start a new pair. 10442 // Get to the next slice. 10443 if (!First) 10444 continue; 10445 10446 EVT LoadedType = First->getLoadedType(); 10447 10448 // If the types of the slices are different, we cannot pair them. 10449 if (LoadedType != Second->getLoadedType()) 10450 continue; 10451 10452 // Check if the target supplies paired loads for this type. 10453 unsigned RequiredAlignment = 0; 10454 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10455 // move to the next pair, this type is hopeless. 10456 Second = nullptr; 10457 continue; 10458 } 10459 // Check if we meet the alignment requirement. 10460 if (RequiredAlignment > First->getAlignment()) 10461 continue; 10462 10463 // Check that both loads are next to each other in memory. 10464 if (!areSlicesNextToEachOther(*First, *Second)) 10465 continue; 10466 10467 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10468 --GlobalLSCost.Loads; 10469 // Move to the next pair. 10470 Second = nullptr; 10471 } 10472 } 10473 10474 /// \brief Check the profitability of all involved LoadedSlice. 10475 /// Currently, it is considered profitable if there is exactly two 10476 /// involved slices (1) which are (2) next to each other in memory, and 10477 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10478 /// 10479 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10480 /// the elements themselves. 10481 /// 10482 /// FIXME: When the cost model will be mature enough, we can relax 10483 /// constraints (1) and (2). 10484 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10485 const APInt &UsedBits, bool ForCodeSize) { 10486 unsigned NumberOfSlices = LoadedSlices.size(); 10487 if (StressLoadSlicing) 10488 return NumberOfSlices > 1; 10489 10490 // Check (1). 10491 if (NumberOfSlices != 2) 10492 return false; 10493 10494 // Check (2). 10495 if (!areUsedBitsDense(UsedBits)) 10496 return false; 10497 10498 // Check (3). 10499 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10500 // The original code has one big load. 10501 OrigCost.Loads = 1; 10502 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10503 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10504 // Accumulate the cost of all the slices. 10505 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10506 GlobalSlicingCost += SliceCost; 10507 10508 // Account as cost in the original configuration the gain obtained 10509 // with the current slices. 10510 OrigCost.addSliceGain(LS); 10511 } 10512 10513 // If the target supports paired load, adjust the cost accordingly. 10514 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10515 return OrigCost > GlobalSlicingCost; 10516 } 10517 10518 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10519 /// operations, split it in the various pieces being extracted. 10520 /// 10521 /// This sort of thing is introduced by SROA. 10522 /// This slicing takes care not to insert overlapping loads. 10523 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10524 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10525 if (Level < AfterLegalizeDAG) 10526 return false; 10527 10528 LoadSDNode *LD = cast<LoadSDNode>(N); 10529 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10530 !LD->getValueType(0).isInteger()) 10531 return false; 10532 10533 // Keep track of already used bits to detect overlapping values. 10534 // In that case, we will just abort the transformation. 10535 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10536 10537 SmallVector<LoadedSlice, 4> LoadedSlices; 10538 10539 // Check if this load is used as several smaller chunks of bits. 10540 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10541 // of computation for each trunc. 10542 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10543 UI != UIEnd; ++UI) { 10544 // Skip the uses of the chain. 10545 if (UI.getUse().getResNo() != 0) 10546 continue; 10547 10548 SDNode *User = *UI; 10549 unsigned Shift = 0; 10550 10551 // Check if this is a trunc(lshr). 10552 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10553 isa<ConstantSDNode>(User->getOperand(1))) { 10554 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10555 User = *User->use_begin(); 10556 } 10557 10558 // At this point, User is a Truncate, iff we encountered, trunc or 10559 // trunc(lshr). 10560 if (User->getOpcode() != ISD::TRUNCATE) 10561 return false; 10562 10563 // The width of the type must be a power of 2 and greater than 8-bits. 10564 // Otherwise the load cannot be represented in LLVM IR. 10565 // Moreover, if we shifted with a non-8-bits multiple, the slice 10566 // will be across several bytes. We do not support that. 10567 unsigned Width = User->getValueSizeInBits(0); 10568 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10569 return 0; 10570 10571 // Build the slice for this chain of computations. 10572 LoadedSlice LS(User, LD, Shift, &DAG); 10573 APInt CurrentUsedBits = LS.getUsedBits(); 10574 10575 // Check if this slice overlaps with another. 10576 if ((CurrentUsedBits & UsedBits) != 0) 10577 return false; 10578 // Update the bits used globally. 10579 UsedBits |= CurrentUsedBits; 10580 10581 // Check if the new slice would be legal. 10582 if (!LS.isLegal()) 10583 return false; 10584 10585 // Record the slice. 10586 LoadedSlices.push_back(LS); 10587 } 10588 10589 // Abort slicing if it does not seem to be profitable. 10590 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10591 return false; 10592 10593 ++SlicedLoads; 10594 10595 // Rewrite each chain to use an independent load. 10596 // By construction, each chain can be represented by a unique load. 10597 10598 // Prepare the argument for the new token factor for all the slices. 10599 SmallVector<SDValue, 8> ArgChains; 10600 for (SmallVectorImpl<LoadedSlice>::const_iterator 10601 LSIt = LoadedSlices.begin(), 10602 LSItEnd = LoadedSlices.end(); 10603 LSIt != LSItEnd; ++LSIt) { 10604 SDValue SliceInst = LSIt->loadSlice(); 10605 CombineTo(LSIt->Inst, SliceInst, true); 10606 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10607 SliceInst = SliceInst.getOperand(0); 10608 assert(SliceInst->getOpcode() == ISD::LOAD && 10609 "It takes more than a zext to get to the loaded slice!!"); 10610 ArgChains.push_back(SliceInst.getValue(1)); 10611 } 10612 10613 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10614 ArgChains); 10615 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10616 return true; 10617 } 10618 10619 /// Check to see if V is (and load (ptr), imm), where the load is having 10620 /// specific bytes cleared out. If so, return the byte size being masked out 10621 /// and the shift amount. 10622 static std::pair<unsigned, unsigned> 10623 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10624 std::pair<unsigned, unsigned> Result(0, 0); 10625 10626 // Check for the structure we're looking for. 10627 if (V->getOpcode() != ISD::AND || 10628 !isa<ConstantSDNode>(V->getOperand(1)) || 10629 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10630 return Result; 10631 10632 // Check the chain and pointer. 10633 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10634 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10635 10636 // The store should be chained directly to the load or be an operand of a 10637 // tokenfactor. 10638 if (LD == Chain.getNode()) 10639 ; // ok. 10640 else if (Chain->getOpcode() != ISD::TokenFactor) 10641 return Result; // Fail. 10642 else { 10643 bool isOk = false; 10644 for (const SDValue &ChainOp : Chain->op_values()) 10645 if (ChainOp.getNode() == LD) { 10646 isOk = true; 10647 break; 10648 } 10649 if (!isOk) return Result; 10650 } 10651 10652 // This only handles simple types. 10653 if (V.getValueType() != MVT::i16 && 10654 V.getValueType() != MVT::i32 && 10655 V.getValueType() != MVT::i64) 10656 return Result; 10657 10658 // Check the constant mask. Invert it so that the bits being masked out are 10659 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10660 // follow the sign bit for uniformity. 10661 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10662 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10663 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10664 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10665 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10666 if (NotMaskLZ == 64) return Result; // All zero mask. 10667 10668 // See if we have a continuous run of bits. If so, we have 0*1+0* 10669 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10670 return Result; 10671 10672 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10673 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10674 NotMaskLZ -= 64-V.getValueSizeInBits(); 10675 10676 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10677 switch (MaskedBytes) { 10678 case 1: 10679 case 2: 10680 case 4: break; 10681 default: return Result; // All one mask, or 5-byte mask. 10682 } 10683 10684 // Verify that the first bit starts at a multiple of mask so that the access 10685 // is aligned the same as the access width. 10686 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10687 10688 Result.first = MaskedBytes; 10689 Result.second = NotMaskTZ/8; 10690 return Result; 10691 } 10692 10693 10694 /// Check to see if IVal is something that provides a value as specified by 10695 /// MaskInfo. If so, replace the specified store with a narrower store of 10696 /// truncated IVal. 10697 static SDNode * 10698 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10699 SDValue IVal, StoreSDNode *St, 10700 DAGCombiner *DC) { 10701 unsigned NumBytes = MaskInfo.first; 10702 unsigned ByteShift = MaskInfo.second; 10703 SelectionDAG &DAG = DC->getDAG(); 10704 10705 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10706 // that uses this. If not, this is not a replacement. 10707 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10708 ByteShift*8, (ByteShift+NumBytes)*8); 10709 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10710 10711 // Check that it is legal on the target to do this. It is legal if the new 10712 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10713 // legalization. 10714 MVT VT = MVT::getIntegerVT(NumBytes*8); 10715 if (!DC->isTypeLegal(VT)) 10716 return nullptr; 10717 10718 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10719 // shifted by ByteShift and truncated down to NumBytes. 10720 if (ByteShift) { 10721 SDLoc DL(IVal); 10722 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10723 DAG.getConstant(ByteShift*8, DL, 10724 DC->getShiftAmountTy(IVal.getValueType()))); 10725 } 10726 10727 // Figure out the offset for the store and the alignment of the access. 10728 unsigned StOffset; 10729 unsigned NewAlign = St->getAlignment(); 10730 10731 if (DAG.getDataLayout().isLittleEndian()) 10732 StOffset = ByteShift; 10733 else 10734 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10735 10736 SDValue Ptr = St->getBasePtr(); 10737 if (StOffset) { 10738 SDLoc DL(IVal); 10739 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10740 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10741 NewAlign = MinAlign(NewAlign, StOffset); 10742 } 10743 10744 // Truncate down to the new size. 10745 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10746 10747 ++OpsNarrowed; 10748 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10749 St->getPointerInfo().getWithOffset(StOffset), 10750 false, false, NewAlign).getNode(); 10751 } 10752 10753 10754 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10755 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10756 /// narrowing the load and store if it would end up being a win for performance 10757 /// or code size. 10758 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10759 StoreSDNode *ST = cast<StoreSDNode>(N); 10760 if (ST->isVolatile()) 10761 return SDValue(); 10762 10763 SDValue Chain = ST->getChain(); 10764 SDValue Value = ST->getValue(); 10765 SDValue Ptr = ST->getBasePtr(); 10766 EVT VT = Value.getValueType(); 10767 10768 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10769 return SDValue(); 10770 10771 unsigned Opc = Value.getOpcode(); 10772 10773 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10774 // is a byte mask indicating a consecutive number of bytes, check to see if 10775 // Y is known to provide just those bytes. If so, we try to replace the 10776 // load + replace + store sequence with a single (narrower) store, which makes 10777 // the load dead. 10778 if (Opc == ISD::OR) { 10779 std::pair<unsigned, unsigned> MaskedLoad; 10780 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10781 if (MaskedLoad.first) 10782 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10783 Value.getOperand(1), ST,this)) 10784 return SDValue(NewST, 0); 10785 10786 // Or is commutative, so try swapping X and Y. 10787 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10788 if (MaskedLoad.first) 10789 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10790 Value.getOperand(0), ST,this)) 10791 return SDValue(NewST, 0); 10792 } 10793 10794 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10795 Value.getOperand(1).getOpcode() != ISD::Constant) 10796 return SDValue(); 10797 10798 SDValue N0 = Value.getOperand(0); 10799 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10800 Chain == SDValue(N0.getNode(), 1)) { 10801 LoadSDNode *LD = cast<LoadSDNode>(N0); 10802 if (LD->getBasePtr() != Ptr || 10803 LD->getPointerInfo().getAddrSpace() != 10804 ST->getPointerInfo().getAddrSpace()) 10805 return SDValue(); 10806 10807 // Find the type to narrow it the load / op / store to. 10808 SDValue N1 = Value.getOperand(1); 10809 unsigned BitWidth = N1.getValueSizeInBits(); 10810 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10811 if (Opc == ISD::AND) 10812 Imm ^= APInt::getAllOnesValue(BitWidth); 10813 if (Imm == 0 || Imm.isAllOnesValue()) 10814 return SDValue(); 10815 unsigned ShAmt = Imm.countTrailingZeros(); 10816 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10817 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10818 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10819 // The narrowing should be profitable, the load/store operation should be 10820 // legal (or custom) and the store size should be equal to the NewVT width. 10821 while (NewBW < BitWidth && 10822 (NewVT.getStoreSizeInBits() != NewBW || 10823 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10824 !TLI.isNarrowingProfitable(VT, NewVT))) { 10825 NewBW = NextPowerOf2(NewBW); 10826 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10827 } 10828 if (NewBW >= BitWidth) 10829 return SDValue(); 10830 10831 // If the lsb changed does not start at the type bitwidth boundary, 10832 // start at the previous one. 10833 if (ShAmt % NewBW) 10834 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10835 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10836 std::min(BitWidth, ShAmt + NewBW)); 10837 if ((Imm & Mask) == Imm) { 10838 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10839 if (Opc == ISD::AND) 10840 NewImm ^= APInt::getAllOnesValue(NewBW); 10841 uint64_t PtrOff = ShAmt / 8; 10842 // For big endian targets, we need to adjust the offset to the pointer to 10843 // load the correct bytes. 10844 if (DAG.getDataLayout().isBigEndian()) 10845 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10846 10847 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10848 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10849 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10850 return SDValue(); 10851 10852 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10853 Ptr.getValueType(), Ptr, 10854 DAG.getConstant(PtrOff, SDLoc(LD), 10855 Ptr.getValueType())); 10856 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10857 LD->getChain(), NewPtr, 10858 LD->getPointerInfo().getWithOffset(PtrOff), 10859 LD->isVolatile(), LD->isNonTemporal(), 10860 LD->isInvariant(), NewAlign, 10861 LD->getAAInfo()); 10862 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10863 DAG.getConstant(NewImm, SDLoc(Value), 10864 NewVT)); 10865 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10866 NewVal, NewPtr, 10867 ST->getPointerInfo().getWithOffset(PtrOff), 10868 false, false, NewAlign); 10869 10870 AddToWorklist(NewPtr.getNode()); 10871 AddToWorklist(NewLD.getNode()); 10872 AddToWorklist(NewVal.getNode()); 10873 WorklistRemover DeadNodes(*this); 10874 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10875 ++OpsNarrowed; 10876 return NewST; 10877 } 10878 } 10879 10880 return SDValue(); 10881 } 10882 10883 /// For a given floating point load / store pair, if the load value isn't used 10884 /// by any other operations, then consider transforming the pair to integer 10885 /// load / store operations if the target deems the transformation profitable. 10886 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10887 StoreSDNode *ST = cast<StoreSDNode>(N); 10888 SDValue Chain = ST->getChain(); 10889 SDValue Value = ST->getValue(); 10890 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10891 Value.hasOneUse() && 10892 Chain == SDValue(Value.getNode(), 1)) { 10893 LoadSDNode *LD = cast<LoadSDNode>(Value); 10894 EVT VT = LD->getMemoryVT(); 10895 if (!VT.isFloatingPoint() || 10896 VT != ST->getMemoryVT() || 10897 LD->isNonTemporal() || 10898 ST->isNonTemporal() || 10899 LD->getPointerInfo().getAddrSpace() != 0 || 10900 ST->getPointerInfo().getAddrSpace() != 0) 10901 return SDValue(); 10902 10903 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10904 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10905 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10906 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10907 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10908 return SDValue(); 10909 10910 unsigned LDAlign = LD->getAlignment(); 10911 unsigned STAlign = ST->getAlignment(); 10912 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10913 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10914 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10915 return SDValue(); 10916 10917 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10918 LD->getChain(), LD->getBasePtr(), 10919 LD->getPointerInfo(), 10920 false, false, false, LDAlign); 10921 10922 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10923 NewLD, ST->getBasePtr(), 10924 ST->getPointerInfo(), 10925 false, false, STAlign); 10926 10927 AddToWorklist(NewLD.getNode()); 10928 AddToWorklist(NewST.getNode()); 10929 WorklistRemover DeadNodes(*this); 10930 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10931 ++LdStFP2Int; 10932 return NewST; 10933 } 10934 10935 return SDValue(); 10936 } 10937 10938 namespace { 10939 /// Helper struct to parse and store a memory address as base + index + offset. 10940 /// We ignore sign extensions when it is safe to do so. 10941 /// The following two expressions are not equivalent. To differentiate we need 10942 /// to store whether there was a sign extension involved in the index 10943 /// computation. 10944 /// (load (i64 add (i64 copyfromreg %c) 10945 /// (i64 signextend (add (i8 load %index) 10946 /// (i8 1)))) 10947 /// vs 10948 /// 10949 /// (load (i64 add (i64 copyfromreg %c) 10950 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10951 /// (i32 1))))) 10952 struct BaseIndexOffset { 10953 SDValue Base; 10954 SDValue Index; 10955 int64_t Offset; 10956 bool IsIndexSignExt; 10957 10958 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10959 10960 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10961 bool IsIndexSignExt) : 10962 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10963 10964 bool equalBaseIndex(const BaseIndexOffset &Other) { 10965 return Other.Base == Base && Other.Index == Index && 10966 Other.IsIndexSignExt == IsIndexSignExt; 10967 } 10968 10969 /// Parses tree in Ptr for base, index, offset addresses. 10970 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 10971 bool IsIndexSignExt = false; 10972 10973 // Split up a folded GlobalAddress+Offset into its component parts. 10974 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 10975 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 10976 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 10977 SDLoc(GA), 10978 GA->getValueType(0), 10979 /*Offset=*/0, 10980 /*isTargetGA=*/false, 10981 GA->getTargetFlags()), 10982 SDValue(), 10983 GA->getOffset(), 10984 IsIndexSignExt); 10985 } 10986 10987 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10988 // instruction, then it could be just the BASE or everything else we don't 10989 // know how to handle. Just use Ptr as BASE and give up. 10990 if (Ptr->getOpcode() != ISD::ADD) 10991 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10992 10993 // We know that we have at least an ADD instruction. Try to pattern match 10994 // the simple case of BASE + OFFSET. 10995 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10996 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10997 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10998 IsIndexSignExt); 10999 } 11000 11001 // Inside a loop the current BASE pointer is calculated using an ADD and a 11002 // MUL instruction. In this case Ptr is the actual BASE pointer. 11003 // (i64 add (i64 %array_ptr) 11004 // (i64 mul (i64 %induction_var) 11005 // (i64 %element_size))) 11006 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11007 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11008 11009 // Look at Base + Index + Offset cases. 11010 SDValue Base = Ptr->getOperand(0); 11011 SDValue IndexOffset = Ptr->getOperand(1); 11012 11013 // Skip signextends. 11014 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11015 IndexOffset = IndexOffset->getOperand(0); 11016 IsIndexSignExt = true; 11017 } 11018 11019 // Either the case of Base + Index (no offset) or something else. 11020 if (IndexOffset->getOpcode() != ISD::ADD) 11021 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11022 11023 // Now we have the case of Base + Index + offset. 11024 SDValue Index = IndexOffset->getOperand(0); 11025 SDValue Offset = IndexOffset->getOperand(1); 11026 11027 if (!isa<ConstantSDNode>(Offset)) 11028 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11029 11030 // Ignore signextends. 11031 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11032 Index = Index->getOperand(0); 11033 IsIndexSignExt = true; 11034 } else IsIndexSignExt = false; 11035 11036 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11037 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11038 } 11039 }; 11040 } // namespace 11041 11042 // This is a helper function for visitMUL to check the profitability 11043 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11044 // MulNode is the original multiply, AddNode is (add x, c1), 11045 // and ConstNode is c2. 11046 // 11047 // If the (add x, c1) has multiple uses, we could increase 11048 // the number of adds if we make this transformation. 11049 // It would only be worth doing this if we can remove a 11050 // multiply in the process. Check for that here. 11051 // To illustrate: 11052 // (A + c1) * c3 11053 // (A + c2) * c3 11054 // We're checking for cases where we have common "c3 * A" expressions. 11055 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11056 SDValue &AddNode, 11057 SDValue &ConstNode) { 11058 APInt Val; 11059 11060 // If the add only has one use, this would be OK to do. 11061 if (AddNode.getNode()->hasOneUse()) 11062 return true; 11063 11064 // Walk all the users of the constant with which we're multiplying. 11065 for (SDNode *Use : ConstNode->uses()) { 11066 11067 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11068 continue; 11069 11070 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11071 SDNode *OtherOp; 11072 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11073 11074 // OtherOp is what we're multiplying against the constant. 11075 if (Use->getOperand(0) == ConstNode) 11076 OtherOp = Use->getOperand(1).getNode(); 11077 else 11078 OtherOp = Use->getOperand(0).getNode(); 11079 11080 // Check to see if multiply is with the same operand of our "add". 11081 // 11082 // ConstNode = CONST 11083 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11084 // ... 11085 // AddNode = (A + c1) <-- MulVar is A. 11086 // = AddNode * ConstNode <-- current visiting instruction. 11087 // 11088 // If we make this transformation, we will have a common 11089 // multiply (ConstNode * A) that we can save. 11090 if (OtherOp == MulVar) 11091 return true; 11092 11093 // Now check to see if a future expansion will give us a common 11094 // multiply. 11095 // 11096 // ConstNode = CONST 11097 // AddNode = (A + c1) 11098 // ... = AddNode * ConstNode <-- current visiting instruction. 11099 // ... 11100 // OtherOp = (A + c2) 11101 // Use = OtherOp * ConstNode <-- visiting Use. 11102 // 11103 // If we make this transformation, we will have a common 11104 // multiply (CONST * A) after we also do the same transformation 11105 // to the "t2" instruction. 11106 if (OtherOp->getOpcode() == ISD::ADD && 11107 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11108 OtherOp->getOperand(0).getNode() == MulVar) 11109 return true; 11110 } 11111 } 11112 11113 // Didn't find a case where this would be profitable. 11114 return false; 11115 } 11116 11117 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 11118 SDLoc SL, 11119 ArrayRef<MemOpLink> Stores, 11120 SmallVectorImpl<SDValue> &Chains, 11121 EVT Ty) const { 11122 SmallVector<SDValue, 8> BuildVector; 11123 11124 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11125 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11126 Chains.push_back(St->getChain()); 11127 BuildVector.push_back(St->getValue()); 11128 } 11129 11130 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 11131 } 11132 11133 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11134 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11135 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11136 // Make sure we have something to merge. 11137 if (NumStores < 2) 11138 return false; 11139 11140 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11141 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11142 unsigned LatestNodeUsed = 0; 11143 11144 for (unsigned i=0; i < NumStores; ++i) { 11145 // Find a chain for the new wide-store operand. Notice that some 11146 // of the store nodes that we found may not be selected for inclusion 11147 // in the wide store. The chain we use needs to be the chain of the 11148 // latest store node which is *used* and replaced by the wide store. 11149 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11150 LatestNodeUsed = i; 11151 } 11152 11153 SmallVector<SDValue, 8> Chains; 11154 11155 // The latest Node in the DAG. 11156 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11157 SDLoc DL(StoreNodes[0].MemNode); 11158 11159 SDValue StoredVal; 11160 if (UseVector) { 11161 bool IsVec = MemVT.isVector(); 11162 unsigned Elts = NumStores; 11163 if (IsVec) { 11164 // When merging vector stores, get the total number of elements. 11165 Elts *= MemVT.getVectorNumElements(); 11166 } 11167 // Get the type for the merged vector store. 11168 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11169 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11170 11171 if (IsConstantSrc) { 11172 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11173 } else { 11174 SmallVector<SDValue, 8> Ops; 11175 for (unsigned i = 0; i < NumStores; ++i) { 11176 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11177 SDValue Val = St->getValue(); 11178 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11179 if (Val.getValueType() != MemVT) 11180 return false; 11181 Ops.push_back(Val); 11182 Chains.push_back(St->getChain()); 11183 } 11184 11185 // Build the extracted vector elements back into a vector. 11186 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11187 DL, Ty, Ops); } 11188 } else { 11189 // We should always use a vector store when merging extracted vector 11190 // elements, so this path implies a store of constants. 11191 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11192 11193 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11194 APInt StoreInt(SizeInBits, 0); 11195 11196 // Construct a single integer constant which is made of the smaller 11197 // constant inputs. 11198 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11199 for (unsigned i = 0; i < NumStores; ++i) { 11200 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11201 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11202 Chains.push_back(St->getChain()); 11203 11204 SDValue Val = St->getValue(); 11205 StoreInt <<= ElementSizeBytes * 8; 11206 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11207 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11208 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11209 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11210 } else { 11211 llvm_unreachable("Invalid constant element type"); 11212 } 11213 } 11214 11215 // Create the new Load and Store operations. 11216 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11217 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11218 } 11219 11220 assert(!Chains.empty()); 11221 11222 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11223 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11224 FirstInChain->getBasePtr(), 11225 FirstInChain->getPointerInfo(), 11226 false, false, 11227 FirstInChain->getAlignment()); 11228 11229 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11230 : DAG.getSubtarget().useAA(); 11231 if (UseAA) { 11232 // Replace all merged stores with the new store. 11233 for (unsigned i = 0; i < NumStores; ++i) 11234 CombineTo(StoreNodes[i].MemNode, NewStore); 11235 } else { 11236 // Replace the last store with the new store. 11237 CombineTo(LatestOp, NewStore); 11238 // Erase all other stores. 11239 for (unsigned i = 0; i < NumStores; ++i) { 11240 if (StoreNodes[i].MemNode == LatestOp) 11241 continue; 11242 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11243 // ReplaceAllUsesWith will replace all uses that existed when it was 11244 // called, but graph optimizations may cause new ones to appear. For 11245 // example, the case in pr14333 looks like 11246 // 11247 // St's chain -> St -> another store -> X 11248 // 11249 // And the only difference from St to the other store is the chain. 11250 // When we change it's chain to be St's chain they become identical, 11251 // get CSEed and the net result is that X is now a use of St. 11252 // Since we know that St is redundant, just iterate. 11253 while (!St->use_empty()) 11254 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11255 deleteAndRecombine(St); 11256 } 11257 } 11258 11259 return true; 11260 } 11261 11262 void DAGCombiner::getStoreMergeAndAliasCandidates( 11263 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11264 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11265 // This holds the base pointer, index, and the offset in bytes from the base 11266 // pointer. 11267 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11268 11269 // We must have a base and an offset. 11270 if (!BasePtr.Base.getNode()) 11271 return; 11272 11273 // Do not handle stores to undef base pointers. 11274 if (BasePtr.Base.isUndef()) 11275 return; 11276 11277 // Walk up the chain and look for nodes with offsets from the same 11278 // base pointer. Stop when reaching an instruction with a different kind 11279 // or instruction which has a different base pointer. 11280 EVT MemVT = St->getMemoryVT(); 11281 unsigned Seq = 0; 11282 StoreSDNode *Index = St; 11283 11284 11285 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11286 : DAG.getSubtarget().useAA(); 11287 11288 if (UseAA) { 11289 // Look at other users of the same chain. Stores on the same chain do not 11290 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11291 // to be on the same chain, so don't bother looking at adjacent chains. 11292 11293 SDValue Chain = St->getChain(); 11294 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11295 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11296 if (I.getOperandNo() != 0) 11297 continue; 11298 11299 if (OtherST->isVolatile() || OtherST->isIndexed()) 11300 continue; 11301 11302 if (OtherST->getMemoryVT() != MemVT) 11303 continue; 11304 11305 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11306 11307 if (Ptr.equalBaseIndex(BasePtr)) 11308 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11309 } 11310 } 11311 11312 return; 11313 } 11314 11315 while (Index) { 11316 // If the chain has more than one use, then we can't reorder the mem ops. 11317 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11318 break; 11319 11320 // Find the base pointer and offset for this memory node. 11321 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11322 11323 // Check that the base pointer is the same as the original one. 11324 if (!Ptr.equalBaseIndex(BasePtr)) 11325 break; 11326 11327 // The memory operands must not be volatile. 11328 if (Index->isVolatile() || Index->isIndexed()) 11329 break; 11330 11331 // No truncation. 11332 if (Index->isTruncatingStore()) 11333 break; 11334 11335 // The stored memory type must be the same. 11336 if (Index->getMemoryVT() != MemVT) 11337 break; 11338 11339 // We do not allow under-aligned stores in order to prevent 11340 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11341 // be irrelevant here; what MATTERS is that we not move memory 11342 // operations that potentially overlap past each-other. 11343 if (Index->getAlignment() < MemVT.getStoreSize()) 11344 break; 11345 11346 // We found a potential memory operand to merge. 11347 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11348 11349 // Find the next memory operand in the chain. If the next operand in the 11350 // chain is a store then move up and continue the scan with the next 11351 // memory operand. If the next operand is a load save it and use alias 11352 // information to check if it interferes with anything. 11353 SDNode *NextInChain = Index->getChain().getNode(); 11354 while (1) { 11355 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11356 // We found a store node. Use it for the next iteration. 11357 Index = STn; 11358 break; 11359 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11360 if (Ldn->isVolatile()) { 11361 Index = nullptr; 11362 break; 11363 } 11364 11365 // Save the load node for later. Continue the scan. 11366 AliasLoadNodes.push_back(Ldn); 11367 NextInChain = Ldn->getChain().getNode(); 11368 continue; 11369 } else { 11370 Index = nullptr; 11371 break; 11372 } 11373 } 11374 } 11375 } 11376 11377 // We need to check that merging these stores does not cause a loop 11378 // in the DAG. Any store candidate may depend on another candidate 11379 // indirectly through its operand (we already consider dependencies 11380 // through the chain). Check in parallel by searching up from 11381 // non-chain operands of candidates. 11382 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11383 SmallVectorImpl<MemOpLink> &StoreNodes) { 11384 SmallPtrSet<const SDNode *, 16> Visited; 11385 SmallVector<const SDNode *, 8> Worklist; 11386 // search ops of store candidates 11387 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11388 SDNode *n = StoreNodes[i].MemNode; 11389 // Potential loops may happen only through non-chain operands 11390 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11391 Worklist.push_back(n->getOperand(j).getNode()); 11392 } 11393 // search through DAG. We can stop early if we find a storenode 11394 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11395 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11396 return false; 11397 } 11398 return true; 11399 } 11400 11401 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11402 if (OptLevel == CodeGenOpt::None) 11403 return false; 11404 11405 EVT MemVT = St->getMemoryVT(); 11406 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11407 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11408 Attribute::NoImplicitFloat); 11409 11410 // This function cannot currently deal with non-byte-sized memory sizes. 11411 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11412 return false; 11413 11414 if (!MemVT.isSimple()) 11415 return false; 11416 11417 // Perform an early exit check. Do not bother looking at stored values that 11418 // are not constants, loads, or extracted vector elements. 11419 SDValue StoredVal = St->getValue(); 11420 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11421 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11422 isa<ConstantFPSDNode>(StoredVal); 11423 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11424 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11425 11426 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11427 return false; 11428 11429 // Don't merge vectors into wider vectors if the source data comes from loads. 11430 // TODO: This restriction can be lifted by using logic similar to the 11431 // ExtractVecSrc case. 11432 if (MemVT.isVector() && IsLoadSrc) 11433 return false; 11434 11435 // Only look at ends of store sequences. 11436 SDValue Chain = SDValue(St, 0); 11437 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11438 return false; 11439 11440 // Save the LoadSDNodes that we find in the chain. 11441 // We need to make sure that these nodes do not interfere with 11442 // any of the store nodes. 11443 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11444 11445 // Save the StoreSDNodes that we find in the chain. 11446 SmallVector<MemOpLink, 8> StoreNodes; 11447 11448 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11449 11450 // Check if there is anything to merge. 11451 if (StoreNodes.size() < 2) 11452 return false; 11453 11454 // only do dep endence check in AA case 11455 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11456 : DAG.getSubtarget().useAA(); 11457 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11458 return false; 11459 11460 // Sort the memory operands according to their distance from the 11461 // base pointer. As a secondary criteria: make sure stores coming 11462 // later in the code come first in the list. This is important for 11463 // the non-UseAA case, because we're merging stores into the FINAL 11464 // store along a chain which potentially contains aliasing stores. 11465 // Thus, if there are multiple stores to the same address, the last 11466 // one can be considered for merging but not the others. 11467 std::sort(StoreNodes.begin(), StoreNodes.end(), 11468 [](MemOpLink LHS, MemOpLink RHS) { 11469 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11470 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11471 LHS.SequenceNum < RHS.SequenceNum); 11472 }); 11473 11474 // Scan the memory operations on the chain and find the first non-consecutive 11475 // store memory address. 11476 unsigned LastConsecutiveStore = 0; 11477 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11478 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11479 11480 // Check that the addresses are consecutive starting from the second 11481 // element in the list of stores. 11482 if (i > 0) { 11483 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11484 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11485 break; 11486 } 11487 11488 // Check if this store interferes with any of the loads that we found. 11489 // If we find a load that alias with this store. Stop the sequence. 11490 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(), 11491 [&](LSBaseSDNode* Ldn) { 11492 return isAlias(Ldn, StoreNodes[i].MemNode); 11493 })) 11494 break; 11495 11496 // Mark this node as useful. 11497 LastConsecutiveStore = i; 11498 } 11499 11500 // The node with the lowest store address. 11501 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11502 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11503 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11504 LLVMContext &Context = *DAG.getContext(); 11505 const DataLayout &DL = DAG.getDataLayout(); 11506 11507 // Store the constants into memory as one consecutive store. 11508 if (IsConstantSrc) { 11509 unsigned LastLegalType = 0; 11510 unsigned LastLegalVectorType = 0; 11511 bool NonZero = false; 11512 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11513 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11514 SDValue StoredVal = St->getValue(); 11515 11516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11517 NonZero |= !C->isNullValue(); 11518 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11519 NonZero |= !C->getConstantFPValue()->isNullValue(); 11520 } else { 11521 // Non-constant. 11522 break; 11523 } 11524 11525 // Find a legal type for the constant store. 11526 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11527 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11528 bool IsFast; 11529 if (TLI.isTypeLegal(StoreTy) && 11530 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11531 FirstStoreAlign, &IsFast) && IsFast) { 11532 LastLegalType = i+1; 11533 // Or check whether a truncstore is legal. 11534 } else if (TLI.getTypeAction(Context, StoreTy) == 11535 TargetLowering::TypePromoteInteger) { 11536 EVT LegalizedStoredValueTy = 11537 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11538 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11539 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11540 FirstStoreAS, FirstStoreAlign, &IsFast) && 11541 IsFast) { 11542 LastLegalType = i + 1; 11543 } 11544 } 11545 11546 // We only use vectors if the constant is known to be zero or the target 11547 // allows it and the function is not marked with the noimplicitfloat 11548 // attribute. 11549 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11550 FirstStoreAS)) && 11551 !NoVectors) { 11552 // Find a legal type for the vector store. 11553 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11554 if (TLI.isTypeLegal(Ty) && 11555 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11556 FirstStoreAlign, &IsFast) && IsFast) 11557 LastLegalVectorType = i + 1; 11558 } 11559 } 11560 11561 // Check if we found a legal integer type to store. 11562 if (LastLegalType == 0 && LastLegalVectorType == 0) 11563 return false; 11564 11565 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11566 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11567 11568 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11569 true, UseVector); 11570 } 11571 11572 // When extracting multiple vector elements, try to store them 11573 // in one vector store rather than a sequence of scalar stores. 11574 if (IsExtractVecSrc) { 11575 unsigned NumStoresToMerge = 0; 11576 bool IsVec = MemVT.isVector(); 11577 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11578 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11579 unsigned StoreValOpcode = St->getValue().getOpcode(); 11580 // This restriction could be loosened. 11581 // Bail out if any stored values are not elements extracted from a vector. 11582 // It should be possible to handle mixed sources, but load sources need 11583 // more careful handling (see the block of code below that handles 11584 // consecutive loads). 11585 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11586 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11587 return false; 11588 11589 // Find a legal type for the vector store. 11590 unsigned Elts = i + 1; 11591 if (IsVec) { 11592 // When merging vector stores, get the total number of elements. 11593 Elts *= MemVT.getVectorNumElements(); 11594 } 11595 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11596 bool IsFast; 11597 if (TLI.isTypeLegal(Ty) && 11598 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11599 FirstStoreAlign, &IsFast) && IsFast) 11600 NumStoresToMerge = i + 1; 11601 } 11602 11603 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11604 false, true); 11605 } 11606 11607 // Below we handle the case of multiple consecutive stores that 11608 // come from multiple consecutive loads. We merge them into a single 11609 // wide load and a single wide store. 11610 11611 // Look for load nodes which are used by the stored values. 11612 SmallVector<MemOpLink, 8> LoadNodes; 11613 11614 // Find acceptable loads. Loads need to have the same chain (token factor), 11615 // must not be zext, volatile, indexed, and they must be consecutive. 11616 BaseIndexOffset LdBasePtr; 11617 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11618 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11619 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11620 if (!Ld) break; 11621 11622 // Loads must only have one use. 11623 if (!Ld->hasNUsesOfValue(1, 0)) 11624 break; 11625 11626 // The memory operands must not be volatile. 11627 if (Ld->isVolatile() || Ld->isIndexed()) 11628 break; 11629 11630 // We do not accept ext loads. 11631 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11632 break; 11633 11634 // The stored memory type must be the same. 11635 if (Ld->getMemoryVT() != MemVT) 11636 break; 11637 11638 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11639 // If this is not the first ptr that we check. 11640 if (LdBasePtr.Base.getNode()) { 11641 // The base ptr must be the same. 11642 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11643 break; 11644 } else { 11645 // Check that all other base pointers are the same as this one. 11646 LdBasePtr = LdPtr; 11647 } 11648 11649 // We found a potential memory operand to merge. 11650 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11651 } 11652 11653 if (LoadNodes.size() < 2) 11654 return false; 11655 11656 // If we have load/store pair instructions and we only have two values, 11657 // don't bother. 11658 unsigned RequiredAlignment; 11659 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11660 St->getAlignment() >= RequiredAlignment) 11661 return false; 11662 11663 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11664 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11665 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11666 11667 // Scan the memory operations on the chain and find the first non-consecutive 11668 // load memory address. These variables hold the index in the store node 11669 // array. 11670 unsigned LastConsecutiveLoad = 0; 11671 // This variable refers to the size and not index in the array. 11672 unsigned LastLegalVectorType = 0; 11673 unsigned LastLegalIntegerType = 0; 11674 StartAddress = LoadNodes[0].OffsetFromBase; 11675 SDValue FirstChain = FirstLoad->getChain(); 11676 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11677 // All loads must share the same chain. 11678 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11679 break; 11680 11681 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11682 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11683 break; 11684 LastConsecutiveLoad = i; 11685 // Find a legal type for the vector store. 11686 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11687 bool IsFastSt, IsFastLd; 11688 if (TLI.isTypeLegal(StoreTy) && 11689 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11690 FirstStoreAlign, &IsFastSt) && IsFastSt && 11691 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11692 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11693 LastLegalVectorType = i + 1; 11694 } 11695 11696 // Find a legal type for the integer store. 11697 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11698 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11699 if (TLI.isTypeLegal(StoreTy) && 11700 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11701 FirstStoreAlign, &IsFastSt) && IsFastSt && 11702 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11703 FirstLoadAlign, &IsFastLd) && IsFastLd) 11704 LastLegalIntegerType = i + 1; 11705 // Or check whether a truncstore and extload is legal. 11706 else if (TLI.getTypeAction(Context, StoreTy) == 11707 TargetLowering::TypePromoteInteger) { 11708 EVT LegalizedStoredValueTy = 11709 TLI.getTypeToTransformTo(Context, StoreTy); 11710 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11711 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11712 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11713 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11714 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11715 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11716 IsFastSt && 11717 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11718 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11719 IsFastLd) 11720 LastLegalIntegerType = i+1; 11721 } 11722 } 11723 11724 // Only use vector types if the vector type is larger than the integer type. 11725 // If they are the same, use integers. 11726 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11727 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11728 11729 // We add +1 here because the LastXXX variables refer to location while 11730 // the NumElem refers to array/index size. 11731 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11732 NumElem = std::min(LastLegalType, NumElem); 11733 11734 if (NumElem < 2) 11735 return false; 11736 11737 // Collect the chains from all merged stores. 11738 SmallVector<SDValue, 8> MergeStoreChains; 11739 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11740 11741 // The latest Node in the DAG. 11742 unsigned LatestNodeUsed = 0; 11743 for (unsigned i=1; i<NumElem; ++i) { 11744 // Find a chain for the new wide-store operand. Notice that some 11745 // of the store nodes that we found may not be selected for inclusion 11746 // in the wide store. The chain we use needs to be the chain of the 11747 // latest store node which is *used* and replaced by the wide store. 11748 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11749 LatestNodeUsed = i; 11750 11751 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11752 } 11753 11754 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11755 11756 // Find if it is better to use vectors or integers to load and store 11757 // to memory. 11758 EVT JointMemOpVT; 11759 if (UseVectorTy) { 11760 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11761 } else { 11762 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11763 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11764 } 11765 11766 SDLoc LoadDL(LoadNodes[0].MemNode); 11767 SDLoc StoreDL(StoreNodes[0].MemNode); 11768 11769 // The merged loads are required to have the same incoming chain, so 11770 // using the first's chain is acceptable. 11771 SDValue NewLoad = DAG.getLoad( 11772 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11773 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11774 11775 SDValue NewStoreChain = 11776 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11777 11778 SDValue NewStore = DAG.getStore( 11779 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11780 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11781 11782 // Transfer chain users from old loads to the new load. 11783 for (unsigned i = 0; i < NumElem; ++i) { 11784 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11785 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11786 SDValue(NewLoad.getNode(), 1)); 11787 } 11788 11789 if (UseAA) { 11790 // Replace the all stores with the new store. 11791 for (unsigned i = 0; i < NumElem; ++i) 11792 CombineTo(StoreNodes[i].MemNode, NewStore); 11793 } else { 11794 // Replace the last store with the new store. 11795 CombineTo(LatestOp, NewStore); 11796 // Erase all other stores. 11797 for (unsigned i = 0; i < NumElem; ++i) { 11798 // Remove all Store nodes. 11799 if (StoreNodes[i].MemNode == LatestOp) 11800 continue; 11801 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11802 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11803 deleteAndRecombine(St); 11804 } 11805 } 11806 11807 return true; 11808 } 11809 11810 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11811 SDLoc SL(ST); 11812 SDValue ReplStore; 11813 11814 // Replace the chain to avoid dependency. 11815 if (ST->isTruncatingStore()) { 11816 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11817 ST->getBasePtr(), ST->getMemoryVT(), 11818 ST->getMemOperand()); 11819 } else { 11820 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11821 ST->getMemOperand()); 11822 } 11823 11824 // Create token to keep both nodes around. 11825 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11826 MVT::Other, ST->getChain(), ReplStore); 11827 11828 // Make sure the new and old chains are cleaned up. 11829 AddToWorklist(Token.getNode()); 11830 11831 // Don't add users to work list. 11832 return CombineTo(ST, Token, false); 11833 } 11834 11835 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11836 SDValue Value = ST->getValue(); 11837 if (Value.getOpcode() == ISD::TargetConstantFP) 11838 return SDValue(); 11839 11840 SDLoc DL(ST); 11841 11842 SDValue Chain = ST->getChain(); 11843 SDValue Ptr = ST->getBasePtr(); 11844 11845 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11846 11847 // NOTE: If the original store is volatile, this transform must not increase 11848 // the number of stores. For example, on x86-32 an f64 can be stored in one 11849 // processor operation but an i64 (which is not legal) requires two. So the 11850 // transform should not be done in this case. 11851 11852 SDValue Tmp; 11853 switch (CFP->getSimpleValueType(0).SimpleTy) { 11854 default: 11855 llvm_unreachable("Unknown FP type"); 11856 case MVT::f16: // We don't do this for these yet. 11857 case MVT::f80: 11858 case MVT::f128: 11859 case MVT::ppcf128: 11860 return SDValue(); 11861 case MVT::f32: 11862 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11863 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11864 ; 11865 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11866 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11867 MVT::i32); 11868 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11869 } 11870 11871 return SDValue(); 11872 case MVT::f64: 11873 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11874 !ST->isVolatile()) || 11875 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11876 ; 11877 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11878 getZExtValue(), SDLoc(CFP), MVT::i64); 11879 return DAG.getStore(Chain, DL, Tmp, 11880 Ptr, ST->getMemOperand()); 11881 } 11882 11883 if (!ST->isVolatile() && 11884 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11885 // Many FP stores are not made apparent until after legalize, e.g. for 11886 // argument passing. Since this is so common, custom legalize the 11887 // 64-bit integer store into two 32-bit stores. 11888 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11889 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11890 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11891 if (DAG.getDataLayout().isBigEndian()) 11892 std::swap(Lo, Hi); 11893 11894 unsigned Alignment = ST->getAlignment(); 11895 bool isVolatile = ST->isVolatile(); 11896 bool isNonTemporal = ST->isNonTemporal(); 11897 AAMDNodes AAInfo = ST->getAAInfo(); 11898 11899 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11900 Ptr, ST->getPointerInfo(), 11901 isVolatile, isNonTemporal, 11902 ST->getAlignment(), AAInfo); 11903 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11904 DAG.getConstant(4, DL, Ptr.getValueType())); 11905 Alignment = MinAlign(Alignment, 4U); 11906 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11907 Ptr, ST->getPointerInfo().getWithOffset(4), 11908 isVolatile, isNonTemporal, 11909 Alignment, AAInfo); 11910 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11911 St0, St1); 11912 } 11913 11914 return SDValue(); 11915 } 11916 } 11917 11918 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11919 StoreSDNode *ST = cast<StoreSDNode>(N); 11920 SDValue Chain = ST->getChain(); 11921 SDValue Value = ST->getValue(); 11922 SDValue Ptr = ST->getBasePtr(); 11923 11924 // If this is a store of a bit convert, store the input value if the 11925 // resultant store does not need a higher alignment than the original. 11926 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11927 ST->isUnindexed()) { 11928 unsigned OrigAlign = ST->getAlignment(); 11929 EVT SVT = Value.getOperand(0).getValueType(); 11930 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11931 SVT.getTypeForEVT(*DAG.getContext())); 11932 if (Align <= OrigAlign && 11933 ((!LegalOperations && !ST->isVolatile()) || 11934 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11935 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11936 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11937 ST->isNonTemporal(), OrigAlign, 11938 ST->getAAInfo()); 11939 } 11940 11941 // Turn 'store undef, Ptr' -> nothing. 11942 if (Value.isUndef() && ST->isUnindexed()) 11943 return Chain; 11944 11945 // Try to infer better alignment information than the store already has. 11946 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11947 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11948 if (Align > ST->getAlignment()) { 11949 SDValue NewStore = 11950 DAG.getTruncStore(Chain, SDLoc(N), Value, 11951 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11952 ST->isVolatile(), ST->isNonTemporal(), Align, 11953 ST->getAAInfo()); 11954 if (NewStore.getNode() != N) 11955 return CombineTo(ST, NewStore, true); 11956 } 11957 } 11958 } 11959 11960 // Try transforming a pair floating point load / store ops to integer 11961 // load / store ops. 11962 if (SDValue NewST = TransformFPLoadStorePair(N)) 11963 return NewST; 11964 11965 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11966 : DAG.getSubtarget().useAA(); 11967 #ifndef NDEBUG 11968 if (CombinerAAOnlyFunc.getNumOccurrences() && 11969 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11970 UseAA = false; 11971 #endif 11972 if (UseAA && ST->isUnindexed()) { 11973 // FIXME: We should do this even without AA enabled. AA will just allow 11974 // FindBetterChain to work in more situations. The problem with this is that 11975 // any combine that expects memory operations to be on consecutive chains 11976 // first needs to be updated to look for users of the same chain. 11977 11978 // Walk up chain skipping non-aliasing memory nodes, on this store and any 11979 // adjacent stores. 11980 if (findBetterNeighborChains(ST)) { 11981 // replaceStoreChain uses CombineTo, which handled all of the worklist 11982 // manipulation. Return the original node to not do anything else. 11983 return SDValue(ST, 0); 11984 } 11985 } 11986 11987 // Try transforming N to an indexed store. 11988 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11989 return SDValue(N, 0); 11990 11991 // FIXME: is there such a thing as a truncating indexed store? 11992 if (ST->isTruncatingStore() && ST->isUnindexed() && 11993 Value.getValueType().isInteger()) { 11994 // See if we can simplify the input to this truncstore with knowledge that 11995 // only the low bits are being used. For example: 11996 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11997 SDValue Shorter = 11998 GetDemandedBits(Value, 11999 APInt::getLowBitsSet( 12000 Value.getValueType().getScalarType().getSizeInBits(), 12001 ST->getMemoryVT().getScalarType().getSizeInBits())); 12002 AddToWorklist(Value.getNode()); 12003 if (Shorter.getNode()) 12004 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12005 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12006 12007 // Otherwise, see if we can simplify the operation with 12008 // SimplifyDemandedBits, which only works if the value has a single use. 12009 if (SimplifyDemandedBits(Value, 12010 APInt::getLowBitsSet( 12011 Value.getValueType().getScalarType().getSizeInBits(), 12012 ST->getMemoryVT().getScalarType().getSizeInBits()))) 12013 return SDValue(N, 0); 12014 } 12015 12016 // If this is a load followed by a store to the same location, then the store 12017 // is dead/noop. 12018 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12019 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12020 ST->isUnindexed() && !ST->isVolatile() && 12021 // There can't be any side effects between the load and store, such as 12022 // a call or store. 12023 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12024 // The store is dead, remove it. 12025 return Chain; 12026 } 12027 } 12028 12029 // If this is a store followed by a store with the same value to the same 12030 // location, then the store is dead/noop. 12031 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12032 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12033 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12034 ST1->isUnindexed() && !ST1->isVolatile()) { 12035 // The store is dead, remove it. 12036 return Chain; 12037 } 12038 } 12039 12040 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12041 // truncating store. We can do this even if this is already a truncstore. 12042 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12043 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12044 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12045 ST->getMemoryVT())) { 12046 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12047 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12048 } 12049 12050 // Only perform this optimization before the types are legal, because we 12051 // don't want to perform this optimization on every DAGCombine invocation. 12052 if (!LegalTypes) { 12053 bool EverChanged = false; 12054 12055 do { 12056 // There can be multiple store sequences on the same chain. 12057 // Keep trying to merge store sequences until we are unable to do so 12058 // or until we merge the last store on the chain. 12059 bool Changed = MergeConsecutiveStores(ST); 12060 EverChanged |= Changed; 12061 if (!Changed) break; 12062 } while (ST->getOpcode() != ISD::DELETED_NODE); 12063 12064 if (EverChanged) 12065 return SDValue(N, 0); 12066 } 12067 12068 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12069 // 12070 // Make sure to do this only after attempting to merge stores in order to 12071 // avoid changing the types of some subset of stores due to visit order, 12072 // preventing their merging. 12073 if (isa<ConstantFPSDNode>(Value)) { 12074 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12075 return NewSt; 12076 } 12077 12078 return ReduceLoadOpStoreWidth(N); 12079 } 12080 12081 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12082 SDValue InVec = N->getOperand(0); 12083 SDValue InVal = N->getOperand(1); 12084 SDValue EltNo = N->getOperand(2); 12085 SDLoc dl(N); 12086 12087 // If the inserted element is an UNDEF, just use the input vector. 12088 if (InVal.isUndef()) 12089 return InVec; 12090 12091 EVT VT = InVec.getValueType(); 12092 12093 // If we can't generate a legal BUILD_VECTOR, exit 12094 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12095 return SDValue(); 12096 12097 // Check that we know which element is being inserted 12098 if (!isa<ConstantSDNode>(EltNo)) 12099 return SDValue(); 12100 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12101 12102 // Canonicalize insert_vector_elt dag nodes. 12103 // Example: 12104 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12105 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12106 // 12107 // Do this only if the child insert_vector node has one use; also 12108 // do this only if indices are both constants and Idx1 < Idx0. 12109 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12110 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12111 unsigned OtherElt = 12112 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12113 if (Elt < OtherElt) { 12114 // Swap nodes. 12115 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12116 InVec.getOperand(0), InVal, EltNo); 12117 AddToWorklist(NewOp.getNode()); 12118 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12119 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12120 } 12121 } 12122 12123 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12124 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12125 // vector elements. 12126 SmallVector<SDValue, 8> Ops; 12127 // Do not combine these two vectors if the output vector will not replace 12128 // the input vector. 12129 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12130 Ops.append(InVec.getNode()->op_begin(), 12131 InVec.getNode()->op_end()); 12132 } else if (InVec.isUndef()) { 12133 unsigned NElts = VT.getVectorNumElements(); 12134 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12135 } else { 12136 return SDValue(); 12137 } 12138 12139 // Insert the element 12140 if (Elt < Ops.size()) { 12141 // All the operands of BUILD_VECTOR must have the same type; 12142 // we enforce that here. 12143 EVT OpVT = Ops[0].getValueType(); 12144 if (InVal.getValueType() != OpVT) 12145 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12146 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12147 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12148 Ops[Elt] = InVal; 12149 } 12150 12151 // Return the new vector 12152 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 12153 } 12154 12155 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12156 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12157 EVT ResultVT = EVE->getValueType(0); 12158 EVT VecEltVT = InVecVT.getVectorElementType(); 12159 unsigned Align = OriginalLoad->getAlignment(); 12160 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12161 VecEltVT.getTypeForEVT(*DAG.getContext())); 12162 12163 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12164 return SDValue(); 12165 12166 Align = NewAlign; 12167 12168 SDValue NewPtr = OriginalLoad->getBasePtr(); 12169 SDValue Offset; 12170 EVT PtrType = NewPtr.getValueType(); 12171 MachinePointerInfo MPI; 12172 SDLoc DL(EVE); 12173 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12174 int Elt = ConstEltNo->getZExtValue(); 12175 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12176 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12177 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12178 } else { 12179 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12180 Offset = DAG.getNode( 12181 ISD::MUL, DL, PtrType, Offset, 12182 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12183 MPI = OriginalLoad->getPointerInfo(); 12184 } 12185 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12186 12187 // The replacement we need to do here is a little tricky: we need to 12188 // replace an extractelement of a load with a load. 12189 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12190 // Note that this replacement assumes that the extractvalue is the only 12191 // use of the load; that's okay because we don't want to perform this 12192 // transformation in other cases anyway. 12193 SDValue Load; 12194 SDValue Chain; 12195 if (ResultVT.bitsGT(VecEltVT)) { 12196 // If the result type of vextract is wider than the load, then issue an 12197 // extending load instead. 12198 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12199 VecEltVT) 12200 ? ISD::ZEXTLOAD 12201 : ISD::EXTLOAD; 12202 Load = DAG.getExtLoad( 12203 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 12204 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12205 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12206 Chain = Load.getValue(1); 12207 } else { 12208 Load = DAG.getLoad( 12209 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 12210 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12211 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12212 Chain = Load.getValue(1); 12213 if (ResultVT.bitsLT(VecEltVT)) 12214 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12215 else 12216 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 12217 } 12218 WorklistRemover DeadNodes(*this); 12219 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12220 SDValue To[] = { Load, Chain }; 12221 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12222 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12223 // worklist explicitly as well. 12224 AddToWorklist(Load.getNode()); 12225 AddUsersToWorklist(Load.getNode()); // Add users too 12226 // Make sure to revisit this node to clean it up; it will usually be dead. 12227 AddToWorklist(EVE); 12228 ++OpsNarrowed; 12229 return SDValue(EVE, 0); 12230 } 12231 12232 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12233 // (vextract (scalar_to_vector val, 0) -> val 12234 SDValue InVec = N->getOperand(0); 12235 EVT VT = InVec.getValueType(); 12236 EVT NVT = N->getValueType(0); 12237 12238 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12239 // Check if the result type doesn't match the inserted element type. A 12240 // SCALAR_TO_VECTOR may truncate the inserted element and the 12241 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12242 SDValue InOp = InVec.getOperand(0); 12243 if (InOp.getValueType() != NVT) { 12244 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12245 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12246 } 12247 return InOp; 12248 } 12249 12250 SDValue EltNo = N->getOperand(1); 12251 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12252 12253 // extract_vector_elt (build_vector x, y), 1 -> y 12254 if (ConstEltNo && 12255 InVec.getOpcode() == ISD::BUILD_VECTOR && 12256 TLI.isTypeLegal(VT) && 12257 (InVec.hasOneUse() || 12258 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12259 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12260 EVT InEltVT = Elt.getValueType(); 12261 12262 // Sometimes build_vector's scalar input types do not match result type. 12263 if (NVT == InEltVT) 12264 return Elt; 12265 12266 // TODO: It may be useful to truncate if free if the build_vector implicitly 12267 // converts. 12268 } 12269 12270 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12271 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12272 ConstEltNo->isNullValue() && VT.isInteger()) { 12273 SDValue BCSrc = InVec.getOperand(0); 12274 if (BCSrc.getValueType().isScalarInteger()) 12275 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12276 } 12277 12278 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12279 // We only perform this optimization before the op legalization phase because 12280 // we may introduce new vector instructions which are not backed by TD 12281 // patterns. For example on AVX, extracting elements from a wide vector 12282 // without using extract_subvector. However, if we can find an underlying 12283 // scalar value, then we can always use that. 12284 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12285 int NumElem = VT.getVectorNumElements(); 12286 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12287 // Find the new index to extract from. 12288 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12289 12290 // Extracting an undef index is undef. 12291 if (OrigElt == -1) 12292 return DAG.getUNDEF(NVT); 12293 12294 // Select the right vector half to extract from. 12295 SDValue SVInVec; 12296 if (OrigElt < NumElem) { 12297 SVInVec = InVec->getOperand(0); 12298 } else { 12299 SVInVec = InVec->getOperand(1); 12300 OrigElt -= NumElem; 12301 } 12302 12303 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12304 SDValue InOp = SVInVec.getOperand(OrigElt); 12305 if (InOp.getValueType() != NVT) { 12306 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12307 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12308 } 12309 12310 return InOp; 12311 } 12312 12313 // FIXME: We should handle recursing on other vector shuffles and 12314 // scalar_to_vector here as well. 12315 12316 if (!LegalOperations) { 12317 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12318 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12319 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12320 } 12321 } 12322 12323 bool BCNumEltsChanged = false; 12324 EVT ExtVT = VT.getVectorElementType(); 12325 EVT LVT = ExtVT; 12326 12327 // If the result of load has to be truncated, then it's not necessarily 12328 // profitable. 12329 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12330 return SDValue(); 12331 12332 if (InVec.getOpcode() == ISD::BITCAST) { 12333 // Don't duplicate a load with other uses. 12334 if (!InVec.hasOneUse()) 12335 return SDValue(); 12336 12337 EVT BCVT = InVec.getOperand(0).getValueType(); 12338 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12339 return SDValue(); 12340 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12341 BCNumEltsChanged = true; 12342 InVec = InVec.getOperand(0); 12343 ExtVT = BCVT.getVectorElementType(); 12344 } 12345 12346 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12347 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12348 ISD::isNormalLoad(InVec.getNode()) && 12349 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12350 SDValue Index = N->getOperand(1); 12351 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 12352 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12353 OrigLoad); 12354 } 12355 12356 // Perform only after legalization to ensure build_vector / vector_shuffle 12357 // optimizations have already been done. 12358 if (!LegalOperations) return SDValue(); 12359 12360 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12361 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12362 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12363 12364 if (ConstEltNo) { 12365 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12366 12367 LoadSDNode *LN0 = nullptr; 12368 const ShuffleVectorSDNode *SVN = nullptr; 12369 if (ISD::isNormalLoad(InVec.getNode())) { 12370 LN0 = cast<LoadSDNode>(InVec); 12371 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12372 InVec.getOperand(0).getValueType() == ExtVT && 12373 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12374 // Don't duplicate a load with other uses. 12375 if (!InVec.hasOneUse()) 12376 return SDValue(); 12377 12378 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12379 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12380 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12381 // => 12382 // (load $addr+1*size) 12383 12384 // Don't duplicate a load with other uses. 12385 if (!InVec.hasOneUse()) 12386 return SDValue(); 12387 12388 // If the bit convert changed the number of elements, it is unsafe 12389 // to examine the mask. 12390 if (BCNumEltsChanged) 12391 return SDValue(); 12392 12393 // Select the input vector, guarding against out of range extract vector. 12394 unsigned NumElems = VT.getVectorNumElements(); 12395 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12396 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12397 12398 if (InVec.getOpcode() == ISD::BITCAST) { 12399 // Don't duplicate a load with other uses. 12400 if (!InVec.hasOneUse()) 12401 return SDValue(); 12402 12403 InVec = InVec.getOperand(0); 12404 } 12405 if (ISD::isNormalLoad(InVec.getNode())) { 12406 LN0 = cast<LoadSDNode>(InVec); 12407 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12408 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12409 } 12410 } 12411 12412 // Make sure we found a non-volatile load and the extractelement is 12413 // the only use. 12414 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12415 return SDValue(); 12416 12417 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12418 if (Elt == -1) 12419 return DAG.getUNDEF(LVT); 12420 12421 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12422 } 12423 12424 return SDValue(); 12425 } 12426 12427 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12428 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12429 // We perform this optimization post type-legalization because 12430 // the type-legalizer often scalarizes integer-promoted vectors. 12431 // Performing this optimization before may create bit-casts which 12432 // will be type-legalized to complex code sequences. 12433 // We perform this optimization only before the operation legalizer because we 12434 // may introduce illegal operations. 12435 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12436 return SDValue(); 12437 12438 unsigned NumInScalars = N->getNumOperands(); 12439 SDLoc dl(N); 12440 EVT VT = N->getValueType(0); 12441 12442 // Check to see if this is a BUILD_VECTOR of a bunch of values 12443 // which come from any_extend or zero_extend nodes. If so, we can create 12444 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12445 // optimizations. We do not handle sign-extend because we can't fill the sign 12446 // using shuffles. 12447 EVT SourceType = MVT::Other; 12448 bool AllAnyExt = true; 12449 12450 for (unsigned i = 0; i != NumInScalars; ++i) { 12451 SDValue In = N->getOperand(i); 12452 // Ignore undef inputs. 12453 if (In.isUndef()) continue; 12454 12455 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12456 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12457 12458 // Abort if the element is not an extension. 12459 if (!ZeroExt && !AnyExt) { 12460 SourceType = MVT::Other; 12461 break; 12462 } 12463 12464 // The input is a ZeroExt or AnyExt. Check the original type. 12465 EVT InTy = In.getOperand(0).getValueType(); 12466 12467 // Check that all of the widened source types are the same. 12468 if (SourceType == MVT::Other) 12469 // First time. 12470 SourceType = InTy; 12471 else if (InTy != SourceType) { 12472 // Multiple income types. Abort. 12473 SourceType = MVT::Other; 12474 break; 12475 } 12476 12477 // Check if all of the extends are ANY_EXTENDs. 12478 AllAnyExt &= AnyExt; 12479 } 12480 12481 // In order to have valid types, all of the inputs must be extended from the 12482 // same source type and all of the inputs must be any or zero extend. 12483 // Scalar sizes must be a power of two. 12484 EVT OutScalarTy = VT.getScalarType(); 12485 bool ValidTypes = SourceType != MVT::Other && 12486 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12487 isPowerOf2_32(SourceType.getSizeInBits()); 12488 12489 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12490 // turn into a single shuffle instruction. 12491 if (!ValidTypes) 12492 return SDValue(); 12493 12494 bool isLE = DAG.getDataLayout().isLittleEndian(); 12495 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12496 assert(ElemRatio > 1 && "Invalid element size ratio"); 12497 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12498 DAG.getConstant(0, SDLoc(N), SourceType); 12499 12500 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12501 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12502 12503 // Populate the new build_vector 12504 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12505 SDValue Cast = N->getOperand(i); 12506 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12507 Cast.getOpcode() == ISD::ZERO_EXTEND || 12508 Cast.isUndef()) && "Invalid cast opcode"); 12509 SDValue In; 12510 if (Cast.isUndef()) 12511 In = DAG.getUNDEF(SourceType); 12512 else 12513 In = Cast->getOperand(0); 12514 unsigned Index = isLE ? (i * ElemRatio) : 12515 (i * ElemRatio + (ElemRatio - 1)); 12516 12517 assert(Index < Ops.size() && "Invalid index"); 12518 Ops[Index] = In; 12519 } 12520 12521 // The type of the new BUILD_VECTOR node. 12522 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12523 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12524 "Invalid vector size"); 12525 // Check if the new vector type is legal. 12526 if (!isTypeLegal(VecVT)) return SDValue(); 12527 12528 // Make the new BUILD_VECTOR. 12529 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 12530 12531 // The new BUILD_VECTOR node has the potential to be further optimized. 12532 AddToWorklist(BV.getNode()); 12533 // Bitcast to the desired type. 12534 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12535 } 12536 12537 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12538 EVT VT = N->getValueType(0); 12539 12540 unsigned NumInScalars = N->getNumOperands(); 12541 SDLoc dl(N); 12542 12543 EVT SrcVT = MVT::Other; 12544 unsigned Opcode = ISD::DELETED_NODE; 12545 unsigned NumDefs = 0; 12546 12547 for (unsigned i = 0; i != NumInScalars; ++i) { 12548 SDValue In = N->getOperand(i); 12549 unsigned Opc = In.getOpcode(); 12550 12551 if (Opc == ISD::UNDEF) 12552 continue; 12553 12554 // If all scalar values are floats and converted from integers. 12555 if (Opcode == ISD::DELETED_NODE && 12556 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12557 Opcode = Opc; 12558 } 12559 12560 if (Opc != Opcode) 12561 return SDValue(); 12562 12563 EVT InVT = In.getOperand(0).getValueType(); 12564 12565 // If all scalar values are typed differently, bail out. It's chosen to 12566 // simplify BUILD_VECTOR of integer types. 12567 if (SrcVT == MVT::Other) 12568 SrcVT = InVT; 12569 if (SrcVT != InVT) 12570 return SDValue(); 12571 NumDefs++; 12572 } 12573 12574 // If the vector has just one element defined, it's not worth to fold it into 12575 // a vectorized one. 12576 if (NumDefs < 2) 12577 return SDValue(); 12578 12579 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12580 && "Should only handle conversion from integer to float."); 12581 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12582 12583 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12584 12585 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12586 return SDValue(); 12587 12588 // Just because the floating-point vector type is legal does not necessarily 12589 // mean that the corresponding integer vector type is. 12590 if (!isTypeLegal(NVT)) 12591 return SDValue(); 12592 12593 SmallVector<SDValue, 8> Opnds; 12594 for (unsigned i = 0; i != NumInScalars; ++i) { 12595 SDValue In = N->getOperand(i); 12596 12597 if (In.isUndef()) 12598 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12599 else 12600 Opnds.push_back(In.getOperand(0)); 12601 } 12602 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 12603 AddToWorklist(BV.getNode()); 12604 12605 return DAG.getNode(Opcode, dl, VT, BV); 12606 } 12607 12608 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12609 unsigned NumInScalars = N->getNumOperands(); 12610 SDLoc dl(N); 12611 EVT VT = N->getValueType(0); 12612 12613 // A vector built entirely of undefs is undef. 12614 if (ISD::allOperandsUndef(N)) 12615 return DAG.getUNDEF(VT); 12616 12617 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12618 return V; 12619 12620 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12621 return V; 12622 12623 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12624 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12625 // at most two distinct vectors, turn this into a shuffle node. 12626 12627 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12628 if (!isTypeLegal(VT)) 12629 return SDValue(); 12630 12631 // May only combine to shuffle after legalize if shuffle is legal. 12632 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12633 return SDValue(); 12634 12635 SDValue VecIn1, VecIn2; 12636 bool UsesZeroVector = false; 12637 for (unsigned i = 0; i != NumInScalars; ++i) { 12638 SDValue Op = N->getOperand(i); 12639 // Ignore undef inputs. 12640 if (Op.isUndef()) continue; 12641 12642 // See if we can combine this build_vector into a blend with a zero vector. 12643 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12644 UsesZeroVector = true; 12645 continue; 12646 } 12647 12648 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12649 // constant index, bail out. 12650 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12651 !isa<ConstantSDNode>(Op.getOperand(1))) { 12652 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12653 break; 12654 } 12655 12656 // We allow up to two distinct input vectors. 12657 SDValue ExtractedFromVec = Op.getOperand(0); 12658 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12659 continue; 12660 12661 if (!VecIn1.getNode()) { 12662 VecIn1 = ExtractedFromVec; 12663 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12664 VecIn2 = ExtractedFromVec; 12665 } else { 12666 // Too many inputs. 12667 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12668 break; 12669 } 12670 } 12671 12672 // If everything is good, we can make a shuffle operation. 12673 if (VecIn1.getNode()) { 12674 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12675 SmallVector<int, 8> Mask; 12676 for (unsigned i = 0; i != NumInScalars; ++i) { 12677 unsigned Opcode = N->getOperand(i).getOpcode(); 12678 if (Opcode == ISD::UNDEF) { 12679 Mask.push_back(-1); 12680 continue; 12681 } 12682 12683 // Operands can also be zero. 12684 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12685 assert(UsesZeroVector && 12686 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12687 "Unexpected node found!"); 12688 Mask.push_back(NumInScalars+i); 12689 continue; 12690 } 12691 12692 // If extracting from the first vector, just use the index directly. 12693 SDValue Extract = N->getOperand(i); 12694 SDValue ExtVal = Extract.getOperand(1); 12695 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12696 if (Extract.getOperand(0) == VecIn1) { 12697 Mask.push_back(ExtIndex); 12698 continue; 12699 } 12700 12701 // Otherwise, use InIdx + InputVecSize 12702 Mask.push_back(InNumElements + ExtIndex); 12703 } 12704 12705 // Avoid introducing illegal shuffles with zero. 12706 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12707 return SDValue(); 12708 12709 // We can't generate a shuffle node with mismatched input and output types. 12710 // Attempt to transform a single input vector to the correct type. 12711 if ((VT != VecIn1.getValueType())) { 12712 // If the input vector type has a different base type to the output 12713 // vector type, bail out. 12714 EVT VTElemType = VT.getVectorElementType(); 12715 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12716 (VecIn2.getNode() && 12717 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12718 return SDValue(); 12719 12720 // If the input vector is too small, widen it. 12721 // We only support widening of vectors which are half the size of the 12722 // output registers. For example XMM->YMM widening on X86 with AVX. 12723 EVT VecInT = VecIn1.getValueType(); 12724 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12725 // If we only have one small input, widen it by adding undef values. 12726 if (!VecIn2.getNode()) 12727 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12728 DAG.getUNDEF(VecIn1.getValueType())); 12729 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12730 // If we have two small inputs of the same type, try to concat them. 12731 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12732 VecIn2 = SDValue(nullptr, 0); 12733 } else 12734 return SDValue(); 12735 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12736 // If the input vector is too large, try to split it. 12737 // We don't support having two input vectors that are too large. 12738 // If the zero vector was used, we can not split the vector, 12739 // since we'd need 3 inputs. 12740 if (UsesZeroVector || VecIn2.getNode()) 12741 return SDValue(); 12742 12743 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12744 return SDValue(); 12745 12746 // Try to replace VecIn1 with two extract_subvectors 12747 // No need to update the masks, they should still be correct. 12748 VecIn2 = DAG.getNode( 12749 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12750 DAG.getConstant(VT.getVectorNumElements(), dl, 12751 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12752 VecIn1 = DAG.getNode( 12753 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12754 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12755 } else 12756 return SDValue(); 12757 } 12758 12759 if (UsesZeroVector) 12760 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12761 DAG.getConstantFP(0.0, dl, VT); 12762 else 12763 // If VecIn2 is unused then change it to undef. 12764 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12765 12766 // Check that we were able to transform all incoming values to the same 12767 // type. 12768 if (VecIn2.getValueType() != VecIn1.getValueType() || 12769 VecIn1.getValueType() != VT) 12770 return SDValue(); 12771 12772 // Return the new VECTOR_SHUFFLE node. 12773 SDValue Ops[2]; 12774 Ops[0] = VecIn1; 12775 Ops[1] = VecIn2; 12776 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12777 } 12778 12779 return SDValue(); 12780 } 12781 12782 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12783 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12784 EVT OpVT = N->getOperand(0).getValueType(); 12785 12786 // If the operands are legal vectors, leave them alone. 12787 if (TLI.isTypeLegal(OpVT)) 12788 return SDValue(); 12789 12790 SDLoc DL(N); 12791 EVT VT = N->getValueType(0); 12792 SmallVector<SDValue, 8> Ops; 12793 12794 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12795 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12796 12797 // Keep track of what we encounter. 12798 bool AnyInteger = false; 12799 bool AnyFP = false; 12800 for (const SDValue &Op : N->ops()) { 12801 if (ISD::BITCAST == Op.getOpcode() && 12802 !Op.getOperand(0).getValueType().isVector()) 12803 Ops.push_back(Op.getOperand(0)); 12804 else if (ISD::UNDEF == Op.getOpcode()) 12805 Ops.push_back(ScalarUndef); 12806 else 12807 return SDValue(); 12808 12809 // Note whether we encounter an integer or floating point scalar. 12810 // If it's neither, bail out, it could be something weird like x86mmx. 12811 EVT LastOpVT = Ops.back().getValueType(); 12812 if (LastOpVT.isFloatingPoint()) 12813 AnyFP = true; 12814 else if (LastOpVT.isInteger()) 12815 AnyInteger = true; 12816 else 12817 return SDValue(); 12818 } 12819 12820 // If any of the operands is a floating point scalar bitcast to a vector, 12821 // use floating point types throughout, and bitcast everything. 12822 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12823 if (AnyFP) { 12824 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12825 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12826 if (AnyInteger) { 12827 for (SDValue &Op : Ops) { 12828 if (Op.getValueType() == SVT) 12829 continue; 12830 if (Op.isUndef()) 12831 Op = ScalarUndef; 12832 else 12833 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12834 } 12835 } 12836 } 12837 12838 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12839 VT.getSizeInBits() / SVT.getSizeInBits()); 12840 return DAG.getNode(ISD::BITCAST, DL, VT, 12841 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12842 } 12843 12844 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12845 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12846 // most two distinct vectors the same size as the result, attempt to turn this 12847 // into a legal shuffle. 12848 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12849 EVT VT = N->getValueType(0); 12850 EVT OpVT = N->getOperand(0).getValueType(); 12851 int NumElts = VT.getVectorNumElements(); 12852 int NumOpElts = OpVT.getVectorNumElements(); 12853 12854 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12855 SmallVector<int, 8> Mask; 12856 12857 for (SDValue Op : N->ops()) { 12858 // Peek through any bitcast. 12859 while (Op.getOpcode() == ISD::BITCAST) 12860 Op = Op.getOperand(0); 12861 12862 // UNDEF nodes convert to UNDEF shuffle mask values. 12863 if (Op.isUndef()) { 12864 Mask.append((unsigned)NumOpElts, -1); 12865 continue; 12866 } 12867 12868 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12869 return SDValue(); 12870 12871 // What vector are we extracting the subvector from and at what index? 12872 SDValue ExtVec = Op.getOperand(0); 12873 12874 // We want the EVT of the original extraction to correctly scale the 12875 // extraction index. 12876 EVT ExtVT = ExtVec.getValueType(); 12877 12878 // Peek through any bitcast. 12879 while (ExtVec.getOpcode() == ISD::BITCAST) 12880 ExtVec = ExtVec.getOperand(0); 12881 12882 // UNDEF nodes convert to UNDEF shuffle mask values. 12883 if (ExtVec.isUndef()) { 12884 Mask.append((unsigned)NumOpElts, -1); 12885 continue; 12886 } 12887 12888 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12889 return SDValue(); 12890 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12891 12892 // Ensure that we are extracting a subvector from a vector the same 12893 // size as the result. 12894 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12895 return SDValue(); 12896 12897 // Scale the subvector index to account for any bitcast. 12898 int NumExtElts = ExtVT.getVectorNumElements(); 12899 if (0 == (NumExtElts % NumElts)) 12900 ExtIdx /= (NumExtElts / NumElts); 12901 else if (0 == (NumElts % NumExtElts)) 12902 ExtIdx *= (NumElts / NumExtElts); 12903 else 12904 return SDValue(); 12905 12906 // At most we can reference 2 inputs in the final shuffle. 12907 if (SV0.isUndef() || SV0 == ExtVec) { 12908 SV0 = ExtVec; 12909 for (int i = 0; i != NumOpElts; ++i) 12910 Mask.push_back(i + ExtIdx); 12911 } else if (SV1.isUndef() || SV1 == ExtVec) { 12912 SV1 = ExtVec; 12913 for (int i = 0; i != NumOpElts; ++i) 12914 Mask.push_back(i + ExtIdx + NumElts); 12915 } else { 12916 return SDValue(); 12917 } 12918 } 12919 12920 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12921 return SDValue(); 12922 12923 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12924 DAG.getBitcast(VT, SV1), Mask); 12925 } 12926 12927 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12928 // If we only have one input vector, we don't need to do any concatenation. 12929 if (N->getNumOperands() == 1) 12930 return N->getOperand(0); 12931 12932 // Check if all of the operands are undefs. 12933 EVT VT = N->getValueType(0); 12934 if (ISD::allOperandsUndef(N)) 12935 return DAG.getUNDEF(VT); 12936 12937 // Optimize concat_vectors where all but the first of the vectors are undef. 12938 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12939 return Op.isUndef(); 12940 })) { 12941 SDValue In = N->getOperand(0); 12942 assert(In.getValueType().isVector() && "Must concat vectors"); 12943 12944 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12945 if (In->getOpcode() == ISD::BITCAST && 12946 !In->getOperand(0)->getValueType(0).isVector()) { 12947 SDValue Scalar = In->getOperand(0); 12948 12949 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12950 // look through the trunc so we can still do the transform: 12951 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12952 if (Scalar->getOpcode() == ISD::TRUNCATE && 12953 !TLI.isTypeLegal(Scalar.getValueType()) && 12954 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12955 Scalar = Scalar->getOperand(0); 12956 12957 EVT SclTy = Scalar->getValueType(0); 12958 12959 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12960 return SDValue(); 12961 12962 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12963 VT.getSizeInBits() / SclTy.getSizeInBits()); 12964 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12965 return SDValue(); 12966 12967 SDLoc dl = SDLoc(N); 12968 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12969 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12970 } 12971 } 12972 12973 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12974 // We have already tested above for an UNDEF only concatenation. 12975 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12976 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12977 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12978 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12979 }; 12980 bool AllBuildVectorsOrUndefs = 12981 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12982 if (AllBuildVectorsOrUndefs) { 12983 SmallVector<SDValue, 8> Opnds; 12984 EVT SVT = VT.getScalarType(); 12985 12986 EVT MinVT = SVT; 12987 if (!SVT.isFloatingPoint()) { 12988 // If BUILD_VECTOR are from built from integer, they may have different 12989 // operand types. Get the smallest type and truncate all operands to it. 12990 bool FoundMinVT = false; 12991 for (const SDValue &Op : N->ops()) 12992 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12993 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12994 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12995 FoundMinVT = true; 12996 } 12997 assert(FoundMinVT && "Concat vector type mismatch"); 12998 } 12999 13000 for (const SDValue &Op : N->ops()) { 13001 EVT OpVT = Op.getValueType(); 13002 unsigned NumElts = OpVT.getVectorNumElements(); 13003 13004 if (ISD::UNDEF == Op.getOpcode()) 13005 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13006 13007 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13008 if (SVT.isFloatingPoint()) { 13009 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13010 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13011 } else { 13012 for (unsigned i = 0; i != NumElts; ++i) 13013 Opnds.push_back( 13014 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13015 } 13016 } 13017 } 13018 13019 assert(VT.getVectorNumElements() == Opnds.size() && 13020 "Concat vector type mismatch"); 13021 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 13022 } 13023 13024 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13025 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13026 return V; 13027 13028 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13029 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13030 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13031 return V; 13032 13033 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13034 // nodes often generate nop CONCAT_VECTOR nodes. 13035 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13036 // place the incoming vectors at the exact same location. 13037 SDValue SingleSource = SDValue(); 13038 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13039 13040 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13041 SDValue Op = N->getOperand(i); 13042 13043 if (Op.isUndef()) 13044 continue; 13045 13046 // Check if this is the identity extract: 13047 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13048 return SDValue(); 13049 13050 // Find the single incoming vector for the extract_subvector. 13051 if (SingleSource.getNode()) { 13052 if (Op.getOperand(0) != SingleSource) 13053 return SDValue(); 13054 } else { 13055 SingleSource = Op.getOperand(0); 13056 13057 // Check the source type is the same as the type of the result. 13058 // If not, this concat may extend the vector, so we can not 13059 // optimize it away. 13060 if (SingleSource.getValueType() != N->getValueType(0)) 13061 return SDValue(); 13062 } 13063 13064 unsigned IdentityIndex = i * PartNumElem; 13065 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13066 // The extract index must be constant. 13067 if (!CS) 13068 return SDValue(); 13069 13070 // Check that we are reading from the identity index. 13071 if (CS->getZExtValue() != IdentityIndex) 13072 return SDValue(); 13073 } 13074 13075 if (SingleSource.getNode()) 13076 return SingleSource; 13077 13078 return SDValue(); 13079 } 13080 13081 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13082 EVT NVT = N->getValueType(0); 13083 SDValue V = N->getOperand(0); 13084 13085 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13086 // Combine: 13087 // (extract_subvec (concat V1, V2, ...), i) 13088 // Into: 13089 // Vi if possible 13090 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13091 // type. 13092 if (V->getOperand(0).getValueType() != NVT) 13093 return SDValue(); 13094 unsigned Idx = N->getConstantOperandVal(1); 13095 unsigned NumElems = NVT.getVectorNumElements(); 13096 assert((Idx % NumElems) == 0 && 13097 "IDX in concat is not a multiple of the result vector length."); 13098 return V->getOperand(Idx / NumElems); 13099 } 13100 13101 // Skip bitcasting 13102 if (V->getOpcode() == ISD::BITCAST) 13103 V = V.getOperand(0); 13104 13105 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13106 SDLoc dl(N); 13107 // Handle only simple case where vector being inserted and vector 13108 // being extracted are of same type, and are half size of larger vectors. 13109 EVT BigVT = V->getOperand(0).getValueType(); 13110 EVT SmallVT = V->getOperand(1).getValueType(); 13111 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13112 return SDValue(); 13113 13114 // Only handle cases where both indexes are constants with the same type. 13115 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13116 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13117 13118 if (InsIdx && ExtIdx && 13119 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13120 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13121 // Combine: 13122 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13123 // Into: 13124 // indices are equal or bit offsets are equal => V1 13125 // otherwise => (extract_subvec V1, ExtIdx) 13126 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13127 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13128 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 13129 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 13130 DAG.getNode(ISD::BITCAST, dl, 13131 N->getOperand(0).getValueType(), 13132 V->getOperand(0)), N->getOperand(1)); 13133 } 13134 } 13135 13136 return SDValue(); 13137 } 13138 13139 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13140 SDValue V, SelectionDAG &DAG) { 13141 SDLoc DL(V); 13142 EVT VT = V.getValueType(); 13143 13144 switch (V.getOpcode()) { 13145 default: 13146 return V; 13147 13148 case ISD::CONCAT_VECTORS: { 13149 EVT OpVT = V->getOperand(0).getValueType(); 13150 int OpSize = OpVT.getVectorNumElements(); 13151 SmallBitVector OpUsedElements(OpSize, false); 13152 bool FoundSimplification = false; 13153 SmallVector<SDValue, 4> NewOps; 13154 NewOps.reserve(V->getNumOperands()); 13155 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13156 SDValue Op = V->getOperand(i); 13157 bool OpUsed = false; 13158 for (int j = 0; j < OpSize; ++j) 13159 if (UsedElements[i * OpSize + j]) { 13160 OpUsedElements[j] = true; 13161 OpUsed = true; 13162 } 13163 NewOps.push_back( 13164 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13165 : DAG.getUNDEF(OpVT)); 13166 FoundSimplification |= Op == NewOps.back(); 13167 OpUsedElements.reset(); 13168 } 13169 if (FoundSimplification) 13170 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13171 return V; 13172 } 13173 13174 case ISD::INSERT_SUBVECTOR: { 13175 SDValue BaseV = V->getOperand(0); 13176 SDValue SubV = V->getOperand(1); 13177 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13178 if (!IdxN) 13179 return V; 13180 13181 int SubSize = SubV.getValueType().getVectorNumElements(); 13182 int Idx = IdxN->getZExtValue(); 13183 bool SubVectorUsed = false; 13184 SmallBitVector SubUsedElements(SubSize, false); 13185 for (int i = 0; i < SubSize; ++i) 13186 if (UsedElements[i + Idx]) { 13187 SubVectorUsed = true; 13188 SubUsedElements[i] = true; 13189 UsedElements[i + Idx] = false; 13190 } 13191 13192 // Now recurse on both the base and sub vectors. 13193 SDValue SimplifiedSubV = 13194 SubVectorUsed 13195 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13196 : DAG.getUNDEF(SubV.getValueType()); 13197 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13198 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13199 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13200 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13201 return V; 13202 } 13203 } 13204 } 13205 13206 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13207 SDValue N1, SelectionDAG &DAG) { 13208 EVT VT = SVN->getValueType(0); 13209 int NumElts = VT.getVectorNumElements(); 13210 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13211 for (int M : SVN->getMask()) 13212 if (M >= 0 && M < NumElts) 13213 N0UsedElements[M] = true; 13214 else if (M >= NumElts) 13215 N1UsedElements[M - NumElts] = true; 13216 13217 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13218 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13219 if (S0 == N0 && S1 == N1) 13220 return SDValue(); 13221 13222 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13223 } 13224 13225 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13226 // or turn a shuffle of a single concat into simpler shuffle then concat. 13227 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13228 EVT VT = N->getValueType(0); 13229 unsigned NumElts = VT.getVectorNumElements(); 13230 13231 SDValue N0 = N->getOperand(0); 13232 SDValue N1 = N->getOperand(1); 13233 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13234 13235 SmallVector<SDValue, 4> Ops; 13236 EVT ConcatVT = N0.getOperand(0).getValueType(); 13237 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13238 unsigned NumConcats = NumElts / NumElemsPerConcat; 13239 13240 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13241 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13242 // half vector elements. 13243 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13244 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13245 SVN->getMask().end(), [](int i) { return i == -1; })) { 13246 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13247 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13248 N1 = DAG.getUNDEF(ConcatVT); 13249 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13250 } 13251 13252 // Look at every vector that's inserted. We're looking for exact 13253 // subvector-sized copies from a concatenated vector 13254 for (unsigned I = 0; I != NumConcats; ++I) { 13255 // Make sure we're dealing with a copy. 13256 unsigned Begin = I * NumElemsPerConcat; 13257 bool AllUndef = true, NoUndef = true; 13258 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13259 if (SVN->getMaskElt(J) >= 0) 13260 AllUndef = false; 13261 else 13262 NoUndef = false; 13263 } 13264 13265 if (NoUndef) { 13266 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13267 return SDValue(); 13268 13269 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13270 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13271 return SDValue(); 13272 13273 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13274 if (FirstElt < N0.getNumOperands()) 13275 Ops.push_back(N0.getOperand(FirstElt)); 13276 else 13277 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13278 13279 } else if (AllUndef) { 13280 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13281 } else { // Mixed with general masks and undefs, can't do optimization. 13282 return SDValue(); 13283 } 13284 } 13285 13286 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13287 } 13288 13289 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13290 EVT VT = N->getValueType(0); 13291 unsigned NumElts = VT.getVectorNumElements(); 13292 13293 SDValue N0 = N->getOperand(0); 13294 SDValue N1 = N->getOperand(1); 13295 13296 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13297 13298 // Canonicalize shuffle undef, undef -> undef 13299 if (N0.isUndef() && N1.isUndef()) 13300 return DAG.getUNDEF(VT); 13301 13302 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13303 13304 // Canonicalize shuffle v, v -> v, undef 13305 if (N0 == N1) { 13306 SmallVector<int, 8> NewMask; 13307 for (unsigned i = 0; i != NumElts; ++i) { 13308 int Idx = SVN->getMaskElt(i); 13309 if (Idx >= (int)NumElts) Idx -= NumElts; 13310 NewMask.push_back(Idx); 13311 } 13312 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 13313 &NewMask[0]); 13314 } 13315 13316 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13317 if (N0.isUndef()) { 13318 SmallVector<int, 8> NewMask; 13319 for (unsigned i = 0; i != NumElts; ++i) { 13320 int Idx = SVN->getMaskElt(i); 13321 if (Idx >= 0) { 13322 if (Idx >= (int)NumElts) 13323 Idx -= NumElts; 13324 else 13325 Idx = -1; // remove reference to lhs 13326 } 13327 NewMask.push_back(Idx); 13328 } 13329 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 13330 &NewMask[0]); 13331 } 13332 13333 // Remove references to rhs if it is undef 13334 if (N1.isUndef()) { 13335 bool Changed = false; 13336 SmallVector<int, 8> NewMask; 13337 for (unsigned i = 0; i != NumElts; ++i) { 13338 int Idx = SVN->getMaskElt(i); 13339 if (Idx >= (int)NumElts) { 13340 Idx = -1; 13341 Changed = true; 13342 } 13343 NewMask.push_back(Idx); 13344 } 13345 if (Changed) 13346 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 13347 } 13348 13349 // If it is a splat, check if the argument vector is another splat or a 13350 // build_vector. 13351 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13352 SDNode *V = N0.getNode(); 13353 13354 // If this is a bit convert that changes the element type of the vector but 13355 // not the number of vector elements, look through it. Be careful not to 13356 // look though conversions that change things like v4f32 to v2f64. 13357 if (V->getOpcode() == ISD::BITCAST) { 13358 SDValue ConvInput = V->getOperand(0); 13359 if (ConvInput.getValueType().isVector() && 13360 ConvInput.getValueType().getVectorNumElements() == NumElts) 13361 V = ConvInput.getNode(); 13362 } 13363 13364 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13365 assert(V->getNumOperands() == NumElts && 13366 "BUILD_VECTOR has wrong number of operands"); 13367 SDValue Base; 13368 bool AllSame = true; 13369 for (unsigned i = 0; i != NumElts; ++i) { 13370 if (!V->getOperand(i).isUndef()) { 13371 Base = V->getOperand(i); 13372 break; 13373 } 13374 } 13375 // Splat of <u, u, u, u>, return <u, u, u, u> 13376 if (!Base.getNode()) 13377 return N0; 13378 for (unsigned i = 0; i != NumElts; ++i) { 13379 if (V->getOperand(i) != Base) { 13380 AllSame = false; 13381 break; 13382 } 13383 } 13384 // Splat of <x, x, x, x>, return <x, x, x, x> 13385 if (AllSame) 13386 return N0; 13387 13388 // Canonicalize any other splat as a build_vector. 13389 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13390 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13391 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 13392 V->getValueType(0), Ops); 13393 13394 // We may have jumped through bitcasts, so the type of the 13395 // BUILD_VECTOR may not match the type of the shuffle. 13396 if (V->getValueType(0) != VT) 13397 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13398 return NewBV; 13399 } 13400 } 13401 13402 // There are various patterns used to build up a vector from smaller vectors, 13403 // subvectors, or elements. Scan chains of these and replace unused insertions 13404 // or components with undef. 13405 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13406 return S; 13407 13408 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13409 Level < AfterLegalizeVectorOps && 13410 (N1.isUndef() || 13411 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13412 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13413 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13414 return V; 13415 } 13416 13417 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13418 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13419 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13420 SmallVector<SDValue, 8> Ops; 13421 for (int M : SVN->getMask()) { 13422 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13423 if (M >= 0) { 13424 int Idx = M % NumElts; 13425 SDValue &S = (M < (int)NumElts ? N0 : N1); 13426 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13427 Op = S.getOperand(Idx); 13428 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13429 if (Idx == 0) 13430 Op = S.getOperand(0); 13431 } else { 13432 // Operand can't be combined - bail out. 13433 break; 13434 } 13435 } 13436 Ops.push_back(Op); 13437 } 13438 if (Ops.size() == VT.getVectorNumElements()) { 13439 // BUILD_VECTOR requires all inputs to be of the same type, find the 13440 // maximum type and extend them all. 13441 EVT SVT = VT.getScalarType(); 13442 if (SVT.isInteger()) 13443 for (SDValue &Op : Ops) 13444 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13445 if (SVT != VT.getScalarType()) 13446 for (SDValue &Op : Ops) 13447 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13448 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13449 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13450 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 13451 } 13452 } 13453 13454 // If this shuffle only has a single input that is a bitcasted shuffle, 13455 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13456 // back to their original types. 13457 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13458 N1.isUndef() && Level < AfterLegalizeVectorOps && 13459 TLI.isTypeLegal(VT)) { 13460 13461 // Peek through the bitcast only if there is one user. 13462 SDValue BC0 = N0; 13463 while (BC0.getOpcode() == ISD::BITCAST) { 13464 if (!BC0.hasOneUse()) 13465 break; 13466 BC0 = BC0.getOperand(0); 13467 } 13468 13469 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13470 if (Scale == 1) 13471 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13472 13473 SmallVector<int, 8> NewMask; 13474 for (int M : Mask) 13475 for (int s = 0; s != Scale; ++s) 13476 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13477 return NewMask; 13478 }; 13479 13480 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13481 EVT SVT = VT.getScalarType(); 13482 EVT InnerVT = BC0->getValueType(0); 13483 EVT InnerSVT = InnerVT.getScalarType(); 13484 13485 // Determine which shuffle works with the smaller scalar type. 13486 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13487 EVT ScaleSVT = ScaleVT.getScalarType(); 13488 13489 if (TLI.isTypeLegal(ScaleVT) && 13490 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13491 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13492 13493 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13494 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13495 13496 // Scale the shuffle masks to the smaller scalar type. 13497 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13498 SmallVector<int, 8> InnerMask = 13499 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13500 SmallVector<int, 8> OuterMask = 13501 ScaleShuffleMask(SVN->getMask(), OuterScale); 13502 13503 // Merge the shuffle masks. 13504 SmallVector<int, 8> NewMask; 13505 for (int M : OuterMask) 13506 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13507 13508 // Test for shuffle mask legality over both commutations. 13509 SDValue SV0 = BC0->getOperand(0); 13510 SDValue SV1 = BC0->getOperand(1); 13511 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13512 if (!LegalMask) { 13513 std::swap(SV0, SV1); 13514 ShuffleVectorSDNode::commuteMask(NewMask); 13515 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13516 } 13517 13518 if (LegalMask) { 13519 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13520 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13521 return DAG.getNode( 13522 ISD::BITCAST, SDLoc(N), VT, 13523 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13524 } 13525 } 13526 } 13527 } 13528 13529 // Canonicalize shuffles according to rules: 13530 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13531 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13532 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13533 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13534 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13535 TLI.isTypeLegal(VT)) { 13536 // The incoming shuffle must be of the same type as the result of the 13537 // current shuffle. 13538 assert(N1->getOperand(0).getValueType() == VT && 13539 "Shuffle types don't match"); 13540 13541 SDValue SV0 = N1->getOperand(0); 13542 SDValue SV1 = N1->getOperand(1); 13543 bool HasSameOp0 = N0 == SV0; 13544 bool IsSV1Undef = SV1.isUndef(); 13545 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13546 // Commute the operands of this shuffle so that next rule 13547 // will trigger. 13548 return DAG.getCommutedVectorShuffle(*SVN); 13549 } 13550 13551 // Try to fold according to rules: 13552 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13553 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13554 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13555 // Don't try to fold shuffles with illegal type. 13556 // Only fold if this shuffle is the only user of the other shuffle. 13557 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13558 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13559 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13560 13561 // The incoming shuffle must be of the same type as the result of the 13562 // current shuffle. 13563 assert(OtherSV->getOperand(0).getValueType() == VT && 13564 "Shuffle types don't match"); 13565 13566 SDValue SV0, SV1; 13567 SmallVector<int, 4> Mask; 13568 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13569 // operand, and SV1 as the second operand. 13570 for (unsigned i = 0; i != NumElts; ++i) { 13571 int Idx = SVN->getMaskElt(i); 13572 if (Idx < 0) { 13573 // Propagate Undef. 13574 Mask.push_back(Idx); 13575 continue; 13576 } 13577 13578 SDValue CurrentVec; 13579 if (Idx < (int)NumElts) { 13580 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13581 // shuffle mask to identify which vector is actually referenced. 13582 Idx = OtherSV->getMaskElt(Idx); 13583 if (Idx < 0) { 13584 // Propagate Undef. 13585 Mask.push_back(Idx); 13586 continue; 13587 } 13588 13589 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13590 : OtherSV->getOperand(1); 13591 } else { 13592 // This shuffle index references an element within N1. 13593 CurrentVec = N1; 13594 } 13595 13596 // Simple case where 'CurrentVec' is UNDEF. 13597 if (CurrentVec.isUndef()) { 13598 Mask.push_back(-1); 13599 continue; 13600 } 13601 13602 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13603 // will be the first or second operand of the combined shuffle. 13604 Idx = Idx % NumElts; 13605 if (!SV0.getNode() || SV0 == CurrentVec) { 13606 // Ok. CurrentVec is the left hand side. 13607 // Update the mask accordingly. 13608 SV0 = CurrentVec; 13609 Mask.push_back(Idx); 13610 continue; 13611 } 13612 13613 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13614 if (SV1.getNode() && SV1 != CurrentVec) 13615 return SDValue(); 13616 13617 // Ok. CurrentVec is the right hand side. 13618 // Update the mask accordingly. 13619 SV1 = CurrentVec; 13620 Mask.push_back(Idx + NumElts); 13621 } 13622 13623 // Check if all indices in Mask are Undef. In case, propagate Undef. 13624 bool isUndefMask = true; 13625 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13626 isUndefMask &= Mask[i] < 0; 13627 13628 if (isUndefMask) 13629 return DAG.getUNDEF(VT); 13630 13631 if (!SV0.getNode()) 13632 SV0 = DAG.getUNDEF(VT); 13633 if (!SV1.getNode()) 13634 SV1 = DAG.getUNDEF(VT); 13635 13636 // Avoid introducing shuffles with illegal mask. 13637 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13638 ShuffleVectorSDNode::commuteMask(Mask); 13639 13640 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13641 return SDValue(); 13642 13643 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13644 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13645 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13646 std::swap(SV0, SV1); 13647 } 13648 13649 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13650 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13651 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13652 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13653 } 13654 13655 return SDValue(); 13656 } 13657 13658 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13659 SDValue InVal = N->getOperand(0); 13660 EVT VT = N->getValueType(0); 13661 13662 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13663 // with a VECTOR_SHUFFLE. 13664 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13665 SDValue InVec = InVal->getOperand(0); 13666 SDValue EltNo = InVal->getOperand(1); 13667 13668 // FIXME: We could support implicit truncation if the shuffle can be 13669 // scaled to a smaller vector scalar type. 13670 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13671 if (C0 && VT == InVec.getValueType() && 13672 VT.getScalarType() == InVal.getValueType()) { 13673 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13674 int Elt = C0->getZExtValue(); 13675 NewMask[0] = Elt; 13676 13677 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13678 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13679 NewMask); 13680 } 13681 } 13682 13683 return SDValue(); 13684 } 13685 13686 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13687 SDValue N0 = N->getOperand(0); 13688 SDValue N2 = N->getOperand(2); 13689 13690 // If the input vector is a concatenation, and the insert replaces 13691 // one of the halves, we can optimize into a single concat_vectors. 13692 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13693 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13694 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13695 EVT VT = N->getValueType(0); 13696 13697 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13698 // (concat_vectors Z, Y) 13699 if (InsIdx == 0) 13700 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13701 N->getOperand(1), N0.getOperand(1)); 13702 13703 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13704 // (concat_vectors X, Z) 13705 if (InsIdx == VT.getVectorNumElements()/2) 13706 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13707 N0.getOperand(0), N->getOperand(1)); 13708 } 13709 13710 return SDValue(); 13711 } 13712 13713 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13714 SDValue N0 = N->getOperand(0); 13715 13716 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13717 if (N0->getOpcode() == ISD::FP16_TO_FP) 13718 return N0->getOperand(0); 13719 13720 return SDValue(); 13721 } 13722 13723 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13724 SDValue N0 = N->getOperand(0); 13725 13726 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13727 if (N0->getOpcode() == ISD::AND) { 13728 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13729 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13730 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13731 N0.getOperand(0)); 13732 } 13733 } 13734 13735 return SDValue(); 13736 } 13737 13738 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13739 /// with the destination vector and a zero vector. 13740 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13741 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13742 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13743 EVT VT = N->getValueType(0); 13744 SDValue LHS = N->getOperand(0); 13745 SDValue RHS = N->getOperand(1); 13746 SDLoc dl(N); 13747 13748 // Make sure we're not running after operation legalization where it 13749 // may have custom lowered the vector shuffles. 13750 if (LegalOperations) 13751 return SDValue(); 13752 13753 if (N->getOpcode() != ISD::AND) 13754 return SDValue(); 13755 13756 if (RHS.getOpcode() == ISD::BITCAST) 13757 RHS = RHS.getOperand(0); 13758 13759 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13760 return SDValue(); 13761 13762 EVT RVT = RHS.getValueType(); 13763 unsigned NumElts = RHS.getNumOperands(); 13764 13765 // Attempt to create a valid clear mask, splitting the mask into 13766 // sub elements and checking to see if each is 13767 // all zeros or all ones - suitable for shuffle masking. 13768 auto BuildClearMask = [&](int Split) { 13769 int NumSubElts = NumElts * Split; 13770 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13771 13772 SmallVector<int, 8> Indices; 13773 for (int i = 0; i != NumSubElts; ++i) { 13774 int EltIdx = i / Split; 13775 int SubIdx = i % Split; 13776 SDValue Elt = RHS.getOperand(EltIdx); 13777 if (Elt.isUndef()) { 13778 Indices.push_back(-1); 13779 continue; 13780 } 13781 13782 APInt Bits; 13783 if (isa<ConstantSDNode>(Elt)) 13784 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13785 else if (isa<ConstantFPSDNode>(Elt)) 13786 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13787 else 13788 return SDValue(); 13789 13790 // Extract the sub element from the constant bit mask. 13791 if (DAG.getDataLayout().isBigEndian()) { 13792 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13793 } else { 13794 Bits = Bits.lshr(SubIdx * NumSubBits); 13795 } 13796 13797 if (Split > 1) 13798 Bits = Bits.trunc(NumSubBits); 13799 13800 if (Bits.isAllOnesValue()) 13801 Indices.push_back(i); 13802 else if (Bits == 0) 13803 Indices.push_back(i + NumSubElts); 13804 else 13805 return SDValue(); 13806 } 13807 13808 // Let's see if the target supports this vector_shuffle. 13809 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13810 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13811 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13812 return SDValue(); 13813 13814 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13815 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13816 DAG.getBitcast(ClearVT, LHS), 13817 Zero, &Indices[0])); 13818 }; 13819 13820 // Determine maximum split level (byte level masking). 13821 int MaxSplit = 1; 13822 if (RVT.getScalarSizeInBits() % 8 == 0) 13823 MaxSplit = RVT.getScalarSizeInBits() / 8; 13824 13825 for (int Split = 1; Split <= MaxSplit; ++Split) 13826 if (RVT.getScalarSizeInBits() % Split == 0) 13827 if (SDValue S = BuildClearMask(Split)) 13828 return S; 13829 13830 return SDValue(); 13831 } 13832 13833 /// Visit a binary vector operation, like ADD. 13834 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13835 assert(N->getValueType(0).isVector() && 13836 "SimplifyVBinOp only works on vectors!"); 13837 13838 SDValue LHS = N->getOperand(0); 13839 SDValue RHS = N->getOperand(1); 13840 SDValue Ops[] = {LHS, RHS}; 13841 13842 // See if we can constant fold the vector operation. 13843 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13844 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13845 return Fold; 13846 13847 // Try to convert a constant mask AND into a shuffle clear mask. 13848 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13849 return Shuffle; 13850 13851 // Type legalization might introduce new shuffles in the DAG. 13852 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13853 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13854 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13855 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13856 LHS.getOperand(1).isUndef() && 13857 RHS.getOperand(1).isUndef()) { 13858 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13859 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13860 13861 if (SVN0->getMask().equals(SVN1->getMask())) { 13862 EVT VT = N->getValueType(0); 13863 SDValue UndefVector = LHS.getOperand(1); 13864 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13865 LHS.getOperand(0), RHS.getOperand(0), 13866 N->getFlags()); 13867 AddUsersToWorklist(N); 13868 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13869 &SVN0->getMask()[0]); 13870 } 13871 } 13872 13873 return SDValue(); 13874 } 13875 13876 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13877 SDValue N1, SDValue N2){ 13878 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13879 13880 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13881 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13882 13883 // If we got a simplified select_cc node back from SimplifySelectCC, then 13884 // break it down into a new SETCC node, and a new SELECT node, and then return 13885 // the SELECT node, since we were called with a SELECT node. 13886 if (SCC.getNode()) { 13887 // Check to see if we got a select_cc back (to turn into setcc/select). 13888 // Otherwise, just return whatever node we got back, like fabs. 13889 if (SCC.getOpcode() == ISD::SELECT_CC) { 13890 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13891 N0.getValueType(), 13892 SCC.getOperand(0), SCC.getOperand(1), 13893 SCC.getOperand(4)); 13894 AddToWorklist(SETCC.getNode()); 13895 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13896 SCC.getOperand(2), SCC.getOperand(3)); 13897 } 13898 13899 return SCC; 13900 } 13901 return SDValue(); 13902 } 13903 13904 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13905 /// being selected between, see if we can simplify the select. Callers of this 13906 /// should assume that TheSelect is deleted if this returns true. As such, they 13907 /// should return the appropriate thing (e.g. the node) back to the top-level of 13908 /// the DAG combiner loop to avoid it being looked at. 13909 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13910 SDValue RHS) { 13911 13912 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 13913 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 13914 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13915 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13916 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13917 SDValue Sqrt = RHS; 13918 ISD::CondCode CC; 13919 SDValue CmpLHS; 13920 const ConstantFPSDNode *Zero = nullptr; 13921 13922 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13923 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13924 CmpLHS = TheSelect->getOperand(0); 13925 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13926 } else { 13927 // SELECT or VSELECT 13928 SDValue Cmp = TheSelect->getOperand(0); 13929 if (Cmp.getOpcode() == ISD::SETCC) { 13930 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13931 CmpLHS = Cmp.getOperand(0); 13932 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13933 } 13934 } 13935 if (Zero && Zero->isZero() && 13936 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13937 CC == ISD::SETULT || CC == ISD::SETLT)) { 13938 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 13939 CombineTo(TheSelect, Sqrt); 13940 return true; 13941 } 13942 } 13943 } 13944 // Cannot simplify select with vector condition 13945 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13946 13947 // If this is a select from two identical things, try to pull the operation 13948 // through the select. 13949 if (LHS.getOpcode() != RHS.getOpcode() || 13950 !LHS.hasOneUse() || !RHS.hasOneUse()) 13951 return false; 13952 13953 // If this is a load and the token chain is identical, replace the select 13954 // of two loads with a load through a select of the address to load from. 13955 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13956 // constants have been dropped into the constant pool. 13957 if (LHS.getOpcode() == ISD::LOAD) { 13958 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13959 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13960 13961 // Token chains must be identical. 13962 if (LHS.getOperand(0) != RHS.getOperand(0) || 13963 // Do not let this transformation reduce the number of volatile loads. 13964 LLD->isVolatile() || RLD->isVolatile() || 13965 // FIXME: If either is a pre/post inc/dec load, 13966 // we'd need to split out the address adjustment. 13967 LLD->isIndexed() || RLD->isIndexed() || 13968 // If this is an EXTLOAD, the VT's must match. 13969 LLD->getMemoryVT() != RLD->getMemoryVT() || 13970 // If this is an EXTLOAD, the kind of extension must match. 13971 (LLD->getExtensionType() != RLD->getExtensionType() && 13972 // The only exception is if one of the extensions is anyext. 13973 LLD->getExtensionType() != ISD::EXTLOAD && 13974 RLD->getExtensionType() != ISD::EXTLOAD) || 13975 // FIXME: this discards src value information. This is 13976 // over-conservative. It would be beneficial to be able to remember 13977 // both potential memory locations. Since we are discarding 13978 // src value info, don't do the transformation if the memory 13979 // locations are not in the default address space. 13980 LLD->getPointerInfo().getAddrSpace() != 0 || 13981 RLD->getPointerInfo().getAddrSpace() != 0 || 13982 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13983 LLD->getBasePtr().getValueType())) 13984 return false; 13985 13986 // Check that the select condition doesn't reach either load. If so, 13987 // folding this will induce a cycle into the DAG. If not, this is safe to 13988 // xform, so create a select of the addresses. 13989 SDValue Addr; 13990 if (TheSelect->getOpcode() == ISD::SELECT) { 13991 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13992 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13993 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13994 return false; 13995 // The loads must not depend on one another. 13996 if (LLD->isPredecessorOf(RLD) || 13997 RLD->isPredecessorOf(LLD)) 13998 return false; 13999 Addr = DAG.getSelect(SDLoc(TheSelect), 14000 LLD->getBasePtr().getValueType(), 14001 TheSelect->getOperand(0), LLD->getBasePtr(), 14002 RLD->getBasePtr()); 14003 } else { // Otherwise SELECT_CC 14004 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14005 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14006 14007 if ((LLD->hasAnyUseOfValue(1) && 14008 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14009 (RLD->hasAnyUseOfValue(1) && 14010 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14011 return false; 14012 14013 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14014 LLD->getBasePtr().getValueType(), 14015 TheSelect->getOperand(0), 14016 TheSelect->getOperand(1), 14017 LLD->getBasePtr(), RLD->getBasePtr(), 14018 TheSelect->getOperand(4)); 14019 } 14020 14021 SDValue Load; 14022 // It is safe to replace the two loads if they have different alignments, 14023 // but the new load must be the minimum (most restrictive) alignment of the 14024 // inputs. 14025 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 14026 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14027 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14028 Load = DAG.getLoad(TheSelect->getValueType(0), 14029 SDLoc(TheSelect), 14030 // FIXME: Discards pointer and AA info. 14031 LLD->getChain(), Addr, MachinePointerInfo(), 14032 LLD->isVolatile(), LLD->isNonTemporal(), 14033 isInvariant, Alignment); 14034 } else { 14035 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 14036 RLD->getExtensionType() : LLD->getExtensionType(), 14037 SDLoc(TheSelect), 14038 TheSelect->getValueType(0), 14039 // FIXME: Discards pointer and AA info. 14040 LLD->getChain(), Addr, MachinePointerInfo(), 14041 LLD->getMemoryVT(), LLD->isVolatile(), 14042 LLD->isNonTemporal(), isInvariant, Alignment); 14043 } 14044 14045 // Users of the select now use the result of the load. 14046 CombineTo(TheSelect, Load); 14047 14048 // Users of the old loads now use the new load's chain. We know the 14049 // old-load value is dead now. 14050 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14051 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14052 return true; 14053 } 14054 14055 return false; 14056 } 14057 14058 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14059 /// where 'cond' is the comparison specified by CC. 14060 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 14061 SDValue N2, SDValue N3, 14062 ISD::CondCode CC, bool NotExtCompare) { 14063 // (x ? y : y) -> y. 14064 if (N2 == N3) return N2; 14065 14066 EVT VT = N2.getValueType(); 14067 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14068 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14069 14070 // Determine if the condition we're dealing with is constant 14071 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14072 N0, N1, CC, DL, false); 14073 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14074 14075 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14076 // fold select_cc true, x, y -> x 14077 // fold select_cc false, x, y -> y 14078 return !SCCC->isNullValue() ? N2 : N3; 14079 } 14080 14081 // Check to see if we can simplify the select into an fabs node 14082 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14083 // Allow either -0.0 or 0.0 14084 if (CFP->isZero()) { 14085 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14086 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14087 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14088 N2 == N3.getOperand(0)) 14089 return DAG.getNode(ISD::FABS, DL, VT, N0); 14090 14091 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14092 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14093 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14094 N2.getOperand(0) == N3) 14095 return DAG.getNode(ISD::FABS, DL, VT, N3); 14096 } 14097 } 14098 14099 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14100 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14101 // in it. This is a win when the constant is not otherwise available because 14102 // it replaces two constant pool loads with one. We only do this if the FP 14103 // type is known to be legal, because if it isn't, then we are before legalize 14104 // types an we want the other legalization to happen first (e.g. to avoid 14105 // messing with soft float) and if the ConstantFP is not legal, because if 14106 // it is legal, we may not need to store the FP constant in a constant pool. 14107 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14108 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14109 if (TLI.isTypeLegal(N2.getValueType()) && 14110 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14111 TargetLowering::Legal && 14112 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14113 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14114 // If both constants have multiple uses, then we won't need to do an 14115 // extra load, they are likely around in registers for other users. 14116 (TV->hasOneUse() || FV->hasOneUse())) { 14117 Constant *Elts[] = { 14118 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14119 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14120 }; 14121 Type *FPTy = Elts[0]->getType(); 14122 const DataLayout &TD = DAG.getDataLayout(); 14123 14124 // Create a ConstantArray of the two constants. 14125 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14126 SDValue CPIdx = 14127 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14128 TD.getPrefTypeAlignment(FPTy)); 14129 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14130 14131 // Get the offsets to the 0 and 1 element of the array so that we can 14132 // select between them. 14133 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14134 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14135 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14136 14137 SDValue Cond = DAG.getSetCC(DL, 14138 getSetCCResultType(N0.getValueType()), 14139 N0, N1, CC); 14140 AddToWorklist(Cond.getNode()); 14141 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14142 Cond, One, Zero); 14143 AddToWorklist(CstOffset.getNode()); 14144 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14145 CstOffset); 14146 AddToWorklist(CPIdx.getNode()); 14147 return DAG.getLoad( 14148 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14149 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14150 false, false, false, Alignment); 14151 } 14152 } 14153 14154 // Check to see if we can perform the "gzip trick", transforming 14155 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14156 if (isNullConstant(N3) && CC == ISD::SETLT && 14157 (isNullConstant(N1) || // (a < 0) ? b : 0 14158 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14159 EVT XType = N0.getValueType(); 14160 EVT AType = N2.getValueType(); 14161 if (XType.bitsGE(AType)) { 14162 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14163 // single-bit constant. 14164 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14165 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14166 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14167 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14168 getShiftAmountTy(N0.getValueType())); 14169 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14170 XType, N0, ShCt); 14171 AddToWorklist(Shift.getNode()); 14172 14173 if (XType.bitsGT(AType)) { 14174 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14175 AddToWorklist(Shift.getNode()); 14176 } 14177 14178 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14179 } 14180 14181 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14182 XType, N0, 14183 DAG.getConstant(XType.getSizeInBits() - 1, 14184 SDLoc(N0), 14185 getShiftAmountTy(N0.getValueType()))); 14186 AddToWorklist(Shift.getNode()); 14187 14188 if (XType.bitsGT(AType)) { 14189 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14190 AddToWorklist(Shift.getNode()); 14191 } 14192 14193 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14194 } 14195 } 14196 14197 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14198 // where y is has a single bit set. 14199 // A plaintext description would be, we can turn the SELECT_CC into an AND 14200 // when the condition can be materialized as an all-ones register. Any 14201 // single bit-test can be materialized as an all-ones register with 14202 // shift-left and shift-right-arith. 14203 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14204 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14205 SDValue AndLHS = N0->getOperand(0); 14206 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14207 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14208 // Shift the tested bit over the sign bit. 14209 APInt AndMask = ConstAndRHS->getAPIntValue(); 14210 SDValue ShlAmt = 14211 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14212 getShiftAmountTy(AndLHS.getValueType())); 14213 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14214 14215 // Now arithmetic right shift it all the way over, so the result is either 14216 // all-ones, or zero. 14217 SDValue ShrAmt = 14218 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14219 getShiftAmountTy(Shl.getValueType())); 14220 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14221 14222 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14223 } 14224 } 14225 14226 // fold select C, 16, 0 -> shl C, 4 14227 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14228 TLI.getBooleanContents(N0.getValueType()) == 14229 TargetLowering::ZeroOrOneBooleanContent) { 14230 14231 // If the caller doesn't want us to simplify this into a zext of a compare, 14232 // don't do it. 14233 if (NotExtCompare && N2C->isOne()) 14234 return SDValue(); 14235 14236 // Get a SetCC of the condition 14237 // NOTE: Don't create a SETCC if it's not legal on this target. 14238 if (!LegalOperations || 14239 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14240 SDValue Temp, SCC; 14241 // cast from setcc result type to select result type 14242 if (LegalTypes) { 14243 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14244 N0, N1, CC); 14245 if (N2.getValueType().bitsLT(SCC.getValueType())) 14246 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14247 N2.getValueType()); 14248 else 14249 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14250 N2.getValueType(), SCC); 14251 } else { 14252 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14253 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14254 N2.getValueType(), SCC); 14255 } 14256 14257 AddToWorklist(SCC.getNode()); 14258 AddToWorklist(Temp.getNode()); 14259 14260 if (N2C->isOne()) 14261 return Temp; 14262 14263 // shl setcc result by log2 n2c 14264 return DAG.getNode( 14265 ISD::SHL, DL, N2.getValueType(), Temp, 14266 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14267 getShiftAmountTy(Temp.getValueType()))); 14268 } 14269 } 14270 14271 // Check to see if this is an integer abs. 14272 // select_cc setg[te] X, 0, X, -X -> 14273 // select_cc setgt X, -1, X, -X -> 14274 // select_cc setl[te] X, 0, -X, X -> 14275 // select_cc setlt X, 1, -X, X -> 14276 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14277 if (N1C) { 14278 ConstantSDNode *SubC = nullptr; 14279 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14280 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14281 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14282 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14283 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14284 (N1C->isOne() && CC == ISD::SETLT)) && 14285 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14286 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14287 14288 EVT XType = N0.getValueType(); 14289 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14290 SDLoc DL(N0); 14291 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14292 N0, 14293 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14294 getShiftAmountTy(N0.getValueType()))); 14295 SDValue Add = DAG.getNode(ISD::ADD, DL, 14296 XType, N0, Shift); 14297 AddToWorklist(Shift.getNode()); 14298 AddToWorklist(Add.getNode()); 14299 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14300 } 14301 } 14302 14303 return SDValue(); 14304 } 14305 14306 /// This is a stub for TargetLowering::SimplifySetCC. 14307 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 14308 SDValue N1, ISD::CondCode Cond, 14309 SDLoc DL, bool foldBooleans) { 14310 TargetLowering::DAGCombinerInfo 14311 DagCombineInfo(DAG, Level, false, this); 14312 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14313 } 14314 14315 /// Given an ISD::SDIV node expressing a divide by constant, return 14316 /// a DAG expression to select that will generate the same value by multiplying 14317 /// by a magic number. 14318 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14319 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14320 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14321 if (!C) 14322 return SDValue(); 14323 14324 // Avoid division by zero. 14325 if (C->isNullValue()) 14326 return SDValue(); 14327 14328 std::vector<SDNode*> Built; 14329 SDValue S = 14330 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14331 14332 for (SDNode *N : Built) 14333 AddToWorklist(N); 14334 return S; 14335 } 14336 14337 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14338 /// DAG expression that will generate the same value by right shifting. 14339 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14340 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14341 if (!C) 14342 return SDValue(); 14343 14344 // Avoid division by zero. 14345 if (C->isNullValue()) 14346 return SDValue(); 14347 14348 std::vector<SDNode *> Built; 14349 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14350 14351 for (SDNode *N : Built) 14352 AddToWorklist(N); 14353 return S; 14354 } 14355 14356 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14357 /// expression that will generate the same value by multiplying by a magic 14358 /// number. 14359 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14360 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14361 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14362 if (!C) 14363 return SDValue(); 14364 14365 // Avoid division by zero. 14366 if (C->isNullValue()) 14367 return SDValue(); 14368 14369 std::vector<SDNode*> Built; 14370 SDValue S = 14371 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14372 14373 for (SDNode *N : Built) 14374 AddToWorklist(N); 14375 return S; 14376 } 14377 14378 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14379 if (Level >= AfterLegalizeDAG) 14380 return SDValue(); 14381 14382 // Expose the DAG combiner to the target combiner implementations. 14383 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14384 14385 unsigned Iterations = 0; 14386 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14387 if (Iterations) { 14388 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14389 // For the reciprocal, we need to find the zero of the function: 14390 // F(X) = A X - 1 [which has a zero at X = 1/A] 14391 // => 14392 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14393 // does not require additional intermediate precision] 14394 EVT VT = Op.getValueType(); 14395 SDLoc DL(Op); 14396 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14397 14398 AddToWorklist(Est.getNode()); 14399 14400 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14401 for (unsigned i = 0; i < Iterations; ++i) { 14402 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14403 AddToWorklist(NewEst.getNode()); 14404 14405 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14406 AddToWorklist(NewEst.getNode()); 14407 14408 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14409 AddToWorklist(NewEst.getNode()); 14410 14411 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14412 AddToWorklist(Est.getNode()); 14413 } 14414 } 14415 return Est; 14416 } 14417 14418 return SDValue(); 14419 } 14420 14421 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14422 /// For the reciprocal sqrt, we need to find the zero of the function: 14423 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14424 /// => 14425 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14426 /// As a result, we precompute A/2 prior to the iteration loop. 14427 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14428 unsigned Iterations, 14429 SDNodeFlags *Flags) { 14430 EVT VT = Arg.getValueType(); 14431 SDLoc DL(Arg); 14432 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14433 14434 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14435 // this entire sequence requires only one FP constant. 14436 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14437 AddToWorklist(HalfArg.getNode()); 14438 14439 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14440 AddToWorklist(HalfArg.getNode()); 14441 14442 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14443 for (unsigned i = 0; i < Iterations; ++i) { 14444 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14445 AddToWorklist(NewEst.getNode()); 14446 14447 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14448 AddToWorklist(NewEst.getNode()); 14449 14450 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14451 AddToWorklist(NewEst.getNode()); 14452 14453 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14454 AddToWorklist(Est.getNode()); 14455 } 14456 return Est; 14457 } 14458 14459 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14460 /// For the reciprocal sqrt, we need to find the zero of the function: 14461 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14462 /// => 14463 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14464 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14465 unsigned Iterations, 14466 SDNodeFlags *Flags) { 14467 EVT VT = Arg.getValueType(); 14468 SDLoc DL(Arg); 14469 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14470 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14471 14472 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14473 for (unsigned i = 0; i < Iterations; ++i) { 14474 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14475 AddToWorklist(HalfEst.getNode()); 14476 14477 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14478 AddToWorklist(Est.getNode()); 14479 14480 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14481 AddToWorklist(Est.getNode()); 14482 14483 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14484 AddToWorklist(Est.getNode()); 14485 14486 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14487 AddToWorklist(Est.getNode()); 14488 } 14489 return Est; 14490 } 14491 14492 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14493 if (Level >= AfterLegalizeDAG) 14494 return SDValue(); 14495 14496 // Expose the DAG combiner to the target combiner implementations. 14497 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14498 unsigned Iterations = 0; 14499 bool UseOneConstNR = false; 14500 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14501 AddToWorklist(Est.getNode()); 14502 if (Iterations) { 14503 Est = UseOneConstNR ? 14504 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14505 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14506 } 14507 return Est; 14508 } 14509 14510 return SDValue(); 14511 } 14512 14513 /// Return true if base is a frame index, which is known not to alias with 14514 /// anything but itself. Provides base object and offset as results. 14515 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14516 const GlobalValue *&GV, const void *&CV) { 14517 // Assume it is a primitive operation. 14518 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14519 14520 // If it's an adding a simple constant then integrate the offset. 14521 if (Base.getOpcode() == ISD::ADD) { 14522 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14523 Base = Base.getOperand(0); 14524 Offset += C->getZExtValue(); 14525 } 14526 } 14527 14528 // Return the underlying GlobalValue, and update the Offset. Return false 14529 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14530 // by multiple nodes with different offsets. 14531 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14532 GV = G->getGlobal(); 14533 Offset += G->getOffset(); 14534 return false; 14535 } 14536 14537 // Return the underlying Constant value, and update the Offset. Return false 14538 // for ConstantSDNodes since the same constant pool entry may be represented 14539 // by multiple nodes with different offsets. 14540 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14541 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14542 : (const void *)C->getConstVal(); 14543 Offset += C->getOffset(); 14544 return false; 14545 } 14546 // If it's any of the following then it can't alias with anything but itself. 14547 return isa<FrameIndexSDNode>(Base); 14548 } 14549 14550 /// Return true if there is any possibility that the two addresses overlap. 14551 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14552 // If they are the same then they must be aliases. 14553 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14554 14555 // If they are both volatile then they cannot be reordered. 14556 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14557 14558 // If one operation reads from invariant memory, and the other may store, they 14559 // cannot alias. These should really be checking the equivalent of mayWrite, 14560 // but it only matters for memory nodes other than load /store. 14561 if (Op0->isInvariant() && Op1->writeMem()) 14562 return false; 14563 14564 if (Op1->isInvariant() && Op0->writeMem()) 14565 return false; 14566 14567 // Gather base node and offset information. 14568 SDValue Base1, Base2; 14569 int64_t Offset1, Offset2; 14570 const GlobalValue *GV1, *GV2; 14571 const void *CV1, *CV2; 14572 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14573 Base1, Offset1, GV1, CV1); 14574 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14575 Base2, Offset2, GV2, CV2); 14576 14577 // If they have a same base address then check to see if they overlap. 14578 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14579 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14580 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14581 14582 // It is possible for different frame indices to alias each other, mostly 14583 // when tail call optimization reuses return address slots for arguments. 14584 // To catch this case, look up the actual index of frame indices to compute 14585 // the real alias relationship. 14586 if (isFrameIndex1 && isFrameIndex2) { 14587 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14588 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14589 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14590 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14591 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14592 } 14593 14594 // Otherwise, if we know what the bases are, and they aren't identical, then 14595 // we know they cannot alias. 14596 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14597 return false; 14598 14599 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14600 // compared to the size and offset of the access, we may be able to prove they 14601 // do not alias. This check is conservative for now to catch cases created by 14602 // splitting vector types. 14603 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14604 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14605 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14606 Op1->getMemoryVT().getSizeInBits() >> 3) && 14607 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14608 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14609 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14610 14611 // There is no overlap between these relatively aligned accesses of similar 14612 // size, return no alias. 14613 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14614 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14615 return false; 14616 } 14617 14618 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14619 ? CombinerGlobalAA 14620 : DAG.getSubtarget().useAA(); 14621 #ifndef NDEBUG 14622 if (CombinerAAOnlyFunc.getNumOccurrences() && 14623 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14624 UseAA = false; 14625 #endif 14626 if (UseAA && 14627 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14628 // Use alias analysis information. 14629 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14630 Op1->getSrcValueOffset()); 14631 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14632 Op0->getSrcValueOffset() - MinOffset; 14633 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14634 Op1->getSrcValueOffset() - MinOffset; 14635 AliasResult AAResult = 14636 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14637 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14638 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14639 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14640 if (AAResult == NoAlias) 14641 return false; 14642 } 14643 14644 // Otherwise we have to assume they alias. 14645 return true; 14646 } 14647 14648 /// Walk up chain skipping non-aliasing memory nodes, 14649 /// looking for aliasing nodes and adding them to the Aliases vector. 14650 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14651 SmallVectorImpl<SDValue> &Aliases) { 14652 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14653 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14654 14655 // Get alias information for node. 14656 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14657 14658 // Starting off. 14659 Chains.push_back(OriginalChain); 14660 unsigned Depth = 0; 14661 14662 // Look at each chain and determine if it is an alias. If so, add it to the 14663 // aliases list. If not, then continue up the chain looking for the next 14664 // candidate. 14665 while (!Chains.empty()) { 14666 SDValue Chain = Chains.pop_back_val(); 14667 14668 // For TokenFactor nodes, look at each operand and only continue up the 14669 // chain until we reach the depth limit. 14670 // 14671 // FIXME: The depth check could be made to return the last non-aliasing 14672 // chain we found before we hit a tokenfactor rather than the original 14673 // chain. 14674 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14675 Aliases.clear(); 14676 Aliases.push_back(OriginalChain); 14677 return; 14678 } 14679 14680 // Don't bother if we've been before. 14681 if (!Visited.insert(Chain.getNode()).second) 14682 continue; 14683 14684 switch (Chain.getOpcode()) { 14685 case ISD::EntryToken: 14686 // Entry token is ideal chain operand, but handled in FindBetterChain. 14687 break; 14688 14689 case ISD::LOAD: 14690 case ISD::STORE: { 14691 // Get alias information for Chain. 14692 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14693 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14694 14695 // If chain is alias then stop here. 14696 if (!(IsLoad && IsOpLoad) && 14697 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14698 Aliases.push_back(Chain); 14699 } else { 14700 // Look further up the chain. 14701 Chains.push_back(Chain.getOperand(0)); 14702 ++Depth; 14703 } 14704 break; 14705 } 14706 14707 case ISD::TokenFactor: 14708 // We have to check each of the operands of the token factor for "small" 14709 // token factors, so we queue them up. Adding the operands to the queue 14710 // (stack) in reverse order maintains the original order and increases the 14711 // likelihood that getNode will find a matching token factor (CSE.) 14712 if (Chain.getNumOperands() > 16) { 14713 Aliases.push_back(Chain); 14714 break; 14715 } 14716 for (unsigned n = Chain.getNumOperands(); n;) 14717 Chains.push_back(Chain.getOperand(--n)); 14718 ++Depth; 14719 break; 14720 14721 default: 14722 // For all other instructions we will just have to take what we can get. 14723 Aliases.push_back(Chain); 14724 break; 14725 } 14726 } 14727 } 14728 14729 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14730 /// (aliasing node.) 14731 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14732 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14733 14734 // Accumulate all the aliases to this node. 14735 GatherAllAliases(N, OldChain, Aliases); 14736 14737 // If no operands then chain to entry token. 14738 if (Aliases.size() == 0) 14739 return DAG.getEntryNode(); 14740 14741 // If a single operand then chain to it. We don't need to revisit it. 14742 if (Aliases.size() == 1) 14743 return Aliases[0]; 14744 14745 // Construct a custom tailored token factor. 14746 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14747 } 14748 14749 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14750 // This holds the base pointer, index, and the offset in bytes from the base 14751 // pointer. 14752 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14753 14754 // We must have a base and an offset. 14755 if (!BasePtr.Base.getNode()) 14756 return false; 14757 14758 // Do not handle stores to undef base pointers. 14759 if (BasePtr.Base.isUndef()) 14760 return false; 14761 14762 SmallVector<StoreSDNode *, 8> ChainedStores; 14763 ChainedStores.push_back(St); 14764 14765 // Walk up the chain and look for nodes with offsets from the same 14766 // base pointer. Stop when reaching an instruction with a different kind 14767 // or instruction which has a different base pointer. 14768 StoreSDNode *Index = St; 14769 while (Index) { 14770 // If the chain has more than one use, then we can't reorder the mem ops. 14771 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14772 break; 14773 14774 if (Index->isVolatile() || Index->isIndexed()) 14775 break; 14776 14777 // Find the base pointer and offset for this memory node. 14778 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 14779 14780 // Check that the base pointer is the same as the original one. 14781 if (!Ptr.equalBaseIndex(BasePtr)) 14782 break; 14783 14784 // Find the next memory operand in the chain. If the next operand in the 14785 // chain is a store then move up and continue the scan with the next 14786 // memory operand. If the next operand is a load save it and use alias 14787 // information to check if it interferes with anything. 14788 SDNode *NextInChain = Index->getChain().getNode(); 14789 while (true) { 14790 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14791 // We found a store node. Use it for the next iteration. 14792 if (STn->isVolatile() || STn->isIndexed()) { 14793 Index = nullptr; 14794 break; 14795 } 14796 ChainedStores.push_back(STn); 14797 Index = STn; 14798 break; 14799 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14800 NextInChain = Ldn->getChain().getNode(); 14801 continue; 14802 } else { 14803 Index = nullptr; 14804 break; 14805 } 14806 } 14807 } 14808 14809 bool MadeChange = false; 14810 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14811 14812 for (StoreSDNode *ChainedStore : ChainedStores) { 14813 SDValue Chain = ChainedStore->getChain(); 14814 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14815 14816 if (Chain != BetterChain) { 14817 MadeChange = true; 14818 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14819 } 14820 } 14821 14822 // Do all replacements after finding the replacements to make to avoid making 14823 // the chains more complicated by introducing new TokenFactors. 14824 for (auto Replacement : BetterChains) 14825 replaceStoreChain(Replacement.first, Replacement.second); 14826 14827 return MadeChange; 14828 } 14829 14830 /// This is the entry point for the file. 14831 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14832 CodeGenOpt::Level OptLevel) { 14833 /// This is the main entry point to this class. 14834 DAGCombiner(*this, AA, OptLevel).Run(Level); 14835 } 14836