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/CodeGen/SelectionDAGTargetInfo.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetLowering.h" 38 #include "llvm/Target/TargetOptions.h" 39 #include "llvm/Target/TargetRegisterInfo.h" 40 #include "llvm/Target/TargetSubtargetInfo.h" 41 #include <algorithm> 42 using namespace llvm; 43 44 #define DEBUG_TYPE "dagcombine" 45 46 STATISTIC(NodesCombined , "Number of dag nodes combined"); 47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 49 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 50 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 51 STATISTIC(SlicedLoads, "Number of load sliced"); 52 53 namespace { 54 static cl::opt<bool> 55 CombinerAA("combiner-alias-analysis", cl::Hidden, 56 cl::desc("Enable DAG combiner alias-analysis heuristics")); 57 58 static cl::opt<bool> 59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 60 cl::desc("Enable DAG combiner's use of IR alias analysis")); 61 62 static cl::opt<bool> 63 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 64 cl::desc("Enable DAG combiner's use of TBAA")); 65 66 #ifndef NDEBUG 67 static cl::opt<std::string> 68 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 69 cl::desc("Only use DAG-combiner alias analysis in this" 70 " function")); 71 #endif 72 73 /// Hidden option to stress test load slicing, i.e., when this option 74 /// is enabled, load slicing bypasses most of its profitability guards. 75 static cl::opt<bool> 76 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 77 cl::desc("Bypass the profitability model of load " 78 "slicing"), 79 cl::init(false)); 80 81 static cl::opt<bool> 82 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 83 cl::desc("DAG combiner may split indexing from loads")); 84 85 //------------------------------ DAGCombiner ---------------------------------// 86 87 class DAGCombiner { 88 SelectionDAG &DAG; 89 const TargetLowering &TLI; 90 CombineLevel Level; 91 CodeGenOpt::Level OptLevel; 92 bool LegalOperations; 93 bool LegalTypes; 94 bool ForCodeSize; 95 96 /// \brief Worklist of all of the nodes that need to be simplified. 97 /// 98 /// This must behave as a stack -- new nodes to process are pushed onto the 99 /// back and when processing we pop off of the back. 100 /// 101 /// The worklist will not contain duplicates but may contain null entries 102 /// due to nodes being deleted from the underlying DAG. 103 SmallVector<SDNode *, 64> Worklist; 104 105 /// \brief Mapping from an SDNode to its position on the worklist. 106 /// 107 /// This is used to find and remove nodes from the worklist (by nulling 108 /// them) when they are deleted from the underlying DAG. It relies on 109 /// stable indices of nodes within the worklist. 110 DenseMap<SDNode *, unsigned> WorklistMap; 111 112 /// \brief Set of nodes which have been combined (at least once). 113 /// 114 /// This is used to allow us to reliably add any operands of a DAG node 115 /// which have not yet been combined to the worklist. 116 SmallPtrSet<SDNode *, 32> CombinedNodes; 117 118 // AA - Used for DAG load/store alias analysis. 119 AliasAnalysis &AA; 120 121 /// When an instruction is simplified, add all users of the instruction to 122 /// the work lists because they might get more simplified now. 123 void AddUsersToWorklist(SDNode *N) { 124 for (SDNode *Node : N->uses()) 125 AddToWorklist(Node); 126 } 127 128 /// Call the node-specific routine that folds each particular type of node. 129 SDValue visit(SDNode *N); 130 131 public: 132 /// Add to the worklist making sure its instance is at the back (next to be 133 /// processed.) 134 void AddToWorklist(SDNode *N) { 135 // Skip handle nodes as they can't usefully be combined and confuse the 136 // zero-use deletion strategy. 137 if (N->getOpcode() == ISD::HANDLENODE) 138 return; 139 140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 141 Worklist.push_back(N); 142 } 143 144 /// Remove all instances of N from the worklist. 145 void removeFromWorklist(SDNode *N) { 146 CombinedNodes.erase(N); 147 148 auto It = WorklistMap.find(N); 149 if (It == WorklistMap.end()) 150 return; // Not in the worklist. 151 152 // Null out the entry rather than erasing it to avoid a linear operation. 153 Worklist[It->second] = nullptr; 154 WorklistMap.erase(It); 155 } 156 157 void deleteAndRecombine(SDNode *N); 158 bool recursivelyDeleteUnusedNodes(SDNode *N); 159 160 /// Replaces all uses of the results of one DAG node with new values. 161 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 162 bool AddTo = true); 163 164 /// Replaces all uses of the results of one DAG node with new values. 165 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 166 return CombineTo(N, &Res, 1, AddTo); 167 } 168 169 /// Replaces all uses of the results of one DAG node with new values. 170 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 171 bool AddTo = true) { 172 SDValue To[] = { Res0, Res1 }; 173 return CombineTo(N, To, 2, AddTo); 174 } 175 176 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 177 178 private: 179 180 /// Check the specified integer node value to see if it can be simplified or 181 /// if things it uses can be simplified by bit propagation. 182 /// If so, return true. 183 bool SimplifyDemandedBits(SDValue Op) { 184 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 185 APInt Demanded = APInt::getAllOnesValue(BitWidth); 186 return SimplifyDemandedBits(Op, Demanded); 187 } 188 189 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 190 191 bool CombineToPreIndexedLoadStore(SDNode *N); 192 bool CombineToPostIndexedLoadStore(SDNode *N); 193 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 194 bool SliceUpLoad(SDNode *N); 195 196 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 197 /// load. 198 /// 199 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 200 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 201 /// \param EltNo index of the vector element to load. 202 /// \param OriginalLoad load that EVE came from to be replaced. 203 /// \returns EVE on success SDValue() on failure. 204 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 205 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 206 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 207 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 208 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 210 SDValue PromoteIntBinOp(SDValue Op); 211 SDValue PromoteIntShiftOp(SDValue Op); 212 SDValue PromoteExtend(SDValue Op); 213 bool PromoteLoad(SDValue Op); 214 215 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 216 SDValue ExtLoad, const SDLoc &DL, 217 ISD::NodeType ExtType); 218 219 /// Call the node-specific routine that knows how to fold each 220 /// particular type of node. If that doesn't do anything, try the 221 /// target-specific DAG combines. 222 SDValue combine(SDNode *N); 223 224 // Visitation implementation - Implement dag node combining for different 225 // node types. The semantics are as follows: 226 // Return Value: 227 // SDValue.getNode() == 0 - No change was made 228 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 229 // otherwise - N should be replaced by the returned Operand. 230 // 231 SDValue visitTokenFactor(SDNode *N); 232 SDValue visitMERGE_VALUES(SDNode *N); 233 SDValue visitADD(SDNode *N); 234 SDValue visitSUB(SDNode *N); 235 SDValue visitADDC(SDNode *N); 236 SDValue visitSUBC(SDNode *N); 237 SDValue visitADDE(SDNode *N); 238 SDValue visitSUBE(SDNode *N); 239 SDValue visitMUL(SDNode *N); 240 SDValue useDivRem(SDNode *N); 241 SDValue visitSDIV(SDNode *N); 242 SDValue visitUDIV(SDNode *N); 243 SDValue visitREM(SDNode *N); 244 SDValue visitMULHU(SDNode *N); 245 SDValue visitMULHS(SDNode *N); 246 SDValue visitSMUL_LOHI(SDNode *N); 247 SDValue visitUMUL_LOHI(SDNode *N); 248 SDValue visitSMULO(SDNode *N); 249 SDValue visitUMULO(SDNode *N); 250 SDValue visitIMINMAX(SDNode *N); 251 SDValue visitAND(SDNode *N); 252 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 253 SDValue visitOR(SDNode *N); 254 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 255 SDValue visitXOR(SDNode *N); 256 SDValue SimplifyVBinOp(SDNode *N); 257 SDValue visitSHL(SDNode *N); 258 SDValue visitSRA(SDNode *N); 259 SDValue visitSRL(SDNode *N); 260 SDValue visitRotate(SDNode *N); 261 SDValue visitBSWAP(SDNode *N); 262 SDValue visitBITREVERSE(SDNode *N); 263 SDValue visitCTLZ(SDNode *N); 264 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 265 SDValue visitCTTZ(SDNode *N); 266 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 267 SDValue visitCTPOP(SDNode *N); 268 SDValue visitSELECT(SDNode *N); 269 SDValue visitVSELECT(SDNode *N); 270 SDValue visitSELECT_CC(SDNode *N); 271 SDValue visitSETCC(SDNode *N); 272 SDValue visitSETCCE(SDNode *N); 273 SDValue visitSIGN_EXTEND(SDNode *N); 274 SDValue visitZERO_EXTEND(SDNode *N); 275 SDValue visitANY_EXTEND(SDNode *N); 276 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 277 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 278 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 279 SDValue visitTRUNCATE(SDNode *N); 280 SDValue visitBITCAST(SDNode *N); 281 SDValue visitBUILD_PAIR(SDNode *N); 282 SDValue visitFADD(SDNode *N); 283 SDValue visitFSUB(SDNode *N); 284 SDValue visitFMUL(SDNode *N); 285 SDValue visitFMA(SDNode *N); 286 SDValue visitFDIV(SDNode *N); 287 SDValue visitFREM(SDNode *N); 288 SDValue visitFSQRT(SDNode *N); 289 SDValue visitFCOPYSIGN(SDNode *N); 290 SDValue visitSINT_TO_FP(SDNode *N); 291 SDValue visitUINT_TO_FP(SDNode *N); 292 SDValue visitFP_TO_SINT(SDNode *N); 293 SDValue visitFP_TO_UINT(SDNode *N); 294 SDValue visitFP_ROUND(SDNode *N); 295 SDValue visitFP_ROUND_INREG(SDNode *N); 296 SDValue visitFP_EXTEND(SDNode *N); 297 SDValue visitFNEG(SDNode *N); 298 SDValue visitFABS(SDNode *N); 299 SDValue visitFCEIL(SDNode *N); 300 SDValue visitFTRUNC(SDNode *N); 301 SDValue visitFFLOOR(SDNode *N); 302 SDValue visitFMINNUM(SDNode *N); 303 SDValue visitFMAXNUM(SDNode *N); 304 SDValue visitBRCOND(SDNode *N); 305 SDValue visitBR_CC(SDNode *N); 306 SDValue visitLOAD(SDNode *N); 307 308 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 309 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 310 311 SDValue visitSTORE(SDNode *N); 312 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 313 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 314 SDValue visitBUILD_VECTOR(SDNode *N); 315 SDValue visitCONCAT_VECTORS(SDNode *N); 316 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 317 SDValue visitVECTOR_SHUFFLE(SDNode *N); 318 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 319 SDValue visitINSERT_SUBVECTOR(SDNode *N); 320 SDValue visitMLOAD(SDNode *N); 321 SDValue visitMSTORE(SDNode *N); 322 SDValue visitMGATHER(SDNode *N); 323 SDValue visitMSCATTER(SDNode *N); 324 SDValue visitFP_TO_FP16(SDNode *N); 325 SDValue visitFP16_TO_FP(SDNode *N); 326 327 SDValue visitFADDForFMACombine(SDNode *N); 328 SDValue visitFSUBForFMACombine(SDNode *N); 329 SDValue visitFMULForFMACombine(SDNode *N); 330 331 SDValue XformToShuffleWithZero(SDNode *N); 332 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 333 SDValue RHS); 334 335 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 336 337 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 338 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 339 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 340 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 341 SDValue N2, SDValue N3, ISD::CondCode CC, 342 bool NotExtCompare = false); 343 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 344 const SDLoc &DL, bool foldBooleans = true); 345 346 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 347 SDValue &CC) const; 348 bool isOneUseSetCC(SDValue N) const; 349 350 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 351 unsigned HiOp); 352 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 353 SDValue CombineExtLoad(SDNode *N); 354 SDValue combineRepeatedFPDivisors(SDNode *N); 355 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 356 SDValue BuildSDIV(SDNode *N); 357 SDValue BuildSDIVPow2(SDNode *N); 358 SDValue BuildUDIV(SDNode *N); 359 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 360 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 361 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags); 362 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip); 363 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 364 SDNodeFlags *Flags, bool Reciprocal); 365 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 366 SDNodeFlags *Flags, bool Reciprocal); 367 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 368 bool DemandHighBits = true); 369 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 370 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 371 SDValue InnerPos, SDValue InnerNeg, 372 unsigned PosOpcode, unsigned NegOpcode, 373 const SDLoc &DL); 374 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 375 SDValue ReduceLoadWidth(SDNode *N); 376 SDValue ReduceLoadOpStoreWidth(SDNode *N); 377 SDValue TransformFPLoadStorePair(SDNode *N); 378 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 379 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 380 381 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 382 383 /// Walk up chain skipping non-aliasing memory nodes, 384 /// looking for aliasing nodes and adding them to the Aliases vector. 385 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 386 SmallVectorImpl<SDValue> &Aliases); 387 388 /// Return true if there is any possibility that the two addresses overlap. 389 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 390 391 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 392 /// chain (aliasing node.) 393 SDValue FindBetterChain(SDNode *N, SDValue Chain); 394 395 /// Try to replace a store and any possibly adjacent stores on 396 /// consecutive chains with better chains. Return true only if St is 397 /// replaced. 398 /// 399 /// Notice that other chains may still be replaced even if the function 400 /// returns false. 401 bool findBetterNeighborChains(StoreSDNode *St); 402 403 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 404 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 405 406 /// Holds a pointer to an LSBaseSDNode as well as information on where it 407 /// is located in a sequence of memory operations connected by a chain. 408 struct MemOpLink { 409 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 410 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 411 // Ptr to the mem node. 412 LSBaseSDNode *MemNode; 413 // Offset from the base ptr. 414 int64_t OffsetFromBase; 415 // What is the sequence number of this mem node. 416 // Lowest mem operand in the DAG starts at zero. 417 unsigned SequenceNum; 418 }; 419 420 /// This is a helper function for visitMUL to check the profitability 421 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 422 /// MulNode is the original multiply, AddNode is (add x, c1), 423 /// and ConstNode is c2. 424 bool isMulAddWithConstProfitable(SDNode *MulNode, 425 SDValue &AddNode, 426 SDValue &ConstNode); 427 428 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 429 /// constant build_vector of the stored constant values in Stores. 430 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL, 431 ArrayRef<MemOpLink> Stores, 432 SmallVectorImpl<SDValue> &Chains, 433 EVT Ty) const; 434 435 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 436 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 437 /// the type of the loaded value to be extended. LoadedVT returns the type 438 /// of the original loaded value. NarrowLoad returns whether the load would 439 /// need to be narrowed in order to match. 440 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 441 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 442 bool &NarrowLoad); 443 444 /// This is a helper function for MergeConsecutiveStores. When the source 445 /// elements of the consecutive stores are all constants or all extracted 446 /// vector elements, try to merge them into one larger store. 447 /// \return True if a merged store was created. 448 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 449 EVT MemVT, unsigned NumStores, 450 bool IsConstantSrc, bool UseVector); 451 452 /// This is a helper function for MergeConsecutiveStores. 453 /// Stores that may be merged are placed in StoreNodes. 454 /// Loads that may alias with those stores are placed in AliasLoadNodes. 455 void getStoreMergeAndAliasCandidates( 456 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 457 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 458 459 /// Helper function for MergeConsecutiveStores. Checks if 460 /// Candidate stores have indirect dependency through their 461 /// operands. \return True if safe to merge 462 bool checkMergeStoreCandidatesForDependencies( 463 SmallVectorImpl<MemOpLink> &StoreNodes); 464 465 /// Merge consecutive store operations into a wide store. 466 /// This optimization uses wide integers or vectors when possible. 467 /// \return True if some memory operations were changed. 468 bool MergeConsecutiveStores(StoreSDNode *N); 469 470 /// \brief Try to transform a truncation where C is a constant: 471 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 472 /// 473 /// \p N needs to be a truncation and its first operand an AND. Other 474 /// requirements are checked by the function (e.g. that trunc is 475 /// single-use) and if missed an empty SDValue is returned. 476 SDValue distributeTruncateThroughAnd(SDNode *N); 477 478 public: 479 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 480 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 481 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 482 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 483 } 484 485 /// Runs the dag combiner on all nodes in the work list 486 void Run(CombineLevel AtLevel); 487 488 SelectionDAG &getDAG() const { return DAG; } 489 490 /// Returns a type large enough to hold any valid shift amount - before type 491 /// legalization these can be huge. 492 EVT getShiftAmountTy(EVT LHSTy) { 493 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 494 if (LHSTy.isVector()) 495 return LHSTy; 496 auto &DL = DAG.getDataLayout(); 497 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 498 : TLI.getPointerTy(DL); 499 } 500 501 /// This method returns true if we are running before type legalization or 502 /// if the specified VT is legal. 503 bool isTypeLegal(const EVT &VT) { 504 if (!LegalTypes) return true; 505 return TLI.isTypeLegal(VT); 506 } 507 508 /// Convenience wrapper around TargetLowering::getSetCCResultType 509 EVT getSetCCResultType(EVT VT) const { 510 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 511 } 512 }; 513 } 514 515 516 namespace { 517 /// This class is a DAGUpdateListener that removes any deleted 518 /// nodes from the worklist. 519 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 520 DAGCombiner &DC; 521 public: 522 explicit WorklistRemover(DAGCombiner &dc) 523 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 524 525 void NodeDeleted(SDNode *N, SDNode *E) override { 526 DC.removeFromWorklist(N); 527 } 528 }; 529 } 530 531 //===----------------------------------------------------------------------===// 532 // TargetLowering::DAGCombinerInfo implementation 533 //===----------------------------------------------------------------------===// 534 535 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 536 ((DAGCombiner*)DC)->AddToWorklist(N); 537 } 538 539 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 540 ((DAGCombiner*)DC)->removeFromWorklist(N); 541 } 542 543 SDValue TargetLowering::DAGCombinerInfo:: 544 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 545 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 546 } 547 548 SDValue TargetLowering::DAGCombinerInfo:: 549 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 550 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 551 } 552 553 554 SDValue TargetLowering::DAGCombinerInfo:: 555 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 556 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 557 } 558 559 void TargetLowering::DAGCombinerInfo:: 560 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 561 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 562 } 563 564 //===----------------------------------------------------------------------===// 565 // Helper Functions 566 //===----------------------------------------------------------------------===// 567 568 void DAGCombiner::deleteAndRecombine(SDNode *N) { 569 removeFromWorklist(N); 570 571 // If the operands of this node are only used by the node, they will now be 572 // dead. Make sure to re-visit them and recursively delete dead nodes. 573 for (const SDValue &Op : N->ops()) 574 // For an operand generating multiple values, one of the values may 575 // become dead allowing further simplification (e.g. split index 576 // arithmetic from an indexed load). 577 if (Op->hasOneUse() || Op->getNumValues() > 1) 578 AddToWorklist(Op.getNode()); 579 580 DAG.DeleteNode(N); 581 } 582 583 /// Return 1 if we can compute the negated form of the specified expression for 584 /// the same cost as the expression itself, or 2 if we can compute the negated 585 /// form more cheaply than the expression itself. 586 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 587 const TargetLowering &TLI, 588 const TargetOptions *Options, 589 unsigned Depth = 0) { 590 // fneg is removable even if it has multiple uses. 591 if (Op.getOpcode() == ISD::FNEG) return 2; 592 593 // Don't allow anything with multiple uses. 594 if (!Op.hasOneUse()) return 0; 595 596 // Don't recurse exponentially. 597 if (Depth > 6) return 0; 598 599 switch (Op.getOpcode()) { 600 default: return false; 601 case ISD::ConstantFP: 602 // Don't invert constant FP values after legalize. The negated constant 603 // isn't necessarily legal. 604 return LegalOperations ? 0 : 1; 605 case ISD::FADD: 606 // FIXME: determine better conditions for this xform. 607 if (!Options->UnsafeFPMath) return 0; 608 609 // After operation legalization, it might not be legal to create new FSUBs. 610 if (LegalOperations && 611 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 612 return 0; 613 614 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 615 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 616 Options, Depth + 1)) 617 return V; 618 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 619 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 620 Depth + 1); 621 case ISD::FSUB: 622 // We can't turn -(A-B) into B-A when we honor signed zeros. 623 if (!Options->UnsafeFPMath) return 0; 624 625 // fold (fneg (fsub A, B)) -> (fsub B, A) 626 return 1; 627 628 case ISD::FMUL: 629 case ISD::FDIV: 630 if (Options->HonorSignDependentRoundingFPMath()) return 0; 631 632 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 633 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 634 Options, Depth + 1)) 635 return V; 636 637 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 638 Depth + 1); 639 640 case ISD::FP_EXTEND: 641 case ISD::FP_ROUND: 642 case ISD::FSIN: 643 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 644 Depth + 1); 645 } 646 } 647 648 /// If isNegatibleForFree returns true, return the newly negated expression. 649 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 650 bool LegalOperations, unsigned Depth = 0) { 651 const TargetOptions &Options = DAG.getTarget().Options; 652 // fneg is removable even if it has multiple uses. 653 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 654 655 // Don't allow anything with multiple uses. 656 assert(Op.hasOneUse() && "Unknown reuse!"); 657 658 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 659 660 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 661 662 switch (Op.getOpcode()) { 663 default: llvm_unreachable("Unknown code"); 664 case ISD::ConstantFP: { 665 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 666 V.changeSign(); 667 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 668 } 669 case ISD::FADD: 670 // FIXME: determine better conditions for this xform. 671 assert(Options.UnsafeFPMath); 672 673 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 674 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 675 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 676 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 677 GetNegatedExpression(Op.getOperand(0), DAG, 678 LegalOperations, Depth+1), 679 Op.getOperand(1), Flags); 680 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 681 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 682 GetNegatedExpression(Op.getOperand(1), DAG, 683 LegalOperations, Depth+1), 684 Op.getOperand(0), Flags); 685 case ISD::FSUB: 686 // We can't turn -(A-B) into B-A when we honor signed zeros. 687 assert(Options.UnsafeFPMath); 688 689 // fold (fneg (fsub 0, B)) -> B 690 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 691 if (N0CFP->isZero()) 692 return Op.getOperand(1); 693 694 // fold (fneg (fsub A, B)) -> (fsub B, A) 695 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 696 Op.getOperand(1), Op.getOperand(0), Flags); 697 698 case ISD::FMUL: 699 case ISD::FDIV: 700 assert(!Options.HonorSignDependentRoundingFPMath()); 701 702 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 703 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 704 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 705 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 706 GetNegatedExpression(Op.getOperand(0), DAG, 707 LegalOperations, Depth+1), 708 Op.getOperand(1), Flags); 709 710 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 711 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 712 Op.getOperand(0), 713 GetNegatedExpression(Op.getOperand(1), DAG, 714 LegalOperations, Depth+1), Flags); 715 716 case ISD::FP_EXTEND: 717 case ISD::FSIN: 718 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 719 GetNegatedExpression(Op.getOperand(0), DAG, 720 LegalOperations, Depth+1)); 721 case ISD::FP_ROUND: 722 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 723 GetNegatedExpression(Op.getOperand(0), DAG, 724 LegalOperations, Depth+1), 725 Op.getOperand(1)); 726 } 727 } 728 729 // Return true if this node is a setcc, or is a select_cc 730 // that selects between the target values used for true and false, making it 731 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 732 // the appropriate nodes based on the type of node we are checking. This 733 // simplifies life a bit for the callers. 734 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 735 SDValue &CC) const { 736 if (N.getOpcode() == ISD::SETCC) { 737 LHS = N.getOperand(0); 738 RHS = N.getOperand(1); 739 CC = N.getOperand(2); 740 return true; 741 } 742 743 if (N.getOpcode() != ISD::SELECT_CC || 744 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 745 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 746 return false; 747 748 if (TLI.getBooleanContents(N.getValueType()) == 749 TargetLowering::UndefinedBooleanContent) 750 return false; 751 752 LHS = N.getOperand(0); 753 RHS = N.getOperand(1); 754 CC = N.getOperand(4); 755 return true; 756 } 757 758 /// Return true if this is a SetCC-equivalent operation with only one use. 759 /// If this is true, it allows the users to invert the operation for free when 760 /// it is profitable to do so. 761 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 762 SDValue N0, N1, N2; 763 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 764 return true; 765 return false; 766 } 767 768 // \brief Returns the SDNode if it is a constant float BuildVector 769 // or constant float. 770 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 771 if (isa<ConstantFPSDNode>(N)) 772 return N.getNode(); 773 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 774 return N.getNode(); 775 return nullptr; 776 } 777 778 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 779 // int. 780 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 781 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 782 return CN; 783 784 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 785 BitVector UndefElements; 786 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 787 788 // BuildVectors can truncate their operands. Ignore that case here. 789 // FIXME: We blindly ignore splats which include undef which is overly 790 // pessimistic. 791 if (CN && UndefElements.none() && 792 CN->getValueType(0) == N.getValueType().getScalarType()) 793 return CN; 794 } 795 796 return nullptr; 797 } 798 799 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 800 // float. 801 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 802 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 803 return CN; 804 805 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 806 BitVector UndefElements; 807 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 808 809 if (CN && UndefElements.none()) 810 return CN; 811 } 812 813 return nullptr; 814 } 815 816 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 817 SDValue N1) { 818 EVT VT = N0.getValueType(); 819 if (N0.getOpcode() == Opc) { 820 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 821 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 822 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 823 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 824 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 825 return SDValue(); 826 } 827 if (N0.hasOneUse()) { 828 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 829 // use 830 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 831 if (!OpNode.getNode()) 832 return SDValue(); 833 AddToWorklist(OpNode.getNode()); 834 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 835 } 836 } 837 } 838 839 if (N1.getOpcode() == Opc) { 840 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 841 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 842 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 843 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 844 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 845 return SDValue(); 846 } 847 if (N1.hasOneUse()) { 848 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 849 // use 850 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 851 if (!OpNode.getNode()) 852 return SDValue(); 853 AddToWorklist(OpNode.getNode()); 854 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 855 } 856 } 857 } 858 859 return SDValue(); 860 } 861 862 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 863 bool AddTo) { 864 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 865 ++NodesCombined; 866 DEBUG(dbgs() << "\nReplacing.1 "; 867 N->dump(&DAG); 868 dbgs() << "\nWith: "; 869 To[0].getNode()->dump(&DAG); 870 dbgs() << " and " << NumTo-1 << " other values\n"); 871 for (unsigned i = 0, e = NumTo; i != e; ++i) 872 assert((!To[i].getNode() || 873 N->getValueType(i) == To[i].getValueType()) && 874 "Cannot combine value to value of different type!"); 875 876 WorklistRemover DeadNodes(*this); 877 DAG.ReplaceAllUsesWith(N, To); 878 if (AddTo) { 879 // Push the new nodes and any users onto the worklist 880 for (unsigned i = 0, e = NumTo; i != e; ++i) { 881 if (To[i].getNode()) { 882 AddToWorklist(To[i].getNode()); 883 AddUsersToWorklist(To[i].getNode()); 884 } 885 } 886 } 887 888 // Finally, if the node is now dead, remove it from the graph. The node 889 // may not be dead if the replacement process recursively simplified to 890 // something else needing this node. 891 if (N->use_empty()) 892 deleteAndRecombine(N); 893 return SDValue(N, 0); 894 } 895 896 void DAGCombiner:: 897 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 898 // Replace all uses. If any nodes become isomorphic to other nodes and 899 // are deleted, make sure to remove them from our worklist. 900 WorklistRemover DeadNodes(*this); 901 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 902 903 // Push the new node and any (possibly new) users onto the worklist. 904 AddToWorklist(TLO.New.getNode()); 905 AddUsersToWorklist(TLO.New.getNode()); 906 907 // Finally, if the node is now dead, remove it from the graph. The node 908 // may not be dead if the replacement process recursively simplified to 909 // something else needing this node. 910 if (TLO.Old.getNode()->use_empty()) 911 deleteAndRecombine(TLO.Old.getNode()); 912 } 913 914 /// Check the specified integer node value to see if it can be simplified or if 915 /// things it uses can be simplified by bit propagation. If so, return true. 916 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 917 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 918 APInt KnownZero, KnownOne; 919 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 920 return false; 921 922 // Revisit the node. 923 AddToWorklist(Op.getNode()); 924 925 // Replace the old value with the new one. 926 ++NodesCombined; 927 DEBUG(dbgs() << "\nReplacing.2 "; 928 TLO.Old.getNode()->dump(&DAG); 929 dbgs() << "\nWith: "; 930 TLO.New.getNode()->dump(&DAG); 931 dbgs() << '\n'); 932 933 CommitTargetLoweringOpt(TLO); 934 return true; 935 } 936 937 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 938 SDLoc dl(Load); 939 EVT VT = Load->getValueType(0); 940 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 941 942 DEBUG(dbgs() << "\nReplacing.9 "; 943 Load->dump(&DAG); 944 dbgs() << "\nWith: "; 945 Trunc.getNode()->dump(&DAG); 946 dbgs() << '\n'); 947 WorklistRemover DeadNodes(*this); 948 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 949 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 950 deleteAndRecombine(Load); 951 AddToWorklist(Trunc.getNode()); 952 } 953 954 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 955 Replace = false; 956 SDLoc dl(Op); 957 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 958 LoadSDNode *LD = cast<LoadSDNode>(Op); 959 EVT MemVT = LD->getMemoryVT(); 960 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 961 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 962 : ISD::EXTLOAD) 963 : LD->getExtensionType(); 964 Replace = true; 965 return DAG.getExtLoad(ExtType, dl, PVT, 966 LD->getChain(), LD->getBasePtr(), 967 MemVT, LD->getMemOperand()); 968 } 969 970 unsigned Opc = Op.getOpcode(); 971 switch (Opc) { 972 default: break; 973 case ISD::AssertSext: 974 return DAG.getNode(ISD::AssertSext, dl, PVT, 975 SExtPromoteOperand(Op.getOperand(0), PVT), 976 Op.getOperand(1)); 977 case ISD::AssertZext: 978 return DAG.getNode(ISD::AssertZext, dl, PVT, 979 ZExtPromoteOperand(Op.getOperand(0), PVT), 980 Op.getOperand(1)); 981 case ISD::Constant: { 982 unsigned ExtOpc = 983 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 984 return DAG.getNode(ExtOpc, dl, PVT, Op); 985 } 986 } 987 988 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 989 return SDValue(); 990 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 991 } 992 993 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 994 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 995 return SDValue(); 996 EVT OldVT = Op.getValueType(); 997 SDLoc dl(Op); 998 bool Replace = false; 999 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1000 if (!NewOp.getNode()) 1001 return SDValue(); 1002 AddToWorklist(NewOp.getNode()); 1003 1004 if (Replace) 1005 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1006 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1007 DAG.getValueType(OldVT)); 1008 } 1009 1010 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1011 EVT OldVT = Op.getValueType(); 1012 SDLoc dl(Op); 1013 bool Replace = false; 1014 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1015 if (!NewOp.getNode()) 1016 return SDValue(); 1017 AddToWorklist(NewOp.getNode()); 1018 1019 if (Replace) 1020 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1021 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1022 } 1023 1024 /// Promote the specified integer binary operation if the target indicates it is 1025 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1026 /// i32 since i16 instructions are longer. 1027 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1028 if (!LegalOperations) 1029 return SDValue(); 1030 1031 EVT VT = Op.getValueType(); 1032 if (VT.isVector() || !VT.isInteger()) 1033 return SDValue(); 1034 1035 // If operation type is 'undesirable', e.g. i16 on x86, consider 1036 // promoting it. 1037 unsigned Opc = Op.getOpcode(); 1038 if (TLI.isTypeDesirableForOp(Opc, VT)) 1039 return SDValue(); 1040 1041 EVT PVT = VT; 1042 // Consult target whether it is a good idea to promote this operation and 1043 // what's the right type to promote it to. 1044 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1045 assert(PVT != VT && "Don't know what type to promote to!"); 1046 1047 bool Replace0 = false; 1048 SDValue N0 = Op.getOperand(0); 1049 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1050 if (!NN0.getNode()) 1051 return SDValue(); 1052 1053 bool Replace1 = false; 1054 SDValue N1 = Op.getOperand(1); 1055 SDValue NN1; 1056 if (N0 == N1) 1057 NN1 = NN0; 1058 else { 1059 NN1 = PromoteOperand(N1, PVT, Replace1); 1060 if (!NN1.getNode()) 1061 return SDValue(); 1062 } 1063 1064 AddToWorklist(NN0.getNode()); 1065 if (NN1.getNode()) 1066 AddToWorklist(NN1.getNode()); 1067 1068 if (Replace0) 1069 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1070 if (Replace1) 1071 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1072 1073 DEBUG(dbgs() << "\nPromoting "; 1074 Op.getNode()->dump(&DAG)); 1075 SDLoc dl(Op); 1076 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1077 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1078 } 1079 return SDValue(); 1080 } 1081 1082 /// Promote the specified integer shift operation if the target indicates it is 1083 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1084 /// i32 since i16 instructions are longer. 1085 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1086 if (!LegalOperations) 1087 return SDValue(); 1088 1089 EVT VT = Op.getValueType(); 1090 if (VT.isVector() || !VT.isInteger()) 1091 return SDValue(); 1092 1093 // If operation type is 'undesirable', e.g. i16 on x86, consider 1094 // promoting it. 1095 unsigned Opc = Op.getOpcode(); 1096 if (TLI.isTypeDesirableForOp(Opc, VT)) 1097 return SDValue(); 1098 1099 EVT PVT = VT; 1100 // Consult target whether it is a good idea to promote this operation and 1101 // what's the right type to promote it to. 1102 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1103 assert(PVT != VT && "Don't know what type to promote to!"); 1104 1105 bool Replace = false; 1106 SDValue N0 = Op.getOperand(0); 1107 if (Opc == ISD::SRA) 1108 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1109 else if (Opc == ISD::SRL) 1110 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1111 else 1112 N0 = PromoteOperand(N0, PVT, Replace); 1113 if (!N0.getNode()) 1114 return SDValue(); 1115 1116 AddToWorklist(N0.getNode()); 1117 if (Replace) 1118 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1119 1120 DEBUG(dbgs() << "\nPromoting "; 1121 Op.getNode()->dump(&DAG)); 1122 SDLoc dl(Op); 1123 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1124 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1125 } 1126 return SDValue(); 1127 } 1128 1129 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1130 if (!LegalOperations) 1131 return SDValue(); 1132 1133 EVT VT = Op.getValueType(); 1134 if (VT.isVector() || !VT.isInteger()) 1135 return SDValue(); 1136 1137 // If operation type is 'undesirable', e.g. i16 on x86, consider 1138 // promoting it. 1139 unsigned Opc = Op.getOpcode(); 1140 if (TLI.isTypeDesirableForOp(Opc, VT)) 1141 return SDValue(); 1142 1143 EVT PVT = VT; 1144 // Consult target whether it is a good idea to promote this operation and 1145 // what's the right type to promote it to. 1146 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1147 assert(PVT != VT && "Don't know what type to promote to!"); 1148 // fold (aext (aext x)) -> (aext x) 1149 // fold (aext (zext x)) -> (zext x) 1150 // fold (aext (sext x)) -> (sext x) 1151 DEBUG(dbgs() << "\nPromoting "; 1152 Op.getNode()->dump(&DAG)); 1153 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1154 } 1155 return SDValue(); 1156 } 1157 1158 bool DAGCombiner::PromoteLoad(SDValue Op) { 1159 if (!LegalOperations) 1160 return false; 1161 1162 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1163 return false; 1164 1165 EVT VT = Op.getValueType(); 1166 if (VT.isVector() || !VT.isInteger()) 1167 return false; 1168 1169 // If operation type is 'undesirable', e.g. i16 on x86, consider 1170 // promoting it. 1171 unsigned Opc = Op.getOpcode(); 1172 if (TLI.isTypeDesirableForOp(Opc, VT)) 1173 return false; 1174 1175 EVT PVT = VT; 1176 // Consult target whether it is a good idea to promote this operation and 1177 // what's the right type to promote it to. 1178 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1179 assert(PVT != VT && "Don't know what type to promote to!"); 1180 1181 SDLoc dl(Op); 1182 SDNode *N = Op.getNode(); 1183 LoadSDNode *LD = cast<LoadSDNode>(N); 1184 EVT MemVT = LD->getMemoryVT(); 1185 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1186 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1187 : ISD::EXTLOAD) 1188 : LD->getExtensionType(); 1189 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1190 LD->getChain(), LD->getBasePtr(), 1191 MemVT, LD->getMemOperand()); 1192 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1193 1194 DEBUG(dbgs() << "\nPromoting "; 1195 N->dump(&DAG); 1196 dbgs() << "\nTo: "; 1197 Result.getNode()->dump(&DAG); 1198 dbgs() << '\n'); 1199 WorklistRemover DeadNodes(*this); 1200 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1201 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1202 deleteAndRecombine(N); 1203 AddToWorklist(Result.getNode()); 1204 return true; 1205 } 1206 return false; 1207 } 1208 1209 /// \brief Recursively delete a node which has no uses and any operands for 1210 /// which it is the only use. 1211 /// 1212 /// Note that this both deletes the nodes and removes them from the worklist. 1213 /// It also adds any nodes who have had a user deleted to the worklist as they 1214 /// may now have only one use and subject to other combines. 1215 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1216 if (!N->use_empty()) 1217 return false; 1218 1219 SmallSetVector<SDNode *, 16> Nodes; 1220 Nodes.insert(N); 1221 do { 1222 N = Nodes.pop_back_val(); 1223 if (!N) 1224 continue; 1225 1226 if (N->use_empty()) { 1227 for (const SDValue &ChildN : N->op_values()) 1228 Nodes.insert(ChildN.getNode()); 1229 1230 removeFromWorklist(N); 1231 DAG.DeleteNode(N); 1232 } else { 1233 AddToWorklist(N); 1234 } 1235 } while (!Nodes.empty()); 1236 return true; 1237 } 1238 1239 //===----------------------------------------------------------------------===// 1240 // Main DAG Combiner implementation 1241 //===----------------------------------------------------------------------===// 1242 1243 void DAGCombiner::Run(CombineLevel AtLevel) { 1244 // set the instance variables, so that the various visit routines may use it. 1245 Level = AtLevel; 1246 LegalOperations = Level >= AfterLegalizeVectorOps; 1247 LegalTypes = Level >= AfterLegalizeTypes; 1248 1249 // Add all the dag nodes to the worklist. 1250 for (SDNode &Node : DAG.allnodes()) 1251 AddToWorklist(&Node); 1252 1253 // Create a dummy node (which is not added to allnodes), that adds a reference 1254 // to the root node, preventing it from being deleted, and tracking any 1255 // changes of the root. 1256 HandleSDNode Dummy(DAG.getRoot()); 1257 1258 // While the worklist isn't empty, find a node and try to combine it. 1259 while (!WorklistMap.empty()) { 1260 SDNode *N; 1261 // The Worklist holds the SDNodes in order, but it may contain null entries. 1262 do { 1263 N = Worklist.pop_back_val(); 1264 } while (!N); 1265 1266 bool GoodWorklistEntry = WorklistMap.erase(N); 1267 (void)GoodWorklistEntry; 1268 assert(GoodWorklistEntry && 1269 "Found a worklist entry without a corresponding map entry!"); 1270 1271 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1272 // N is deleted from the DAG, since they too may now be dead or may have a 1273 // reduced number of uses, allowing other xforms. 1274 if (recursivelyDeleteUnusedNodes(N)) 1275 continue; 1276 1277 WorklistRemover DeadNodes(*this); 1278 1279 // If this combine is running after legalizing the DAG, re-legalize any 1280 // nodes pulled off the worklist. 1281 if (Level == AfterLegalizeDAG) { 1282 SmallSetVector<SDNode *, 16> UpdatedNodes; 1283 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1284 1285 for (SDNode *LN : UpdatedNodes) { 1286 AddToWorklist(LN); 1287 AddUsersToWorklist(LN); 1288 } 1289 if (!NIsValid) 1290 continue; 1291 } 1292 1293 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1294 1295 // Add any operands of the new node which have not yet been combined to the 1296 // worklist as well. Because the worklist uniques things already, this 1297 // won't repeatedly process the same operand. 1298 CombinedNodes.insert(N); 1299 for (const SDValue &ChildN : N->op_values()) 1300 if (!CombinedNodes.count(ChildN.getNode())) 1301 AddToWorklist(ChildN.getNode()); 1302 1303 SDValue RV = combine(N); 1304 1305 if (!RV.getNode()) 1306 continue; 1307 1308 ++NodesCombined; 1309 1310 // If we get back the same node we passed in, rather than a new node or 1311 // zero, we know that the node must have defined multiple values and 1312 // CombineTo was used. Since CombineTo takes care of the worklist 1313 // mechanics for us, we have no work to do in this case. 1314 if (RV.getNode() == N) 1315 continue; 1316 1317 assert(N->getOpcode() != ISD::DELETED_NODE && 1318 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1319 "Node was deleted but visit returned new node!"); 1320 1321 DEBUG(dbgs() << " ... into: "; 1322 RV.getNode()->dump(&DAG)); 1323 1324 if (N->getNumValues() == RV.getNode()->getNumValues()) 1325 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1326 else { 1327 assert(N->getValueType(0) == RV.getValueType() && 1328 N->getNumValues() == 1 && "Type mismatch"); 1329 SDValue OpV = RV; 1330 DAG.ReplaceAllUsesWith(N, &OpV); 1331 } 1332 1333 // Push the new node and any users onto the worklist 1334 AddToWorklist(RV.getNode()); 1335 AddUsersToWorklist(RV.getNode()); 1336 1337 // Finally, if the node is now dead, remove it from the graph. The node 1338 // may not be dead if the replacement process recursively simplified to 1339 // something else needing this node. This will also take care of adding any 1340 // operands which have lost a user to the worklist. 1341 recursivelyDeleteUnusedNodes(N); 1342 } 1343 1344 // If the root changed (e.g. it was a dead load, update the root). 1345 DAG.setRoot(Dummy.getValue()); 1346 DAG.RemoveDeadNodes(); 1347 } 1348 1349 SDValue DAGCombiner::visit(SDNode *N) { 1350 switch (N->getOpcode()) { 1351 default: break; 1352 case ISD::TokenFactor: return visitTokenFactor(N); 1353 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1354 case ISD::ADD: return visitADD(N); 1355 case ISD::SUB: return visitSUB(N); 1356 case ISD::ADDC: return visitADDC(N); 1357 case ISD::SUBC: return visitSUBC(N); 1358 case ISD::ADDE: return visitADDE(N); 1359 case ISD::SUBE: return visitSUBE(N); 1360 case ISD::MUL: return visitMUL(N); 1361 case ISD::SDIV: return visitSDIV(N); 1362 case ISD::UDIV: return visitUDIV(N); 1363 case ISD::SREM: 1364 case ISD::UREM: return visitREM(N); 1365 case ISD::MULHU: return visitMULHU(N); 1366 case ISD::MULHS: return visitMULHS(N); 1367 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1368 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1369 case ISD::SMULO: return visitSMULO(N); 1370 case ISD::UMULO: return visitUMULO(N); 1371 case ISD::SMIN: 1372 case ISD::SMAX: 1373 case ISD::UMIN: 1374 case ISD::UMAX: return visitIMINMAX(N); 1375 case ISD::AND: return visitAND(N); 1376 case ISD::OR: return visitOR(N); 1377 case ISD::XOR: return visitXOR(N); 1378 case ISD::SHL: return visitSHL(N); 1379 case ISD::SRA: return visitSRA(N); 1380 case ISD::SRL: return visitSRL(N); 1381 case ISD::ROTR: 1382 case ISD::ROTL: return visitRotate(N); 1383 case ISD::BSWAP: return visitBSWAP(N); 1384 case ISD::BITREVERSE: return visitBITREVERSE(N); 1385 case ISD::CTLZ: return visitCTLZ(N); 1386 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1387 case ISD::CTTZ: return visitCTTZ(N); 1388 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1389 case ISD::CTPOP: return visitCTPOP(N); 1390 case ISD::SELECT: return visitSELECT(N); 1391 case ISD::VSELECT: return visitVSELECT(N); 1392 case ISD::SELECT_CC: return visitSELECT_CC(N); 1393 case ISD::SETCC: return visitSETCC(N); 1394 case ISD::SETCCE: return visitSETCCE(N); 1395 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1396 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1397 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1398 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1399 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1400 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1401 case ISD::TRUNCATE: return visitTRUNCATE(N); 1402 case ISD::BITCAST: return visitBITCAST(N); 1403 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1404 case ISD::FADD: return visitFADD(N); 1405 case ISD::FSUB: return visitFSUB(N); 1406 case ISD::FMUL: return visitFMUL(N); 1407 case ISD::FMA: return visitFMA(N); 1408 case ISD::FDIV: return visitFDIV(N); 1409 case ISD::FREM: return visitFREM(N); 1410 case ISD::FSQRT: return visitFSQRT(N); 1411 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1412 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1413 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1414 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1415 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1416 case ISD::FP_ROUND: return visitFP_ROUND(N); 1417 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1418 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1419 case ISD::FNEG: return visitFNEG(N); 1420 case ISD::FABS: return visitFABS(N); 1421 case ISD::FFLOOR: return visitFFLOOR(N); 1422 case ISD::FMINNUM: return visitFMINNUM(N); 1423 case ISD::FMAXNUM: return visitFMAXNUM(N); 1424 case ISD::FCEIL: return visitFCEIL(N); 1425 case ISD::FTRUNC: return visitFTRUNC(N); 1426 case ISD::BRCOND: return visitBRCOND(N); 1427 case ISD::BR_CC: return visitBR_CC(N); 1428 case ISD::LOAD: return visitLOAD(N); 1429 case ISD::STORE: return visitSTORE(N); 1430 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1431 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1432 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1433 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1434 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1435 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1436 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1437 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1438 case ISD::MGATHER: return visitMGATHER(N); 1439 case ISD::MLOAD: return visitMLOAD(N); 1440 case ISD::MSCATTER: return visitMSCATTER(N); 1441 case ISD::MSTORE: return visitMSTORE(N); 1442 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1443 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1444 } 1445 return SDValue(); 1446 } 1447 1448 SDValue DAGCombiner::combine(SDNode *N) { 1449 SDValue RV = visit(N); 1450 1451 // If nothing happened, try a target-specific DAG combine. 1452 if (!RV.getNode()) { 1453 assert(N->getOpcode() != ISD::DELETED_NODE && 1454 "Node was deleted but visit returned NULL!"); 1455 1456 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1457 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1458 1459 // Expose the DAG combiner to the target combiner impls. 1460 TargetLowering::DAGCombinerInfo 1461 DagCombineInfo(DAG, Level, false, this); 1462 1463 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1464 } 1465 } 1466 1467 // If nothing happened still, try promoting the operation. 1468 if (!RV.getNode()) { 1469 switch (N->getOpcode()) { 1470 default: break; 1471 case ISD::ADD: 1472 case ISD::SUB: 1473 case ISD::MUL: 1474 case ISD::AND: 1475 case ISD::OR: 1476 case ISD::XOR: 1477 RV = PromoteIntBinOp(SDValue(N, 0)); 1478 break; 1479 case ISD::SHL: 1480 case ISD::SRA: 1481 case ISD::SRL: 1482 RV = PromoteIntShiftOp(SDValue(N, 0)); 1483 break; 1484 case ISD::SIGN_EXTEND: 1485 case ISD::ZERO_EXTEND: 1486 case ISD::ANY_EXTEND: 1487 RV = PromoteExtend(SDValue(N, 0)); 1488 break; 1489 case ISD::LOAD: 1490 if (PromoteLoad(SDValue(N, 0))) 1491 RV = SDValue(N, 0); 1492 break; 1493 } 1494 } 1495 1496 // If N is a commutative binary node, try commuting it to enable more 1497 // sdisel CSE. 1498 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1499 N->getNumValues() == 1) { 1500 SDValue N0 = N->getOperand(0); 1501 SDValue N1 = N->getOperand(1); 1502 1503 // Constant operands are canonicalized to RHS. 1504 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1505 SDValue Ops[] = {N1, N0}; 1506 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1507 N->getFlags()); 1508 if (CSENode) 1509 return SDValue(CSENode, 0); 1510 } 1511 } 1512 1513 return RV; 1514 } 1515 1516 /// Given a node, return its input chain if it has one, otherwise return a null 1517 /// sd operand. 1518 static SDValue getInputChainForNode(SDNode *N) { 1519 if (unsigned NumOps = N->getNumOperands()) { 1520 if (N->getOperand(0).getValueType() == MVT::Other) 1521 return N->getOperand(0); 1522 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1523 return N->getOperand(NumOps-1); 1524 for (unsigned i = 1; i < NumOps-1; ++i) 1525 if (N->getOperand(i).getValueType() == MVT::Other) 1526 return N->getOperand(i); 1527 } 1528 return SDValue(); 1529 } 1530 1531 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1532 // If N has two operands, where one has an input chain equal to the other, 1533 // the 'other' chain is redundant. 1534 if (N->getNumOperands() == 2) { 1535 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1536 return N->getOperand(0); 1537 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1538 return N->getOperand(1); 1539 } 1540 1541 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1542 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1543 SmallPtrSet<SDNode*, 16> SeenOps; 1544 bool Changed = false; // If we should replace this token factor. 1545 1546 // Start out with this token factor. 1547 TFs.push_back(N); 1548 1549 // Iterate through token factors. The TFs grows when new token factors are 1550 // encountered. 1551 for (unsigned i = 0; i < TFs.size(); ++i) { 1552 SDNode *TF = TFs[i]; 1553 1554 // Check each of the operands. 1555 for (const SDValue &Op : TF->op_values()) { 1556 1557 switch (Op.getOpcode()) { 1558 case ISD::EntryToken: 1559 // Entry tokens don't need to be added to the list. They are 1560 // redundant. 1561 Changed = true; 1562 break; 1563 1564 case ISD::TokenFactor: 1565 if (Op.hasOneUse() && 1566 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1567 // Queue up for processing. 1568 TFs.push_back(Op.getNode()); 1569 // Clean up in case the token factor is removed. 1570 AddToWorklist(Op.getNode()); 1571 Changed = true; 1572 break; 1573 } 1574 // Fall thru 1575 1576 default: 1577 // Only add if it isn't already in the list. 1578 if (SeenOps.insert(Op.getNode()).second) 1579 Ops.push_back(Op); 1580 else 1581 Changed = true; 1582 break; 1583 } 1584 } 1585 } 1586 1587 SDValue Result; 1588 1589 // If we've changed things around then replace token factor. 1590 if (Changed) { 1591 if (Ops.empty()) { 1592 // The entry token is the only possible outcome. 1593 Result = DAG.getEntryNode(); 1594 } else { 1595 // New and improved token factor. 1596 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1597 } 1598 1599 // Add users to worklist if AA is enabled, since it may introduce 1600 // a lot of new chained token factors while removing memory deps. 1601 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1602 : DAG.getSubtarget().useAA(); 1603 return CombineTo(N, Result, UseAA /*add to worklist*/); 1604 } 1605 1606 return Result; 1607 } 1608 1609 /// MERGE_VALUES can always be eliminated. 1610 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1611 WorklistRemover DeadNodes(*this); 1612 // Replacing results may cause a different MERGE_VALUES to suddenly 1613 // be CSE'd with N, and carry its uses with it. Iterate until no 1614 // uses remain, to ensure that the node can be safely deleted. 1615 // First add the users of this node to the work list so that they 1616 // can be tried again once they have new operands. 1617 AddUsersToWorklist(N); 1618 do { 1619 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1620 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1621 } while (!N->use_empty()); 1622 deleteAndRecombine(N); 1623 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1624 } 1625 1626 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1627 /// ConstantSDNode pointer else nullptr. 1628 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1629 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1630 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1631 } 1632 1633 SDValue DAGCombiner::visitADD(SDNode *N) { 1634 SDValue N0 = N->getOperand(0); 1635 SDValue N1 = N->getOperand(1); 1636 EVT VT = N0.getValueType(); 1637 1638 // fold vector ops 1639 if (VT.isVector()) { 1640 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1641 return FoldedVOp; 1642 1643 // fold (add x, 0) -> x, vector edition 1644 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1645 return N0; 1646 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1647 return N1; 1648 } 1649 1650 // fold (add x, undef) -> undef 1651 if (N0.isUndef()) 1652 return N0; 1653 if (N1.isUndef()) 1654 return N1; 1655 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1656 // canonicalize constant to RHS 1657 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1658 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1659 // fold (add c1, c2) -> c1+c2 1660 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1661 N0.getNode(), N1.getNode()); 1662 } 1663 // fold (add x, 0) -> x 1664 if (isNullConstant(N1)) 1665 return N0; 1666 // fold ((c1-A)+c2) -> (c1+c2)-A 1667 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1668 if (N0.getOpcode() == ISD::SUB) 1669 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1670 SDLoc DL(N); 1671 return DAG.getNode(ISD::SUB, DL, VT, 1672 DAG.getConstant(N1C->getAPIntValue()+ 1673 N0C->getAPIntValue(), DL, VT), 1674 N0.getOperand(1)); 1675 } 1676 } 1677 // reassociate add 1678 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1679 return RADD; 1680 // fold ((0-A) + B) -> B-A 1681 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1682 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1683 // fold (A + (0-B)) -> A-B 1684 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1685 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1686 // fold (A+(B-A)) -> B 1687 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1688 return N1.getOperand(0); 1689 // fold ((B-A)+A) -> B 1690 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1691 return N0.getOperand(0); 1692 // fold (A+(B-(A+C))) to (B-C) 1693 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1694 N0 == N1.getOperand(1).getOperand(0)) 1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1696 N1.getOperand(1).getOperand(1)); 1697 // fold (A+(B-(C+A))) to (B-C) 1698 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1699 N0 == N1.getOperand(1).getOperand(1)) 1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1701 N1.getOperand(1).getOperand(0)); 1702 // fold (A+((B-A)+or-C)) to (B+or-C) 1703 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1704 N1.getOperand(0).getOpcode() == ISD::SUB && 1705 N0 == N1.getOperand(0).getOperand(1)) 1706 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1707 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1708 1709 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1710 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1711 SDValue N00 = N0.getOperand(0); 1712 SDValue N01 = N0.getOperand(1); 1713 SDValue N10 = N1.getOperand(0); 1714 SDValue N11 = N1.getOperand(1); 1715 1716 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1717 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1718 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1719 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1720 } 1721 1722 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1723 return SDValue(N, 0); 1724 1725 // fold (a+b) -> (a|b) iff a and b share no bits. 1726 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1727 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1728 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1729 1730 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1731 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1732 isNullConstant(N1.getOperand(0).getOperand(0))) 1733 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1734 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1735 N1.getOperand(0).getOperand(1), 1736 N1.getOperand(1))); 1737 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1738 isNullConstant(N0.getOperand(0).getOperand(0))) 1739 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1740 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1741 N0.getOperand(0).getOperand(1), 1742 N0.getOperand(1))); 1743 1744 if (N1.getOpcode() == ISD::AND) { 1745 SDValue AndOp0 = N1.getOperand(0); 1746 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1747 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1748 1749 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1750 // and similar xforms where the inner op is either ~0 or 0. 1751 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1752 SDLoc DL(N); 1753 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1754 } 1755 } 1756 1757 // add (sext i1), X -> sub X, (zext i1) 1758 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1759 N0.getOperand(0).getValueType() == MVT::i1 && 1760 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1761 SDLoc DL(N); 1762 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1763 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1764 } 1765 1766 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1767 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1768 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1769 if (TN->getVT() == MVT::i1) { 1770 SDLoc DL(N); 1771 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1772 DAG.getConstant(1, DL, VT)); 1773 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1774 } 1775 } 1776 1777 return SDValue(); 1778 } 1779 1780 SDValue DAGCombiner::visitADDC(SDNode *N) { 1781 SDValue N0 = N->getOperand(0); 1782 SDValue N1 = N->getOperand(1); 1783 EVT VT = N0.getValueType(); 1784 1785 // If the flag result is dead, turn this into an ADD. 1786 if (!N->hasAnyUseOfValue(1)) 1787 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1788 DAG.getNode(ISD::CARRY_FALSE, 1789 SDLoc(N), MVT::Glue)); 1790 1791 // canonicalize constant to RHS. 1792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1794 if (N0C && !N1C) 1795 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1796 1797 // fold (addc x, 0) -> x + no carry out 1798 if (isNullConstant(N1)) 1799 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1800 SDLoc(N), MVT::Glue)); 1801 1802 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1803 APInt LHSZero, LHSOne; 1804 APInt RHSZero, RHSOne; 1805 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1806 1807 if (LHSZero.getBoolValue()) { 1808 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1809 1810 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1811 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1812 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1813 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1814 DAG.getNode(ISD::CARRY_FALSE, 1815 SDLoc(N), MVT::Glue)); 1816 } 1817 1818 return SDValue(); 1819 } 1820 1821 SDValue DAGCombiner::visitADDE(SDNode *N) { 1822 SDValue N0 = N->getOperand(0); 1823 SDValue N1 = N->getOperand(1); 1824 SDValue CarryIn = N->getOperand(2); 1825 1826 // canonicalize constant to RHS 1827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1829 if (N0C && !N1C) 1830 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1831 N1, N0, CarryIn); 1832 1833 // fold (adde x, y, false) -> (addc x, y) 1834 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1835 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1836 1837 return SDValue(); 1838 } 1839 1840 // Since it may not be valid to emit a fold to zero for vector initializers 1841 // check if we can before folding. 1842 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 1843 SelectionDAG &DAG, bool LegalOperations, 1844 bool LegalTypes) { 1845 if (!VT.isVector()) 1846 return DAG.getConstant(0, DL, VT); 1847 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1848 return DAG.getConstant(0, DL, VT); 1849 return SDValue(); 1850 } 1851 1852 SDValue DAGCombiner::visitSUB(SDNode *N) { 1853 SDValue N0 = N->getOperand(0); 1854 SDValue N1 = N->getOperand(1); 1855 EVT VT = N0.getValueType(); 1856 1857 // fold vector ops 1858 if (VT.isVector()) { 1859 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1860 return FoldedVOp; 1861 1862 // fold (sub x, 0) -> x, vector edition 1863 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1864 return N0; 1865 } 1866 1867 // fold (sub x, x) -> 0 1868 // FIXME: Refactor this and xor and other similar operations together. 1869 if (N0 == N1) 1870 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1871 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1872 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1873 // fold (sub c1, c2) -> c1-c2 1874 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1875 N0.getNode(), N1.getNode()); 1876 } 1877 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1878 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1879 // fold (sub x, c) -> (add x, -c) 1880 if (N1C) { 1881 SDLoc DL(N); 1882 return DAG.getNode(ISD::ADD, DL, VT, N0, 1883 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1884 } 1885 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1886 if (isAllOnesConstant(N0)) 1887 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1888 // fold A-(A-B) -> B 1889 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1890 return N1.getOperand(1); 1891 // fold (A+B)-A -> B 1892 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1893 return N0.getOperand(1); 1894 // fold (A+B)-B -> A 1895 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1896 return N0.getOperand(0); 1897 // fold C2-(A+C1) -> (C2-C1)-A 1898 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1899 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1900 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1901 SDLoc DL(N); 1902 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1903 DL, VT); 1904 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1905 N1.getOperand(0)); 1906 } 1907 // fold ((A+(B+or-C))-B) -> A+or-C 1908 if (N0.getOpcode() == ISD::ADD && 1909 (N0.getOperand(1).getOpcode() == ISD::SUB || 1910 N0.getOperand(1).getOpcode() == ISD::ADD) && 1911 N0.getOperand(1).getOperand(0) == N1) 1912 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1913 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1914 // fold ((A+(C+B))-B) -> A+C 1915 if (N0.getOpcode() == ISD::ADD && 1916 N0.getOperand(1).getOpcode() == ISD::ADD && 1917 N0.getOperand(1).getOperand(1) == N1) 1918 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1919 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1920 // fold ((A-(B-C))-C) -> A-B 1921 if (N0.getOpcode() == ISD::SUB && 1922 N0.getOperand(1).getOpcode() == ISD::SUB && 1923 N0.getOperand(1).getOperand(1) == N1) 1924 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1925 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1926 1927 // If either operand of a sub is undef, the result is undef 1928 if (N0.isUndef()) 1929 return N0; 1930 if (N1.isUndef()) 1931 return N1; 1932 1933 // If the relocation model supports it, consider symbol offsets. 1934 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1935 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1936 // fold (sub Sym, c) -> Sym-c 1937 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1938 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1939 GA->getOffset() - 1940 (uint64_t)N1C->getSExtValue()); 1941 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1942 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1943 if (GA->getGlobal() == GB->getGlobal()) 1944 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1945 SDLoc(N), VT); 1946 } 1947 1948 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1949 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1950 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1951 if (TN->getVT() == MVT::i1) { 1952 SDLoc DL(N); 1953 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1954 DAG.getConstant(1, DL, VT)); 1955 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1956 } 1957 } 1958 1959 return SDValue(); 1960 } 1961 1962 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1963 SDValue N0 = N->getOperand(0); 1964 SDValue N1 = N->getOperand(1); 1965 EVT VT = N0.getValueType(); 1966 SDLoc DL(N); 1967 1968 // If the flag result is dead, turn this into an SUB. 1969 if (!N->hasAnyUseOfValue(1)) 1970 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1971 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1972 1973 // fold (subc x, x) -> 0 + no borrow 1974 if (N0 == N1) 1975 return CombineTo(N, DAG.getConstant(0, DL, VT), 1976 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1977 1978 // fold (subc x, 0) -> x + no borrow 1979 if (isNullConstant(N1)) 1980 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1981 1982 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1983 if (isAllOnesConstant(N0)) 1984 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1985 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1986 1987 return SDValue(); 1988 } 1989 1990 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1991 SDValue N0 = N->getOperand(0); 1992 SDValue N1 = N->getOperand(1); 1993 SDValue CarryIn = N->getOperand(2); 1994 1995 // fold (sube x, y, false) -> (subc x, y) 1996 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1997 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1998 1999 return SDValue(); 2000 } 2001 2002 SDValue DAGCombiner::visitMUL(SDNode *N) { 2003 SDValue N0 = N->getOperand(0); 2004 SDValue N1 = N->getOperand(1); 2005 EVT VT = N0.getValueType(); 2006 2007 // fold (mul x, undef) -> 0 2008 if (N0.isUndef() || N1.isUndef()) 2009 return DAG.getConstant(0, SDLoc(N), VT); 2010 2011 bool N0IsConst = false; 2012 bool N1IsConst = false; 2013 bool N1IsOpaqueConst = false; 2014 bool N0IsOpaqueConst = false; 2015 APInt ConstValue0, ConstValue1; 2016 // fold vector ops 2017 if (VT.isVector()) { 2018 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2019 return FoldedVOp; 2020 2021 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2022 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2023 } else { 2024 N0IsConst = isa<ConstantSDNode>(N0); 2025 if (N0IsConst) { 2026 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2027 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2028 } 2029 N1IsConst = isa<ConstantSDNode>(N1); 2030 if (N1IsConst) { 2031 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2032 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2033 } 2034 } 2035 2036 // fold (mul c1, c2) -> c1*c2 2037 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2038 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2039 N0.getNode(), N1.getNode()); 2040 2041 // canonicalize constant to RHS (vector doesn't have to splat) 2042 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2043 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2044 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2045 // fold (mul x, 0) -> 0 2046 if (N1IsConst && ConstValue1 == 0) 2047 return N1; 2048 // We require a splat of the entire scalar bit width for non-contiguous 2049 // bit patterns. 2050 bool IsFullSplat = 2051 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2052 // fold (mul x, 1) -> x 2053 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2054 return N0; 2055 // fold (mul x, -1) -> 0-x 2056 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2057 SDLoc DL(N); 2058 return DAG.getNode(ISD::SUB, DL, VT, 2059 DAG.getConstant(0, DL, VT), N0); 2060 } 2061 // fold (mul x, (1 << c)) -> x << c 2062 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2063 IsFullSplat) { 2064 SDLoc DL(N); 2065 return DAG.getNode(ISD::SHL, DL, VT, N0, 2066 DAG.getConstant(ConstValue1.logBase2(), DL, 2067 getShiftAmountTy(N0.getValueType()))); 2068 } 2069 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2070 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2071 IsFullSplat) { 2072 unsigned Log2Val = (-ConstValue1).logBase2(); 2073 SDLoc DL(N); 2074 // FIXME: If the input is something that is easily negated (e.g. a 2075 // single-use add), we should put the negate there. 2076 return DAG.getNode(ISD::SUB, DL, VT, 2077 DAG.getConstant(0, DL, VT), 2078 DAG.getNode(ISD::SHL, DL, VT, N0, 2079 DAG.getConstant(Log2Val, DL, 2080 getShiftAmountTy(N0.getValueType())))); 2081 } 2082 2083 APInt Val; 2084 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2085 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2086 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2087 isa<ConstantSDNode>(N0.getOperand(1)))) { 2088 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2089 AddToWorklist(C3.getNode()); 2090 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2091 } 2092 2093 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2094 // use. 2095 { 2096 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2097 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2098 if (N0.getOpcode() == ISD::SHL && 2099 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2100 isa<ConstantSDNode>(N0.getOperand(1))) && 2101 N0.getNode()->hasOneUse()) { 2102 Sh = N0; Y = N1; 2103 } else if (N1.getOpcode() == ISD::SHL && 2104 isa<ConstantSDNode>(N1.getOperand(1)) && 2105 N1.getNode()->hasOneUse()) { 2106 Sh = N1; Y = N0; 2107 } 2108 2109 if (Sh.getNode()) { 2110 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2111 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2112 } 2113 } 2114 2115 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2116 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2117 N0.getOpcode() == ISD::ADD && 2118 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2119 isMulAddWithConstProfitable(N, N0, N1)) 2120 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2121 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2122 N0.getOperand(0), N1), 2123 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2124 N0.getOperand(1), N1)); 2125 2126 // reassociate mul 2127 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2128 return RMUL; 2129 2130 return SDValue(); 2131 } 2132 2133 /// Return true if divmod libcall is available. 2134 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2135 const TargetLowering &TLI) { 2136 RTLIB::Libcall LC; 2137 EVT NodeType = Node->getValueType(0); 2138 if (!NodeType.isSimple()) 2139 return false; 2140 switch (NodeType.getSimpleVT().SimpleTy) { 2141 default: return false; // No libcall for vector types. 2142 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2143 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2144 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2145 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2146 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2147 } 2148 2149 return TLI.getLibcallName(LC) != nullptr; 2150 } 2151 2152 /// Issue divrem if both quotient and remainder are needed. 2153 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2154 if (Node->use_empty()) 2155 return SDValue(); // This is a dead node, leave it alone. 2156 2157 unsigned Opcode = Node->getOpcode(); 2158 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2159 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2160 2161 // DivMod lib calls can still work on non-legal types if using lib-calls. 2162 EVT VT = Node->getValueType(0); 2163 if (VT.isVector() || !VT.isInteger()) 2164 return SDValue(); 2165 2166 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2167 return SDValue(); 2168 2169 // If DIVREM is going to get expanded into a libcall, 2170 // but there is no libcall available, then don't combine. 2171 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2172 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2173 return SDValue(); 2174 2175 // If div is legal, it's better to do the normal expansion 2176 unsigned OtherOpcode = 0; 2177 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2178 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2179 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2180 return SDValue(); 2181 } else { 2182 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2183 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2184 return SDValue(); 2185 } 2186 2187 SDValue Op0 = Node->getOperand(0); 2188 SDValue Op1 = Node->getOperand(1); 2189 SDValue combined; 2190 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2191 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2192 SDNode *User = *UI; 2193 if (User == Node || User->use_empty()) 2194 continue; 2195 // Convert the other matching node(s), too; 2196 // otherwise, the DIVREM may get target-legalized into something 2197 // target-specific that we won't be able to recognize. 2198 unsigned UserOpc = User->getOpcode(); 2199 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2200 User->getOperand(0) == Op0 && 2201 User->getOperand(1) == Op1) { 2202 if (!combined) { 2203 if (UserOpc == OtherOpcode) { 2204 SDVTList VTs = DAG.getVTList(VT, VT); 2205 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2206 } else if (UserOpc == DivRemOpc) { 2207 combined = SDValue(User, 0); 2208 } else { 2209 assert(UserOpc == Opcode); 2210 continue; 2211 } 2212 } 2213 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2214 CombineTo(User, combined); 2215 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2216 CombineTo(User, combined.getValue(1)); 2217 } 2218 } 2219 return combined; 2220 } 2221 2222 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2223 SDValue N0 = N->getOperand(0); 2224 SDValue N1 = N->getOperand(1); 2225 EVT VT = N->getValueType(0); 2226 2227 // fold vector ops 2228 if (VT.isVector()) 2229 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2230 return FoldedVOp; 2231 2232 SDLoc DL(N); 2233 2234 // fold (sdiv c1, c2) -> c1/c2 2235 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2236 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2237 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2238 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2239 // fold (sdiv X, 1) -> X 2240 if (N1C && N1C->isOne()) 2241 return N0; 2242 // fold (sdiv X, -1) -> 0-X 2243 if (N1C && N1C->isAllOnesValue()) 2244 return DAG.getNode(ISD::SUB, DL, VT, 2245 DAG.getConstant(0, DL, VT), N0); 2246 2247 // If we know the sign bits of both operands are zero, strength reduce to a 2248 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2249 if (!VT.isVector()) { 2250 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2251 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2252 } 2253 2254 // fold (sdiv X, pow2) -> simple ops after legalize 2255 // FIXME: We check for the exact bit here because the generic lowering gives 2256 // better results in that case. The target-specific lowering should learn how 2257 // to handle exact sdivs efficiently. 2258 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2259 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2260 (N1C->getAPIntValue().isPowerOf2() || 2261 (-N1C->getAPIntValue()).isPowerOf2())) { 2262 // Target-specific implementation of sdiv x, pow2. 2263 if (SDValue Res = BuildSDIVPow2(N)) 2264 return Res; 2265 2266 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2267 2268 // Splat the sign bit into the register 2269 SDValue SGN = 2270 DAG.getNode(ISD::SRA, DL, VT, N0, 2271 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2272 getShiftAmountTy(N0.getValueType()))); 2273 AddToWorklist(SGN.getNode()); 2274 2275 // Add (N0 < 0) ? abs2 - 1 : 0; 2276 SDValue SRL = 2277 DAG.getNode(ISD::SRL, DL, VT, SGN, 2278 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2279 getShiftAmountTy(SGN.getValueType()))); 2280 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2281 AddToWorklist(SRL.getNode()); 2282 AddToWorklist(ADD.getNode()); // Divide by pow2 2283 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2284 DAG.getConstant(lg2, DL, 2285 getShiftAmountTy(ADD.getValueType()))); 2286 2287 // If we're dividing by a positive value, we're done. Otherwise, we must 2288 // negate the result. 2289 if (N1C->getAPIntValue().isNonNegative()) 2290 return SRA; 2291 2292 AddToWorklist(SRA.getNode()); 2293 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2294 } 2295 2296 // If integer divide is expensive and we satisfy the requirements, emit an 2297 // alternate sequence. Targets may check function attributes for size/speed 2298 // trade-offs. 2299 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2300 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2301 if (SDValue Op = BuildSDIV(N)) 2302 return Op; 2303 2304 // sdiv, srem -> sdivrem 2305 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2306 // Otherwise, we break the simplification logic in visitREM(). 2307 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2308 if (SDValue DivRem = useDivRem(N)) 2309 return DivRem; 2310 2311 // undef / X -> 0 2312 if (N0.isUndef()) 2313 return DAG.getConstant(0, DL, VT); 2314 // X / undef -> undef 2315 if (N1.isUndef()) 2316 return N1; 2317 2318 return SDValue(); 2319 } 2320 2321 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2322 SDValue N0 = N->getOperand(0); 2323 SDValue N1 = N->getOperand(1); 2324 EVT VT = N->getValueType(0); 2325 2326 // fold vector ops 2327 if (VT.isVector()) 2328 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2329 return FoldedVOp; 2330 2331 SDLoc DL(N); 2332 2333 // fold (udiv c1, c2) -> c1/c2 2334 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2335 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2336 if (N0C && N1C) 2337 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2338 N0C, N1C)) 2339 return Folded; 2340 // fold (udiv x, (1 << c)) -> x >>u c 2341 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2342 return DAG.getNode(ISD::SRL, DL, VT, N0, 2343 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2344 getShiftAmountTy(N0.getValueType()))); 2345 2346 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2347 if (N1.getOpcode() == ISD::SHL) { 2348 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2349 if (SHC->getAPIntValue().isPowerOf2()) { 2350 EVT ADDVT = N1.getOperand(1).getValueType(); 2351 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2352 N1.getOperand(1), 2353 DAG.getConstant(SHC->getAPIntValue() 2354 .logBase2(), 2355 DL, ADDVT)); 2356 AddToWorklist(Add.getNode()); 2357 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2358 } 2359 } 2360 } 2361 2362 // fold (udiv x, c) -> alternate 2363 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2364 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2365 if (SDValue Op = BuildUDIV(N)) 2366 return Op; 2367 2368 // sdiv, srem -> sdivrem 2369 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2370 // Otherwise, we break the simplification logic in visitREM(). 2371 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2372 if (SDValue DivRem = useDivRem(N)) 2373 return DivRem; 2374 2375 // undef / X -> 0 2376 if (N0.isUndef()) 2377 return DAG.getConstant(0, DL, VT); 2378 // X / undef -> undef 2379 if (N1.isUndef()) 2380 return N1; 2381 2382 return SDValue(); 2383 } 2384 2385 // handles ISD::SREM and ISD::UREM 2386 SDValue DAGCombiner::visitREM(SDNode *N) { 2387 unsigned Opcode = N->getOpcode(); 2388 SDValue N0 = N->getOperand(0); 2389 SDValue N1 = N->getOperand(1); 2390 EVT VT = N->getValueType(0); 2391 bool isSigned = (Opcode == ISD::SREM); 2392 SDLoc DL(N); 2393 2394 // fold (rem c1, c2) -> c1%c2 2395 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2396 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2397 if (N0C && N1C) 2398 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2399 return Folded; 2400 2401 if (isSigned) { 2402 // If we know the sign bits of both operands are zero, strength reduce to a 2403 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2404 if (!VT.isVector()) { 2405 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2406 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2407 } 2408 } else { 2409 // fold (urem x, pow2) -> (and x, pow2-1) 2410 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2411 N1C->getAPIntValue().isPowerOf2()) { 2412 return DAG.getNode(ISD::AND, DL, VT, N0, 2413 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2414 } 2415 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2416 if (N1.getOpcode() == ISD::SHL) { 2417 ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0)); 2418 if (SHC && SHC->getAPIntValue().isPowerOf2()) { 2419 APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits()); 2420 SDValue Add = 2421 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT)); 2422 AddToWorklist(Add.getNode()); 2423 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2424 } 2425 } 2426 } 2427 2428 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2429 2430 // If X/C can be simplified by the division-by-constant logic, lower 2431 // X%C to the equivalent of X-X/C*C. 2432 // To avoid mangling nodes, this simplification requires that the combine() 2433 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2434 // against this by skipping the simplification if isIntDivCheap(). When 2435 // div is not cheap, combine will not return a DIVREM. Regardless, 2436 // checking cheapness here makes sense since the simplification results in 2437 // fatter code. 2438 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2439 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2440 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2441 AddToWorklist(Div.getNode()); 2442 SDValue OptimizedDiv = combine(Div.getNode()); 2443 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2444 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2445 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2446 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2447 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2448 AddToWorklist(Mul.getNode()); 2449 return Sub; 2450 } 2451 } 2452 2453 // sdiv, srem -> sdivrem 2454 if (SDValue DivRem = useDivRem(N)) 2455 return DivRem.getValue(1); 2456 2457 // undef % X -> 0 2458 if (N0.isUndef()) 2459 return DAG.getConstant(0, DL, VT); 2460 // X % undef -> undef 2461 if (N1.isUndef()) 2462 return N1; 2463 2464 return SDValue(); 2465 } 2466 2467 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2468 SDValue N0 = N->getOperand(0); 2469 SDValue N1 = N->getOperand(1); 2470 EVT VT = N->getValueType(0); 2471 SDLoc DL(N); 2472 2473 // fold (mulhs x, 0) -> 0 2474 if (isNullConstant(N1)) 2475 return N1; 2476 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2477 if (isOneConstant(N1)) { 2478 SDLoc DL(N); 2479 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2480 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2481 DL, 2482 getShiftAmountTy(N0.getValueType()))); 2483 } 2484 // fold (mulhs x, undef) -> 0 2485 if (N0.isUndef() || N1.isUndef()) 2486 return DAG.getConstant(0, SDLoc(N), VT); 2487 2488 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2489 // plus a shift. 2490 if (VT.isSimple() && !VT.isVector()) { 2491 MVT Simple = VT.getSimpleVT(); 2492 unsigned SimpleSize = Simple.getSizeInBits(); 2493 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2494 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2495 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2496 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2497 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2498 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2499 DAG.getConstant(SimpleSize, DL, 2500 getShiftAmountTy(N1.getValueType()))); 2501 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2502 } 2503 } 2504 2505 return SDValue(); 2506 } 2507 2508 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2509 SDValue N0 = N->getOperand(0); 2510 SDValue N1 = N->getOperand(1); 2511 EVT VT = N->getValueType(0); 2512 SDLoc DL(N); 2513 2514 // fold (mulhu x, 0) -> 0 2515 if (isNullConstant(N1)) 2516 return N1; 2517 // fold (mulhu x, 1) -> 0 2518 if (isOneConstant(N1)) 2519 return DAG.getConstant(0, DL, N0.getValueType()); 2520 // fold (mulhu x, undef) -> 0 2521 if (N0.isUndef() || N1.isUndef()) 2522 return DAG.getConstant(0, DL, VT); 2523 2524 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2525 // plus a shift. 2526 if (VT.isSimple() && !VT.isVector()) { 2527 MVT Simple = VT.getSimpleVT(); 2528 unsigned SimpleSize = Simple.getSizeInBits(); 2529 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2530 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2531 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2532 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2533 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2534 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2535 DAG.getConstant(SimpleSize, DL, 2536 getShiftAmountTy(N1.getValueType()))); 2537 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2538 } 2539 } 2540 2541 return SDValue(); 2542 } 2543 2544 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2545 /// give the opcodes for the two computations that are being performed. Return 2546 /// true if a simplification was made. 2547 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2548 unsigned HiOp) { 2549 // If the high half is not needed, just compute the low half. 2550 bool HiExists = N->hasAnyUseOfValue(1); 2551 if (!HiExists && 2552 (!LegalOperations || 2553 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2554 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2555 return CombineTo(N, Res, Res); 2556 } 2557 2558 // If the low half is not needed, just compute the high half. 2559 bool LoExists = N->hasAnyUseOfValue(0); 2560 if (!LoExists && 2561 (!LegalOperations || 2562 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2563 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2564 return CombineTo(N, Res, Res); 2565 } 2566 2567 // If both halves are used, return as it is. 2568 if (LoExists && HiExists) 2569 return SDValue(); 2570 2571 // If the two computed results can be simplified separately, separate them. 2572 if (LoExists) { 2573 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2574 AddToWorklist(Lo.getNode()); 2575 SDValue LoOpt = combine(Lo.getNode()); 2576 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2577 (!LegalOperations || 2578 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2579 return CombineTo(N, LoOpt, LoOpt); 2580 } 2581 2582 if (HiExists) { 2583 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2584 AddToWorklist(Hi.getNode()); 2585 SDValue HiOpt = combine(Hi.getNode()); 2586 if (HiOpt.getNode() && HiOpt != Hi && 2587 (!LegalOperations || 2588 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2589 return CombineTo(N, HiOpt, HiOpt); 2590 } 2591 2592 return SDValue(); 2593 } 2594 2595 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2596 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2597 return Res; 2598 2599 EVT VT = N->getValueType(0); 2600 SDLoc DL(N); 2601 2602 // If the type is twice as wide is legal, transform the mulhu to a wider 2603 // multiply plus a shift. 2604 if (VT.isSimple() && !VT.isVector()) { 2605 MVT Simple = VT.getSimpleVT(); 2606 unsigned SimpleSize = Simple.getSizeInBits(); 2607 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2608 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2609 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2610 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2611 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2612 // Compute the high part as N1. 2613 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2614 DAG.getConstant(SimpleSize, DL, 2615 getShiftAmountTy(Lo.getValueType()))); 2616 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2617 // Compute the low part as N0. 2618 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2619 return CombineTo(N, Lo, Hi); 2620 } 2621 } 2622 2623 return SDValue(); 2624 } 2625 2626 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2627 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2628 return Res; 2629 2630 EVT VT = N->getValueType(0); 2631 SDLoc DL(N); 2632 2633 // If the type is twice as wide is legal, transform the mulhu to a wider 2634 // multiply plus a shift. 2635 if (VT.isSimple() && !VT.isVector()) { 2636 MVT Simple = VT.getSimpleVT(); 2637 unsigned SimpleSize = Simple.getSizeInBits(); 2638 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2639 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2640 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2641 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2642 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2643 // Compute the high part as N1. 2644 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2645 DAG.getConstant(SimpleSize, DL, 2646 getShiftAmountTy(Lo.getValueType()))); 2647 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2648 // Compute the low part as N0. 2649 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2650 return CombineTo(N, Lo, Hi); 2651 } 2652 } 2653 2654 return SDValue(); 2655 } 2656 2657 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2658 // (smulo x, 2) -> (saddo x, x) 2659 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2660 if (C2->getAPIntValue() == 2) 2661 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2662 N->getOperand(0), N->getOperand(0)); 2663 2664 return SDValue(); 2665 } 2666 2667 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2668 // (umulo x, 2) -> (uaddo x, x) 2669 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2670 if (C2->getAPIntValue() == 2) 2671 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2672 N->getOperand(0), N->getOperand(0)); 2673 2674 return SDValue(); 2675 } 2676 2677 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2678 SDValue N0 = N->getOperand(0); 2679 SDValue N1 = N->getOperand(1); 2680 EVT VT = N0.getValueType(); 2681 2682 // fold vector ops 2683 if (VT.isVector()) 2684 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2685 return FoldedVOp; 2686 2687 // fold (add c1, c2) -> c1+c2 2688 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2689 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2690 if (N0C && N1C) 2691 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2692 2693 // canonicalize constant to RHS 2694 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2695 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2696 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2697 2698 return SDValue(); 2699 } 2700 2701 /// If this is a binary operator with two operands of the same opcode, try to 2702 /// simplify it. 2703 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2704 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2705 EVT VT = N0.getValueType(); 2706 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2707 2708 // Bail early if none of these transforms apply. 2709 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2710 2711 // For each of OP in AND/OR/XOR: 2712 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2713 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2714 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2715 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2716 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2717 // 2718 // do not sink logical op inside of a vector extend, since it may combine 2719 // into a vsetcc. 2720 EVT Op0VT = N0.getOperand(0).getValueType(); 2721 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2722 N0.getOpcode() == ISD::SIGN_EXTEND || 2723 N0.getOpcode() == ISD::BSWAP || 2724 // Avoid infinite looping with PromoteIntBinOp. 2725 (N0.getOpcode() == ISD::ANY_EXTEND && 2726 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2727 (N0.getOpcode() == ISD::TRUNCATE && 2728 (!TLI.isZExtFree(VT, Op0VT) || 2729 !TLI.isTruncateFree(Op0VT, VT)) && 2730 TLI.isTypeLegal(Op0VT))) && 2731 !VT.isVector() && 2732 Op0VT == N1.getOperand(0).getValueType() && 2733 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2734 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2735 N0.getOperand(0).getValueType(), 2736 N0.getOperand(0), N1.getOperand(0)); 2737 AddToWorklist(ORNode.getNode()); 2738 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2739 } 2740 2741 // For each of OP in SHL/SRL/SRA/AND... 2742 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2743 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2744 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2745 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2746 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2747 N0.getOperand(1) == N1.getOperand(1)) { 2748 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2749 N0.getOperand(0).getValueType(), 2750 N0.getOperand(0), N1.getOperand(0)); 2751 AddToWorklist(ORNode.getNode()); 2752 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2753 ORNode, N0.getOperand(1)); 2754 } 2755 2756 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2757 // Only perform this optimization up until type legalization, before 2758 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2759 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2760 // we don't want to undo this promotion. 2761 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2762 // on scalars. 2763 if ((N0.getOpcode() == ISD::BITCAST || 2764 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2765 Level <= AfterLegalizeTypes) { 2766 SDValue In0 = N0.getOperand(0); 2767 SDValue In1 = N1.getOperand(0); 2768 EVT In0Ty = In0.getValueType(); 2769 EVT In1Ty = In1.getValueType(); 2770 SDLoc DL(N); 2771 // If both incoming values are integers, and the original types are the 2772 // same. 2773 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2774 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2775 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2776 AddToWorklist(Op.getNode()); 2777 return BC; 2778 } 2779 } 2780 2781 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2782 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2783 // If both shuffles use the same mask, and both shuffle within a single 2784 // vector, then it is worthwhile to move the swizzle after the operation. 2785 // The type-legalizer generates this pattern when loading illegal 2786 // vector types from memory. In many cases this allows additional shuffle 2787 // optimizations. 2788 // There are other cases where moving the shuffle after the xor/and/or 2789 // is profitable even if shuffles don't perform a swizzle. 2790 // If both shuffles use the same mask, and both shuffles have the same first 2791 // or second operand, then it might still be profitable to move the shuffle 2792 // after the xor/and/or operation. 2793 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2794 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2795 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2796 2797 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2798 "Inputs to shuffles are not the same type"); 2799 2800 // Check that both shuffles use the same mask. The masks are known to be of 2801 // the same length because the result vector type is the same. 2802 // Check also that shuffles have only one use to avoid introducing extra 2803 // instructions. 2804 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2805 SVN0->getMask().equals(SVN1->getMask())) { 2806 SDValue ShOp = N0->getOperand(1); 2807 2808 // Don't try to fold this node if it requires introducing a 2809 // build vector of all zeros that might be illegal at this stage. 2810 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2811 if (!LegalTypes) 2812 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2813 else 2814 ShOp = SDValue(); 2815 } 2816 2817 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2818 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2819 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2820 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2821 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2822 N0->getOperand(0), N1->getOperand(0)); 2823 AddToWorklist(NewNode.getNode()); 2824 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2825 SVN0->getMask()); 2826 } 2827 2828 // Don't try to fold this node if it requires introducing a 2829 // build vector of all zeros that might be illegal at this stage. 2830 ShOp = N0->getOperand(0); 2831 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2832 if (!LegalTypes) 2833 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2834 else 2835 ShOp = SDValue(); 2836 } 2837 2838 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2839 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2840 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2841 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2842 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2843 N0->getOperand(1), N1->getOperand(1)); 2844 AddToWorklist(NewNode.getNode()); 2845 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2846 SVN0->getMask()); 2847 } 2848 } 2849 } 2850 2851 return SDValue(); 2852 } 2853 2854 /// This contains all DAGCombine rules which reduce two values combined by 2855 /// an And operation to a single value. This makes them reusable in the context 2856 /// of visitSELECT(). Rules involving constants are not included as 2857 /// visitSELECT() already handles those cases. 2858 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2859 SDNode *LocReference) { 2860 EVT VT = N1.getValueType(); 2861 2862 // fold (and x, undef) -> 0 2863 if (N0.isUndef() || N1.isUndef()) 2864 return DAG.getConstant(0, SDLoc(LocReference), VT); 2865 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2866 SDValue LL, LR, RL, RR, CC0, CC1; 2867 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2868 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2869 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2870 2871 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2872 LL.getValueType().isInteger()) { 2873 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2874 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2875 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2876 LR.getValueType(), LL, RL); 2877 AddToWorklist(ORNode.getNode()); 2878 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2879 } 2880 if (isAllOnesConstant(LR)) { 2881 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2882 if (Op1 == ISD::SETEQ) { 2883 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2884 LR.getValueType(), LL, RL); 2885 AddToWorklist(ANDNode.getNode()); 2886 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2887 } 2888 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2889 if (Op1 == ISD::SETGT) { 2890 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2891 LR.getValueType(), LL, RL); 2892 AddToWorklist(ORNode.getNode()); 2893 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2894 } 2895 } 2896 } 2897 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2898 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2899 Op0 == Op1 && LL.getValueType().isInteger() && 2900 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2901 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2902 SDLoc DL(N0); 2903 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2904 LL, DAG.getConstant(1, DL, 2905 LL.getValueType())); 2906 AddToWorklist(ADDNode.getNode()); 2907 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2908 DAG.getConstant(2, DL, LL.getValueType()), 2909 ISD::SETUGE); 2910 } 2911 // canonicalize equivalent to ll == rl 2912 if (LL == RR && LR == RL) { 2913 Op1 = ISD::getSetCCSwappedOperands(Op1); 2914 std::swap(RL, RR); 2915 } 2916 if (LL == RL && LR == RR) { 2917 bool isInteger = LL.getValueType().isInteger(); 2918 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2919 if (Result != ISD::SETCC_INVALID && 2920 (!LegalOperations || 2921 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2922 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2923 EVT CCVT = getSetCCResultType(LL.getValueType()); 2924 if (N0.getValueType() == CCVT || 2925 (!LegalOperations && N0.getValueType() == MVT::i1)) 2926 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2927 LL, LR, Result); 2928 } 2929 } 2930 } 2931 2932 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2933 VT.getSizeInBits() <= 64) { 2934 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2935 APInt ADDC = ADDI->getAPIntValue(); 2936 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2937 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2938 // immediate for an add, but it is legal if its top c2 bits are set, 2939 // transform the ADD so the immediate doesn't need to be materialized 2940 // in a register. 2941 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2942 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2943 SRLI->getZExtValue()); 2944 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2945 ADDC |= Mask; 2946 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2947 SDLoc DL(N0); 2948 SDValue NewAdd = 2949 DAG.getNode(ISD::ADD, DL, VT, 2950 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2951 CombineTo(N0.getNode(), NewAdd); 2952 // Return N so it doesn't get rechecked! 2953 return SDValue(LocReference, 0); 2954 } 2955 } 2956 } 2957 } 2958 } 2959 } 2960 2961 // Reduce bit extract of low half of an integer to the narrower type. 2962 // (and (srl i64:x, K), KMask) -> 2963 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 2964 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 2965 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 2966 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2967 unsigned Size = VT.getSizeInBits(); 2968 const APInt &AndMask = CAnd->getAPIntValue(); 2969 unsigned ShiftBits = CShift->getZExtValue(); 2970 unsigned MaskBits = AndMask.countTrailingOnes(); 2971 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 2972 2973 if (APIntOps::isMask(AndMask) && 2974 // Required bits must not span the two halves of the integer and 2975 // must fit in the half size type. 2976 (ShiftBits + MaskBits <= Size / 2) && 2977 TLI.isNarrowingProfitable(VT, HalfVT) && 2978 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 2979 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 2980 TLI.isTruncateFree(VT, HalfVT) && 2981 TLI.isZExtFree(HalfVT, VT)) { 2982 // The isNarrowingProfitable is to avoid regressions on PPC and 2983 // AArch64 which match a few 64-bit bit insert / bit extract patterns 2984 // on downstream users of this. Those patterns could probably be 2985 // extended to handle extensions mixed in. 2986 2987 SDValue SL(N0); 2988 assert(ShiftBits != 0 && MaskBits <= Size); 2989 2990 // Extracting the highest bit of the low half. 2991 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 2992 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 2993 N0.getOperand(0)); 2994 2995 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 2996 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 2997 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 2998 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 2999 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3000 } 3001 } 3002 } 3003 } 3004 3005 return SDValue(); 3006 } 3007 3008 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3009 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3010 bool &NarrowLoad) { 3011 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3012 3013 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3014 return false; 3015 3016 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3017 LoadedVT = LoadN->getMemoryVT(); 3018 3019 if (ExtVT == LoadedVT && 3020 (!LegalOperations || 3021 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3022 // ZEXTLOAD will match without needing to change the size of the value being 3023 // loaded. 3024 NarrowLoad = false; 3025 return true; 3026 } 3027 3028 // Do not change the width of a volatile load. 3029 if (LoadN->isVolatile()) 3030 return false; 3031 3032 // Do not generate loads of non-round integer types since these can 3033 // be expensive (and would be wrong if the type is not byte sized). 3034 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3035 return false; 3036 3037 if (LegalOperations && 3038 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3039 return false; 3040 3041 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3042 return false; 3043 3044 NarrowLoad = true; 3045 return true; 3046 } 3047 3048 SDValue DAGCombiner::visitAND(SDNode *N) { 3049 SDValue N0 = N->getOperand(0); 3050 SDValue N1 = N->getOperand(1); 3051 EVT VT = N1.getValueType(); 3052 3053 // fold vector ops 3054 if (VT.isVector()) { 3055 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3056 return FoldedVOp; 3057 3058 // fold (and x, 0) -> 0, vector edition 3059 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3060 // do not return N0, because undef node may exist in N0 3061 return DAG.getConstant( 3062 APInt::getNullValue( 3063 N0.getValueType().getScalarType().getSizeInBits()), 3064 SDLoc(N), N0.getValueType()); 3065 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3066 // do not return N1, because undef node may exist in N1 3067 return DAG.getConstant( 3068 APInt::getNullValue( 3069 N1.getValueType().getScalarType().getSizeInBits()), 3070 SDLoc(N), N1.getValueType()); 3071 3072 // fold (and x, -1) -> x, vector edition 3073 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3074 return N1; 3075 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3076 return N0; 3077 } 3078 3079 // fold (and c1, c2) -> c1&c2 3080 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3081 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3082 if (N0C && N1C && !N1C->isOpaque()) 3083 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3084 // canonicalize constant to RHS 3085 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3086 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3087 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3088 // fold (and x, -1) -> x 3089 if (isAllOnesConstant(N1)) 3090 return N0; 3091 // if (and x, c) is known to be zero, return 0 3092 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3093 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3094 APInt::getAllOnesValue(BitWidth))) 3095 return DAG.getConstant(0, SDLoc(N), VT); 3096 // reassociate and 3097 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3098 return RAND; 3099 // fold (and (or x, C), D) -> D if (C & D) == D 3100 if (N1C && N0.getOpcode() == ISD::OR) 3101 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3102 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3103 return N1; 3104 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3105 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3106 SDValue N0Op0 = N0.getOperand(0); 3107 APInt Mask = ~N1C->getAPIntValue(); 3108 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3109 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3110 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3111 N0.getValueType(), N0Op0); 3112 3113 // Replace uses of the AND with uses of the Zero extend node. 3114 CombineTo(N, Zext); 3115 3116 // We actually want to replace all uses of the any_extend with the 3117 // zero_extend, to avoid duplicating things. This will later cause this 3118 // AND to be folded. 3119 CombineTo(N0.getNode(), Zext); 3120 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3121 } 3122 } 3123 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3124 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3125 // already be zero by virtue of the width of the base type of the load. 3126 // 3127 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3128 // more cases. 3129 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3130 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3131 N0.getOperand(0).getOpcode() == ISD::LOAD && 3132 N0.getOperand(0).getResNo() == 0) || 3133 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3134 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3135 N0 : N0.getOperand(0) ); 3136 3137 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3138 // This can be a pure constant or a vector splat, in which case we treat the 3139 // vector as a scalar and use the splat value. 3140 APInt Constant = APInt::getNullValue(1); 3141 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3142 Constant = C->getAPIntValue(); 3143 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3144 APInt SplatValue, SplatUndef; 3145 unsigned SplatBitSize; 3146 bool HasAnyUndefs; 3147 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3148 SplatBitSize, HasAnyUndefs); 3149 if (IsSplat) { 3150 // Undef bits can contribute to a possible optimisation if set, so 3151 // set them. 3152 SplatValue |= SplatUndef; 3153 3154 // The splat value may be something like "0x00FFFFFF", which means 0 for 3155 // the first vector value and FF for the rest, repeating. We need a mask 3156 // that will apply equally to all members of the vector, so AND all the 3157 // lanes of the constant together. 3158 EVT VT = Vector->getValueType(0); 3159 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3160 3161 // If the splat value has been compressed to a bitlength lower 3162 // than the size of the vector lane, we need to re-expand it to 3163 // the lane size. 3164 if (BitWidth > SplatBitSize) 3165 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3166 SplatBitSize < BitWidth; 3167 SplatBitSize = SplatBitSize * 2) 3168 SplatValue |= SplatValue.shl(SplatBitSize); 3169 3170 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3171 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3172 if (SplatBitSize % BitWidth == 0) { 3173 Constant = APInt::getAllOnesValue(BitWidth); 3174 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3175 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3176 } 3177 } 3178 } 3179 3180 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3181 // actually legal and isn't going to get expanded, else this is a false 3182 // optimisation. 3183 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3184 Load->getValueType(0), 3185 Load->getMemoryVT()); 3186 3187 // Resize the constant to the same size as the original memory access before 3188 // extension. If it is still the AllOnesValue then this AND is completely 3189 // unneeded. 3190 Constant = 3191 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3192 3193 bool B; 3194 switch (Load->getExtensionType()) { 3195 default: B = false; break; 3196 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3197 case ISD::ZEXTLOAD: 3198 case ISD::NON_EXTLOAD: B = true; break; 3199 } 3200 3201 if (B && Constant.isAllOnesValue()) { 3202 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3203 // preserve semantics once we get rid of the AND. 3204 SDValue NewLoad(Load, 0); 3205 if (Load->getExtensionType() == ISD::EXTLOAD) { 3206 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3207 Load->getValueType(0), SDLoc(Load), 3208 Load->getChain(), Load->getBasePtr(), 3209 Load->getOffset(), Load->getMemoryVT(), 3210 Load->getMemOperand()); 3211 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3212 if (Load->getNumValues() == 3) { 3213 // PRE/POST_INC loads have 3 values. 3214 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3215 NewLoad.getValue(2) }; 3216 CombineTo(Load, To, 3, true); 3217 } else { 3218 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3219 } 3220 } 3221 3222 // Fold the AND away, taking care not to fold to the old load node if we 3223 // replaced it. 3224 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3225 3226 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3227 } 3228 } 3229 3230 // fold (and (load x), 255) -> (zextload x, i8) 3231 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3232 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3233 if (N1C && (N0.getOpcode() == ISD::LOAD || 3234 (N0.getOpcode() == ISD::ANY_EXTEND && 3235 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3236 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3237 LoadSDNode *LN0 = HasAnyExt 3238 ? cast<LoadSDNode>(N0.getOperand(0)) 3239 : cast<LoadSDNode>(N0); 3240 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3241 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3242 auto NarrowLoad = false; 3243 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3244 EVT ExtVT, LoadedVT; 3245 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3246 NarrowLoad)) { 3247 if (!NarrowLoad) { 3248 SDValue NewLoad = 3249 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3250 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3251 LN0->getMemOperand()); 3252 AddToWorklist(N); 3253 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3254 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3255 } else { 3256 EVT PtrType = LN0->getOperand(1).getValueType(); 3257 3258 unsigned Alignment = LN0->getAlignment(); 3259 SDValue NewPtr = LN0->getBasePtr(); 3260 3261 // For big endian targets, we need to add an offset to the pointer 3262 // to load the correct bytes. For little endian systems, we merely 3263 // need to read fewer bytes from the same pointer. 3264 if (DAG.getDataLayout().isBigEndian()) { 3265 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3266 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3267 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3268 SDLoc DL(LN0); 3269 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3270 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3271 Alignment = MinAlign(Alignment, PtrOff); 3272 } 3273 3274 AddToWorklist(NewPtr.getNode()); 3275 3276 SDValue Load = DAG.getExtLoad( 3277 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3278 LN0->getPointerInfo(), ExtVT, Alignment, 3279 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3280 AddToWorklist(N); 3281 CombineTo(LN0, Load, Load.getValue(1)); 3282 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3283 } 3284 } 3285 } 3286 } 3287 3288 if (SDValue Combined = visitANDLike(N0, N1, N)) 3289 return Combined; 3290 3291 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3292 if (N0.getOpcode() == N1.getOpcode()) 3293 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3294 return Tmp; 3295 3296 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3297 // fold (and (sra)) -> (and (srl)) when possible. 3298 if (!VT.isVector() && 3299 SimplifyDemandedBits(SDValue(N, 0))) 3300 return SDValue(N, 0); 3301 3302 // fold (zext_inreg (extload x)) -> (zextload x) 3303 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3304 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3305 EVT MemVT = LN0->getMemoryVT(); 3306 // If we zero all the possible extended bits, then we can turn this into 3307 // a zextload if we are running before legalize or the operation is legal. 3308 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3309 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3310 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3311 ((!LegalOperations && !LN0->isVolatile()) || 3312 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3313 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3314 LN0->getChain(), LN0->getBasePtr(), 3315 MemVT, LN0->getMemOperand()); 3316 AddToWorklist(N); 3317 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3318 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3319 } 3320 } 3321 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3322 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3323 N0.hasOneUse()) { 3324 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3325 EVT MemVT = LN0->getMemoryVT(); 3326 // If we zero all the possible extended bits, then we can turn this into 3327 // a zextload if we are running before legalize or the operation is legal. 3328 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3329 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3330 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3331 ((!LegalOperations && !LN0->isVolatile()) || 3332 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3333 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3334 LN0->getChain(), LN0->getBasePtr(), 3335 MemVT, LN0->getMemOperand()); 3336 AddToWorklist(N); 3337 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3338 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3339 } 3340 } 3341 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3342 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3343 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3344 N0.getOperand(1), false)) 3345 return BSwap; 3346 } 3347 3348 return SDValue(); 3349 } 3350 3351 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3352 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3353 bool DemandHighBits) { 3354 if (!LegalOperations) 3355 return SDValue(); 3356 3357 EVT VT = N->getValueType(0); 3358 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3359 return SDValue(); 3360 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3361 return SDValue(); 3362 3363 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3364 bool LookPassAnd0 = false; 3365 bool LookPassAnd1 = false; 3366 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3367 std::swap(N0, N1); 3368 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3369 std::swap(N0, N1); 3370 if (N0.getOpcode() == ISD::AND) { 3371 if (!N0.getNode()->hasOneUse()) 3372 return SDValue(); 3373 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3374 if (!N01C || N01C->getZExtValue() != 0xFF00) 3375 return SDValue(); 3376 N0 = N0.getOperand(0); 3377 LookPassAnd0 = true; 3378 } 3379 3380 if (N1.getOpcode() == ISD::AND) { 3381 if (!N1.getNode()->hasOneUse()) 3382 return SDValue(); 3383 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3384 if (!N11C || N11C->getZExtValue() != 0xFF) 3385 return SDValue(); 3386 N1 = N1.getOperand(0); 3387 LookPassAnd1 = true; 3388 } 3389 3390 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3391 std::swap(N0, N1); 3392 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3393 return SDValue(); 3394 if (!N0.getNode()->hasOneUse() || 3395 !N1.getNode()->hasOneUse()) 3396 return SDValue(); 3397 3398 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3399 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3400 if (!N01C || !N11C) 3401 return SDValue(); 3402 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3403 return SDValue(); 3404 3405 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3406 SDValue N00 = N0->getOperand(0); 3407 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3408 if (!N00.getNode()->hasOneUse()) 3409 return SDValue(); 3410 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3411 if (!N001C || N001C->getZExtValue() != 0xFF) 3412 return SDValue(); 3413 N00 = N00.getOperand(0); 3414 LookPassAnd0 = true; 3415 } 3416 3417 SDValue N10 = N1->getOperand(0); 3418 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3419 if (!N10.getNode()->hasOneUse()) 3420 return SDValue(); 3421 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3422 if (!N101C || N101C->getZExtValue() != 0xFF00) 3423 return SDValue(); 3424 N10 = N10.getOperand(0); 3425 LookPassAnd1 = true; 3426 } 3427 3428 if (N00 != N10) 3429 return SDValue(); 3430 3431 // Make sure everything beyond the low halfword gets set to zero since the SRL 3432 // 16 will clear the top bits. 3433 unsigned OpSizeInBits = VT.getSizeInBits(); 3434 if (DemandHighBits && OpSizeInBits > 16) { 3435 // If the left-shift isn't masked out then the only way this is a bswap is 3436 // if all bits beyond the low 8 are 0. In that case the entire pattern 3437 // reduces to a left shift anyway: leave it for other parts of the combiner. 3438 if (!LookPassAnd0) 3439 return SDValue(); 3440 3441 // However, if the right shift isn't masked out then it might be because 3442 // it's not needed. See if we can spot that too. 3443 if (!LookPassAnd1 && 3444 !DAG.MaskedValueIsZero( 3445 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3446 return SDValue(); 3447 } 3448 3449 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3450 if (OpSizeInBits > 16) { 3451 SDLoc DL(N); 3452 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3453 DAG.getConstant(OpSizeInBits - 16, DL, 3454 getShiftAmountTy(VT))); 3455 } 3456 return Res; 3457 } 3458 3459 /// Return true if the specified node is an element that makes up a 32-bit 3460 /// packed halfword byteswap. 3461 /// ((x & 0x000000ff) << 8) | 3462 /// ((x & 0x0000ff00) >> 8) | 3463 /// ((x & 0x00ff0000) << 8) | 3464 /// ((x & 0xff000000) >> 8) 3465 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3466 if (!N.getNode()->hasOneUse()) 3467 return false; 3468 3469 unsigned Opc = N.getOpcode(); 3470 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3471 return false; 3472 3473 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3474 if (!N1C) 3475 return false; 3476 3477 unsigned Num; 3478 switch (N1C->getZExtValue()) { 3479 default: 3480 return false; 3481 case 0xFF: Num = 0; break; 3482 case 0xFF00: Num = 1; break; 3483 case 0xFF0000: Num = 2; break; 3484 case 0xFF000000: Num = 3; break; 3485 } 3486 3487 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3488 SDValue N0 = N.getOperand(0); 3489 if (Opc == ISD::AND) { 3490 if (Num == 0 || Num == 2) { 3491 // (x >> 8) & 0xff 3492 // (x >> 8) & 0xff0000 3493 if (N0.getOpcode() != ISD::SRL) 3494 return false; 3495 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3496 if (!C || C->getZExtValue() != 8) 3497 return false; 3498 } else { 3499 // (x << 8) & 0xff00 3500 // (x << 8) & 0xff000000 3501 if (N0.getOpcode() != ISD::SHL) 3502 return false; 3503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3504 if (!C || C->getZExtValue() != 8) 3505 return false; 3506 } 3507 } else if (Opc == ISD::SHL) { 3508 // (x & 0xff) << 8 3509 // (x & 0xff0000) << 8 3510 if (Num != 0 && Num != 2) 3511 return false; 3512 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3513 if (!C || C->getZExtValue() != 8) 3514 return false; 3515 } else { // Opc == ISD::SRL 3516 // (x & 0xff00) >> 8 3517 // (x & 0xff000000) >> 8 3518 if (Num != 1 && Num != 3) 3519 return false; 3520 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3521 if (!C || C->getZExtValue() != 8) 3522 return false; 3523 } 3524 3525 if (Parts[Num]) 3526 return false; 3527 3528 Parts[Num] = N0.getOperand(0).getNode(); 3529 return true; 3530 } 3531 3532 /// Match a 32-bit packed halfword bswap. That is 3533 /// ((x & 0x000000ff) << 8) | 3534 /// ((x & 0x0000ff00) >> 8) | 3535 /// ((x & 0x00ff0000) << 8) | 3536 /// ((x & 0xff000000) >> 8) 3537 /// => (rotl (bswap x), 16) 3538 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3539 if (!LegalOperations) 3540 return SDValue(); 3541 3542 EVT VT = N->getValueType(0); 3543 if (VT != MVT::i32) 3544 return SDValue(); 3545 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3546 return SDValue(); 3547 3548 // Look for either 3549 // (or (or (and), (and)), (or (and), (and))) 3550 // (or (or (or (and), (and)), (and)), (and)) 3551 if (N0.getOpcode() != ISD::OR) 3552 return SDValue(); 3553 SDValue N00 = N0.getOperand(0); 3554 SDValue N01 = N0.getOperand(1); 3555 SDNode *Parts[4] = {}; 3556 3557 if (N1.getOpcode() == ISD::OR && 3558 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3559 // (or (or (and), (and)), (or (and), (and))) 3560 SDValue N000 = N00.getOperand(0); 3561 if (!isBSwapHWordElement(N000, Parts)) 3562 return SDValue(); 3563 3564 SDValue N001 = N00.getOperand(1); 3565 if (!isBSwapHWordElement(N001, Parts)) 3566 return SDValue(); 3567 SDValue N010 = N01.getOperand(0); 3568 if (!isBSwapHWordElement(N010, Parts)) 3569 return SDValue(); 3570 SDValue N011 = N01.getOperand(1); 3571 if (!isBSwapHWordElement(N011, Parts)) 3572 return SDValue(); 3573 } else { 3574 // (or (or (or (and), (and)), (and)), (and)) 3575 if (!isBSwapHWordElement(N1, Parts)) 3576 return SDValue(); 3577 if (!isBSwapHWordElement(N01, Parts)) 3578 return SDValue(); 3579 if (N00.getOpcode() != ISD::OR) 3580 return SDValue(); 3581 SDValue N000 = N00.getOperand(0); 3582 if (!isBSwapHWordElement(N000, Parts)) 3583 return SDValue(); 3584 SDValue N001 = N00.getOperand(1); 3585 if (!isBSwapHWordElement(N001, Parts)) 3586 return SDValue(); 3587 } 3588 3589 // Make sure the parts are all coming from the same node. 3590 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3591 return SDValue(); 3592 3593 SDLoc DL(N); 3594 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3595 SDValue(Parts[0], 0)); 3596 3597 // Result of the bswap should be rotated by 16. If it's not legal, then 3598 // do (x << 16) | (x >> 16). 3599 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3600 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3601 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3602 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3603 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3604 return DAG.getNode(ISD::OR, DL, VT, 3605 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3606 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3607 } 3608 3609 /// This contains all DAGCombine rules which reduce two values combined by 3610 /// an Or operation to a single value \see visitANDLike(). 3611 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3612 EVT VT = N1.getValueType(); 3613 // fold (or x, undef) -> -1 3614 if (!LegalOperations && 3615 (N0.isUndef() || N1.isUndef())) { 3616 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3617 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3618 SDLoc(LocReference), VT); 3619 } 3620 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3621 SDValue LL, LR, RL, RR, CC0, CC1; 3622 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3623 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3624 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3625 3626 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3627 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3628 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3629 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3630 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3631 LR.getValueType(), LL, RL); 3632 AddToWorklist(ORNode.getNode()); 3633 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3634 } 3635 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3636 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3637 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3638 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3639 LR.getValueType(), LL, RL); 3640 AddToWorklist(ANDNode.getNode()); 3641 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3642 } 3643 } 3644 // canonicalize equivalent to ll == rl 3645 if (LL == RR && LR == RL) { 3646 Op1 = ISD::getSetCCSwappedOperands(Op1); 3647 std::swap(RL, RR); 3648 } 3649 if (LL == RL && LR == RR) { 3650 bool isInteger = LL.getValueType().isInteger(); 3651 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3652 if (Result != ISD::SETCC_INVALID && 3653 (!LegalOperations || 3654 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3655 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3656 EVT CCVT = getSetCCResultType(LL.getValueType()); 3657 if (N0.getValueType() == CCVT || 3658 (!LegalOperations && N0.getValueType() == MVT::i1)) 3659 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3660 LL, LR, Result); 3661 } 3662 } 3663 } 3664 3665 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3666 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3667 // Don't increase # computations. 3668 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3669 // We can only do this xform if we know that bits from X that are set in C2 3670 // but not in C1 are already zero. Likewise for Y. 3671 if (const ConstantSDNode *N0O1C = 3672 getAsNonOpaqueConstant(N0.getOperand(1))) { 3673 if (const ConstantSDNode *N1O1C = 3674 getAsNonOpaqueConstant(N1.getOperand(1))) { 3675 // We can only do this xform if we know that bits from X that are set in 3676 // C2 but not in C1 are already zero. Likewise for Y. 3677 const APInt &LHSMask = N0O1C->getAPIntValue(); 3678 const APInt &RHSMask = N1O1C->getAPIntValue(); 3679 3680 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3681 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3682 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3683 N0.getOperand(0), N1.getOperand(0)); 3684 SDLoc DL(LocReference); 3685 return DAG.getNode(ISD::AND, DL, VT, X, 3686 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3687 } 3688 } 3689 } 3690 } 3691 3692 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3693 if (N0.getOpcode() == ISD::AND && 3694 N1.getOpcode() == ISD::AND && 3695 N0.getOperand(0) == N1.getOperand(0) && 3696 // Don't increase # computations. 3697 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3698 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3699 N0.getOperand(1), N1.getOperand(1)); 3700 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3701 } 3702 3703 return SDValue(); 3704 } 3705 3706 SDValue DAGCombiner::visitOR(SDNode *N) { 3707 SDValue N0 = N->getOperand(0); 3708 SDValue N1 = N->getOperand(1); 3709 EVT VT = N1.getValueType(); 3710 3711 // fold vector ops 3712 if (VT.isVector()) { 3713 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3714 return FoldedVOp; 3715 3716 // fold (or x, 0) -> x, vector edition 3717 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3718 return N1; 3719 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3720 return N0; 3721 3722 // fold (or x, -1) -> -1, vector edition 3723 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3724 // do not return N0, because undef node may exist in N0 3725 return DAG.getConstant( 3726 APInt::getAllOnesValue( 3727 N0.getValueType().getScalarType().getSizeInBits()), 3728 SDLoc(N), N0.getValueType()); 3729 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3730 // do not return N1, because undef node may exist in N1 3731 return DAG.getConstant( 3732 APInt::getAllOnesValue( 3733 N1.getValueType().getScalarType().getSizeInBits()), 3734 SDLoc(N), N1.getValueType()); 3735 3736 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 3737 // Do this only if the resulting shuffle is legal. 3738 if (isa<ShuffleVectorSDNode>(N0) && 3739 isa<ShuffleVectorSDNode>(N1) && 3740 // Avoid folding a node with illegal type. 3741 TLI.isTypeLegal(VT)) { 3742 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 3743 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 3744 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 3745 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 3746 // Ensure both shuffles have a zero input. 3747 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 3748 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 3749 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 3750 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3751 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3752 bool CanFold = true; 3753 int NumElts = VT.getVectorNumElements(); 3754 SmallVector<int, 4> Mask(NumElts); 3755 3756 for (int i = 0; i != NumElts; ++i) { 3757 int M0 = SV0->getMaskElt(i); 3758 int M1 = SV1->getMaskElt(i); 3759 3760 // Determine if either index is pointing to a zero vector. 3761 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 3762 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 3763 3764 // If one element is zero and the otherside is undef, keep undef. 3765 // This also handles the case that both are undef. 3766 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 3767 Mask[i] = -1; 3768 continue; 3769 } 3770 3771 // Make sure only one of the elements is zero. 3772 if (M0Zero == M1Zero) { 3773 CanFold = false; 3774 break; 3775 } 3776 3777 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 3778 3779 // We have a zero and non-zero element. If the non-zero came from 3780 // SV0 make the index a LHS index. If it came from SV1, make it 3781 // a RHS index. We need to mod by NumElts because we don't care 3782 // which operand it came from in the original shuffles. 3783 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 3784 } 3785 3786 if (CanFold) { 3787 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 3788 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 3789 3790 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3791 if (!LegalMask) { 3792 std::swap(NewLHS, NewRHS); 3793 ShuffleVectorSDNode::commuteMask(Mask); 3794 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3795 } 3796 3797 if (LegalMask) 3798 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 3799 } 3800 } 3801 } 3802 } 3803 3804 // fold (or c1, c2) -> c1|c2 3805 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3806 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3807 if (N0C && N1C && !N1C->isOpaque()) 3808 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3809 // canonicalize constant to RHS 3810 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3811 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3812 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3813 // fold (or x, 0) -> x 3814 if (isNullConstant(N1)) 3815 return N0; 3816 // fold (or x, -1) -> -1 3817 if (isAllOnesConstant(N1)) 3818 return N1; 3819 // fold (or x, c) -> c iff (x & ~c) == 0 3820 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3821 return N1; 3822 3823 if (SDValue Combined = visitORLike(N0, N1, N)) 3824 return Combined; 3825 3826 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3827 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3828 return BSwap; 3829 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3830 return BSwap; 3831 3832 // reassociate or 3833 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3834 return ROR; 3835 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3836 // iff (c1 & c2) == 0. 3837 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3838 isa<ConstantSDNode>(N0.getOperand(1))) { 3839 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3840 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3841 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3842 N1C, C1)) 3843 return DAG.getNode( 3844 ISD::AND, SDLoc(N), VT, 3845 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3846 return SDValue(); 3847 } 3848 } 3849 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3850 if (N0.getOpcode() == N1.getOpcode()) 3851 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3852 return Tmp; 3853 3854 // See if this is some rotate idiom. 3855 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3856 return SDValue(Rot, 0); 3857 3858 // Simplify the operands using demanded-bits information. 3859 if (!VT.isVector() && 3860 SimplifyDemandedBits(SDValue(N, 0))) 3861 return SDValue(N, 0); 3862 3863 return SDValue(); 3864 } 3865 3866 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3867 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3868 if (Op.getOpcode() == ISD::AND) { 3869 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3870 Mask = Op.getOperand(1); 3871 Op = Op.getOperand(0); 3872 } else { 3873 return false; 3874 } 3875 } 3876 3877 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3878 Shift = Op; 3879 return true; 3880 } 3881 3882 return false; 3883 } 3884 3885 // Return true if we can prove that, whenever Neg and Pos are both in the 3886 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3887 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3888 // 3889 // (or (shift1 X, Neg), (shift2 X, Pos)) 3890 // 3891 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3892 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3893 // to consider shift amounts with defined behavior. 3894 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3895 // If EltSize is a power of 2 then: 3896 // 3897 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3898 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3899 // 3900 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3901 // for the stronger condition: 3902 // 3903 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3904 // 3905 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3906 // we can just replace Neg with Neg' for the rest of the function. 3907 // 3908 // In other cases we check for the even stronger condition: 3909 // 3910 // Neg == EltSize - Pos [B] 3911 // 3912 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3913 // behavior if Pos == 0 (and consequently Neg == EltSize). 3914 // 3915 // We could actually use [A] whenever EltSize is a power of 2, but the 3916 // only extra cases that it would match are those uninteresting ones 3917 // where Neg and Pos are never in range at the same time. E.g. for 3918 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3919 // as well as (sub 32, Pos), but: 3920 // 3921 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3922 // 3923 // always invokes undefined behavior for 32-bit X. 3924 // 3925 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3926 unsigned MaskLoBits = 0; 3927 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3928 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3929 if (NegC->getAPIntValue() == EltSize - 1) { 3930 Neg = Neg.getOperand(0); 3931 MaskLoBits = Log2_64(EltSize); 3932 } 3933 } 3934 } 3935 3936 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3937 if (Neg.getOpcode() != ISD::SUB) 3938 return false; 3939 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3940 if (!NegC) 3941 return false; 3942 SDValue NegOp1 = Neg.getOperand(1); 3943 3944 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3945 // Pos'. The truncation is redundant for the purpose of the equality. 3946 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3947 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3948 if (PosC->getAPIntValue() == EltSize - 1) 3949 Pos = Pos.getOperand(0); 3950 3951 // The condition we need is now: 3952 // 3953 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3954 // 3955 // If NegOp1 == Pos then we need: 3956 // 3957 // EltSize & Mask == NegC & Mask 3958 // 3959 // (because "x & Mask" is a truncation and distributes through subtraction). 3960 APInt Width; 3961 if (Pos == NegOp1) 3962 Width = NegC->getAPIntValue(); 3963 3964 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3965 // Then the condition we want to prove becomes: 3966 // 3967 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3968 // 3969 // which, again because "x & Mask" is a truncation, becomes: 3970 // 3971 // NegC & Mask == (EltSize - PosC) & Mask 3972 // EltSize & Mask == (NegC + PosC) & Mask 3973 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3974 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3975 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3976 else 3977 return false; 3978 } else 3979 return false; 3980 3981 // Now we just need to check that EltSize & Mask == Width & Mask. 3982 if (MaskLoBits) 3983 // EltSize & Mask is 0 since Mask is EltSize - 1. 3984 return Width.getLoBits(MaskLoBits) == 0; 3985 return Width == EltSize; 3986 } 3987 3988 // A subroutine of MatchRotate used once we have found an OR of two opposite 3989 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3990 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3991 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3992 // Neg with outer conversions stripped away. 3993 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3994 SDValue Neg, SDValue InnerPos, 3995 SDValue InnerNeg, unsigned PosOpcode, 3996 unsigned NegOpcode, const SDLoc &DL) { 3997 // fold (or (shl x, (*ext y)), 3998 // (srl x, (*ext (sub 32, y)))) -> 3999 // (rotl x, y) or (rotr x, (sub 32, y)) 4000 // 4001 // fold (or (shl x, (*ext (sub 32, y))), 4002 // (srl x, (*ext y))) -> 4003 // (rotr x, y) or (rotl x, (sub 32, y)) 4004 EVT VT = Shifted.getValueType(); 4005 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4006 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4007 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4008 HasPos ? Pos : Neg).getNode(); 4009 } 4010 4011 return nullptr; 4012 } 4013 4014 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4015 // idioms for rotate, and if the target supports rotation instructions, generate 4016 // a rot[lr]. 4017 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4018 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4019 EVT VT = LHS.getValueType(); 4020 if (!TLI.isTypeLegal(VT)) return nullptr; 4021 4022 // The target must have at least one rotate flavor. 4023 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4024 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4025 if (!HasROTL && !HasROTR) return nullptr; 4026 4027 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4028 SDValue LHSShift; // The shift. 4029 SDValue LHSMask; // AND value if any. 4030 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4031 return nullptr; // Not part of a rotate. 4032 4033 SDValue RHSShift; // The shift. 4034 SDValue RHSMask; // AND value if any. 4035 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4036 return nullptr; // Not part of a rotate. 4037 4038 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4039 return nullptr; // Not shifting the same value. 4040 4041 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4042 return nullptr; // Shifts must disagree. 4043 4044 // Canonicalize shl to left side in a shl/srl pair. 4045 if (RHSShift.getOpcode() == ISD::SHL) { 4046 std::swap(LHS, RHS); 4047 std::swap(LHSShift, RHSShift); 4048 std::swap(LHSMask, RHSMask); 4049 } 4050 4051 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4052 SDValue LHSShiftArg = LHSShift.getOperand(0); 4053 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4054 SDValue RHSShiftArg = RHSShift.getOperand(0); 4055 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4056 4057 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4058 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4059 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4060 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4061 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4062 if ((LShVal + RShVal) != EltSizeInBits) 4063 return nullptr; 4064 4065 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4066 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4067 4068 // If there is an AND of either shifted operand, apply it to the result. 4069 if (LHSMask.getNode() || RHSMask.getNode()) { 4070 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4071 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4072 4073 if (LHSMask.getNode()) { 4074 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4075 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4076 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4077 DAG.getConstant(RHSBits, DL, VT))); 4078 } 4079 if (RHSMask.getNode()) { 4080 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4081 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4082 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4083 DAG.getConstant(LHSBits, DL, VT))); 4084 } 4085 4086 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4087 } 4088 4089 return Rot.getNode(); 4090 } 4091 4092 // If there is a mask here, and we have a variable shift, we can't be sure 4093 // that we're masking out the right stuff. 4094 if (LHSMask.getNode() || RHSMask.getNode()) 4095 return nullptr; 4096 4097 // If the shift amount is sign/zext/any-extended just peel it off. 4098 SDValue LExtOp0 = LHSShiftAmt; 4099 SDValue RExtOp0 = RHSShiftAmt; 4100 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4101 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4102 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4103 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4104 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4105 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4106 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4107 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4108 LExtOp0 = LHSShiftAmt.getOperand(0); 4109 RExtOp0 = RHSShiftAmt.getOperand(0); 4110 } 4111 4112 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4113 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4114 if (TryL) 4115 return TryL; 4116 4117 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4118 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4119 if (TryR) 4120 return TryR; 4121 4122 return nullptr; 4123 } 4124 4125 SDValue DAGCombiner::visitXOR(SDNode *N) { 4126 SDValue N0 = N->getOperand(0); 4127 SDValue N1 = N->getOperand(1); 4128 EVT VT = N0.getValueType(); 4129 4130 // fold vector ops 4131 if (VT.isVector()) { 4132 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4133 return FoldedVOp; 4134 4135 // fold (xor x, 0) -> x, vector edition 4136 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4137 return N1; 4138 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4139 return N0; 4140 } 4141 4142 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4143 if (N0.isUndef() && N1.isUndef()) 4144 return DAG.getConstant(0, SDLoc(N), VT); 4145 // fold (xor x, undef) -> undef 4146 if (N0.isUndef()) 4147 return N0; 4148 if (N1.isUndef()) 4149 return N1; 4150 // fold (xor c1, c2) -> c1^c2 4151 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4152 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4153 if (N0C && N1C) 4154 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4155 // canonicalize constant to RHS 4156 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4157 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4158 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4159 // fold (xor x, 0) -> x 4160 if (isNullConstant(N1)) 4161 return N0; 4162 // reassociate xor 4163 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4164 return RXOR; 4165 4166 // fold !(x cc y) -> (x !cc y) 4167 SDValue LHS, RHS, CC; 4168 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4169 bool isInt = LHS.getValueType().isInteger(); 4170 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4171 isInt); 4172 4173 if (!LegalOperations || 4174 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4175 switch (N0.getOpcode()) { 4176 default: 4177 llvm_unreachable("Unhandled SetCC Equivalent!"); 4178 case ISD::SETCC: 4179 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4180 case ISD::SELECT_CC: 4181 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4182 N0.getOperand(3), NotCC); 4183 } 4184 } 4185 } 4186 4187 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4188 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4189 N0.getNode()->hasOneUse() && 4190 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4191 SDValue V = N0.getOperand(0); 4192 SDLoc DL(N0); 4193 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4194 DAG.getConstant(1, DL, V.getValueType())); 4195 AddToWorklist(V.getNode()); 4196 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4197 } 4198 4199 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4200 if (isOneConstant(N1) && VT == MVT::i1 && 4201 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4202 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4203 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4204 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4205 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4206 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4207 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4208 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4209 } 4210 } 4211 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4212 if (isAllOnesConstant(N1) && 4213 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4214 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4215 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4216 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4217 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4218 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4219 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4220 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4221 } 4222 } 4223 // fold (xor (and x, y), y) -> (and (not x), y) 4224 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4225 N0->getOperand(1) == N1) { 4226 SDValue X = N0->getOperand(0); 4227 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4228 AddToWorklist(NotX.getNode()); 4229 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4230 } 4231 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4232 if (N1C && N0.getOpcode() == ISD::XOR) { 4233 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4234 SDLoc DL(N); 4235 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4236 DAG.getConstant(N1C->getAPIntValue() ^ 4237 N00C->getAPIntValue(), DL, VT)); 4238 } 4239 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4240 SDLoc DL(N); 4241 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4242 DAG.getConstant(N1C->getAPIntValue() ^ 4243 N01C->getAPIntValue(), DL, VT)); 4244 } 4245 } 4246 // fold (xor x, x) -> 0 4247 if (N0 == N1) 4248 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4249 4250 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4251 // Here is a concrete example of this equivalence: 4252 // i16 x == 14 4253 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4254 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4255 // 4256 // => 4257 // 4258 // i16 ~1 == 0b1111111111111110 4259 // i16 rol(~1, 14) == 0b1011111111111111 4260 // 4261 // Some additional tips to help conceptualize this transform: 4262 // - Try to see the operation as placing a single zero in a value of all ones. 4263 // - There exists no value for x which would allow the result to contain zero. 4264 // - Values of x larger than the bitwidth are undefined and do not require a 4265 // consistent result. 4266 // - Pushing the zero left requires shifting one bits in from the right. 4267 // A rotate left of ~1 is a nice way of achieving the desired result. 4268 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4269 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4270 SDLoc DL(N); 4271 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4272 N0.getOperand(1)); 4273 } 4274 4275 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4276 if (N0.getOpcode() == N1.getOpcode()) 4277 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4278 return Tmp; 4279 4280 // Simplify the expression using non-local knowledge. 4281 if (!VT.isVector() && 4282 SimplifyDemandedBits(SDValue(N, 0))) 4283 return SDValue(N, 0); 4284 4285 return SDValue(); 4286 } 4287 4288 /// Handle transforms common to the three shifts, when the shift amount is a 4289 /// constant. 4290 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4291 SDNode *LHS = N->getOperand(0).getNode(); 4292 if (!LHS->hasOneUse()) return SDValue(); 4293 4294 // We want to pull some binops through shifts, so that we have (and (shift)) 4295 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4296 // thing happens with address calculations, so it's important to canonicalize 4297 // it. 4298 bool HighBitSet = false; // Can we transform this if the high bit is set? 4299 4300 switch (LHS->getOpcode()) { 4301 default: return SDValue(); 4302 case ISD::OR: 4303 case ISD::XOR: 4304 HighBitSet = false; // We can only transform sra if the high bit is clear. 4305 break; 4306 case ISD::AND: 4307 HighBitSet = true; // We can only transform sra if the high bit is set. 4308 break; 4309 case ISD::ADD: 4310 if (N->getOpcode() != ISD::SHL) 4311 return SDValue(); // only shl(add) not sr[al](add). 4312 HighBitSet = false; // We can only transform sra if the high bit is clear. 4313 break; 4314 } 4315 4316 // We require the RHS of the binop to be a constant and not opaque as well. 4317 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4318 if (!BinOpCst) return SDValue(); 4319 4320 // FIXME: disable this unless the input to the binop is a shift by a constant. 4321 // If it is not a shift, it pessimizes some common cases like: 4322 // 4323 // void foo(int *X, int i) { X[i & 1235] = 1; } 4324 // int bar(int *X, int i) { return X[i & 255]; } 4325 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4326 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4327 BinOpLHSVal->getOpcode() != ISD::SRA && 4328 BinOpLHSVal->getOpcode() != ISD::SRL) || 4329 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4330 return SDValue(); 4331 4332 EVT VT = N->getValueType(0); 4333 4334 // If this is a signed shift right, and the high bit is modified by the 4335 // logical operation, do not perform the transformation. The highBitSet 4336 // boolean indicates the value of the high bit of the constant which would 4337 // cause it to be modified for this operation. 4338 if (N->getOpcode() == ISD::SRA) { 4339 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4340 if (BinOpRHSSignSet != HighBitSet) 4341 return SDValue(); 4342 } 4343 4344 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4345 return SDValue(); 4346 4347 // Fold the constants, shifting the binop RHS by the shift amount. 4348 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4349 N->getValueType(0), 4350 LHS->getOperand(1), N->getOperand(1)); 4351 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4352 4353 // Create the new shift. 4354 SDValue NewShift = DAG.getNode(N->getOpcode(), 4355 SDLoc(LHS->getOperand(0)), 4356 VT, LHS->getOperand(0), N->getOperand(1)); 4357 4358 // Create the new binop. 4359 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4360 } 4361 4362 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4363 assert(N->getOpcode() == ISD::TRUNCATE); 4364 assert(N->getOperand(0).getOpcode() == ISD::AND); 4365 4366 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4367 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4368 SDValue N01 = N->getOperand(0).getOperand(1); 4369 4370 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4371 if (!N01C->isOpaque()) { 4372 EVT TruncVT = N->getValueType(0); 4373 SDValue N00 = N->getOperand(0).getOperand(0); 4374 APInt TruncC = N01C->getAPIntValue(); 4375 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4376 SDLoc DL(N); 4377 4378 return DAG.getNode(ISD::AND, DL, TruncVT, 4379 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4380 DAG.getConstant(TruncC, DL, TruncVT)); 4381 } 4382 } 4383 } 4384 4385 return SDValue(); 4386 } 4387 4388 SDValue DAGCombiner::visitRotate(SDNode *N) { 4389 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4390 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4391 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4392 if (SDValue NewOp1 = 4393 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4394 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4395 N->getOperand(0), NewOp1); 4396 } 4397 return SDValue(); 4398 } 4399 4400 SDValue DAGCombiner::visitSHL(SDNode *N) { 4401 SDValue N0 = N->getOperand(0); 4402 SDValue N1 = N->getOperand(1); 4403 EVT VT = N0.getValueType(); 4404 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4405 4406 // fold vector ops 4407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4408 if (VT.isVector()) { 4409 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4410 return FoldedVOp; 4411 4412 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4413 // If setcc produces all-one true value then: 4414 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4415 if (N1CV && N1CV->isConstant()) { 4416 if (N0.getOpcode() == ISD::AND) { 4417 SDValue N00 = N0->getOperand(0); 4418 SDValue N01 = N0->getOperand(1); 4419 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4420 4421 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4422 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4423 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4424 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4425 N01CV, N1CV)) 4426 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4427 } 4428 } else { 4429 N1C = isConstOrConstSplat(N1); 4430 } 4431 } 4432 } 4433 4434 // fold (shl c1, c2) -> c1<<c2 4435 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4436 if (N0C && N1C && !N1C->isOpaque()) 4437 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4438 // fold (shl 0, x) -> 0 4439 if (isNullConstant(N0)) 4440 return N0; 4441 // fold (shl x, c >= size(x)) -> undef 4442 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4443 return DAG.getUNDEF(VT); 4444 // fold (shl x, 0) -> x 4445 if (N1C && N1C->isNullValue()) 4446 return N0; 4447 // fold (shl undef, x) -> 0 4448 if (N0.isUndef()) 4449 return DAG.getConstant(0, SDLoc(N), VT); 4450 // if (shl x, c) is known to be zero, return 0 4451 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4452 APInt::getAllOnesValue(OpSizeInBits))) 4453 return DAG.getConstant(0, SDLoc(N), VT); 4454 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4455 if (N1.getOpcode() == ISD::TRUNCATE && 4456 N1.getOperand(0).getOpcode() == ISD::AND) { 4457 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4458 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4459 } 4460 4461 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4462 return SDValue(N, 0); 4463 4464 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4465 if (N1C && N0.getOpcode() == ISD::SHL) { 4466 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4467 uint64_t c1 = N0C1->getZExtValue(); 4468 uint64_t c2 = N1C->getZExtValue(); 4469 SDLoc DL(N); 4470 if (c1 + c2 >= OpSizeInBits) 4471 return DAG.getConstant(0, DL, VT); 4472 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4473 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4474 } 4475 } 4476 4477 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4478 // For this to be valid, the second form must not preserve any of the bits 4479 // that are shifted out by the inner shift in the first form. This means 4480 // the outer shift size must be >= the number of bits added by the ext. 4481 // As a corollary, we don't care what kind of ext it is. 4482 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4483 N0.getOpcode() == ISD::ANY_EXTEND || 4484 N0.getOpcode() == ISD::SIGN_EXTEND) && 4485 N0.getOperand(0).getOpcode() == ISD::SHL) { 4486 SDValue N0Op0 = N0.getOperand(0); 4487 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4488 uint64_t c1 = N0Op0C1->getZExtValue(); 4489 uint64_t c2 = N1C->getZExtValue(); 4490 EVT InnerShiftVT = N0Op0.getValueType(); 4491 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4492 if (c2 >= OpSizeInBits - InnerShiftSize) { 4493 SDLoc DL(N0); 4494 if (c1 + c2 >= OpSizeInBits) 4495 return DAG.getConstant(0, DL, VT); 4496 return DAG.getNode(ISD::SHL, DL, VT, 4497 DAG.getNode(N0.getOpcode(), DL, VT, 4498 N0Op0->getOperand(0)), 4499 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4500 } 4501 } 4502 } 4503 4504 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4505 // Only fold this if the inner zext has no other uses to avoid increasing 4506 // the total number of instructions. 4507 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4508 N0.getOperand(0).getOpcode() == ISD::SRL) { 4509 SDValue N0Op0 = N0.getOperand(0); 4510 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4511 uint64_t c1 = N0Op0C1->getZExtValue(); 4512 if (c1 < VT.getScalarSizeInBits()) { 4513 uint64_t c2 = N1C->getZExtValue(); 4514 if (c1 == c2) { 4515 SDValue NewOp0 = N0.getOperand(0); 4516 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4517 SDLoc DL(N); 4518 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4519 NewOp0, 4520 DAG.getConstant(c2, DL, CountVT)); 4521 AddToWorklist(NewSHL.getNode()); 4522 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4523 } 4524 } 4525 } 4526 } 4527 4528 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4529 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4530 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4531 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4532 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4533 uint64_t C1 = N0C1->getZExtValue(); 4534 uint64_t C2 = N1C->getZExtValue(); 4535 SDLoc DL(N); 4536 if (C1 <= C2) 4537 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4538 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4539 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4540 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4541 } 4542 } 4543 4544 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4545 // (and (srl x, (sub c1, c2), MASK) 4546 // Only fold this if the inner shift has no other uses -- if it does, folding 4547 // this will increase the total number of instructions. 4548 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4549 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4550 uint64_t c1 = N0C1->getZExtValue(); 4551 if (c1 < OpSizeInBits) { 4552 uint64_t c2 = N1C->getZExtValue(); 4553 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4554 SDValue Shift; 4555 if (c2 > c1) { 4556 Mask = Mask.shl(c2 - c1); 4557 SDLoc DL(N); 4558 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4559 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4560 } else { 4561 Mask = Mask.lshr(c1 - c2); 4562 SDLoc DL(N); 4563 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4564 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4565 } 4566 SDLoc DL(N0); 4567 return DAG.getNode(ISD::AND, DL, VT, Shift, 4568 DAG.getConstant(Mask, DL, VT)); 4569 } 4570 } 4571 } 4572 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4573 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4574 unsigned BitSize = VT.getScalarSizeInBits(); 4575 SDLoc DL(N); 4576 SDValue HiBitsMask = 4577 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4578 BitSize - N1C->getZExtValue()), 4579 DL, VT); 4580 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4581 HiBitsMask); 4582 } 4583 4584 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4585 // Variant of version done on multiply, except mul by a power of 2 is turned 4586 // into a shift. 4587 APInt Val; 4588 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4589 (isa<ConstantSDNode>(N0.getOperand(1)) || 4590 ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4591 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4592 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4593 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4594 } 4595 4596 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4597 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4598 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4599 if (SDValue Folded = 4600 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4601 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4602 } 4603 } 4604 4605 if (N1C && !N1C->isOpaque()) 4606 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4607 return NewSHL; 4608 4609 return SDValue(); 4610 } 4611 4612 SDValue DAGCombiner::visitSRA(SDNode *N) { 4613 SDValue N0 = N->getOperand(0); 4614 SDValue N1 = N->getOperand(1); 4615 EVT VT = N0.getValueType(); 4616 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4617 4618 // fold vector ops 4619 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4620 if (VT.isVector()) { 4621 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4622 return FoldedVOp; 4623 4624 N1C = isConstOrConstSplat(N1); 4625 } 4626 4627 // fold (sra c1, c2) -> (sra c1, c2) 4628 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4629 if (N0C && N1C && !N1C->isOpaque()) 4630 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4631 // fold (sra 0, x) -> 0 4632 if (isNullConstant(N0)) 4633 return N0; 4634 // fold (sra -1, x) -> -1 4635 if (isAllOnesConstant(N0)) 4636 return N0; 4637 // fold (sra x, (setge c, size(x))) -> undef 4638 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4639 return DAG.getUNDEF(VT); 4640 // fold (sra x, 0) -> x 4641 if (N1C && N1C->isNullValue()) 4642 return N0; 4643 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4644 // sext_inreg. 4645 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4646 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4647 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4648 if (VT.isVector()) 4649 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4650 ExtVT, VT.getVectorNumElements()); 4651 if ((!LegalOperations || 4652 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4653 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4654 N0.getOperand(0), DAG.getValueType(ExtVT)); 4655 } 4656 4657 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4658 if (N1C && N0.getOpcode() == ISD::SRA) { 4659 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4660 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4661 if (Sum >= OpSizeInBits) 4662 Sum = OpSizeInBits - 1; 4663 SDLoc DL(N); 4664 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4665 DAG.getConstant(Sum, DL, N1.getValueType())); 4666 } 4667 } 4668 4669 // fold (sra (shl X, m), (sub result_size, n)) 4670 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4671 // result_size - n != m. 4672 // If truncate is free for the target sext(shl) is likely to result in better 4673 // code. 4674 if (N0.getOpcode() == ISD::SHL && N1C) { 4675 // Get the two constanst of the shifts, CN0 = m, CN = n. 4676 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4677 if (N01C) { 4678 LLVMContext &Ctx = *DAG.getContext(); 4679 // Determine what the truncate's result bitsize and type would be. 4680 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4681 4682 if (VT.isVector()) 4683 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4684 4685 // Determine the residual right-shift amount. 4686 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4687 4688 // If the shift is not a no-op (in which case this should be just a sign 4689 // extend already), the truncated to type is legal, sign_extend is legal 4690 // on that type, and the truncate to that type is both legal and free, 4691 // perform the transform. 4692 if ((ShiftAmt > 0) && 4693 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4694 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4695 TLI.isTruncateFree(VT, TruncVT)) { 4696 4697 SDLoc DL(N); 4698 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4699 getShiftAmountTy(N0.getOperand(0).getValueType())); 4700 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4701 N0.getOperand(0), Amt); 4702 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4703 Shift); 4704 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4705 N->getValueType(0), Trunc); 4706 } 4707 } 4708 } 4709 4710 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4711 if (N1.getOpcode() == ISD::TRUNCATE && 4712 N1.getOperand(0).getOpcode() == ISD::AND) { 4713 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4714 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4715 } 4716 4717 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4718 // if c1 is equal to the number of bits the trunc removes 4719 if (N0.getOpcode() == ISD::TRUNCATE && 4720 (N0.getOperand(0).getOpcode() == ISD::SRL || 4721 N0.getOperand(0).getOpcode() == ISD::SRA) && 4722 N0.getOperand(0).hasOneUse() && 4723 N0.getOperand(0).getOperand(1).hasOneUse() && 4724 N1C) { 4725 SDValue N0Op0 = N0.getOperand(0); 4726 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4727 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4728 EVT LargeVT = N0Op0.getValueType(); 4729 4730 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4731 SDLoc DL(N); 4732 SDValue Amt = 4733 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4734 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4735 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4736 N0Op0.getOperand(0), Amt); 4737 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4738 } 4739 } 4740 } 4741 4742 // Simplify, based on bits shifted out of the LHS. 4743 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4744 return SDValue(N, 0); 4745 4746 4747 // If the sign bit is known to be zero, switch this to a SRL. 4748 if (DAG.SignBitIsZero(N0)) 4749 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4750 4751 if (N1C && !N1C->isOpaque()) 4752 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4753 return NewSRA; 4754 4755 return SDValue(); 4756 } 4757 4758 SDValue DAGCombiner::visitSRL(SDNode *N) { 4759 SDValue N0 = N->getOperand(0); 4760 SDValue N1 = N->getOperand(1); 4761 EVT VT = N0.getValueType(); 4762 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4763 4764 // fold vector ops 4765 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4766 if (VT.isVector()) { 4767 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4768 return FoldedVOp; 4769 4770 N1C = isConstOrConstSplat(N1); 4771 } 4772 4773 // fold (srl c1, c2) -> c1 >>u c2 4774 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4775 if (N0C && N1C && !N1C->isOpaque()) 4776 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4777 // fold (srl 0, x) -> 0 4778 if (isNullConstant(N0)) 4779 return N0; 4780 // fold (srl x, c >= size(x)) -> undef 4781 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4782 return DAG.getUNDEF(VT); 4783 // fold (srl x, 0) -> x 4784 if (N1C && N1C->isNullValue()) 4785 return N0; 4786 // if (srl x, c) is known to be zero, return 0 4787 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4788 APInt::getAllOnesValue(OpSizeInBits))) 4789 return DAG.getConstant(0, SDLoc(N), VT); 4790 4791 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4792 if (N1C && N0.getOpcode() == ISD::SRL) { 4793 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4794 uint64_t c1 = N01C->getZExtValue(); 4795 uint64_t c2 = N1C->getZExtValue(); 4796 SDLoc DL(N); 4797 if (c1 + c2 >= OpSizeInBits) 4798 return DAG.getConstant(0, DL, VT); 4799 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4800 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4801 } 4802 } 4803 4804 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4805 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4806 N0.getOperand(0).getOpcode() == ISD::SRL && 4807 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4808 uint64_t c1 = 4809 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4810 uint64_t c2 = N1C->getZExtValue(); 4811 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4812 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4813 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4814 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4815 if (c1 + OpSizeInBits == InnerShiftSize) { 4816 SDLoc DL(N0); 4817 if (c1 + c2 >= InnerShiftSize) 4818 return DAG.getConstant(0, DL, VT); 4819 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4820 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4821 N0.getOperand(0)->getOperand(0), 4822 DAG.getConstant(c1 + c2, DL, 4823 ShiftCountVT))); 4824 } 4825 } 4826 4827 // fold (srl (shl x, c), c) -> (and x, cst2) 4828 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4829 unsigned BitSize = N0.getScalarValueSizeInBits(); 4830 if (BitSize <= 64) { 4831 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4832 SDLoc DL(N); 4833 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4834 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4835 } 4836 } 4837 4838 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4839 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4840 // Shifting in all undef bits? 4841 EVT SmallVT = N0.getOperand(0).getValueType(); 4842 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4843 if (N1C->getZExtValue() >= BitSize) 4844 return DAG.getUNDEF(VT); 4845 4846 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4847 uint64_t ShiftAmt = N1C->getZExtValue(); 4848 SDLoc DL0(N0); 4849 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4850 N0.getOperand(0), 4851 DAG.getConstant(ShiftAmt, DL0, 4852 getShiftAmountTy(SmallVT))); 4853 AddToWorklist(SmallShift.getNode()); 4854 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4855 SDLoc DL(N); 4856 return DAG.getNode(ISD::AND, DL, VT, 4857 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4858 DAG.getConstant(Mask, DL, VT)); 4859 } 4860 } 4861 4862 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4863 // bit, which is unmodified by sra. 4864 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4865 if (N0.getOpcode() == ISD::SRA) 4866 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4867 } 4868 4869 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4870 if (N1C && N0.getOpcode() == ISD::CTLZ && 4871 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4872 APInt KnownZero, KnownOne; 4873 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4874 4875 // If any of the input bits are KnownOne, then the input couldn't be all 4876 // zeros, thus the result of the srl will always be zero. 4877 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4878 4879 // If all of the bits input the to ctlz node are known to be zero, then 4880 // the result of the ctlz is "32" and the result of the shift is one. 4881 APInt UnknownBits = ~KnownZero; 4882 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4883 4884 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4885 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4886 // Okay, we know that only that the single bit specified by UnknownBits 4887 // could be set on input to the CTLZ node. If this bit is set, the SRL 4888 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4889 // to an SRL/XOR pair, which is likely to simplify more. 4890 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4891 SDValue Op = N0.getOperand(0); 4892 4893 if (ShAmt) { 4894 SDLoc DL(N0); 4895 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4896 DAG.getConstant(ShAmt, DL, 4897 getShiftAmountTy(Op.getValueType()))); 4898 AddToWorklist(Op.getNode()); 4899 } 4900 4901 SDLoc DL(N); 4902 return DAG.getNode(ISD::XOR, DL, VT, 4903 Op, DAG.getConstant(1, DL, VT)); 4904 } 4905 } 4906 4907 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4908 if (N1.getOpcode() == ISD::TRUNCATE && 4909 N1.getOperand(0).getOpcode() == ISD::AND) { 4910 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4911 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4912 } 4913 4914 // fold operands of srl based on knowledge that the low bits are not 4915 // demanded. 4916 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4917 return SDValue(N, 0); 4918 4919 if (N1C && !N1C->isOpaque()) 4920 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4921 return NewSRL; 4922 4923 // Attempt to convert a srl of a load into a narrower zero-extending load. 4924 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4925 return NarrowLoad; 4926 4927 // Here is a common situation. We want to optimize: 4928 // 4929 // %a = ... 4930 // %b = and i32 %a, 2 4931 // %c = srl i32 %b, 1 4932 // brcond i32 %c ... 4933 // 4934 // into 4935 // 4936 // %a = ... 4937 // %b = and %a, 2 4938 // %c = setcc eq %b, 0 4939 // brcond %c ... 4940 // 4941 // However when after the source operand of SRL is optimized into AND, the SRL 4942 // itself may not be optimized further. Look for it and add the BRCOND into 4943 // the worklist. 4944 if (N->hasOneUse()) { 4945 SDNode *Use = *N->use_begin(); 4946 if (Use->getOpcode() == ISD::BRCOND) 4947 AddToWorklist(Use); 4948 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4949 // Also look pass the truncate. 4950 Use = *Use->use_begin(); 4951 if (Use->getOpcode() == ISD::BRCOND) 4952 AddToWorklist(Use); 4953 } 4954 } 4955 4956 return SDValue(); 4957 } 4958 4959 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4960 SDValue N0 = N->getOperand(0); 4961 EVT VT = N->getValueType(0); 4962 4963 // fold (bswap c1) -> c2 4964 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4965 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4966 // fold (bswap (bswap x)) -> x 4967 if (N0.getOpcode() == ISD::BSWAP) 4968 return N0->getOperand(0); 4969 return SDValue(); 4970 } 4971 4972 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 4973 SDValue N0 = N->getOperand(0); 4974 4975 // fold (bitreverse (bitreverse x)) -> x 4976 if (N0.getOpcode() == ISD::BITREVERSE) 4977 return N0.getOperand(0); 4978 return SDValue(); 4979 } 4980 4981 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4982 SDValue N0 = N->getOperand(0); 4983 EVT VT = N->getValueType(0); 4984 4985 // fold (ctlz c1) -> c2 4986 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4987 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4988 return SDValue(); 4989 } 4990 4991 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4992 SDValue N0 = N->getOperand(0); 4993 EVT VT = N->getValueType(0); 4994 4995 // fold (ctlz_zero_undef c1) -> c2 4996 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4997 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4998 return SDValue(); 4999 } 5000 5001 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5002 SDValue N0 = N->getOperand(0); 5003 EVT VT = N->getValueType(0); 5004 5005 // fold (cttz c1) -> c2 5006 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5007 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5008 return SDValue(); 5009 } 5010 5011 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5012 SDValue N0 = N->getOperand(0); 5013 EVT VT = N->getValueType(0); 5014 5015 // fold (cttz_zero_undef c1) -> c2 5016 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5017 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5018 return SDValue(); 5019 } 5020 5021 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5022 SDValue N0 = N->getOperand(0); 5023 EVT VT = N->getValueType(0); 5024 5025 // fold (ctpop c1) -> c2 5026 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5027 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5028 return SDValue(); 5029 } 5030 5031 5032 /// \brief Generate Min/Max node 5033 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5034 SDValue RHS, SDValue True, SDValue False, 5035 ISD::CondCode CC, const TargetLowering &TLI, 5036 SelectionDAG &DAG) { 5037 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5038 return SDValue(); 5039 5040 switch (CC) { 5041 case ISD::SETOLT: 5042 case ISD::SETOLE: 5043 case ISD::SETLT: 5044 case ISD::SETLE: 5045 case ISD::SETULT: 5046 case ISD::SETULE: { 5047 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5048 if (TLI.isOperationLegal(Opcode, VT)) 5049 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5050 return SDValue(); 5051 } 5052 case ISD::SETOGT: 5053 case ISD::SETOGE: 5054 case ISD::SETGT: 5055 case ISD::SETGE: 5056 case ISD::SETUGT: 5057 case ISD::SETUGE: { 5058 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5059 if (TLI.isOperationLegal(Opcode, VT)) 5060 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5061 return SDValue(); 5062 } 5063 default: 5064 return SDValue(); 5065 } 5066 } 5067 5068 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5069 SDValue N0 = N->getOperand(0); 5070 SDValue N1 = N->getOperand(1); 5071 SDValue N2 = N->getOperand(2); 5072 EVT VT = N->getValueType(0); 5073 EVT VT0 = N0.getValueType(); 5074 5075 // fold (select C, X, X) -> X 5076 if (N1 == N2) 5077 return N1; 5078 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5079 // fold (select true, X, Y) -> X 5080 // fold (select false, X, Y) -> Y 5081 return !N0C->isNullValue() ? N1 : N2; 5082 } 5083 // fold (select C, 1, X) -> (or C, X) 5084 if (VT == MVT::i1 && isOneConstant(N1)) 5085 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5086 // fold (select C, 0, 1) -> (xor C, 1) 5087 // We can't do this reliably if integer based booleans have different contents 5088 // to floating point based booleans. This is because we can't tell whether we 5089 // have an integer-based boolean or a floating-point-based boolean unless we 5090 // can find the SETCC that produced it and inspect its operands. This is 5091 // fairly easy if C is the SETCC node, but it can potentially be 5092 // undiscoverable (or not reasonably discoverable). For example, it could be 5093 // in another basic block or it could require searching a complicated 5094 // expression. 5095 if (VT.isInteger() && 5096 (VT0 == MVT::i1 || (VT0.isInteger() && 5097 TLI.getBooleanContents(false, false) == 5098 TLI.getBooleanContents(false, true) && 5099 TLI.getBooleanContents(false, false) == 5100 TargetLowering::ZeroOrOneBooleanContent)) && 5101 isNullConstant(N1) && isOneConstant(N2)) { 5102 SDValue XORNode; 5103 if (VT == VT0) { 5104 SDLoc DL(N); 5105 return DAG.getNode(ISD::XOR, DL, VT0, 5106 N0, DAG.getConstant(1, DL, VT0)); 5107 } 5108 SDLoc DL0(N0); 5109 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5110 N0, DAG.getConstant(1, DL0, VT0)); 5111 AddToWorklist(XORNode.getNode()); 5112 if (VT.bitsGT(VT0)) 5113 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5114 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5115 } 5116 // fold (select C, 0, X) -> (and (not C), X) 5117 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5118 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5119 AddToWorklist(NOTNode.getNode()); 5120 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5121 } 5122 // fold (select C, X, 1) -> (or (not C), X) 5123 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5124 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5125 AddToWorklist(NOTNode.getNode()); 5126 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5127 } 5128 // fold (select C, X, 0) -> (and C, X) 5129 if (VT == MVT::i1 && isNullConstant(N2)) 5130 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5131 // fold (select X, X, Y) -> (or X, Y) 5132 // fold (select X, 1, Y) -> (or X, Y) 5133 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5134 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5135 // fold (select X, Y, X) -> (and X, Y) 5136 // fold (select X, Y, 0) -> (and X, Y) 5137 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5138 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5139 5140 // If we can fold this based on the true/false value, do so. 5141 if (SimplifySelectOps(N, N1, N2)) 5142 return SDValue(N, 0); // Don't revisit N. 5143 5144 if (VT0 == MVT::i1) { 5145 // The code in this block deals with the following 2 equivalences: 5146 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5147 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5148 // The target can specify its prefered form with the 5149 // shouldNormalizeToSelectSequence() callback. However we always transform 5150 // to the right anyway if we find the inner select exists in the DAG anyway 5151 // and we always transform to the left side if we know that we can further 5152 // optimize the combination of the conditions. 5153 bool normalizeToSequence 5154 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5155 // select (and Cond0, Cond1), X, Y 5156 // -> select Cond0, (select Cond1, X, Y), Y 5157 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5158 SDValue Cond0 = N0->getOperand(0); 5159 SDValue Cond1 = N0->getOperand(1); 5160 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5161 N1.getValueType(), Cond1, N1, N2); 5162 if (normalizeToSequence || !InnerSelect.use_empty()) 5163 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5164 InnerSelect, N2); 5165 } 5166 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5167 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5168 SDValue Cond0 = N0->getOperand(0); 5169 SDValue Cond1 = N0->getOperand(1); 5170 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5171 N1.getValueType(), Cond1, N1, N2); 5172 if (normalizeToSequence || !InnerSelect.use_empty()) 5173 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5174 InnerSelect); 5175 } 5176 5177 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5178 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5179 SDValue N1_0 = N1->getOperand(0); 5180 SDValue N1_1 = N1->getOperand(1); 5181 SDValue N1_2 = N1->getOperand(2); 5182 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5183 // Create the actual and node if we can generate good code for it. 5184 if (!normalizeToSequence) { 5185 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5186 N0, N1_0); 5187 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5188 N1_1, N2); 5189 } 5190 // Otherwise see if we can optimize the "and" to a better pattern. 5191 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5192 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5193 N1_1, N2); 5194 } 5195 } 5196 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5197 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5198 SDValue N2_0 = N2->getOperand(0); 5199 SDValue N2_1 = N2->getOperand(1); 5200 SDValue N2_2 = N2->getOperand(2); 5201 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5202 // Create the actual or node if we can generate good code for it. 5203 if (!normalizeToSequence) { 5204 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5205 N0, N2_0); 5206 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5207 N1, N2_2); 5208 } 5209 // Otherwise see if we can optimize to a better pattern. 5210 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5211 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5212 N1, N2_2); 5213 } 5214 } 5215 } 5216 5217 // fold selects based on a setcc into other things, such as min/max/abs 5218 if (N0.getOpcode() == ISD::SETCC) { 5219 // select x, y (fcmp lt x, y) -> fminnum x, y 5220 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5221 // 5222 // This is OK if we don't care about what happens if either operand is a 5223 // NaN. 5224 // 5225 5226 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5227 // no signed zeros as well as no nans. 5228 const TargetOptions &Options = DAG.getTarget().Options; 5229 if (Options.UnsafeFPMath && 5230 VT.isFloatingPoint() && N0.hasOneUse() && 5231 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5232 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5233 5234 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5235 N0.getOperand(1), N1, N2, CC, 5236 TLI, DAG)) 5237 return FMinMax; 5238 } 5239 5240 if ((!LegalOperations && 5241 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5242 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5243 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5244 N0.getOperand(0), N0.getOperand(1), 5245 N1, N2, N0.getOperand(2)); 5246 return SimplifySelect(SDLoc(N), N0, N1, N2); 5247 } 5248 5249 return SDValue(); 5250 } 5251 5252 static 5253 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5254 SDLoc DL(N); 5255 EVT LoVT, HiVT; 5256 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5257 5258 // Split the inputs. 5259 SDValue Lo, Hi, LL, LH, RL, RH; 5260 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5261 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5262 5263 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5264 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5265 5266 return std::make_pair(Lo, Hi); 5267 } 5268 5269 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5270 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5271 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5272 SDLoc dl(N); 5273 SDValue Cond = N->getOperand(0); 5274 SDValue LHS = N->getOperand(1); 5275 SDValue RHS = N->getOperand(2); 5276 EVT VT = N->getValueType(0); 5277 int NumElems = VT.getVectorNumElements(); 5278 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5279 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5280 Cond.getOpcode() == ISD::BUILD_VECTOR); 5281 5282 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5283 // binary ones here. 5284 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5285 return SDValue(); 5286 5287 // We're sure we have an even number of elements due to the 5288 // concat_vectors we have as arguments to vselect. 5289 // Skip BV elements until we find one that's not an UNDEF 5290 // After we find an UNDEF element, keep looping until we get to half the 5291 // length of the BV and see if all the non-undef nodes are the same. 5292 ConstantSDNode *BottomHalf = nullptr; 5293 for (int i = 0; i < NumElems / 2; ++i) { 5294 if (Cond->getOperand(i)->isUndef()) 5295 continue; 5296 5297 if (BottomHalf == nullptr) 5298 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5299 else if (Cond->getOperand(i).getNode() != BottomHalf) 5300 return SDValue(); 5301 } 5302 5303 // Do the same for the second half of the BuildVector 5304 ConstantSDNode *TopHalf = nullptr; 5305 for (int i = NumElems / 2; i < NumElems; ++i) { 5306 if (Cond->getOperand(i)->isUndef()) 5307 continue; 5308 5309 if (TopHalf == nullptr) 5310 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5311 else if (Cond->getOperand(i).getNode() != TopHalf) 5312 return SDValue(); 5313 } 5314 5315 assert(TopHalf && BottomHalf && 5316 "One half of the selector was all UNDEFs and the other was all the " 5317 "same value. This should have been addressed before this function."); 5318 return DAG.getNode( 5319 ISD::CONCAT_VECTORS, dl, VT, 5320 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5321 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5322 } 5323 5324 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5325 5326 if (Level >= AfterLegalizeTypes) 5327 return SDValue(); 5328 5329 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5330 SDValue Mask = MSC->getMask(); 5331 SDValue Data = MSC->getValue(); 5332 SDLoc DL(N); 5333 5334 // If the MSCATTER data type requires splitting and the mask is provided by a 5335 // SETCC, then split both nodes and its operands before legalization. This 5336 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5337 // and enables future optimizations (e.g. min/max pattern matching on X86). 5338 if (Mask.getOpcode() != ISD::SETCC) 5339 return SDValue(); 5340 5341 // Check if any splitting is required. 5342 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5343 TargetLowering::TypeSplitVector) 5344 return SDValue(); 5345 SDValue MaskLo, MaskHi, Lo, Hi; 5346 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5347 5348 EVT LoVT, HiVT; 5349 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5350 5351 SDValue Chain = MSC->getChain(); 5352 5353 EVT MemoryVT = MSC->getMemoryVT(); 5354 unsigned Alignment = MSC->getOriginalAlignment(); 5355 5356 EVT LoMemVT, HiMemVT; 5357 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5358 5359 SDValue DataLo, DataHi; 5360 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5361 5362 SDValue BasePtr = MSC->getBasePtr(); 5363 SDValue IndexLo, IndexHi; 5364 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5365 5366 MachineMemOperand *MMO = DAG.getMachineFunction(). 5367 getMachineMemOperand(MSC->getPointerInfo(), 5368 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5369 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5370 5371 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5372 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5373 DL, OpsLo, MMO); 5374 5375 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5376 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5377 DL, OpsHi, MMO); 5378 5379 AddToWorklist(Lo.getNode()); 5380 AddToWorklist(Hi.getNode()); 5381 5382 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5383 } 5384 5385 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5386 5387 if (Level >= AfterLegalizeTypes) 5388 return SDValue(); 5389 5390 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5391 SDValue Mask = MST->getMask(); 5392 SDValue Data = MST->getValue(); 5393 SDLoc DL(N); 5394 5395 // If the MSTORE data type requires splitting and the mask is provided by a 5396 // SETCC, then split both nodes and its operands before legalization. This 5397 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5398 // and enables future optimizations (e.g. min/max pattern matching on X86). 5399 if (Mask.getOpcode() == ISD::SETCC) { 5400 5401 // Check if any splitting is required. 5402 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5403 TargetLowering::TypeSplitVector) 5404 return SDValue(); 5405 5406 SDValue MaskLo, MaskHi, Lo, Hi; 5407 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5408 5409 EVT LoVT, HiVT; 5410 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5411 5412 SDValue Chain = MST->getChain(); 5413 SDValue Ptr = MST->getBasePtr(); 5414 5415 EVT MemoryVT = MST->getMemoryVT(); 5416 unsigned Alignment = MST->getOriginalAlignment(); 5417 5418 // if Alignment is equal to the vector size, 5419 // take the half of it for the second part 5420 unsigned SecondHalfAlignment = 5421 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5422 Alignment/2 : Alignment; 5423 5424 EVT LoMemVT, HiMemVT; 5425 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5426 5427 SDValue DataLo, DataHi; 5428 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5429 5430 MachineMemOperand *MMO = DAG.getMachineFunction(). 5431 getMachineMemOperand(MST->getPointerInfo(), 5432 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5433 Alignment, MST->getAAInfo(), MST->getRanges()); 5434 5435 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5436 MST->isTruncatingStore()); 5437 5438 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5439 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5440 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5441 5442 MMO = DAG.getMachineFunction(). 5443 getMachineMemOperand(MST->getPointerInfo(), 5444 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5445 SecondHalfAlignment, MST->getAAInfo(), 5446 MST->getRanges()); 5447 5448 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5449 MST->isTruncatingStore()); 5450 5451 AddToWorklist(Lo.getNode()); 5452 AddToWorklist(Hi.getNode()); 5453 5454 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5455 } 5456 return SDValue(); 5457 } 5458 5459 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5460 5461 if (Level >= AfterLegalizeTypes) 5462 return SDValue(); 5463 5464 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5465 SDValue Mask = MGT->getMask(); 5466 SDLoc DL(N); 5467 5468 // If the MGATHER result requires splitting and the mask is provided by a 5469 // SETCC, then split both nodes and its operands before legalization. This 5470 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5471 // and enables future optimizations (e.g. min/max pattern matching on X86). 5472 5473 if (Mask.getOpcode() != ISD::SETCC) 5474 return SDValue(); 5475 5476 EVT VT = N->getValueType(0); 5477 5478 // Check if any splitting is required. 5479 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5480 TargetLowering::TypeSplitVector) 5481 return SDValue(); 5482 5483 SDValue MaskLo, MaskHi, Lo, Hi; 5484 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5485 5486 SDValue Src0 = MGT->getValue(); 5487 SDValue Src0Lo, Src0Hi; 5488 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5489 5490 EVT LoVT, HiVT; 5491 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5492 5493 SDValue Chain = MGT->getChain(); 5494 EVT MemoryVT = MGT->getMemoryVT(); 5495 unsigned Alignment = MGT->getOriginalAlignment(); 5496 5497 EVT LoMemVT, HiMemVT; 5498 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5499 5500 SDValue BasePtr = MGT->getBasePtr(); 5501 SDValue Index = MGT->getIndex(); 5502 SDValue IndexLo, IndexHi; 5503 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5504 5505 MachineMemOperand *MMO = DAG.getMachineFunction(). 5506 getMachineMemOperand(MGT->getPointerInfo(), 5507 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5508 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5509 5510 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5511 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5512 MMO); 5513 5514 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5515 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5516 MMO); 5517 5518 AddToWorklist(Lo.getNode()); 5519 AddToWorklist(Hi.getNode()); 5520 5521 // Build a factor node to remember that this load is independent of the 5522 // other one. 5523 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5524 Hi.getValue(1)); 5525 5526 // Legalized the chain result - switch anything that used the old chain to 5527 // use the new one. 5528 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5529 5530 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5531 5532 SDValue RetOps[] = { GatherRes, Chain }; 5533 return DAG.getMergeValues(RetOps, DL); 5534 } 5535 5536 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5537 5538 if (Level >= AfterLegalizeTypes) 5539 return SDValue(); 5540 5541 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5542 SDValue Mask = MLD->getMask(); 5543 SDLoc DL(N); 5544 5545 // If the MLOAD result requires splitting and the mask is provided by a 5546 // SETCC, then split both nodes and its operands before legalization. This 5547 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5548 // and enables future optimizations (e.g. min/max pattern matching on X86). 5549 5550 if (Mask.getOpcode() == ISD::SETCC) { 5551 EVT VT = N->getValueType(0); 5552 5553 // Check if any splitting is required. 5554 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5555 TargetLowering::TypeSplitVector) 5556 return SDValue(); 5557 5558 SDValue MaskLo, MaskHi, Lo, Hi; 5559 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5560 5561 SDValue Src0 = MLD->getSrc0(); 5562 SDValue Src0Lo, Src0Hi; 5563 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5564 5565 EVT LoVT, HiVT; 5566 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5567 5568 SDValue Chain = MLD->getChain(); 5569 SDValue Ptr = MLD->getBasePtr(); 5570 EVT MemoryVT = MLD->getMemoryVT(); 5571 unsigned Alignment = MLD->getOriginalAlignment(); 5572 5573 // if Alignment is equal to the vector size, 5574 // take the half of it for the second part 5575 unsigned SecondHalfAlignment = 5576 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5577 Alignment/2 : Alignment; 5578 5579 EVT LoMemVT, HiMemVT; 5580 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5581 5582 MachineMemOperand *MMO = DAG.getMachineFunction(). 5583 getMachineMemOperand(MLD->getPointerInfo(), 5584 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5585 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5586 5587 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5588 ISD::NON_EXTLOAD); 5589 5590 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5591 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5592 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5593 5594 MMO = DAG.getMachineFunction(). 5595 getMachineMemOperand(MLD->getPointerInfo(), 5596 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5597 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5598 5599 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5600 ISD::NON_EXTLOAD); 5601 5602 AddToWorklist(Lo.getNode()); 5603 AddToWorklist(Hi.getNode()); 5604 5605 // Build a factor node to remember that this load is independent of the 5606 // other one. 5607 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5608 Hi.getValue(1)); 5609 5610 // Legalized the chain result - switch anything that used the old chain to 5611 // use the new one. 5612 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5613 5614 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5615 5616 SDValue RetOps[] = { LoadRes, Chain }; 5617 return DAG.getMergeValues(RetOps, DL); 5618 } 5619 return SDValue(); 5620 } 5621 5622 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5623 SDValue N0 = N->getOperand(0); 5624 SDValue N1 = N->getOperand(1); 5625 SDValue N2 = N->getOperand(2); 5626 SDLoc DL(N); 5627 5628 // Canonicalize integer abs. 5629 // vselect (setg[te] X, 0), X, -X -> 5630 // vselect (setgt X, -1), X, -X -> 5631 // vselect (setl[te] X, 0), -X, X -> 5632 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5633 if (N0.getOpcode() == ISD::SETCC) { 5634 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5635 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5636 bool isAbs = false; 5637 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5638 5639 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5640 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5641 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5642 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5643 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5644 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5645 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5646 5647 if (isAbs) { 5648 EVT VT = LHS.getValueType(); 5649 SDValue Shift = DAG.getNode( 5650 ISD::SRA, DL, VT, LHS, 5651 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5652 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5653 AddToWorklist(Shift.getNode()); 5654 AddToWorklist(Add.getNode()); 5655 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5656 } 5657 } 5658 5659 if (SimplifySelectOps(N, N1, N2)) 5660 return SDValue(N, 0); // Don't revisit N. 5661 5662 // If the VSELECT result requires splitting and the mask is provided by a 5663 // SETCC, then split both nodes and its operands before legalization. This 5664 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5665 // and enables future optimizations (e.g. min/max pattern matching on X86). 5666 if (N0.getOpcode() == ISD::SETCC) { 5667 EVT VT = N->getValueType(0); 5668 5669 // Check if any splitting is required. 5670 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5671 TargetLowering::TypeSplitVector) 5672 return SDValue(); 5673 5674 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5675 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5676 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5677 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5678 5679 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5680 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5681 5682 // Add the new VSELECT nodes to the work list in case they need to be split 5683 // again. 5684 AddToWorklist(Lo.getNode()); 5685 AddToWorklist(Hi.getNode()); 5686 5687 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5688 } 5689 5690 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5691 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5692 return N1; 5693 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5694 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5695 return N2; 5696 5697 // The ConvertSelectToConcatVector function is assuming both the above 5698 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5699 // and addressed. 5700 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5701 N2.getOpcode() == ISD::CONCAT_VECTORS && 5702 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5703 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5704 return CV; 5705 } 5706 5707 return SDValue(); 5708 } 5709 5710 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5711 SDValue N0 = N->getOperand(0); 5712 SDValue N1 = N->getOperand(1); 5713 SDValue N2 = N->getOperand(2); 5714 SDValue N3 = N->getOperand(3); 5715 SDValue N4 = N->getOperand(4); 5716 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5717 5718 // fold select_cc lhs, rhs, x, x, cc -> x 5719 if (N2 == N3) 5720 return N2; 5721 5722 // Determine if the condition we're dealing with is constant 5723 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5724 CC, SDLoc(N), false)) { 5725 AddToWorklist(SCC.getNode()); 5726 5727 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5728 if (!SCCC->isNullValue()) 5729 return N2; // cond always true -> true val 5730 else 5731 return N3; // cond always false -> false val 5732 } else if (SCC->isUndef()) { 5733 // When the condition is UNDEF, just return the first operand. This is 5734 // coherent the DAG creation, no setcc node is created in this case 5735 return N2; 5736 } else if (SCC.getOpcode() == ISD::SETCC) { 5737 // Fold to a simpler select_cc 5738 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5739 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5740 SCC.getOperand(2)); 5741 } 5742 } 5743 5744 // If we can fold this based on the true/false value, do so. 5745 if (SimplifySelectOps(N, N2, N3)) 5746 return SDValue(N, 0); // Don't revisit N. 5747 5748 // fold select_cc into other things, such as min/max/abs 5749 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5750 } 5751 5752 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5753 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5754 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5755 SDLoc(N)); 5756 } 5757 5758 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5759 SDValue LHS = N->getOperand(0); 5760 SDValue RHS = N->getOperand(1); 5761 SDValue Carry = N->getOperand(2); 5762 SDValue Cond = N->getOperand(3); 5763 5764 // If Carry is false, fold to a regular SETCC. 5765 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5766 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5767 5768 return SDValue(); 5769 } 5770 5771 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5772 /// a build_vector of constants. 5773 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5774 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5775 /// Vector extends are not folded if operations are legal; this is to 5776 /// avoid introducing illegal build_vector dag nodes. 5777 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5778 SelectionDAG &DAG, bool LegalTypes, 5779 bool LegalOperations) { 5780 unsigned Opcode = N->getOpcode(); 5781 SDValue N0 = N->getOperand(0); 5782 EVT VT = N->getValueType(0); 5783 5784 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5785 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5786 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5787 && "Expected EXTEND dag node in input!"); 5788 5789 // fold (sext c1) -> c1 5790 // fold (zext c1) -> c1 5791 // fold (aext c1) -> c1 5792 if (isa<ConstantSDNode>(N0)) 5793 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5794 5795 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5796 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5797 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5798 EVT SVT = VT.getScalarType(); 5799 if (!(VT.isVector() && 5800 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5801 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5802 return nullptr; 5803 5804 // We can fold this node into a build_vector. 5805 unsigned VTBits = SVT.getSizeInBits(); 5806 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5807 SmallVector<SDValue, 8> Elts; 5808 unsigned NumElts = VT.getVectorNumElements(); 5809 SDLoc DL(N); 5810 5811 for (unsigned i=0; i != NumElts; ++i) { 5812 SDValue Op = N0->getOperand(i); 5813 if (Op->isUndef()) { 5814 Elts.push_back(DAG.getUNDEF(SVT)); 5815 continue; 5816 } 5817 5818 SDLoc DL(Op); 5819 // Get the constant value and if needed trunc it to the size of the type. 5820 // Nodes like build_vector might have constants wider than the scalar type. 5821 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5822 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5823 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5824 else 5825 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5826 } 5827 5828 return DAG.getBuildVector(VT, DL, Elts).getNode(); 5829 } 5830 5831 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5832 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5833 // transformation. Returns true if extension are possible and the above 5834 // mentioned transformation is profitable. 5835 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5836 unsigned ExtOpc, 5837 SmallVectorImpl<SDNode *> &ExtendNodes, 5838 const TargetLowering &TLI) { 5839 bool HasCopyToRegUses = false; 5840 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5841 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5842 UE = N0.getNode()->use_end(); 5843 UI != UE; ++UI) { 5844 SDNode *User = *UI; 5845 if (User == N) 5846 continue; 5847 if (UI.getUse().getResNo() != N0.getResNo()) 5848 continue; 5849 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5850 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5851 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5852 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5853 // Sign bits will be lost after a zext. 5854 return false; 5855 bool Add = false; 5856 for (unsigned i = 0; i != 2; ++i) { 5857 SDValue UseOp = User->getOperand(i); 5858 if (UseOp == N0) 5859 continue; 5860 if (!isa<ConstantSDNode>(UseOp)) 5861 return false; 5862 Add = true; 5863 } 5864 if (Add) 5865 ExtendNodes.push_back(User); 5866 continue; 5867 } 5868 // If truncates aren't free and there are users we can't 5869 // extend, it isn't worthwhile. 5870 if (!isTruncFree) 5871 return false; 5872 // Remember if this value is live-out. 5873 if (User->getOpcode() == ISD::CopyToReg) 5874 HasCopyToRegUses = true; 5875 } 5876 5877 if (HasCopyToRegUses) { 5878 bool BothLiveOut = false; 5879 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5880 UI != UE; ++UI) { 5881 SDUse &Use = UI.getUse(); 5882 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5883 BothLiveOut = true; 5884 break; 5885 } 5886 } 5887 if (BothLiveOut) 5888 // Both unextended and extended values are live out. There had better be 5889 // a good reason for the transformation. 5890 return ExtendNodes.size(); 5891 } 5892 return true; 5893 } 5894 5895 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5896 SDValue Trunc, SDValue ExtLoad, 5897 const SDLoc &DL, ISD::NodeType ExtType) { 5898 // Extend SetCC uses if necessary. 5899 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5900 SDNode *SetCC = SetCCs[i]; 5901 SmallVector<SDValue, 4> Ops; 5902 5903 for (unsigned j = 0; j != 2; ++j) { 5904 SDValue SOp = SetCC->getOperand(j); 5905 if (SOp == Trunc) 5906 Ops.push_back(ExtLoad); 5907 else 5908 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5909 } 5910 5911 Ops.push_back(SetCC->getOperand(2)); 5912 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5913 } 5914 } 5915 5916 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5917 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5918 SDValue N0 = N->getOperand(0); 5919 EVT DstVT = N->getValueType(0); 5920 EVT SrcVT = N0.getValueType(); 5921 5922 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5923 N->getOpcode() == ISD::ZERO_EXTEND) && 5924 "Unexpected node type (not an extend)!"); 5925 5926 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5927 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5928 // (v8i32 (sext (v8i16 (load x)))) 5929 // into: 5930 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5931 // (v4i32 (sextload (x + 16))))) 5932 // Where uses of the original load, i.e.: 5933 // (v8i16 (load x)) 5934 // are replaced with: 5935 // (v8i16 (truncate 5936 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5937 // (v4i32 (sextload (x + 16))))))) 5938 // 5939 // This combine is only applicable to illegal, but splittable, vectors. 5940 // All legal types, and illegal non-vector types, are handled elsewhere. 5941 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5942 // 5943 if (N0->getOpcode() != ISD::LOAD) 5944 return SDValue(); 5945 5946 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5947 5948 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5949 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5950 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5951 return SDValue(); 5952 5953 SmallVector<SDNode *, 4> SetCCs; 5954 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5955 return SDValue(); 5956 5957 ISD::LoadExtType ExtType = 5958 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5959 5960 // Try to split the vector types to get down to legal types. 5961 EVT SplitSrcVT = SrcVT; 5962 EVT SplitDstVT = DstVT; 5963 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5964 SplitSrcVT.getVectorNumElements() > 1) { 5965 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5966 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5967 } 5968 5969 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5970 return SDValue(); 5971 5972 SDLoc DL(N); 5973 const unsigned NumSplits = 5974 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5975 const unsigned Stride = SplitSrcVT.getStoreSize(); 5976 SmallVector<SDValue, 4> Loads; 5977 SmallVector<SDValue, 4> Chains; 5978 5979 SDValue BasePtr = LN0->getBasePtr(); 5980 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5981 const unsigned Offset = Idx * Stride; 5982 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5983 5984 SDValue SplitLoad = DAG.getExtLoad( 5985 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5986 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 5987 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 5988 5989 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5990 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5991 5992 Loads.push_back(SplitLoad.getValue(0)); 5993 Chains.push_back(SplitLoad.getValue(1)); 5994 } 5995 5996 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5997 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5998 5999 CombineTo(N, NewValue); 6000 6001 // Replace uses of the original load (before extension) 6002 // with a truncate of the concatenated sextloaded vectors. 6003 SDValue Trunc = 6004 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6005 CombineTo(N0.getNode(), Trunc, NewChain); 6006 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6007 (ISD::NodeType)N->getOpcode()); 6008 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6009 } 6010 6011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6012 SDValue N0 = N->getOperand(0); 6013 EVT VT = N->getValueType(0); 6014 6015 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6016 LegalOperations)) 6017 return SDValue(Res, 0); 6018 6019 // fold (sext (sext x)) -> (sext x) 6020 // fold (sext (aext x)) -> (sext x) 6021 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 6023 N0.getOperand(0)); 6024 6025 if (N0.getOpcode() == ISD::TRUNCATE) { 6026 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6027 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6028 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6029 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6030 if (NarrowLoad.getNode() != N0.getNode()) { 6031 CombineTo(N0.getNode(), NarrowLoad); 6032 // CombineTo deleted the truncate, if needed, but not what's under it. 6033 AddToWorklist(oye); 6034 } 6035 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6036 } 6037 6038 // See if the value being truncated is already sign extended. If so, just 6039 // eliminate the trunc/sext pair. 6040 SDValue Op = N0.getOperand(0); 6041 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 6042 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 6043 unsigned DestBits = VT.getScalarType().getSizeInBits(); 6044 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6045 6046 if (OpBits == DestBits) { 6047 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6048 // bits, it is already ready. 6049 if (NumSignBits > DestBits-MidBits) 6050 return Op; 6051 } else if (OpBits < DestBits) { 6052 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6053 // bits, just sext from i32. 6054 if (NumSignBits > OpBits-MidBits) 6055 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6056 } else { 6057 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6058 // bits, just truncate to i32. 6059 if (NumSignBits > OpBits-MidBits) 6060 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6061 } 6062 6063 // fold (sext (truncate x)) -> (sextinreg x). 6064 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6065 N0.getValueType())) { 6066 if (OpBits < DestBits) 6067 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6068 else if (OpBits > DestBits) 6069 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6070 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6071 DAG.getValueType(N0.getValueType())); 6072 } 6073 } 6074 6075 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6076 // Only generate vector extloads when 1) they're legal, and 2) they are 6077 // deemed desirable by the target. 6078 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6079 ((!LegalOperations && !VT.isVector() && 6080 !cast<LoadSDNode>(N0)->isVolatile()) || 6081 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6082 bool DoXform = true; 6083 SmallVector<SDNode*, 4> SetCCs; 6084 if (!N0.hasOneUse()) 6085 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6086 if (VT.isVector()) 6087 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6088 if (DoXform) { 6089 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6090 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6091 LN0->getChain(), 6092 LN0->getBasePtr(), N0.getValueType(), 6093 LN0->getMemOperand()); 6094 CombineTo(N, ExtLoad); 6095 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6096 N0.getValueType(), ExtLoad); 6097 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6098 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6099 ISD::SIGN_EXTEND); 6100 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6101 } 6102 } 6103 6104 // fold (sext (load x)) to multiple smaller sextloads. 6105 // Only on illegal but splittable vectors. 6106 if (SDValue ExtLoad = CombineExtLoad(N)) 6107 return ExtLoad; 6108 6109 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6110 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6111 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6112 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6113 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6114 EVT MemVT = LN0->getMemoryVT(); 6115 if ((!LegalOperations && !LN0->isVolatile()) || 6116 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6117 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6118 LN0->getChain(), 6119 LN0->getBasePtr(), MemVT, 6120 LN0->getMemOperand()); 6121 CombineTo(N, ExtLoad); 6122 CombineTo(N0.getNode(), 6123 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6124 N0.getValueType(), ExtLoad), 6125 ExtLoad.getValue(1)); 6126 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6127 } 6128 } 6129 6130 // fold (sext (and/or/xor (load x), cst)) -> 6131 // (and/or/xor (sextload x), (sext cst)) 6132 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6133 N0.getOpcode() == ISD::XOR) && 6134 isa<LoadSDNode>(N0.getOperand(0)) && 6135 N0.getOperand(1).getOpcode() == ISD::Constant && 6136 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6137 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6138 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6139 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6140 bool DoXform = true; 6141 SmallVector<SDNode*, 4> SetCCs; 6142 if (!N0.hasOneUse()) 6143 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6144 SetCCs, TLI); 6145 if (DoXform) { 6146 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6147 LN0->getChain(), LN0->getBasePtr(), 6148 LN0->getMemoryVT(), 6149 LN0->getMemOperand()); 6150 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6151 Mask = Mask.sext(VT.getSizeInBits()); 6152 SDLoc DL(N); 6153 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6154 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6155 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6156 SDLoc(N0.getOperand(0)), 6157 N0.getOperand(0).getValueType(), ExtLoad); 6158 CombineTo(N, And); 6159 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6160 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6161 ISD::SIGN_EXTEND); 6162 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6163 } 6164 } 6165 } 6166 6167 if (N0.getOpcode() == ISD::SETCC) { 6168 EVT N0VT = N0.getOperand(0).getValueType(); 6169 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6170 // Only do this before legalize for now. 6171 if (VT.isVector() && !LegalOperations && 6172 TLI.getBooleanContents(N0VT) == 6173 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6174 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6175 // of the same size as the compared operands. Only optimize sext(setcc()) 6176 // if this is the case. 6177 EVT SVT = getSetCCResultType(N0VT); 6178 6179 // We know that the # elements of the results is the same as the 6180 // # elements of the compare (and the # elements of the compare result 6181 // for that matter). Check to see that they are the same size. If so, 6182 // we know that the element size of the sext'd result matches the 6183 // element size of the compare operands. 6184 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6185 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6186 N0.getOperand(1), 6187 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6188 6189 // If the desired elements are smaller or larger than the source 6190 // elements we can use a matching integer vector type and then 6191 // truncate/sign extend 6192 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6193 if (SVT == MatchingVectorType) { 6194 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6195 N0.getOperand(0), N0.getOperand(1), 6196 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6197 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6198 } 6199 } 6200 6201 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6202 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6203 SDLoc DL(N); 6204 SDValue NegOne = 6205 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6206 if (SDValue SCC = SimplifySelectCC( 6207 DL, N0.getOperand(0), N0.getOperand(1), NegOne, 6208 DAG.getConstant(0, DL, VT), 6209 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6210 return SCC; 6211 6212 if (!VT.isVector()) { 6213 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6214 if (!LegalOperations || 6215 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6216 SDLoc DL(N); 6217 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6218 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6219 N0.getOperand(0), N0.getOperand(1), CC); 6220 return DAG.getSelect(DL, VT, SetCC, 6221 NegOne, DAG.getConstant(0, DL, VT)); 6222 } 6223 } 6224 } 6225 6226 // fold (sext x) -> (zext x) if the sign bit is known zero. 6227 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6228 DAG.SignBitIsZero(N0)) 6229 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6230 6231 return SDValue(); 6232 } 6233 6234 // isTruncateOf - If N is a truncate of some other value, return true, record 6235 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6236 // This function computes KnownZero to avoid a duplicated call to 6237 // computeKnownBits in the caller. 6238 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6239 APInt &KnownZero) { 6240 APInt KnownOne; 6241 if (N->getOpcode() == ISD::TRUNCATE) { 6242 Op = N->getOperand(0); 6243 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6244 return true; 6245 } 6246 6247 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6248 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6249 return false; 6250 6251 SDValue Op0 = N->getOperand(0); 6252 SDValue Op1 = N->getOperand(1); 6253 assert(Op0.getValueType() == Op1.getValueType()); 6254 6255 if (isNullConstant(Op0)) 6256 Op = Op1; 6257 else if (isNullConstant(Op1)) 6258 Op = Op0; 6259 else 6260 return false; 6261 6262 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6263 6264 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6265 return false; 6266 6267 return true; 6268 } 6269 6270 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6271 SDValue N0 = N->getOperand(0); 6272 EVT VT = N->getValueType(0); 6273 6274 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6275 LegalOperations)) 6276 return SDValue(Res, 0); 6277 6278 // fold (zext (zext x)) -> (zext x) 6279 // fold (zext (aext x)) -> (zext x) 6280 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6281 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6282 N0.getOperand(0)); 6283 6284 // fold (zext (truncate x)) -> (zext x) or 6285 // (zext (truncate x)) -> (truncate x) 6286 // This is valid when the truncated bits of x are already zero. 6287 // FIXME: We should extend this to work for vectors too. 6288 SDValue Op; 6289 APInt KnownZero; 6290 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6291 APInt TruncatedBits = 6292 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6293 APInt(Op.getValueSizeInBits(), 0) : 6294 APInt::getBitsSet(Op.getValueSizeInBits(), 6295 N0.getValueSizeInBits(), 6296 std::min(Op.getValueSizeInBits(), 6297 VT.getSizeInBits())); 6298 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6299 if (VT.bitsGT(Op.getValueType())) 6300 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6301 if (VT.bitsLT(Op.getValueType())) 6302 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6303 6304 return Op; 6305 } 6306 } 6307 6308 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6309 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6310 if (N0.getOpcode() == ISD::TRUNCATE) { 6311 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6312 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6313 if (NarrowLoad.getNode() != N0.getNode()) { 6314 CombineTo(N0.getNode(), NarrowLoad); 6315 // CombineTo deleted the truncate, if needed, but not what's under it. 6316 AddToWorklist(oye); 6317 } 6318 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6319 } 6320 } 6321 6322 // fold (zext (truncate x)) -> (and x, mask) 6323 if (N0.getOpcode() == ISD::TRUNCATE) { 6324 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6325 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6326 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6327 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6328 if (NarrowLoad.getNode() != N0.getNode()) { 6329 CombineTo(N0.getNode(), NarrowLoad); 6330 // CombineTo deleted the truncate, if needed, but not what's under it. 6331 AddToWorklist(oye); 6332 } 6333 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6334 } 6335 6336 EVT SrcVT = N0.getOperand(0).getValueType(); 6337 EVT MinVT = N0.getValueType(); 6338 6339 // Try to mask before the extension to avoid having to generate a larger mask, 6340 // possibly over several sub-vectors. 6341 if (SrcVT.bitsLT(VT)) { 6342 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6343 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6344 SDValue Op = N0.getOperand(0); 6345 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6346 AddToWorklist(Op.getNode()); 6347 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6348 } 6349 } 6350 6351 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6352 SDValue Op = N0.getOperand(0); 6353 if (SrcVT.bitsLT(VT)) { 6354 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6355 AddToWorklist(Op.getNode()); 6356 } else if (SrcVT.bitsGT(VT)) { 6357 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6358 AddToWorklist(Op.getNode()); 6359 } 6360 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6361 } 6362 } 6363 6364 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6365 // if either of the casts is not free. 6366 if (N0.getOpcode() == ISD::AND && 6367 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6368 N0.getOperand(1).getOpcode() == ISD::Constant && 6369 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6370 N0.getValueType()) || 6371 !TLI.isZExtFree(N0.getValueType(), VT))) { 6372 SDValue X = N0.getOperand(0).getOperand(0); 6373 if (X.getValueType().bitsLT(VT)) { 6374 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6375 } else if (X.getValueType().bitsGT(VT)) { 6376 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6377 } 6378 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6379 Mask = Mask.zext(VT.getSizeInBits()); 6380 SDLoc DL(N); 6381 return DAG.getNode(ISD::AND, DL, VT, 6382 X, DAG.getConstant(Mask, DL, VT)); 6383 } 6384 6385 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6386 // Only generate vector extloads when 1) they're legal, and 2) they are 6387 // deemed desirable by the target. 6388 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6389 ((!LegalOperations && !VT.isVector() && 6390 !cast<LoadSDNode>(N0)->isVolatile()) || 6391 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6392 bool DoXform = true; 6393 SmallVector<SDNode*, 4> SetCCs; 6394 if (!N0.hasOneUse()) 6395 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6396 if (VT.isVector()) 6397 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6398 if (DoXform) { 6399 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6400 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6401 LN0->getChain(), 6402 LN0->getBasePtr(), N0.getValueType(), 6403 LN0->getMemOperand()); 6404 CombineTo(N, ExtLoad); 6405 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6406 N0.getValueType(), ExtLoad); 6407 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6408 6409 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6410 ISD::ZERO_EXTEND); 6411 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6412 } 6413 } 6414 6415 // fold (zext (load x)) to multiple smaller zextloads. 6416 // Only on illegal but splittable vectors. 6417 if (SDValue ExtLoad = CombineExtLoad(N)) 6418 return ExtLoad; 6419 6420 // fold (zext (and/or/xor (load x), cst)) -> 6421 // (and/or/xor (zextload x), (zext cst)) 6422 // Unless (and (load x) cst) will match as a zextload already and has 6423 // additional users. 6424 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6425 N0.getOpcode() == ISD::XOR) && 6426 isa<LoadSDNode>(N0.getOperand(0)) && 6427 N0.getOperand(1).getOpcode() == ISD::Constant && 6428 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6429 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6430 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6431 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6432 bool DoXform = true; 6433 SmallVector<SDNode*, 4> SetCCs; 6434 if (!N0.hasOneUse()) { 6435 if (N0.getOpcode() == ISD::AND) { 6436 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6437 auto NarrowLoad = false; 6438 EVT LoadResultTy = AndC->getValueType(0); 6439 EVT ExtVT, LoadedVT; 6440 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6441 NarrowLoad)) 6442 DoXform = false; 6443 } 6444 if (DoXform) 6445 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6446 ISD::ZERO_EXTEND, SetCCs, TLI); 6447 } 6448 if (DoXform) { 6449 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6450 LN0->getChain(), LN0->getBasePtr(), 6451 LN0->getMemoryVT(), 6452 LN0->getMemOperand()); 6453 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6454 Mask = Mask.zext(VT.getSizeInBits()); 6455 SDLoc DL(N); 6456 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6457 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6458 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6459 SDLoc(N0.getOperand(0)), 6460 N0.getOperand(0).getValueType(), ExtLoad); 6461 CombineTo(N, And); 6462 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6463 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6464 ISD::ZERO_EXTEND); 6465 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6466 } 6467 } 6468 } 6469 6470 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6471 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6472 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6473 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6474 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6475 EVT MemVT = LN0->getMemoryVT(); 6476 if ((!LegalOperations && !LN0->isVolatile()) || 6477 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6478 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6479 LN0->getChain(), 6480 LN0->getBasePtr(), MemVT, 6481 LN0->getMemOperand()); 6482 CombineTo(N, ExtLoad); 6483 CombineTo(N0.getNode(), 6484 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6485 ExtLoad), 6486 ExtLoad.getValue(1)); 6487 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6488 } 6489 } 6490 6491 if (N0.getOpcode() == ISD::SETCC) { 6492 // Only do this before legalize for now. 6493 if (!LegalOperations && VT.isVector() && 6494 N0.getValueType().getVectorElementType() == MVT::i1) { 6495 EVT N00VT = N0.getOperand(0).getValueType(); 6496 if (getSetCCResultType(N00VT) == N0.getValueType()) 6497 return SDValue(); 6498 6499 // We know that the # elements of the results is the same as the # 6500 // elements of the compare (and the # elements of the compare result for 6501 // that matter). Check to see that they are the same size. If so, we know 6502 // that the element size of the sext'd result matches the element size of 6503 // the compare operands. 6504 SDLoc DL(N); 6505 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6506 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 6507 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6508 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 6509 N0.getOperand(1), N0.getOperand(2)); 6510 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 6511 } 6512 6513 // If the desired elements are smaller or larger than the source 6514 // elements we can use a matching integer vector type and then 6515 // truncate/sign extend. 6516 EVT MatchingElementType = EVT::getIntegerVT( 6517 *DAG.getContext(), N00VT.getScalarType().getSizeInBits()); 6518 EVT MatchingVectorType = EVT::getVectorVT( 6519 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 6520 SDValue VsetCC = 6521 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 6522 N0.getOperand(1), N0.getOperand(2)); 6523 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 6524 VecOnes); 6525 } 6526 6527 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6528 SDLoc DL(N); 6529 if (SDValue SCC = SimplifySelectCC( 6530 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6531 DAG.getConstant(0, DL, VT), 6532 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6533 return SCC; 6534 } 6535 6536 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6537 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6538 isa<ConstantSDNode>(N0.getOperand(1)) && 6539 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6540 N0.hasOneUse()) { 6541 SDValue ShAmt = N0.getOperand(1); 6542 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6543 if (N0.getOpcode() == ISD::SHL) { 6544 SDValue InnerZExt = N0.getOperand(0); 6545 // If the original shl may be shifting out bits, do not perform this 6546 // transformation. 6547 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6548 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6549 if (ShAmtVal > KnownZeroBits) 6550 return SDValue(); 6551 } 6552 6553 SDLoc DL(N); 6554 6555 // Ensure that the shift amount is wide enough for the shifted value. 6556 if (VT.getSizeInBits() >= 256) 6557 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6558 6559 return DAG.getNode(N0.getOpcode(), DL, VT, 6560 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6561 ShAmt); 6562 } 6563 6564 return SDValue(); 6565 } 6566 6567 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6568 SDValue N0 = N->getOperand(0); 6569 EVT VT = N->getValueType(0); 6570 6571 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6572 LegalOperations)) 6573 return SDValue(Res, 0); 6574 6575 // fold (aext (aext x)) -> (aext x) 6576 // fold (aext (zext x)) -> (zext x) 6577 // fold (aext (sext x)) -> (sext x) 6578 if (N0.getOpcode() == ISD::ANY_EXTEND || 6579 N0.getOpcode() == ISD::ZERO_EXTEND || 6580 N0.getOpcode() == ISD::SIGN_EXTEND) 6581 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6582 6583 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6584 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6585 if (N0.getOpcode() == ISD::TRUNCATE) { 6586 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6587 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6588 if (NarrowLoad.getNode() != N0.getNode()) { 6589 CombineTo(N0.getNode(), NarrowLoad); 6590 // CombineTo deleted the truncate, if needed, but not what's under it. 6591 AddToWorklist(oye); 6592 } 6593 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6594 } 6595 } 6596 6597 // fold (aext (truncate x)) 6598 if (N0.getOpcode() == ISD::TRUNCATE) { 6599 SDValue TruncOp = N0.getOperand(0); 6600 if (TruncOp.getValueType() == VT) 6601 return TruncOp; // x iff x size == zext size. 6602 if (TruncOp.getValueType().bitsGT(VT)) 6603 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6604 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6605 } 6606 6607 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6608 // if the trunc is not free. 6609 if (N0.getOpcode() == ISD::AND && 6610 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6611 N0.getOperand(1).getOpcode() == ISD::Constant && 6612 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6613 N0.getValueType())) { 6614 SDValue X = N0.getOperand(0).getOperand(0); 6615 if (X.getValueType().bitsLT(VT)) { 6616 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6617 } else if (X.getValueType().bitsGT(VT)) { 6618 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6619 } 6620 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6621 Mask = Mask.zext(VT.getSizeInBits()); 6622 SDLoc DL(N); 6623 return DAG.getNode(ISD::AND, DL, VT, 6624 X, DAG.getConstant(Mask, DL, VT)); 6625 } 6626 6627 // fold (aext (load x)) -> (aext (truncate (extload x))) 6628 // None of the supported targets knows how to perform load and any_ext 6629 // on vectors in one instruction. We only perform this transformation on 6630 // scalars. 6631 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6632 ISD::isUNINDEXEDLoad(N0.getNode()) && 6633 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6634 bool DoXform = true; 6635 SmallVector<SDNode*, 4> SetCCs; 6636 if (!N0.hasOneUse()) 6637 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6638 if (DoXform) { 6639 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6640 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6641 LN0->getChain(), 6642 LN0->getBasePtr(), N0.getValueType(), 6643 LN0->getMemOperand()); 6644 CombineTo(N, ExtLoad); 6645 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6646 N0.getValueType(), ExtLoad); 6647 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6648 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6649 ISD::ANY_EXTEND); 6650 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6651 } 6652 } 6653 6654 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6655 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6656 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6657 if (N0.getOpcode() == ISD::LOAD && 6658 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6659 N0.hasOneUse()) { 6660 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6661 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6662 EVT MemVT = LN0->getMemoryVT(); 6663 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6664 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6665 VT, LN0->getChain(), LN0->getBasePtr(), 6666 MemVT, LN0->getMemOperand()); 6667 CombineTo(N, ExtLoad); 6668 CombineTo(N0.getNode(), 6669 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6670 N0.getValueType(), ExtLoad), 6671 ExtLoad.getValue(1)); 6672 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6673 } 6674 } 6675 6676 if (N0.getOpcode() == ISD::SETCC) { 6677 // For vectors: 6678 // aext(setcc) -> vsetcc 6679 // aext(setcc) -> truncate(vsetcc) 6680 // aext(setcc) -> aext(vsetcc) 6681 // Only do this before legalize for now. 6682 if (VT.isVector() && !LegalOperations) { 6683 EVT N0VT = N0.getOperand(0).getValueType(); 6684 // We know that the # elements of the results is the same as the 6685 // # elements of the compare (and the # elements of the compare result 6686 // for that matter). Check to see that they are the same size. If so, 6687 // we know that the element size of the sext'd result matches the 6688 // element size of the compare operands. 6689 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6690 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6691 N0.getOperand(1), 6692 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6693 // If the desired elements are smaller or larger than the source 6694 // elements we can use a matching integer vector type and then 6695 // truncate/any extend 6696 else { 6697 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6698 SDValue VsetCC = 6699 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6700 N0.getOperand(1), 6701 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6702 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6703 } 6704 } 6705 6706 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6707 SDLoc DL(N); 6708 if (SDValue SCC = SimplifySelectCC( 6709 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6710 DAG.getConstant(0, DL, VT), 6711 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6712 return SCC; 6713 } 6714 6715 return SDValue(); 6716 } 6717 6718 /// See if the specified operand can be simplified with the knowledge that only 6719 /// the bits specified by Mask are used. If so, return the simpler operand, 6720 /// otherwise return a null SDValue. 6721 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6722 switch (V.getOpcode()) { 6723 default: break; 6724 case ISD::Constant: { 6725 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6726 assert(CV && "Const value should be ConstSDNode."); 6727 const APInt &CVal = CV->getAPIntValue(); 6728 APInt NewVal = CVal & Mask; 6729 if (NewVal != CVal) 6730 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6731 break; 6732 } 6733 case ISD::OR: 6734 case ISD::XOR: 6735 // If the LHS or RHS don't contribute bits to the or, drop them. 6736 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6737 return V.getOperand(1); 6738 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6739 return V.getOperand(0); 6740 break; 6741 case ISD::SRL: 6742 // Only look at single-use SRLs. 6743 if (!V.getNode()->hasOneUse()) 6744 break; 6745 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6746 // See if we can recursively simplify the LHS. 6747 unsigned Amt = RHSC->getZExtValue(); 6748 6749 // Watch out for shift count overflow though. 6750 if (Amt >= Mask.getBitWidth()) break; 6751 APInt NewMask = Mask << Amt; 6752 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6753 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6754 SimplifyLHS, V.getOperand(1)); 6755 } 6756 } 6757 return SDValue(); 6758 } 6759 6760 /// If the result of a wider load is shifted to right of N bits and then 6761 /// truncated to a narrower type and where N is a multiple of number of bits of 6762 /// the narrower type, transform it to a narrower load from address + N / num of 6763 /// bits of new type. If the result is to be extended, also fold the extension 6764 /// to form a extending load. 6765 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6766 unsigned Opc = N->getOpcode(); 6767 6768 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6769 SDValue N0 = N->getOperand(0); 6770 EVT VT = N->getValueType(0); 6771 EVT ExtVT = VT; 6772 6773 // This transformation isn't valid for vector loads. 6774 if (VT.isVector()) 6775 return SDValue(); 6776 6777 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6778 // extended to VT. 6779 if (Opc == ISD::SIGN_EXTEND_INREG) { 6780 ExtType = ISD::SEXTLOAD; 6781 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6782 } else if (Opc == ISD::SRL) { 6783 // Another special-case: SRL is basically zero-extending a narrower value. 6784 ExtType = ISD::ZEXTLOAD; 6785 N0 = SDValue(N, 0); 6786 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6787 if (!N01) return SDValue(); 6788 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6789 VT.getSizeInBits() - N01->getZExtValue()); 6790 } 6791 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6792 return SDValue(); 6793 6794 unsigned EVTBits = ExtVT.getSizeInBits(); 6795 6796 // Do not generate loads of non-round integer types since these can 6797 // be expensive (and would be wrong if the type is not byte sized). 6798 if (!ExtVT.isRound()) 6799 return SDValue(); 6800 6801 unsigned ShAmt = 0; 6802 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6803 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6804 ShAmt = N01->getZExtValue(); 6805 // Is the shift amount a multiple of size of VT? 6806 if ((ShAmt & (EVTBits-1)) == 0) { 6807 N0 = N0.getOperand(0); 6808 // Is the load width a multiple of size of VT? 6809 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6810 return SDValue(); 6811 } 6812 6813 // At this point, we must have a load or else we can't do the transform. 6814 if (!isa<LoadSDNode>(N0)) return SDValue(); 6815 6816 // Because a SRL must be assumed to *need* to zero-extend the high bits 6817 // (as opposed to anyext the high bits), we can't combine the zextload 6818 // lowering of SRL and an sextload. 6819 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6820 return SDValue(); 6821 6822 // If the shift amount is larger than the input type then we're not 6823 // accessing any of the loaded bytes. If the load was a zextload/extload 6824 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6825 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6826 return SDValue(); 6827 } 6828 } 6829 6830 // If the load is shifted left (and the result isn't shifted back right), 6831 // we can fold the truncate through the shift. 6832 unsigned ShLeftAmt = 0; 6833 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6834 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6835 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6836 ShLeftAmt = N01->getZExtValue(); 6837 N0 = N0.getOperand(0); 6838 } 6839 } 6840 6841 // If we haven't found a load, we can't narrow it. Don't transform one with 6842 // multiple uses, this would require adding a new load. 6843 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6844 return SDValue(); 6845 6846 // Don't change the width of a volatile load. 6847 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6848 if (LN0->isVolatile()) 6849 return SDValue(); 6850 6851 // Verify that we are actually reducing a load width here. 6852 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6853 return SDValue(); 6854 6855 // For the transform to be legal, the load must produce only two values 6856 // (the value loaded and the chain). Don't transform a pre-increment 6857 // load, for example, which produces an extra value. Otherwise the 6858 // transformation is not equivalent, and the downstream logic to replace 6859 // uses gets things wrong. 6860 if (LN0->getNumValues() > 2) 6861 return SDValue(); 6862 6863 // If the load that we're shrinking is an extload and we're not just 6864 // discarding the extension we can't simply shrink the load. Bail. 6865 // TODO: It would be possible to merge the extensions in some cases. 6866 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6867 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6868 return SDValue(); 6869 6870 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6871 return SDValue(); 6872 6873 EVT PtrType = N0.getOperand(1).getValueType(); 6874 6875 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6876 // It's not possible to generate a constant of extended or untyped type. 6877 return SDValue(); 6878 6879 // For big endian targets, we need to adjust the offset to the pointer to 6880 // load the correct bytes. 6881 if (DAG.getDataLayout().isBigEndian()) { 6882 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6883 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6884 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6885 } 6886 6887 uint64_t PtrOff = ShAmt / 8; 6888 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6889 SDLoc DL(LN0); 6890 // The original load itself didn't wrap, so an offset within it doesn't. 6891 SDNodeFlags Flags; 6892 Flags.setNoUnsignedWrap(true); 6893 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6894 PtrType, LN0->getBasePtr(), 6895 DAG.getConstant(PtrOff, DL, PtrType), 6896 &Flags); 6897 AddToWorklist(NewPtr.getNode()); 6898 6899 SDValue Load; 6900 if (ExtType == ISD::NON_EXTLOAD) 6901 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6902 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 6903 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6904 else 6905 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 6906 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 6907 NewAlign, LN0->getMemOperand()->getFlags(), 6908 LN0->getAAInfo()); 6909 6910 // Replace the old load's chain with the new load's chain. 6911 WorklistRemover DeadNodes(*this); 6912 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6913 6914 // Shift the result left, if we've swallowed a left shift. 6915 SDValue Result = Load; 6916 if (ShLeftAmt != 0) { 6917 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6918 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6919 ShImmTy = VT; 6920 // If the shift amount is as large as the result size (but, presumably, 6921 // no larger than the source) then the useful bits of the result are 6922 // zero; we can't simply return the shortened shift, because the result 6923 // of that operation is undefined. 6924 SDLoc DL(N0); 6925 if (ShLeftAmt >= VT.getSizeInBits()) 6926 Result = DAG.getConstant(0, DL, VT); 6927 else 6928 Result = DAG.getNode(ISD::SHL, DL, VT, 6929 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6930 } 6931 6932 // Return the new loaded value. 6933 return Result; 6934 } 6935 6936 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6937 SDValue N0 = N->getOperand(0); 6938 SDValue N1 = N->getOperand(1); 6939 EVT VT = N->getValueType(0); 6940 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6941 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6942 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6943 6944 if (N0.isUndef()) 6945 return DAG.getUNDEF(VT); 6946 6947 // fold (sext_in_reg c1) -> c1 6948 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6949 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6950 6951 // If the input is already sign extended, just drop the extension. 6952 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6953 return N0; 6954 6955 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6956 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6957 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6958 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6959 N0.getOperand(0), N1); 6960 6961 // fold (sext_in_reg (sext x)) -> (sext x) 6962 // fold (sext_in_reg (aext x)) -> (sext x) 6963 // if x is small enough. 6964 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6965 SDValue N00 = N0.getOperand(0); 6966 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6967 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6968 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6969 } 6970 6971 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6972 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6973 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6974 6975 // fold operands of sext_in_reg based on knowledge that the top bits are not 6976 // demanded. 6977 if (SimplifyDemandedBits(SDValue(N, 0))) 6978 return SDValue(N, 0); 6979 6980 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6981 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6982 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6983 return NarrowLoad; 6984 6985 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6986 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6987 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6988 if (N0.getOpcode() == ISD::SRL) { 6989 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6990 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6991 // We can turn this into an SRA iff the input to the SRL is already sign 6992 // extended enough. 6993 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6994 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6995 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6996 N0.getOperand(0), N0.getOperand(1)); 6997 } 6998 } 6999 7000 // fold (sext_inreg (extload x)) -> (sextload x) 7001 if (ISD::isEXTLoad(N0.getNode()) && 7002 ISD::isUNINDEXEDLoad(N0.getNode()) && 7003 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7004 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7005 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7006 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7007 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7008 LN0->getChain(), 7009 LN0->getBasePtr(), EVT, 7010 LN0->getMemOperand()); 7011 CombineTo(N, ExtLoad); 7012 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7013 AddToWorklist(ExtLoad.getNode()); 7014 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7015 } 7016 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7017 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7018 N0.hasOneUse() && 7019 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7020 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7021 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7022 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7023 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7024 LN0->getChain(), 7025 LN0->getBasePtr(), EVT, 7026 LN0->getMemOperand()); 7027 CombineTo(N, ExtLoad); 7028 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7029 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7030 } 7031 7032 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7033 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7034 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7035 N0.getOperand(1), false)) 7036 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7037 BSwap, N1); 7038 } 7039 7040 return SDValue(); 7041 } 7042 7043 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7044 SDValue N0 = N->getOperand(0); 7045 EVT VT = N->getValueType(0); 7046 7047 if (N0.isUndef()) 7048 return DAG.getUNDEF(VT); 7049 7050 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7051 LegalOperations)) 7052 return SDValue(Res, 0); 7053 7054 return SDValue(); 7055 } 7056 7057 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7058 SDValue N0 = N->getOperand(0); 7059 EVT VT = N->getValueType(0); 7060 7061 if (N0.isUndef()) 7062 return DAG.getUNDEF(VT); 7063 7064 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7065 LegalOperations)) 7066 return SDValue(Res, 0); 7067 7068 return SDValue(); 7069 } 7070 7071 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7072 SDValue N0 = N->getOperand(0); 7073 EVT VT = N->getValueType(0); 7074 bool isLE = DAG.getDataLayout().isLittleEndian(); 7075 7076 // noop truncate 7077 if (N0.getValueType() == N->getValueType(0)) 7078 return N0; 7079 // fold (truncate c1) -> c1 7080 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7081 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7082 // fold (truncate (truncate x)) -> (truncate x) 7083 if (N0.getOpcode() == ISD::TRUNCATE) 7084 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7085 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7086 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7087 N0.getOpcode() == ISD::SIGN_EXTEND || 7088 N0.getOpcode() == ISD::ANY_EXTEND) { 7089 // if the source is smaller than the dest, we still need an extend. 7090 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7091 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7092 // if the source is larger than the dest, than we just need the truncate. 7093 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7094 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7095 // if the source and dest are the same type, we can drop both the extend 7096 // and the truncate. 7097 return N0.getOperand(0); 7098 } 7099 7100 // Fold extract-and-trunc into a narrow extract. For example: 7101 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7102 // i32 y = TRUNCATE(i64 x) 7103 // -- becomes -- 7104 // v16i8 b = BITCAST (v2i64 val) 7105 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7106 // 7107 // Note: We only run this optimization after type legalization (which often 7108 // creates this pattern) and before operation legalization after which 7109 // we need to be more careful about the vector instructions that we generate. 7110 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7111 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7112 7113 EVT VecTy = N0.getOperand(0).getValueType(); 7114 EVT ExTy = N0.getValueType(); 7115 EVT TrTy = N->getValueType(0); 7116 7117 unsigned NumElem = VecTy.getVectorNumElements(); 7118 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7119 7120 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7121 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7122 7123 SDValue EltNo = N0->getOperand(1); 7124 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7125 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7126 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7127 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7128 7129 SDLoc DL(N); 7130 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7131 DAG.getBitcast(NVT, N0.getOperand(0)), 7132 DAG.getConstant(Index, DL, IndexTy)); 7133 } 7134 } 7135 7136 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7137 if (N0.getOpcode() == ISD::SELECT) { 7138 EVT SrcVT = N0.getValueType(); 7139 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7140 TLI.isTruncateFree(SrcVT, VT)) { 7141 SDLoc SL(N0); 7142 SDValue Cond = N0.getOperand(0); 7143 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7144 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7145 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7146 } 7147 } 7148 7149 // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2 7150 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7151 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7152 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7153 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7154 uint64_t Amt = CAmt->getZExtValue(); 7155 unsigned Size = VT.getSizeInBits(); 7156 7157 if (Amt < Size / 2) { 7158 SDLoc SL(N); 7159 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7160 7161 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7162 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7163 DAG.getConstant(Amt, SL, AmtVT)); 7164 } 7165 } 7166 } 7167 7168 // Fold a series of buildvector, bitcast, and truncate if possible. 7169 // For example fold 7170 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7171 // (2xi32 (buildvector x, y)). 7172 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7173 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7174 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7175 N0.getOperand(0).hasOneUse()) { 7176 7177 SDValue BuildVect = N0.getOperand(0); 7178 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7179 EVT TruncVecEltTy = VT.getVectorElementType(); 7180 7181 // Check that the element types match. 7182 if (BuildVectEltTy == TruncVecEltTy) { 7183 // Now we only need to compute the offset of the truncated elements. 7184 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7185 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7186 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7187 7188 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7189 "Invalid number of elements"); 7190 7191 SmallVector<SDValue, 8> Opnds; 7192 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7193 Opnds.push_back(BuildVect.getOperand(i)); 7194 7195 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7196 } 7197 } 7198 7199 // See if we can simplify the input to this truncate through knowledge that 7200 // only the low bits are being used. 7201 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7202 // Currently we only perform this optimization on scalars because vectors 7203 // may have different active low bits. 7204 if (!VT.isVector()) { 7205 if (SDValue Shorter = 7206 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7207 VT.getSizeInBits()))) 7208 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7209 } 7210 // fold (truncate (load x)) -> (smaller load x) 7211 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7212 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7213 if (SDValue Reduced = ReduceLoadWidth(N)) 7214 return Reduced; 7215 7216 // Handle the case where the load remains an extending load even 7217 // after truncation. 7218 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7219 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7220 if (!LN0->isVolatile() && 7221 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7222 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7223 VT, LN0->getChain(), LN0->getBasePtr(), 7224 LN0->getMemoryVT(), 7225 LN0->getMemOperand()); 7226 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7227 return NewLoad; 7228 } 7229 } 7230 } 7231 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7232 // where ... are all 'undef'. 7233 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7234 SmallVector<EVT, 8> VTs; 7235 SDValue V; 7236 unsigned Idx = 0; 7237 unsigned NumDefs = 0; 7238 7239 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7240 SDValue X = N0.getOperand(i); 7241 if (!X.isUndef()) { 7242 V = X; 7243 Idx = i; 7244 NumDefs++; 7245 } 7246 // Stop if more than one members are non-undef. 7247 if (NumDefs > 1) 7248 break; 7249 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7250 VT.getVectorElementType(), 7251 X.getValueType().getVectorNumElements())); 7252 } 7253 7254 if (NumDefs == 0) 7255 return DAG.getUNDEF(VT); 7256 7257 if (NumDefs == 1) { 7258 assert(V.getNode() && "The single defined operand is empty!"); 7259 SmallVector<SDValue, 8> Opnds; 7260 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7261 if (i != Idx) { 7262 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7263 continue; 7264 } 7265 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7266 AddToWorklist(NV.getNode()); 7267 Opnds.push_back(NV); 7268 } 7269 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7270 } 7271 } 7272 7273 // Fold truncate of a bitcast of a vector to an extract of the low vector 7274 // element. 7275 // 7276 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7277 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7278 SDValue VecSrc = N0.getOperand(0); 7279 EVT SrcVT = VecSrc.getValueType(); 7280 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7281 (!LegalOperations || 7282 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7283 SDLoc SL(N); 7284 7285 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7286 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7287 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7288 } 7289 } 7290 7291 // Simplify the operands using demanded-bits information. 7292 if (!VT.isVector() && 7293 SimplifyDemandedBits(SDValue(N, 0))) 7294 return SDValue(N, 0); 7295 7296 return SDValue(); 7297 } 7298 7299 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7300 SDValue Elt = N->getOperand(i); 7301 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7302 return Elt.getNode(); 7303 return Elt.getOperand(Elt.getResNo()).getNode(); 7304 } 7305 7306 /// build_pair (load, load) -> load 7307 /// if load locations are consecutive. 7308 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7309 assert(N->getOpcode() == ISD::BUILD_PAIR); 7310 7311 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7312 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7313 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7314 LD1->getAddressSpace() != LD2->getAddressSpace()) 7315 return SDValue(); 7316 EVT LD1VT = LD1->getValueType(0); 7317 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7318 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7319 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7320 unsigned Align = LD1->getAlignment(); 7321 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7322 VT.getTypeForEVT(*DAG.getContext())); 7323 7324 if (NewAlign <= Align && 7325 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7326 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 7327 LD1->getPointerInfo(), Align); 7328 } 7329 7330 return SDValue(); 7331 } 7332 7333 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7334 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7335 // and Lo parts; on big-endian machines it doesn't. 7336 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7337 } 7338 7339 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 7340 const TargetLowering &TLI) { 7341 // If this is not a bitcast to an FP type or if the target doesn't have 7342 // IEEE754-compliant FP logic, we're done. 7343 EVT VT = N->getValueType(0); 7344 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 7345 return SDValue(); 7346 7347 // TODO: Use splat values for the constant-checking below and remove this 7348 // restriction. 7349 SDValue N0 = N->getOperand(0); 7350 EVT SourceVT = N0.getValueType(); 7351 if (SourceVT.isVector()) 7352 return SDValue(); 7353 7354 unsigned FPOpcode; 7355 APInt SignMask; 7356 switch (N0.getOpcode()) { 7357 case ISD::AND: 7358 FPOpcode = ISD::FABS; 7359 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 7360 break; 7361 case ISD::XOR: 7362 FPOpcode = ISD::FNEG; 7363 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 7364 break; 7365 // TODO: ISD::OR --> ISD::FNABS? 7366 default: 7367 return SDValue(); 7368 } 7369 7370 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 7371 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 7372 SDValue LogicOp0 = N0.getOperand(0); 7373 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7374 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 7375 LogicOp0.getOpcode() == ISD::BITCAST && 7376 LogicOp0->getOperand(0).getValueType() == VT) 7377 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 7378 7379 return SDValue(); 7380 } 7381 7382 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7383 SDValue N0 = N->getOperand(0); 7384 EVT VT = N->getValueType(0); 7385 7386 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7387 // Only do this before legalize, since afterward the target may be depending 7388 // on the bitconvert. 7389 // First check to see if this is all constant. 7390 if (!LegalTypes && 7391 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7392 VT.isVector()) { 7393 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7394 7395 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7396 assert(!DestEltVT.isVector() && 7397 "Element type of vector ValueType must not be vector!"); 7398 if (isSimple) 7399 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7400 } 7401 7402 // If the input is a constant, let getNode fold it. 7403 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7404 // If we can't allow illegal operations, we need to check that this is just 7405 // a fp -> int or int -> conversion and that the resulting operation will 7406 // be legal. 7407 if (!LegalOperations || 7408 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7409 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7410 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7411 TLI.isOperationLegal(ISD::Constant, VT))) 7412 return DAG.getBitcast(VT, N0); 7413 } 7414 7415 // (conv (conv x, t1), t2) -> (conv x, t2) 7416 if (N0.getOpcode() == ISD::BITCAST) 7417 return DAG.getBitcast(VT, N0.getOperand(0)); 7418 7419 // fold (conv (load x)) -> (load (conv*)x) 7420 // If the resultant load doesn't need a higher alignment than the original! 7421 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7422 // Do not change the width of a volatile load. 7423 !cast<LoadSDNode>(N0)->isVolatile() && 7424 // Do not remove the cast if the types differ in endian layout. 7425 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7426 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7427 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7428 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7429 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7430 unsigned OrigAlign = LN0->getAlignment(); 7431 7432 bool Fast = false; 7433 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7434 LN0->getAddressSpace(), OrigAlign, &Fast) && 7435 Fast) { 7436 SDValue Load = 7437 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7438 LN0->getPointerInfo(), OrigAlign, 7439 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7440 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7441 return Load; 7442 } 7443 } 7444 7445 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 7446 return V; 7447 7448 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7449 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7450 // 7451 // For ppc_fp128: 7452 // fold (bitcast (fneg x)) -> 7453 // flipbit = signbit 7454 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7455 // 7456 // fold (bitcast (fabs x)) -> 7457 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7458 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7459 // This often reduces constant pool loads. 7460 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7461 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7462 N0.getNode()->hasOneUse() && VT.isInteger() && 7463 !VT.isVector() && !N0.getValueType().isVector()) { 7464 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 7465 AddToWorklist(NewConv.getNode()); 7466 7467 SDLoc DL(N); 7468 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7469 assert(VT.getSizeInBits() == 128); 7470 SDValue SignBit = DAG.getConstant( 7471 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7472 SDValue FlipBit; 7473 if (N0.getOpcode() == ISD::FNEG) { 7474 FlipBit = SignBit; 7475 AddToWorklist(FlipBit.getNode()); 7476 } else { 7477 assert(N0.getOpcode() == ISD::FABS); 7478 SDValue Hi = 7479 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7480 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7481 SDLoc(NewConv))); 7482 AddToWorklist(Hi.getNode()); 7483 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7484 AddToWorklist(FlipBit.getNode()); 7485 } 7486 SDValue FlipBits = 7487 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7488 AddToWorklist(FlipBits.getNode()); 7489 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7490 } 7491 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7492 if (N0.getOpcode() == ISD::FNEG) 7493 return DAG.getNode(ISD::XOR, DL, VT, 7494 NewConv, DAG.getConstant(SignBit, DL, VT)); 7495 assert(N0.getOpcode() == ISD::FABS); 7496 return DAG.getNode(ISD::AND, DL, VT, 7497 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7498 } 7499 7500 // fold (bitconvert (fcopysign cst, x)) -> 7501 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7502 // Note that we don't handle (copysign x, cst) because this can always be 7503 // folded to an fneg or fabs. 7504 // 7505 // For ppc_fp128: 7506 // fold (bitcast (fcopysign cst, x)) -> 7507 // flipbit = (and (extract_element 7508 // (xor (bitcast cst), (bitcast x)), 0), 7509 // signbit) 7510 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7511 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7512 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7513 VT.isInteger() && !VT.isVector()) { 7514 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7515 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7516 if (isTypeLegal(IntXVT)) { 7517 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 7518 AddToWorklist(X.getNode()); 7519 7520 // If X has a different width than the result/lhs, sext it or truncate it. 7521 unsigned VTWidth = VT.getSizeInBits(); 7522 if (OrigXWidth < VTWidth) { 7523 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7524 AddToWorklist(X.getNode()); 7525 } else if (OrigXWidth > VTWidth) { 7526 // To get the sign bit in the right place, we have to shift it right 7527 // before truncating. 7528 SDLoc DL(X); 7529 X = DAG.getNode(ISD::SRL, DL, 7530 X.getValueType(), X, 7531 DAG.getConstant(OrigXWidth-VTWidth, DL, 7532 X.getValueType())); 7533 AddToWorklist(X.getNode()); 7534 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7535 AddToWorklist(X.getNode()); 7536 } 7537 7538 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7539 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7540 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7541 AddToWorklist(Cst.getNode()); 7542 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7543 AddToWorklist(X.getNode()); 7544 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7545 AddToWorklist(XorResult.getNode()); 7546 SDValue XorResult64 = DAG.getNode( 7547 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7548 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7549 SDLoc(XorResult))); 7550 AddToWorklist(XorResult64.getNode()); 7551 SDValue FlipBit = 7552 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7553 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7554 AddToWorklist(FlipBit.getNode()); 7555 SDValue FlipBits = 7556 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7557 AddToWorklist(FlipBits.getNode()); 7558 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7559 } 7560 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7561 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7562 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7563 AddToWorklist(X.getNode()); 7564 7565 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7566 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7567 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7568 AddToWorklist(Cst.getNode()); 7569 7570 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7571 } 7572 } 7573 7574 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7575 if (N0.getOpcode() == ISD::BUILD_PAIR) 7576 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7577 return CombineLD; 7578 7579 // Remove double bitcasts from shuffles - this is often a legacy of 7580 // XformToShuffleWithZero being used to combine bitmaskings (of 7581 // float vectors bitcast to integer vectors) into shuffles. 7582 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7583 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7584 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7585 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7586 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7587 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7588 7589 // If operands are a bitcast, peek through if it casts the original VT. 7590 // If operands are a constant, just bitcast back to original VT. 7591 auto PeekThroughBitcast = [&](SDValue Op) { 7592 if (Op.getOpcode() == ISD::BITCAST && 7593 Op.getOperand(0).getValueType() == VT) 7594 return SDValue(Op.getOperand(0)); 7595 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7596 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7597 return DAG.getBitcast(VT, Op); 7598 return SDValue(); 7599 }; 7600 7601 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7602 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7603 if (!(SV0 && SV1)) 7604 return SDValue(); 7605 7606 int MaskScale = 7607 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7608 SmallVector<int, 8> NewMask; 7609 for (int M : SVN->getMask()) 7610 for (int i = 0; i != MaskScale; ++i) 7611 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7612 7613 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7614 if (!LegalMask) { 7615 std::swap(SV0, SV1); 7616 ShuffleVectorSDNode::commuteMask(NewMask); 7617 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7618 } 7619 7620 if (LegalMask) 7621 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7622 } 7623 7624 return SDValue(); 7625 } 7626 7627 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7628 EVT VT = N->getValueType(0); 7629 return CombineConsecutiveLoads(N, VT); 7630 } 7631 7632 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7633 /// operands. DstEltVT indicates the destination element value type. 7634 SDValue DAGCombiner:: 7635 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7636 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7637 7638 // If this is already the right type, we're done. 7639 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7640 7641 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7642 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7643 7644 // If this is a conversion of N elements of one type to N elements of another 7645 // type, convert each element. This handles FP<->INT cases. 7646 if (SrcBitSize == DstBitSize) { 7647 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7648 BV->getValueType(0).getVectorNumElements()); 7649 7650 // Due to the FP element handling below calling this routine recursively, 7651 // we can end up with a scalar-to-vector node here. 7652 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7653 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7654 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 7655 7656 SmallVector<SDValue, 8> Ops; 7657 for (SDValue Op : BV->op_values()) { 7658 // If the vector element type is not legal, the BUILD_VECTOR operands 7659 // are promoted and implicitly truncated. Make that explicit here. 7660 if (Op.getValueType() != SrcEltVT) 7661 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7662 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 7663 AddToWorklist(Ops.back().getNode()); 7664 } 7665 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 7666 } 7667 7668 // Otherwise, we're growing or shrinking the elements. To avoid having to 7669 // handle annoying details of growing/shrinking FP values, we convert them to 7670 // int first. 7671 if (SrcEltVT.isFloatingPoint()) { 7672 // Convert the input float vector to a int vector where the elements are the 7673 // same sizes. 7674 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7675 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7676 SrcEltVT = IntVT; 7677 } 7678 7679 // Now we know the input is an integer vector. If the output is a FP type, 7680 // convert to integer first, then to FP of the right size. 7681 if (DstEltVT.isFloatingPoint()) { 7682 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7683 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7684 7685 // Next, convert to FP elements of the same size. 7686 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7687 } 7688 7689 SDLoc DL(BV); 7690 7691 // Okay, we know the src/dst types are both integers of differing types. 7692 // Handling growing first. 7693 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7694 if (SrcBitSize < DstBitSize) { 7695 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7696 7697 SmallVector<SDValue, 8> Ops; 7698 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7699 i += NumInputsPerOutput) { 7700 bool isLE = DAG.getDataLayout().isLittleEndian(); 7701 APInt NewBits = APInt(DstBitSize, 0); 7702 bool EltIsUndef = true; 7703 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7704 // Shift the previously computed bits over. 7705 NewBits <<= SrcBitSize; 7706 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7707 if (Op.isUndef()) continue; 7708 EltIsUndef = false; 7709 7710 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7711 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7712 } 7713 7714 if (EltIsUndef) 7715 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7716 else 7717 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7718 } 7719 7720 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7721 return DAG.getBuildVector(VT, DL, Ops); 7722 } 7723 7724 // Finally, this must be the case where we are shrinking elements: each input 7725 // turns into multiple outputs. 7726 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7727 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7728 NumOutputsPerInput*BV->getNumOperands()); 7729 SmallVector<SDValue, 8> Ops; 7730 7731 for (const SDValue &Op : BV->op_values()) { 7732 if (Op.isUndef()) { 7733 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7734 continue; 7735 } 7736 7737 APInt OpVal = cast<ConstantSDNode>(Op)-> 7738 getAPIntValue().zextOrTrunc(SrcBitSize); 7739 7740 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7741 APInt ThisVal = OpVal.trunc(DstBitSize); 7742 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7743 OpVal = OpVal.lshr(DstBitSize); 7744 } 7745 7746 // For big endian targets, swap the order of the pieces of each element. 7747 if (DAG.getDataLayout().isBigEndian()) 7748 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7749 } 7750 7751 return DAG.getBuildVector(VT, DL, Ops); 7752 } 7753 7754 /// Try to perform FMA combining on a given FADD node. 7755 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7756 SDValue N0 = N->getOperand(0); 7757 SDValue N1 = N->getOperand(1); 7758 EVT VT = N->getValueType(0); 7759 SDLoc SL(N); 7760 7761 const TargetOptions &Options = DAG.getTarget().Options; 7762 bool AllowFusion = 7763 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7764 7765 // Floating-point multiply-add with intermediate rounding. 7766 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7767 7768 // Floating-point multiply-add without intermediate rounding. 7769 bool HasFMA = 7770 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7771 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7772 7773 // No valid opcode, do not combine. 7774 if (!HasFMAD && !HasFMA) 7775 return SDValue(); 7776 7777 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7778 ; 7779 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7780 return SDValue(); 7781 7782 // Always prefer FMAD to FMA for precision. 7783 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7784 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7785 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7786 7787 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7788 // prefer to fold the multiply with fewer uses. 7789 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7790 N1.getOpcode() == ISD::FMUL) { 7791 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7792 std::swap(N0, N1); 7793 } 7794 7795 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7796 if (N0.getOpcode() == ISD::FMUL && 7797 (Aggressive || N0->hasOneUse())) { 7798 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7799 N0.getOperand(0), N0.getOperand(1), N1); 7800 } 7801 7802 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7803 // Note: Commutes FADD operands. 7804 if (N1.getOpcode() == ISD::FMUL && 7805 (Aggressive || N1->hasOneUse())) { 7806 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7807 N1.getOperand(0), N1.getOperand(1), N0); 7808 } 7809 7810 // Look through FP_EXTEND nodes to do more combining. 7811 if (AllowFusion && LookThroughFPExt) { 7812 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7813 if (N0.getOpcode() == ISD::FP_EXTEND) { 7814 SDValue N00 = N0.getOperand(0); 7815 if (N00.getOpcode() == ISD::FMUL) 7816 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7817 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7818 N00.getOperand(0)), 7819 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7820 N00.getOperand(1)), N1); 7821 } 7822 7823 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7824 // Note: Commutes FADD operands. 7825 if (N1.getOpcode() == ISD::FP_EXTEND) { 7826 SDValue N10 = N1.getOperand(0); 7827 if (N10.getOpcode() == ISD::FMUL) 7828 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7829 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7830 N10.getOperand(0)), 7831 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7832 N10.getOperand(1)), N0); 7833 } 7834 } 7835 7836 // More folding opportunities when target permits. 7837 if ((AllowFusion || HasFMAD) && Aggressive) { 7838 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7839 if (N0.getOpcode() == PreferredFusedOpcode && 7840 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7841 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7842 N0.getOperand(0), N0.getOperand(1), 7843 DAG.getNode(PreferredFusedOpcode, SL, VT, 7844 N0.getOperand(2).getOperand(0), 7845 N0.getOperand(2).getOperand(1), 7846 N1)); 7847 } 7848 7849 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7850 if (N1->getOpcode() == PreferredFusedOpcode && 7851 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7852 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7853 N1.getOperand(0), N1.getOperand(1), 7854 DAG.getNode(PreferredFusedOpcode, SL, VT, 7855 N1.getOperand(2).getOperand(0), 7856 N1.getOperand(2).getOperand(1), 7857 N0)); 7858 } 7859 7860 if (AllowFusion && LookThroughFPExt) { 7861 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7862 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7863 auto FoldFAddFMAFPExtFMul = [&] ( 7864 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7865 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7866 DAG.getNode(PreferredFusedOpcode, SL, VT, 7867 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7868 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7869 Z)); 7870 }; 7871 if (N0.getOpcode() == PreferredFusedOpcode) { 7872 SDValue N02 = N0.getOperand(2); 7873 if (N02.getOpcode() == ISD::FP_EXTEND) { 7874 SDValue N020 = N02.getOperand(0); 7875 if (N020.getOpcode() == ISD::FMUL) 7876 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7877 N020.getOperand(0), N020.getOperand(1), 7878 N1); 7879 } 7880 } 7881 7882 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7883 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7884 // FIXME: This turns two single-precision and one double-precision 7885 // operation into two double-precision operations, which might not be 7886 // interesting for all targets, especially GPUs. 7887 auto FoldFAddFPExtFMAFMul = [&] ( 7888 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7889 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7890 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7891 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7892 DAG.getNode(PreferredFusedOpcode, SL, VT, 7893 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7894 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7895 Z)); 7896 }; 7897 if (N0.getOpcode() == ISD::FP_EXTEND) { 7898 SDValue N00 = N0.getOperand(0); 7899 if (N00.getOpcode() == PreferredFusedOpcode) { 7900 SDValue N002 = N00.getOperand(2); 7901 if (N002.getOpcode() == ISD::FMUL) 7902 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7903 N002.getOperand(0), N002.getOperand(1), 7904 N1); 7905 } 7906 } 7907 7908 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7909 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7910 if (N1.getOpcode() == PreferredFusedOpcode) { 7911 SDValue N12 = N1.getOperand(2); 7912 if (N12.getOpcode() == ISD::FP_EXTEND) { 7913 SDValue N120 = N12.getOperand(0); 7914 if (N120.getOpcode() == ISD::FMUL) 7915 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7916 N120.getOperand(0), N120.getOperand(1), 7917 N0); 7918 } 7919 } 7920 7921 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7922 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7923 // FIXME: This turns two single-precision and one double-precision 7924 // operation into two double-precision operations, which might not be 7925 // interesting for all targets, especially GPUs. 7926 if (N1.getOpcode() == ISD::FP_EXTEND) { 7927 SDValue N10 = N1.getOperand(0); 7928 if (N10.getOpcode() == PreferredFusedOpcode) { 7929 SDValue N102 = N10.getOperand(2); 7930 if (N102.getOpcode() == ISD::FMUL) 7931 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7932 N102.getOperand(0), N102.getOperand(1), 7933 N0); 7934 } 7935 } 7936 } 7937 } 7938 7939 return SDValue(); 7940 } 7941 7942 /// Try to perform FMA combining on a given FSUB node. 7943 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7944 SDValue N0 = N->getOperand(0); 7945 SDValue N1 = N->getOperand(1); 7946 EVT VT = N->getValueType(0); 7947 SDLoc SL(N); 7948 7949 const TargetOptions &Options = DAG.getTarget().Options; 7950 bool AllowFusion = 7951 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7952 7953 // Floating-point multiply-add with intermediate rounding. 7954 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7955 7956 // Floating-point multiply-add without intermediate rounding. 7957 bool HasFMA = 7958 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7959 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7960 7961 // No valid opcode, do not combine. 7962 if (!HasFMAD && !HasFMA) 7963 return SDValue(); 7964 7965 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7966 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7967 return SDValue(); 7968 7969 // Always prefer FMAD to FMA for precision. 7970 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7971 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7972 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7973 7974 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7975 if (N0.getOpcode() == ISD::FMUL && 7976 (Aggressive || N0->hasOneUse())) { 7977 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7978 N0.getOperand(0), N0.getOperand(1), 7979 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7980 } 7981 7982 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7983 // Note: Commutes FSUB operands. 7984 if (N1.getOpcode() == ISD::FMUL && 7985 (Aggressive || N1->hasOneUse())) 7986 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7987 DAG.getNode(ISD::FNEG, SL, VT, 7988 N1.getOperand(0)), 7989 N1.getOperand(1), N0); 7990 7991 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7992 if (N0.getOpcode() == ISD::FNEG && 7993 N0.getOperand(0).getOpcode() == ISD::FMUL && 7994 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7995 SDValue N00 = N0.getOperand(0).getOperand(0); 7996 SDValue N01 = N0.getOperand(0).getOperand(1); 7997 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7998 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7999 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8000 } 8001 8002 // Look through FP_EXTEND nodes to do more combining. 8003 if (AllowFusion && LookThroughFPExt) { 8004 // fold (fsub (fpext (fmul x, y)), z) 8005 // -> (fma (fpext x), (fpext y), (fneg z)) 8006 if (N0.getOpcode() == ISD::FP_EXTEND) { 8007 SDValue N00 = N0.getOperand(0); 8008 if (N00.getOpcode() == ISD::FMUL) 8009 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8010 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8011 N00.getOperand(0)), 8012 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8013 N00.getOperand(1)), 8014 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8015 } 8016 8017 // fold (fsub x, (fpext (fmul y, z))) 8018 // -> (fma (fneg (fpext y)), (fpext z), x) 8019 // Note: Commutes FSUB operands. 8020 if (N1.getOpcode() == ISD::FP_EXTEND) { 8021 SDValue N10 = N1.getOperand(0); 8022 if (N10.getOpcode() == ISD::FMUL) 8023 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8024 DAG.getNode(ISD::FNEG, SL, VT, 8025 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8026 N10.getOperand(0))), 8027 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8028 N10.getOperand(1)), 8029 N0); 8030 } 8031 8032 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8033 // -> (fneg (fma (fpext x), (fpext y), z)) 8034 // Note: This could be removed with appropriate canonicalization of the 8035 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8036 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8037 // from implementing the canonicalization in visitFSUB. 8038 if (N0.getOpcode() == ISD::FP_EXTEND) { 8039 SDValue N00 = N0.getOperand(0); 8040 if (N00.getOpcode() == ISD::FNEG) { 8041 SDValue N000 = N00.getOperand(0); 8042 if (N000.getOpcode() == ISD::FMUL) { 8043 return DAG.getNode(ISD::FNEG, SL, VT, 8044 DAG.getNode(PreferredFusedOpcode, SL, VT, 8045 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8046 N000.getOperand(0)), 8047 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8048 N000.getOperand(1)), 8049 N1)); 8050 } 8051 } 8052 } 8053 8054 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8055 // -> (fneg (fma (fpext x)), (fpext y), z) 8056 // Note: This could be removed with appropriate canonicalization of the 8057 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8058 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8059 // from implementing the canonicalization in visitFSUB. 8060 if (N0.getOpcode() == ISD::FNEG) { 8061 SDValue N00 = N0.getOperand(0); 8062 if (N00.getOpcode() == ISD::FP_EXTEND) { 8063 SDValue N000 = N00.getOperand(0); 8064 if (N000.getOpcode() == ISD::FMUL) { 8065 return DAG.getNode(ISD::FNEG, SL, VT, 8066 DAG.getNode(PreferredFusedOpcode, SL, VT, 8067 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8068 N000.getOperand(0)), 8069 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8070 N000.getOperand(1)), 8071 N1)); 8072 } 8073 } 8074 } 8075 8076 } 8077 8078 // More folding opportunities when target permits. 8079 if ((AllowFusion || HasFMAD) && Aggressive) { 8080 // fold (fsub (fma x, y, (fmul u, v)), z) 8081 // -> (fma x, y (fma u, v, (fneg z))) 8082 if (N0.getOpcode() == PreferredFusedOpcode && 8083 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8084 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8085 N0.getOperand(0), N0.getOperand(1), 8086 DAG.getNode(PreferredFusedOpcode, SL, VT, 8087 N0.getOperand(2).getOperand(0), 8088 N0.getOperand(2).getOperand(1), 8089 DAG.getNode(ISD::FNEG, SL, VT, 8090 N1))); 8091 } 8092 8093 // fold (fsub x, (fma y, z, (fmul u, v))) 8094 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8095 if (N1.getOpcode() == PreferredFusedOpcode && 8096 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8097 SDValue N20 = N1.getOperand(2).getOperand(0); 8098 SDValue N21 = N1.getOperand(2).getOperand(1); 8099 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8100 DAG.getNode(ISD::FNEG, SL, VT, 8101 N1.getOperand(0)), 8102 N1.getOperand(1), 8103 DAG.getNode(PreferredFusedOpcode, SL, VT, 8104 DAG.getNode(ISD::FNEG, SL, VT, N20), 8105 8106 N21, N0)); 8107 } 8108 8109 if (AllowFusion && LookThroughFPExt) { 8110 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8111 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8112 if (N0.getOpcode() == PreferredFusedOpcode) { 8113 SDValue N02 = N0.getOperand(2); 8114 if (N02.getOpcode() == ISD::FP_EXTEND) { 8115 SDValue N020 = N02.getOperand(0); 8116 if (N020.getOpcode() == ISD::FMUL) 8117 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8118 N0.getOperand(0), N0.getOperand(1), 8119 DAG.getNode(PreferredFusedOpcode, SL, VT, 8120 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8121 N020.getOperand(0)), 8122 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8123 N020.getOperand(1)), 8124 DAG.getNode(ISD::FNEG, SL, VT, 8125 N1))); 8126 } 8127 } 8128 8129 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8130 // -> (fma (fpext x), (fpext y), 8131 // (fma (fpext u), (fpext v), (fneg z))) 8132 // FIXME: This turns two single-precision and one double-precision 8133 // operation into two double-precision operations, which might not be 8134 // interesting for all targets, especially GPUs. 8135 if (N0.getOpcode() == ISD::FP_EXTEND) { 8136 SDValue N00 = N0.getOperand(0); 8137 if (N00.getOpcode() == PreferredFusedOpcode) { 8138 SDValue N002 = N00.getOperand(2); 8139 if (N002.getOpcode() == ISD::FMUL) 8140 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8141 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8142 N00.getOperand(0)), 8143 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8144 N00.getOperand(1)), 8145 DAG.getNode(PreferredFusedOpcode, SL, VT, 8146 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8147 N002.getOperand(0)), 8148 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8149 N002.getOperand(1)), 8150 DAG.getNode(ISD::FNEG, SL, VT, 8151 N1))); 8152 } 8153 } 8154 8155 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8156 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8157 if (N1.getOpcode() == PreferredFusedOpcode && 8158 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8159 SDValue N120 = N1.getOperand(2).getOperand(0); 8160 if (N120.getOpcode() == ISD::FMUL) { 8161 SDValue N1200 = N120.getOperand(0); 8162 SDValue N1201 = N120.getOperand(1); 8163 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8164 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8165 N1.getOperand(1), 8166 DAG.getNode(PreferredFusedOpcode, SL, VT, 8167 DAG.getNode(ISD::FNEG, SL, VT, 8168 DAG.getNode(ISD::FP_EXTEND, SL, 8169 VT, N1200)), 8170 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8171 N1201), 8172 N0)); 8173 } 8174 } 8175 8176 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8177 // -> (fma (fneg (fpext y)), (fpext z), 8178 // (fma (fneg (fpext u)), (fpext v), x)) 8179 // FIXME: This turns two single-precision and one double-precision 8180 // operation into two double-precision operations, which might not be 8181 // interesting for all targets, especially GPUs. 8182 if (N1.getOpcode() == ISD::FP_EXTEND && 8183 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8184 SDValue N100 = N1.getOperand(0).getOperand(0); 8185 SDValue N101 = N1.getOperand(0).getOperand(1); 8186 SDValue N102 = N1.getOperand(0).getOperand(2); 8187 if (N102.getOpcode() == ISD::FMUL) { 8188 SDValue N1020 = N102.getOperand(0); 8189 SDValue N1021 = N102.getOperand(1); 8190 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8191 DAG.getNode(ISD::FNEG, SL, VT, 8192 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8193 N100)), 8194 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8195 DAG.getNode(PreferredFusedOpcode, SL, VT, 8196 DAG.getNode(ISD::FNEG, SL, VT, 8197 DAG.getNode(ISD::FP_EXTEND, SL, 8198 VT, N1020)), 8199 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8200 N1021), 8201 N0)); 8202 } 8203 } 8204 } 8205 } 8206 8207 return SDValue(); 8208 } 8209 8210 /// Try to perform FMA combining on a given FMUL node. 8211 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8212 SDValue N0 = N->getOperand(0); 8213 SDValue N1 = N->getOperand(1); 8214 EVT VT = N->getValueType(0); 8215 SDLoc SL(N); 8216 8217 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8218 8219 const TargetOptions &Options = DAG.getTarget().Options; 8220 bool AllowFusion = 8221 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8222 8223 // Floating-point multiply-add with intermediate rounding. 8224 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8225 8226 // Floating-point multiply-add without intermediate rounding. 8227 bool HasFMA = 8228 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8229 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8230 8231 // No valid opcode, do not combine. 8232 if (!HasFMAD && !HasFMA) 8233 return SDValue(); 8234 8235 // Always prefer FMAD to FMA for precision. 8236 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8237 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8238 8239 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8240 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8241 auto FuseFADD = [&](SDValue X, SDValue Y) { 8242 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8243 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8244 if (XC1 && XC1->isExactlyValue(+1.0)) 8245 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8246 if (XC1 && XC1->isExactlyValue(-1.0)) 8247 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8248 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8249 } 8250 return SDValue(); 8251 }; 8252 8253 if (SDValue FMA = FuseFADD(N0, N1)) 8254 return FMA; 8255 if (SDValue FMA = FuseFADD(N1, N0)) 8256 return FMA; 8257 8258 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8259 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8260 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8261 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8262 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8263 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8264 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8265 if (XC0 && XC0->isExactlyValue(+1.0)) 8266 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8267 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8268 Y); 8269 if (XC0 && XC0->isExactlyValue(-1.0)) 8270 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8271 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8272 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8273 8274 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8275 if (XC1 && XC1->isExactlyValue(+1.0)) 8276 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8277 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8278 if (XC1 && XC1->isExactlyValue(-1.0)) 8279 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8280 } 8281 return SDValue(); 8282 }; 8283 8284 if (SDValue FMA = FuseFSUB(N0, N1)) 8285 return FMA; 8286 if (SDValue FMA = FuseFSUB(N1, N0)) 8287 return FMA; 8288 8289 return SDValue(); 8290 } 8291 8292 SDValue DAGCombiner::visitFADD(SDNode *N) { 8293 SDValue N0 = N->getOperand(0); 8294 SDValue N1 = N->getOperand(1); 8295 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8296 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8297 EVT VT = N->getValueType(0); 8298 SDLoc DL(N); 8299 const TargetOptions &Options = DAG.getTarget().Options; 8300 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8301 8302 // fold vector ops 8303 if (VT.isVector()) 8304 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8305 return FoldedVOp; 8306 8307 // fold (fadd c1, c2) -> c1 + c2 8308 if (N0CFP && N1CFP) 8309 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8310 8311 // canonicalize constant to RHS 8312 if (N0CFP && !N1CFP) 8313 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8314 8315 // fold (fadd A, (fneg B)) -> (fsub A, B) 8316 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8317 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8318 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8319 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8320 8321 // fold (fadd (fneg A), B) -> (fsub B, A) 8322 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8323 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8324 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8325 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8326 8327 // If 'unsafe math' is enabled, fold lots of things. 8328 if (Options.UnsafeFPMath) { 8329 // No FP constant should be created after legalization as Instruction 8330 // Selection pass has a hard time dealing with FP constants. 8331 bool AllowNewConst = (Level < AfterLegalizeDAG); 8332 8333 // fold (fadd A, 0) -> A 8334 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8335 if (N1C->isZero()) 8336 return N0; 8337 8338 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8339 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8340 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8341 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8342 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8343 Flags), 8344 Flags); 8345 8346 // If allowed, fold (fadd (fneg x), x) -> 0.0 8347 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8348 return DAG.getConstantFP(0.0, DL, VT); 8349 8350 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8351 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8352 return DAG.getConstantFP(0.0, DL, VT); 8353 8354 // We can fold chains of FADD's of the same value into multiplications. 8355 // This transform is not safe in general because we are reducing the number 8356 // of rounding steps. 8357 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8358 if (N0.getOpcode() == ISD::FMUL) { 8359 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8360 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8361 8362 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8363 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8364 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8365 DAG.getConstantFP(1.0, DL, VT), Flags); 8366 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8367 } 8368 8369 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8370 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8371 N1.getOperand(0) == N1.getOperand(1) && 8372 N0.getOperand(0) == N1.getOperand(0)) { 8373 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8374 DAG.getConstantFP(2.0, DL, VT), Flags); 8375 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8376 } 8377 } 8378 8379 if (N1.getOpcode() == ISD::FMUL) { 8380 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8381 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8382 8383 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8384 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8385 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8386 DAG.getConstantFP(1.0, DL, VT), Flags); 8387 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8388 } 8389 8390 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8391 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8392 N0.getOperand(0) == N0.getOperand(1) && 8393 N1.getOperand(0) == N0.getOperand(0)) { 8394 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8395 DAG.getConstantFP(2.0, DL, VT), Flags); 8396 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8397 } 8398 } 8399 8400 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8401 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8402 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8403 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8404 (N0.getOperand(0) == N1)) { 8405 return DAG.getNode(ISD::FMUL, DL, VT, 8406 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8407 } 8408 } 8409 8410 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8411 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8412 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8413 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8414 N1.getOperand(0) == N0) { 8415 return DAG.getNode(ISD::FMUL, DL, VT, 8416 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8417 } 8418 } 8419 8420 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8421 if (AllowNewConst && 8422 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8423 N0.getOperand(0) == N0.getOperand(1) && 8424 N1.getOperand(0) == N1.getOperand(1) && 8425 N0.getOperand(0) == N1.getOperand(0)) { 8426 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8427 DAG.getConstantFP(4.0, DL, VT), Flags); 8428 } 8429 } 8430 } // enable-unsafe-fp-math 8431 8432 // FADD -> FMA combines: 8433 if (SDValue Fused = visitFADDForFMACombine(N)) { 8434 AddToWorklist(Fused.getNode()); 8435 return Fused; 8436 } 8437 return SDValue(); 8438 } 8439 8440 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8441 SDValue N0 = N->getOperand(0); 8442 SDValue N1 = N->getOperand(1); 8443 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8444 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8445 EVT VT = N->getValueType(0); 8446 SDLoc dl(N); 8447 const TargetOptions &Options = DAG.getTarget().Options; 8448 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8449 8450 // fold vector ops 8451 if (VT.isVector()) 8452 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8453 return FoldedVOp; 8454 8455 // fold (fsub c1, c2) -> c1-c2 8456 if (N0CFP && N1CFP) 8457 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8458 8459 // fold (fsub A, (fneg B)) -> (fadd A, B) 8460 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8461 return DAG.getNode(ISD::FADD, dl, VT, N0, 8462 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8463 8464 // If 'unsafe math' is enabled, fold lots of things. 8465 if (Options.UnsafeFPMath) { 8466 // (fsub A, 0) -> A 8467 if (N1CFP && N1CFP->isZero()) 8468 return N0; 8469 8470 // (fsub 0, B) -> -B 8471 if (N0CFP && N0CFP->isZero()) { 8472 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8473 return GetNegatedExpression(N1, DAG, LegalOperations); 8474 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8475 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8476 } 8477 8478 // (fsub x, x) -> 0.0 8479 if (N0 == N1) 8480 return DAG.getConstantFP(0.0f, dl, VT); 8481 8482 // (fsub x, (fadd x, y)) -> (fneg y) 8483 // (fsub x, (fadd y, x)) -> (fneg y) 8484 if (N1.getOpcode() == ISD::FADD) { 8485 SDValue N10 = N1->getOperand(0); 8486 SDValue N11 = N1->getOperand(1); 8487 8488 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8489 return GetNegatedExpression(N11, DAG, LegalOperations); 8490 8491 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8492 return GetNegatedExpression(N10, DAG, LegalOperations); 8493 } 8494 } 8495 8496 // FSUB -> FMA combines: 8497 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8498 AddToWorklist(Fused.getNode()); 8499 return Fused; 8500 } 8501 8502 return SDValue(); 8503 } 8504 8505 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8506 SDValue N0 = N->getOperand(0); 8507 SDValue N1 = N->getOperand(1); 8508 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8509 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8510 EVT VT = N->getValueType(0); 8511 SDLoc DL(N); 8512 const TargetOptions &Options = DAG.getTarget().Options; 8513 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8514 8515 // fold vector ops 8516 if (VT.isVector()) { 8517 // This just handles C1 * C2 for vectors. Other vector folds are below. 8518 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8519 return FoldedVOp; 8520 } 8521 8522 // fold (fmul c1, c2) -> c1*c2 8523 if (N0CFP && N1CFP) 8524 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8525 8526 // canonicalize constant to RHS 8527 if (isConstantFPBuildVectorOrConstantFP(N0) && 8528 !isConstantFPBuildVectorOrConstantFP(N1)) 8529 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8530 8531 // fold (fmul A, 1.0) -> A 8532 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8533 return N0; 8534 8535 if (Options.UnsafeFPMath) { 8536 // fold (fmul A, 0) -> 0 8537 if (N1CFP && N1CFP->isZero()) 8538 return N1; 8539 8540 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8541 if (N0.getOpcode() == ISD::FMUL) { 8542 // Fold scalars or any vector constants (not just splats). 8543 // This fold is done in general by InstCombine, but extra fmul insts 8544 // may have been generated during lowering. 8545 SDValue N00 = N0.getOperand(0); 8546 SDValue N01 = N0.getOperand(1); 8547 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8548 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8549 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8550 8551 // Check 1: Make sure that the first operand of the inner multiply is NOT 8552 // a constant. Otherwise, we may induce infinite looping. 8553 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8554 // Check 2: Make sure that the second operand of the inner multiply and 8555 // the second operand of the outer multiply are constants. 8556 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8557 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8558 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8559 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8560 } 8561 } 8562 } 8563 8564 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8565 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8566 // during an early run of DAGCombiner can prevent folding with fmuls 8567 // inserted during lowering. 8568 if (N0.getOpcode() == ISD::FADD && 8569 (N0.getOperand(0) == N0.getOperand(1)) && 8570 N0.hasOneUse()) { 8571 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8572 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8573 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8574 } 8575 } 8576 8577 // fold (fmul X, 2.0) -> (fadd X, X) 8578 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8579 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8580 8581 // fold (fmul X, -1.0) -> (fneg X) 8582 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8583 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8584 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8585 8586 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8587 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8588 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8589 // Both can be negated for free, check to see if at least one is cheaper 8590 // negated. 8591 if (LHSNeg == 2 || RHSNeg == 2) 8592 return DAG.getNode(ISD::FMUL, DL, VT, 8593 GetNegatedExpression(N0, DAG, LegalOperations), 8594 GetNegatedExpression(N1, DAG, LegalOperations), 8595 Flags); 8596 } 8597 } 8598 8599 // FMUL -> FMA combines: 8600 if (SDValue Fused = visitFMULForFMACombine(N)) { 8601 AddToWorklist(Fused.getNode()); 8602 return Fused; 8603 } 8604 8605 return SDValue(); 8606 } 8607 8608 SDValue DAGCombiner::visitFMA(SDNode *N) { 8609 SDValue N0 = N->getOperand(0); 8610 SDValue N1 = N->getOperand(1); 8611 SDValue N2 = N->getOperand(2); 8612 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8613 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8614 EVT VT = N->getValueType(0); 8615 SDLoc dl(N); 8616 const TargetOptions &Options = DAG.getTarget().Options; 8617 8618 // Constant fold FMA. 8619 if (isa<ConstantFPSDNode>(N0) && 8620 isa<ConstantFPSDNode>(N1) && 8621 isa<ConstantFPSDNode>(N2)) { 8622 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8623 } 8624 8625 if (Options.UnsafeFPMath) { 8626 if (N0CFP && N0CFP->isZero()) 8627 return N2; 8628 if (N1CFP && N1CFP->isZero()) 8629 return N2; 8630 } 8631 // TODO: The FMA node should have flags that propagate to these nodes. 8632 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8633 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8634 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8635 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8636 8637 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8638 if (isConstantFPBuildVectorOrConstantFP(N0) && 8639 !isConstantFPBuildVectorOrConstantFP(N1)) 8640 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8641 8642 // TODO: FMA nodes should have flags that propagate to the created nodes. 8643 // For now, create a Flags object for use with all unsafe math transforms. 8644 SDNodeFlags Flags; 8645 Flags.setUnsafeAlgebra(true); 8646 8647 if (Options.UnsafeFPMath) { 8648 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8649 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8650 isConstantFPBuildVectorOrConstantFP(N1) && 8651 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8652 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8653 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8654 &Flags), &Flags); 8655 } 8656 8657 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8658 if (N0.getOpcode() == ISD::FMUL && 8659 isConstantFPBuildVectorOrConstantFP(N1) && 8660 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8661 return DAG.getNode(ISD::FMA, dl, VT, 8662 N0.getOperand(0), 8663 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8664 &Flags), 8665 N2); 8666 } 8667 } 8668 8669 // (fma x, 1, y) -> (fadd x, y) 8670 // (fma x, -1, y) -> (fadd (fneg x), y) 8671 if (N1CFP) { 8672 if (N1CFP->isExactlyValue(1.0)) 8673 // TODO: The FMA node should have flags that propagate to this node. 8674 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8675 8676 if (N1CFP->isExactlyValue(-1.0) && 8677 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8678 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8679 AddToWorklist(RHSNeg.getNode()); 8680 // TODO: The FMA node should have flags that propagate to this node. 8681 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8682 } 8683 } 8684 8685 if (Options.UnsafeFPMath) { 8686 // (fma x, c, x) -> (fmul x, (c+1)) 8687 if (N1CFP && N0 == N2) { 8688 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8689 DAG.getNode(ISD::FADD, dl, VT, 8690 N1, DAG.getConstantFP(1.0, dl, VT), 8691 &Flags), &Flags); 8692 } 8693 8694 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8695 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8696 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8697 DAG.getNode(ISD::FADD, dl, VT, 8698 N1, DAG.getConstantFP(-1.0, dl, VT), 8699 &Flags), &Flags); 8700 } 8701 } 8702 8703 return SDValue(); 8704 } 8705 8706 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8707 // reciprocal. 8708 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8709 // Notice that this is not always beneficial. One reason is different target 8710 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8711 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8712 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8713 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8714 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8715 const SDNodeFlags *Flags = N->getFlags(); 8716 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8717 return SDValue(); 8718 8719 // Skip if current node is a reciprocal. 8720 SDValue N0 = N->getOperand(0); 8721 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8722 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8723 return SDValue(); 8724 8725 // Exit early if the target does not want this transform or if there can't 8726 // possibly be enough uses of the divisor to make the transform worthwhile. 8727 SDValue N1 = N->getOperand(1); 8728 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8729 if (!MinUses || N1->use_size() < MinUses) 8730 return SDValue(); 8731 8732 // Find all FDIV users of the same divisor. 8733 // Use a set because duplicates may be present in the user list. 8734 SetVector<SDNode *> Users; 8735 for (auto *U : N1->uses()) { 8736 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8737 // This division is eligible for optimization only if global unsafe math 8738 // is enabled or if this division allows reciprocal formation. 8739 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8740 Users.insert(U); 8741 } 8742 } 8743 8744 // Now that we have the actual number of divisor uses, make sure it meets 8745 // the minimum threshold specified by the target. 8746 if (Users.size() < MinUses) 8747 return SDValue(); 8748 8749 EVT VT = N->getValueType(0); 8750 SDLoc DL(N); 8751 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8752 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8753 8754 // Dividend / Divisor -> Dividend * Reciprocal 8755 for (auto *U : Users) { 8756 SDValue Dividend = U->getOperand(0); 8757 if (Dividend != FPOne) { 8758 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8759 Reciprocal, Flags); 8760 CombineTo(U, NewNode); 8761 } else if (U != Reciprocal.getNode()) { 8762 // In the absence of fast-math-flags, this user node is always the 8763 // same node as Reciprocal, but with FMF they may be different nodes. 8764 CombineTo(U, Reciprocal); 8765 } 8766 } 8767 return SDValue(N, 0); // N was replaced. 8768 } 8769 8770 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8771 SDValue N0 = N->getOperand(0); 8772 SDValue N1 = N->getOperand(1); 8773 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8774 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8775 EVT VT = N->getValueType(0); 8776 SDLoc DL(N); 8777 const TargetOptions &Options = DAG.getTarget().Options; 8778 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8779 8780 // fold vector ops 8781 if (VT.isVector()) 8782 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8783 return FoldedVOp; 8784 8785 // fold (fdiv c1, c2) -> c1/c2 8786 if (N0CFP && N1CFP) 8787 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8788 8789 if (Options.UnsafeFPMath) { 8790 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8791 if (N1CFP) { 8792 // Compute the reciprocal 1.0 / c2. 8793 const APFloat &N1APF = N1CFP->getValueAPF(); 8794 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8795 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8796 // Only do the transform if the reciprocal is a legal fp immediate that 8797 // isn't too nasty (eg NaN, denormal, ...). 8798 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8799 (!LegalOperations || 8800 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8801 // backend)... we should handle this gracefully after Legalize. 8802 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8803 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8804 TLI.isFPImmLegal(Recip, VT))) 8805 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8806 DAG.getConstantFP(Recip, DL, VT), Flags); 8807 } 8808 8809 // If this FDIV is part of a reciprocal square root, it may be folded 8810 // into a target-specific square root estimate instruction. 8811 if (N1.getOpcode() == ISD::FSQRT) { 8812 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 8813 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8814 } 8815 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8816 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8817 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8818 Flags)) { 8819 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8820 AddToWorklist(RV.getNode()); 8821 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8822 } 8823 } else if (N1.getOpcode() == ISD::FP_ROUND && 8824 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8825 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8826 Flags)) { 8827 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8828 AddToWorklist(RV.getNode()); 8829 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8830 } 8831 } else if (N1.getOpcode() == ISD::FMUL) { 8832 // Look through an FMUL. Even though this won't remove the FDIV directly, 8833 // it's still worthwhile to get rid of the FSQRT if possible. 8834 SDValue SqrtOp; 8835 SDValue OtherOp; 8836 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8837 SqrtOp = N1.getOperand(0); 8838 OtherOp = N1.getOperand(1); 8839 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8840 SqrtOp = N1.getOperand(1); 8841 OtherOp = N1.getOperand(0); 8842 } 8843 if (SqrtOp.getNode()) { 8844 // We found a FSQRT, so try to make this fold: 8845 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8846 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8847 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8848 AddToWorklist(RV.getNode()); 8849 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8850 } 8851 } 8852 } 8853 8854 // Fold into a reciprocal estimate and multiply instead of a real divide. 8855 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8856 AddToWorklist(RV.getNode()); 8857 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8858 } 8859 } 8860 8861 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8862 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8863 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8864 // Both can be negated for free, check to see if at least one is cheaper 8865 // negated. 8866 if (LHSNeg == 2 || RHSNeg == 2) 8867 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8868 GetNegatedExpression(N0, DAG, LegalOperations), 8869 GetNegatedExpression(N1, DAG, LegalOperations), 8870 Flags); 8871 } 8872 } 8873 8874 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8875 return CombineRepeatedDivisors; 8876 8877 return SDValue(); 8878 } 8879 8880 SDValue DAGCombiner::visitFREM(SDNode *N) { 8881 SDValue N0 = N->getOperand(0); 8882 SDValue N1 = N->getOperand(1); 8883 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8884 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8885 EVT VT = N->getValueType(0); 8886 8887 // fold (frem c1, c2) -> fmod(c1,c2) 8888 if (N0CFP && N1CFP) 8889 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8890 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8891 8892 return SDValue(); 8893 } 8894 8895 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8896 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8897 return SDValue(); 8898 8899 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8900 // For now, create a Flags object for use with all unsafe math transforms. 8901 SDNodeFlags Flags; 8902 Flags.setUnsafeAlgebra(true); 8903 return buildSqrtEstimate(N->getOperand(0), &Flags); 8904 } 8905 8906 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8907 /// copysign(x, fp_round(y)) -> copysign(x, y) 8908 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8909 SDValue N1 = N->getOperand(1); 8910 if ((N1.getOpcode() == ISD::FP_EXTEND || 8911 N1.getOpcode() == ISD::FP_ROUND)) { 8912 // Do not optimize out type conversion of f128 type yet. 8913 // For some targets like x86_64, configuration is changed to keep one f128 8914 // value in one SSE register, but instruction selection cannot handle 8915 // FCOPYSIGN on SSE registers yet. 8916 EVT N1VT = N1->getValueType(0); 8917 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8918 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8919 } 8920 return false; 8921 } 8922 8923 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8924 SDValue N0 = N->getOperand(0); 8925 SDValue N1 = N->getOperand(1); 8926 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8927 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8928 EVT VT = N->getValueType(0); 8929 8930 if (N0CFP && N1CFP) // Constant fold 8931 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8932 8933 if (N1CFP) { 8934 const APFloat& V = N1CFP->getValueAPF(); 8935 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8936 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8937 if (!V.isNegative()) { 8938 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8939 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8940 } else { 8941 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8942 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8943 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8944 } 8945 } 8946 8947 // copysign(fabs(x), y) -> copysign(x, y) 8948 // copysign(fneg(x), y) -> copysign(x, y) 8949 // copysign(copysign(x,z), y) -> copysign(x, y) 8950 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8951 N0.getOpcode() == ISD::FCOPYSIGN) 8952 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8953 N0.getOperand(0), N1); 8954 8955 // copysign(x, abs(y)) -> abs(x) 8956 if (N1.getOpcode() == ISD::FABS) 8957 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8958 8959 // copysign(x, copysign(y,z)) -> copysign(x, z) 8960 if (N1.getOpcode() == ISD::FCOPYSIGN) 8961 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8962 N0, N1.getOperand(1)); 8963 8964 // copysign(x, fp_extend(y)) -> copysign(x, y) 8965 // copysign(x, fp_round(y)) -> copysign(x, y) 8966 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 8967 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8968 N0, N1.getOperand(0)); 8969 8970 return SDValue(); 8971 } 8972 8973 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8974 SDValue N0 = N->getOperand(0); 8975 EVT VT = N->getValueType(0); 8976 EVT OpVT = N0.getValueType(); 8977 8978 // fold (sint_to_fp c1) -> c1fp 8979 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8980 // ...but only if the target supports immediate floating-point values 8981 (!LegalOperations || 8982 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8983 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8984 8985 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8986 // but UINT_TO_FP is legal on this target, try to convert. 8987 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8988 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8989 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8990 if (DAG.SignBitIsZero(N0)) 8991 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8992 } 8993 8994 // The next optimizations are desirable only if SELECT_CC can be lowered. 8995 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8996 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8997 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8998 !VT.isVector() && 8999 (!LegalOperations || 9000 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9001 SDLoc DL(N); 9002 SDValue Ops[] = 9003 { N0.getOperand(0), N0.getOperand(1), 9004 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9005 N0.getOperand(2) }; 9006 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9007 } 9008 9009 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9010 // (select_cc x, y, 1.0, 0.0,, cc) 9011 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9012 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9013 (!LegalOperations || 9014 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9015 SDLoc DL(N); 9016 SDValue Ops[] = 9017 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9018 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9019 N0.getOperand(0).getOperand(2) }; 9020 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9021 } 9022 } 9023 9024 return SDValue(); 9025 } 9026 9027 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9028 SDValue N0 = N->getOperand(0); 9029 EVT VT = N->getValueType(0); 9030 EVT OpVT = N0.getValueType(); 9031 9032 // fold (uint_to_fp c1) -> c1fp 9033 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9034 // ...but only if the target supports immediate floating-point values 9035 (!LegalOperations || 9036 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9037 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9038 9039 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9040 // but SINT_TO_FP is legal on this target, try to convert. 9041 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9042 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9043 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9044 if (DAG.SignBitIsZero(N0)) 9045 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9046 } 9047 9048 // The next optimizations are desirable only if SELECT_CC can be lowered. 9049 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9050 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9051 9052 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9053 (!LegalOperations || 9054 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9055 SDLoc DL(N); 9056 SDValue Ops[] = 9057 { N0.getOperand(0), N0.getOperand(1), 9058 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9059 N0.getOperand(2) }; 9060 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9061 } 9062 } 9063 9064 return SDValue(); 9065 } 9066 9067 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9068 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9069 SDValue N0 = N->getOperand(0); 9070 EVT VT = N->getValueType(0); 9071 9072 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9073 return SDValue(); 9074 9075 SDValue Src = N0.getOperand(0); 9076 EVT SrcVT = Src.getValueType(); 9077 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9078 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9079 9080 // We can safely assume the conversion won't overflow the output range, 9081 // because (for example) (uint8_t)18293.f is undefined behavior. 9082 9083 // Since we can assume the conversion won't overflow, our decision as to 9084 // whether the input will fit in the float should depend on the minimum 9085 // of the input range and output range. 9086 9087 // This means this is also safe for a signed input and unsigned output, since 9088 // a negative input would lead to undefined behavior. 9089 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9090 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9091 unsigned ActualSize = std::min(InputSize, OutputSize); 9092 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9093 9094 // We can only fold away the float conversion if the input range can be 9095 // represented exactly in the float range. 9096 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9097 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9098 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9099 : ISD::ZERO_EXTEND; 9100 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9101 } 9102 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9103 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9104 return DAG.getBitcast(VT, Src); 9105 } 9106 return SDValue(); 9107 } 9108 9109 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9110 SDValue N0 = N->getOperand(0); 9111 EVT VT = N->getValueType(0); 9112 9113 // fold (fp_to_sint c1fp) -> c1 9114 if (isConstantFPBuildVectorOrConstantFP(N0)) 9115 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9116 9117 return FoldIntToFPToInt(N, DAG); 9118 } 9119 9120 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9121 SDValue N0 = N->getOperand(0); 9122 EVT VT = N->getValueType(0); 9123 9124 // fold (fp_to_uint c1fp) -> c1 9125 if (isConstantFPBuildVectorOrConstantFP(N0)) 9126 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9127 9128 return FoldIntToFPToInt(N, DAG); 9129 } 9130 9131 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9132 SDValue N0 = N->getOperand(0); 9133 SDValue N1 = N->getOperand(1); 9134 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9135 EVT VT = N->getValueType(0); 9136 9137 // fold (fp_round c1fp) -> c1fp 9138 if (N0CFP) 9139 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9140 9141 // fold (fp_round (fp_extend x)) -> x 9142 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9143 return N0.getOperand(0); 9144 9145 // fold (fp_round (fp_round x)) -> (fp_round x) 9146 if (N0.getOpcode() == ISD::FP_ROUND) { 9147 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9148 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9149 9150 // Skip this folding if it results in an fp_round from f80 to f16. 9151 // 9152 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9153 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9154 // instructions from f32 or f64. Moreover, the first (value-preserving) 9155 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9156 // x86. 9157 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9158 return SDValue(); 9159 9160 // If the first fp_round isn't a value preserving truncation, it might 9161 // introduce a tie in the second fp_round, that wouldn't occur in the 9162 // single-step fp_round we want to fold to. 9163 // In other words, double rounding isn't the same as rounding. 9164 // Also, this is a value preserving truncation iff both fp_round's are. 9165 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9166 SDLoc DL(N); 9167 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9168 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9169 } 9170 } 9171 9172 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9173 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9174 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9175 N0.getOperand(0), N1); 9176 AddToWorklist(Tmp.getNode()); 9177 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9178 Tmp, N0.getOperand(1)); 9179 } 9180 9181 return SDValue(); 9182 } 9183 9184 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9185 SDValue N0 = N->getOperand(0); 9186 EVT VT = N->getValueType(0); 9187 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9188 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9189 9190 // fold (fp_round_inreg c1fp) -> c1fp 9191 if (N0CFP && isTypeLegal(EVT)) { 9192 SDLoc DL(N); 9193 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9194 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9195 } 9196 9197 return SDValue(); 9198 } 9199 9200 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9201 SDValue N0 = N->getOperand(0); 9202 EVT VT = N->getValueType(0); 9203 9204 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9205 if (N->hasOneUse() && 9206 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9207 return SDValue(); 9208 9209 // fold (fp_extend c1fp) -> c1fp 9210 if (isConstantFPBuildVectorOrConstantFP(N0)) 9211 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9212 9213 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9214 if (N0.getOpcode() == ISD::FP16_TO_FP && 9215 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9216 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9217 9218 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9219 // value of X. 9220 if (N0.getOpcode() == ISD::FP_ROUND 9221 && N0.getNode()->getConstantOperandVal(1) == 1) { 9222 SDValue In = N0.getOperand(0); 9223 if (In.getValueType() == VT) return In; 9224 if (VT.bitsLT(In.getValueType())) 9225 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9226 In, N0.getOperand(1)); 9227 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9228 } 9229 9230 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9231 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9232 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9233 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9234 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9235 LN0->getChain(), 9236 LN0->getBasePtr(), N0.getValueType(), 9237 LN0->getMemOperand()); 9238 CombineTo(N, ExtLoad); 9239 CombineTo(N0.getNode(), 9240 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9241 N0.getValueType(), ExtLoad, 9242 DAG.getIntPtrConstant(1, SDLoc(N0))), 9243 ExtLoad.getValue(1)); 9244 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9245 } 9246 9247 return SDValue(); 9248 } 9249 9250 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9251 SDValue N0 = N->getOperand(0); 9252 EVT VT = N->getValueType(0); 9253 9254 // fold (fceil c1) -> fceil(c1) 9255 if (isConstantFPBuildVectorOrConstantFP(N0)) 9256 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9257 9258 return SDValue(); 9259 } 9260 9261 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9262 SDValue N0 = N->getOperand(0); 9263 EVT VT = N->getValueType(0); 9264 9265 // fold (ftrunc c1) -> ftrunc(c1) 9266 if (isConstantFPBuildVectorOrConstantFP(N0)) 9267 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9268 9269 return SDValue(); 9270 } 9271 9272 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9273 SDValue N0 = N->getOperand(0); 9274 EVT VT = N->getValueType(0); 9275 9276 // fold (ffloor c1) -> ffloor(c1) 9277 if (isConstantFPBuildVectorOrConstantFP(N0)) 9278 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9279 9280 return SDValue(); 9281 } 9282 9283 // FIXME: FNEG and FABS have a lot in common; refactor. 9284 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9285 SDValue N0 = N->getOperand(0); 9286 EVT VT = N->getValueType(0); 9287 9288 // Constant fold FNEG. 9289 if (isConstantFPBuildVectorOrConstantFP(N0)) 9290 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9291 9292 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9293 &DAG.getTarget().Options)) 9294 return GetNegatedExpression(N0, DAG, LegalOperations); 9295 9296 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9297 // constant pool values. 9298 if (!TLI.isFNegFree(VT) && 9299 N0.getOpcode() == ISD::BITCAST && 9300 N0.getNode()->hasOneUse()) { 9301 SDValue Int = N0.getOperand(0); 9302 EVT IntVT = Int.getValueType(); 9303 if (IntVT.isInteger() && !IntVT.isVector()) { 9304 APInt SignMask; 9305 if (N0.getValueType().isVector()) { 9306 // For a vector, get a mask such as 0x80... per scalar element 9307 // and splat it. 9308 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9309 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9310 } else { 9311 // For a scalar, just generate 0x80... 9312 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9313 } 9314 SDLoc DL0(N0); 9315 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9316 DAG.getConstant(SignMask, DL0, IntVT)); 9317 AddToWorklist(Int.getNode()); 9318 return DAG.getBitcast(VT, Int); 9319 } 9320 } 9321 9322 // (fneg (fmul c, x)) -> (fmul -c, x) 9323 if (N0.getOpcode() == ISD::FMUL && 9324 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9325 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9326 if (CFP1) { 9327 APFloat CVal = CFP1->getValueAPF(); 9328 CVal.changeSign(); 9329 if (Level >= AfterLegalizeDAG && 9330 (TLI.isFPImmLegal(CVal, VT) || 9331 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9332 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9333 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9334 N0.getOperand(1)), 9335 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9336 } 9337 } 9338 9339 return SDValue(); 9340 } 9341 9342 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9343 SDValue N0 = N->getOperand(0); 9344 SDValue N1 = N->getOperand(1); 9345 EVT VT = N->getValueType(0); 9346 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9347 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9348 9349 if (N0CFP && N1CFP) { 9350 const APFloat &C0 = N0CFP->getValueAPF(); 9351 const APFloat &C1 = N1CFP->getValueAPF(); 9352 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9353 } 9354 9355 // Canonicalize to constant on RHS. 9356 if (isConstantFPBuildVectorOrConstantFP(N0) && 9357 !isConstantFPBuildVectorOrConstantFP(N1)) 9358 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9359 9360 return SDValue(); 9361 } 9362 9363 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9364 SDValue N0 = N->getOperand(0); 9365 SDValue N1 = N->getOperand(1); 9366 EVT VT = N->getValueType(0); 9367 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9368 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9369 9370 if (N0CFP && N1CFP) { 9371 const APFloat &C0 = N0CFP->getValueAPF(); 9372 const APFloat &C1 = N1CFP->getValueAPF(); 9373 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9374 } 9375 9376 // Canonicalize to constant on RHS. 9377 if (isConstantFPBuildVectorOrConstantFP(N0) && 9378 !isConstantFPBuildVectorOrConstantFP(N1)) 9379 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9380 9381 return SDValue(); 9382 } 9383 9384 SDValue DAGCombiner::visitFABS(SDNode *N) { 9385 SDValue N0 = N->getOperand(0); 9386 EVT VT = N->getValueType(0); 9387 9388 // fold (fabs c1) -> fabs(c1) 9389 if (isConstantFPBuildVectorOrConstantFP(N0)) 9390 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9391 9392 // fold (fabs (fabs x)) -> (fabs x) 9393 if (N0.getOpcode() == ISD::FABS) 9394 return N->getOperand(0); 9395 9396 // fold (fabs (fneg x)) -> (fabs x) 9397 // fold (fabs (fcopysign x, y)) -> (fabs x) 9398 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9399 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9400 9401 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9402 // constant pool values. 9403 if (!TLI.isFAbsFree(VT) && 9404 N0.getOpcode() == ISD::BITCAST && 9405 N0.getNode()->hasOneUse()) { 9406 SDValue Int = N0.getOperand(0); 9407 EVT IntVT = Int.getValueType(); 9408 if (IntVT.isInteger() && !IntVT.isVector()) { 9409 APInt SignMask; 9410 if (N0.getValueType().isVector()) { 9411 // For a vector, get a mask such as 0x7f... per scalar element 9412 // and splat it. 9413 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9414 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9415 } else { 9416 // For a scalar, just generate 0x7f... 9417 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9418 } 9419 SDLoc DL(N0); 9420 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9421 DAG.getConstant(SignMask, DL, IntVT)); 9422 AddToWorklist(Int.getNode()); 9423 return DAG.getBitcast(N->getValueType(0), Int); 9424 } 9425 } 9426 9427 return SDValue(); 9428 } 9429 9430 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9431 SDValue Chain = N->getOperand(0); 9432 SDValue N1 = N->getOperand(1); 9433 SDValue N2 = N->getOperand(2); 9434 9435 // If N is a constant we could fold this into a fallthrough or unconditional 9436 // branch. However that doesn't happen very often in normal code, because 9437 // Instcombine/SimplifyCFG should have handled the available opportunities. 9438 // If we did this folding here, it would be necessary to update the 9439 // MachineBasicBlock CFG, which is awkward. 9440 9441 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9442 // on the target. 9443 if (N1.getOpcode() == ISD::SETCC && 9444 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9445 N1.getOperand(0).getValueType())) { 9446 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9447 Chain, N1.getOperand(2), 9448 N1.getOperand(0), N1.getOperand(1), N2); 9449 } 9450 9451 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9452 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9453 (N1.getOperand(0).hasOneUse() && 9454 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9455 SDNode *Trunc = nullptr; 9456 if (N1.getOpcode() == ISD::TRUNCATE) { 9457 // Look pass the truncate. 9458 Trunc = N1.getNode(); 9459 N1 = N1.getOperand(0); 9460 } 9461 9462 // Match this pattern so that we can generate simpler code: 9463 // 9464 // %a = ... 9465 // %b = and i32 %a, 2 9466 // %c = srl i32 %b, 1 9467 // brcond i32 %c ... 9468 // 9469 // into 9470 // 9471 // %a = ... 9472 // %b = and i32 %a, 2 9473 // %c = setcc eq %b, 0 9474 // brcond %c ... 9475 // 9476 // This applies only when the AND constant value has one bit set and the 9477 // SRL constant is equal to the log2 of the AND constant. The back-end is 9478 // smart enough to convert the result into a TEST/JMP sequence. 9479 SDValue Op0 = N1.getOperand(0); 9480 SDValue Op1 = N1.getOperand(1); 9481 9482 if (Op0.getOpcode() == ISD::AND && 9483 Op1.getOpcode() == ISD::Constant) { 9484 SDValue AndOp1 = Op0.getOperand(1); 9485 9486 if (AndOp1.getOpcode() == ISD::Constant) { 9487 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9488 9489 if (AndConst.isPowerOf2() && 9490 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9491 SDLoc DL(N); 9492 SDValue SetCC = 9493 DAG.getSetCC(DL, 9494 getSetCCResultType(Op0.getValueType()), 9495 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9496 ISD::SETNE); 9497 9498 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9499 MVT::Other, Chain, SetCC, N2); 9500 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9501 // will convert it back to (X & C1) >> C2. 9502 CombineTo(N, NewBRCond, false); 9503 // Truncate is dead. 9504 if (Trunc) 9505 deleteAndRecombine(Trunc); 9506 // Replace the uses of SRL with SETCC 9507 WorklistRemover DeadNodes(*this); 9508 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9509 deleteAndRecombine(N1.getNode()); 9510 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9511 } 9512 } 9513 } 9514 9515 if (Trunc) 9516 // Restore N1 if the above transformation doesn't match. 9517 N1 = N->getOperand(1); 9518 } 9519 9520 // Transform br(xor(x, y)) -> br(x != y) 9521 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9522 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9523 SDNode *TheXor = N1.getNode(); 9524 SDValue Op0 = TheXor->getOperand(0); 9525 SDValue Op1 = TheXor->getOperand(1); 9526 if (Op0.getOpcode() == Op1.getOpcode()) { 9527 // Avoid missing important xor optimizations. 9528 if (SDValue Tmp = visitXOR(TheXor)) { 9529 if (Tmp.getNode() != TheXor) { 9530 DEBUG(dbgs() << "\nReplacing.8 "; 9531 TheXor->dump(&DAG); 9532 dbgs() << "\nWith: "; 9533 Tmp.getNode()->dump(&DAG); 9534 dbgs() << '\n'); 9535 WorklistRemover DeadNodes(*this); 9536 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9537 deleteAndRecombine(TheXor); 9538 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9539 MVT::Other, Chain, Tmp, N2); 9540 } 9541 9542 // visitXOR has changed XOR's operands or replaced the XOR completely, 9543 // bail out. 9544 return SDValue(N, 0); 9545 } 9546 } 9547 9548 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9549 bool Equal = false; 9550 if (isOneConstant(Op0) && Op0.hasOneUse() && 9551 Op0.getOpcode() == ISD::XOR) { 9552 TheXor = Op0.getNode(); 9553 Equal = true; 9554 } 9555 9556 EVT SetCCVT = N1.getValueType(); 9557 if (LegalTypes) 9558 SetCCVT = getSetCCResultType(SetCCVT); 9559 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9560 SetCCVT, 9561 Op0, Op1, 9562 Equal ? ISD::SETEQ : ISD::SETNE); 9563 // Replace the uses of XOR with SETCC 9564 WorklistRemover DeadNodes(*this); 9565 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9566 deleteAndRecombine(N1.getNode()); 9567 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9568 MVT::Other, Chain, SetCC, N2); 9569 } 9570 } 9571 9572 return SDValue(); 9573 } 9574 9575 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9576 // 9577 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9578 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9579 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9580 9581 // If N is a constant we could fold this into a fallthrough or unconditional 9582 // branch. However that doesn't happen very often in normal code, because 9583 // Instcombine/SimplifyCFG should have handled the available opportunities. 9584 // If we did this folding here, it would be necessary to update the 9585 // MachineBasicBlock CFG, which is awkward. 9586 9587 // Use SimplifySetCC to simplify SETCC's. 9588 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9589 CondLHS, CondRHS, CC->get(), SDLoc(N), 9590 false); 9591 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9592 9593 // fold to a simpler setcc 9594 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9595 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9596 N->getOperand(0), Simp.getOperand(2), 9597 Simp.getOperand(0), Simp.getOperand(1), 9598 N->getOperand(4)); 9599 9600 return SDValue(); 9601 } 9602 9603 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9604 /// and that N may be folded in the load / store addressing mode. 9605 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9606 SelectionDAG &DAG, 9607 const TargetLowering &TLI) { 9608 EVT VT; 9609 unsigned AS; 9610 9611 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9612 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9613 return false; 9614 VT = LD->getMemoryVT(); 9615 AS = LD->getAddressSpace(); 9616 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9617 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9618 return false; 9619 VT = ST->getMemoryVT(); 9620 AS = ST->getAddressSpace(); 9621 } else 9622 return false; 9623 9624 TargetLowering::AddrMode AM; 9625 if (N->getOpcode() == ISD::ADD) { 9626 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9627 if (Offset) 9628 // [reg +/- imm] 9629 AM.BaseOffs = Offset->getSExtValue(); 9630 else 9631 // [reg +/- reg] 9632 AM.Scale = 1; 9633 } else if (N->getOpcode() == ISD::SUB) { 9634 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9635 if (Offset) 9636 // [reg +/- imm] 9637 AM.BaseOffs = -Offset->getSExtValue(); 9638 else 9639 // [reg +/- reg] 9640 AM.Scale = 1; 9641 } else 9642 return false; 9643 9644 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9645 VT.getTypeForEVT(*DAG.getContext()), AS); 9646 } 9647 9648 /// Try turning a load/store into a pre-indexed load/store when the base 9649 /// pointer is an add or subtract and it has other uses besides the load/store. 9650 /// After the transformation, the new indexed load/store has effectively folded 9651 /// the add/subtract in and all of its other uses are redirected to the 9652 /// new load/store. 9653 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9654 if (Level < AfterLegalizeDAG) 9655 return false; 9656 9657 bool isLoad = true; 9658 SDValue Ptr; 9659 EVT VT; 9660 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9661 if (LD->isIndexed()) 9662 return false; 9663 VT = LD->getMemoryVT(); 9664 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9665 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9666 return false; 9667 Ptr = LD->getBasePtr(); 9668 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9669 if (ST->isIndexed()) 9670 return false; 9671 VT = ST->getMemoryVT(); 9672 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9673 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9674 return false; 9675 Ptr = ST->getBasePtr(); 9676 isLoad = false; 9677 } else { 9678 return false; 9679 } 9680 9681 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9682 // out. There is no reason to make this a preinc/predec. 9683 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9684 Ptr.getNode()->hasOneUse()) 9685 return false; 9686 9687 // Ask the target to do addressing mode selection. 9688 SDValue BasePtr; 9689 SDValue Offset; 9690 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9691 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9692 return false; 9693 9694 // Backends without true r+i pre-indexed forms may need to pass a 9695 // constant base with a variable offset so that constant coercion 9696 // will work with the patterns in canonical form. 9697 bool Swapped = false; 9698 if (isa<ConstantSDNode>(BasePtr)) { 9699 std::swap(BasePtr, Offset); 9700 Swapped = true; 9701 } 9702 9703 // Don't create a indexed load / store with zero offset. 9704 if (isNullConstant(Offset)) 9705 return false; 9706 9707 // Try turning it into a pre-indexed load / store except when: 9708 // 1) The new base ptr is a frame index. 9709 // 2) If N is a store and the new base ptr is either the same as or is a 9710 // predecessor of the value being stored. 9711 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9712 // that would create a cycle. 9713 // 4) All uses are load / store ops that use it as old base ptr. 9714 9715 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9716 // (plus the implicit offset) to a register to preinc anyway. 9717 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9718 return false; 9719 9720 // Check #2. 9721 if (!isLoad) { 9722 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9723 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9724 return false; 9725 } 9726 9727 // Caches for hasPredecessorHelper. 9728 SmallPtrSet<const SDNode *, 32> Visited; 9729 SmallVector<const SDNode *, 16> Worklist; 9730 Worklist.push_back(N); 9731 9732 // If the offset is a constant, there may be other adds of constants that 9733 // can be folded with this one. We should do this to avoid having to keep 9734 // a copy of the original base pointer. 9735 SmallVector<SDNode *, 16> OtherUses; 9736 if (isa<ConstantSDNode>(Offset)) 9737 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9738 UE = BasePtr.getNode()->use_end(); 9739 UI != UE; ++UI) { 9740 SDUse &Use = UI.getUse(); 9741 // Skip the use that is Ptr and uses of other results from BasePtr's 9742 // node (important for nodes that return multiple results). 9743 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9744 continue; 9745 9746 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9747 continue; 9748 9749 if (Use.getUser()->getOpcode() != ISD::ADD && 9750 Use.getUser()->getOpcode() != ISD::SUB) { 9751 OtherUses.clear(); 9752 break; 9753 } 9754 9755 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9756 if (!isa<ConstantSDNode>(Op1)) { 9757 OtherUses.clear(); 9758 break; 9759 } 9760 9761 // FIXME: In some cases, we can be smarter about this. 9762 if (Op1.getValueType() != Offset.getValueType()) { 9763 OtherUses.clear(); 9764 break; 9765 } 9766 9767 OtherUses.push_back(Use.getUser()); 9768 } 9769 9770 if (Swapped) 9771 std::swap(BasePtr, Offset); 9772 9773 // Now check for #3 and #4. 9774 bool RealUse = false; 9775 9776 for (SDNode *Use : Ptr.getNode()->uses()) { 9777 if (Use == N) 9778 continue; 9779 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9780 return false; 9781 9782 // If Ptr may be folded in addressing mode of other use, then it's 9783 // not profitable to do this transformation. 9784 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9785 RealUse = true; 9786 } 9787 9788 if (!RealUse) 9789 return false; 9790 9791 SDValue Result; 9792 if (isLoad) 9793 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9794 BasePtr, Offset, AM); 9795 else 9796 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9797 BasePtr, Offset, AM); 9798 ++PreIndexedNodes; 9799 ++NodesCombined; 9800 DEBUG(dbgs() << "\nReplacing.4 "; 9801 N->dump(&DAG); 9802 dbgs() << "\nWith: "; 9803 Result.getNode()->dump(&DAG); 9804 dbgs() << '\n'); 9805 WorklistRemover DeadNodes(*this); 9806 if (isLoad) { 9807 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9808 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9809 } else { 9810 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9811 } 9812 9813 // Finally, since the node is now dead, remove it from the graph. 9814 deleteAndRecombine(N); 9815 9816 if (Swapped) 9817 std::swap(BasePtr, Offset); 9818 9819 // Replace other uses of BasePtr that can be updated to use Ptr 9820 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9821 unsigned OffsetIdx = 1; 9822 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9823 OffsetIdx = 0; 9824 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9825 BasePtr.getNode() && "Expected BasePtr operand"); 9826 9827 // We need to replace ptr0 in the following expression: 9828 // x0 * offset0 + y0 * ptr0 = t0 9829 // knowing that 9830 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9831 // 9832 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9833 // indexed load/store and the expresion that needs to be re-written. 9834 // 9835 // Therefore, we have: 9836 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9837 9838 ConstantSDNode *CN = 9839 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9840 int X0, X1, Y0, Y1; 9841 const APInt &Offset0 = CN->getAPIntValue(); 9842 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9843 9844 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9845 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9846 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9847 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9848 9849 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9850 9851 APInt CNV = Offset0; 9852 if (X0 < 0) CNV = -CNV; 9853 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9854 else CNV = CNV - Offset1; 9855 9856 SDLoc DL(OtherUses[i]); 9857 9858 // We can now generate the new expression. 9859 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9860 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9861 9862 SDValue NewUse = DAG.getNode(Opcode, 9863 DL, 9864 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9865 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9866 deleteAndRecombine(OtherUses[i]); 9867 } 9868 9869 // Replace the uses of Ptr with uses of the updated base value. 9870 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9871 deleteAndRecombine(Ptr.getNode()); 9872 9873 return true; 9874 } 9875 9876 /// Try to combine a load/store with a add/sub of the base pointer node into a 9877 /// post-indexed load/store. The transformation folded the add/subtract into the 9878 /// new indexed load/store effectively and all of its uses are redirected to the 9879 /// new load/store. 9880 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9881 if (Level < AfterLegalizeDAG) 9882 return false; 9883 9884 bool isLoad = true; 9885 SDValue Ptr; 9886 EVT VT; 9887 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9888 if (LD->isIndexed()) 9889 return false; 9890 VT = LD->getMemoryVT(); 9891 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9892 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9893 return false; 9894 Ptr = LD->getBasePtr(); 9895 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9896 if (ST->isIndexed()) 9897 return false; 9898 VT = ST->getMemoryVT(); 9899 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9900 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9901 return false; 9902 Ptr = ST->getBasePtr(); 9903 isLoad = false; 9904 } else { 9905 return false; 9906 } 9907 9908 if (Ptr.getNode()->hasOneUse()) 9909 return false; 9910 9911 for (SDNode *Op : Ptr.getNode()->uses()) { 9912 if (Op == N || 9913 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9914 continue; 9915 9916 SDValue BasePtr; 9917 SDValue Offset; 9918 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9919 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9920 // Don't create a indexed load / store with zero offset. 9921 if (isNullConstant(Offset)) 9922 continue; 9923 9924 // Try turning it into a post-indexed load / store except when 9925 // 1) All uses are load / store ops that use it as base ptr (and 9926 // it may be folded as addressing mmode). 9927 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9928 // nor a successor of N. Otherwise, if Op is folded that would 9929 // create a cycle. 9930 9931 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9932 continue; 9933 9934 // Check for #1. 9935 bool TryNext = false; 9936 for (SDNode *Use : BasePtr.getNode()->uses()) { 9937 if (Use == Ptr.getNode()) 9938 continue; 9939 9940 // If all the uses are load / store addresses, then don't do the 9941 // transformation. 9942 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9943 bool RealUse = false; 9944 for (SDNode *UseUse : Use->uses()) { 9945 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9946 RealUse = true; 9947 } 9948 9949 if (!RealUse) { 9950 TryNext = true; 9951 break; 9952 } 9953 } 9954 } 9955 9956 if (TryNext) 9957 continue; 9958 9959 // Check for #2 9960 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9961 SDValue Result = isLoad 9962 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9963 BasePtr, Offset, AM) 9964 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9965 BasePtr, Offset, AM); 9966 ++PostIndexedNodes; 9967 ++NodesCombined; 9968 DEBUG(dbgs() << "\nReplacing.5 "; 9969 N->dump(&DAG); 9970 dbgs() << "\nWith: "; 9971 Result.getNode()->dump(&DAG); 9972 dbgs() << '\n'); 9973 WorklistRemover DeadNodes(*this); 9974 if (isLoad) { 9975 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9976 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9977 } else { 9978 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9979 } 9980 9981 // Finally, since the node is now dead, remove it from the graph. 9982 deleteAndRecombine(N); 9983 9984 // Replace the uses of Use with uses of the updated base value. 9985 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9986 Result.getValue(isLoad ? 1 : 0)); 9987 deleteAndRecombine(Op); 9988 return true; 9989 } 9990 } 9991 } 9992 9993 return false; 9994 } 9995 9996 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9997 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9998 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9999 assert(AM != ISD::UNINDEXED); 10000 SDValue BP = LD->getOperand(1); 10001 SDValue Inc = LD->getOperand(2); 10002 10003 // Some backends use TargetConstants for load offsets, but don't expect 10004 // TargetConstants in general ADD nodes. We can convert these constants into 10005 // regular Constants (if the constant is not opaque). 10006 assert((Inc.getOpcode() != ISD::TargetConstant || 10007 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10008 "Cannot split out indexing using opaque target constants"); 10009 if (Inc.getOpcode() == ISD::TargetConstant) { 10010 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10011 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10012 ConstInc->getValueType(0)); 10013 } 10014 10015 unsigned Opc = 10016 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10017 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10018 } 10019 10020 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10021 LoadSDNode *LD = cast<LoadSDNode>(N); 10022 SDValue Chain = LD->getChain(); 10023 SDValue Ptr = LD->getBasePtr(); 10024 10025 // If load is not volatile and there are no uses of the loaded value (and 10026 // the updated indexed value in case of indexed loads), change uses of the 10027 // chain value into uses of the chain input (i.e. delete the dead load). 10028 if (!LD->isVolatile()) { 10029 if (N->getValueType(1) == MVT::Other) { 10030 // Unindexed loads. 10031 if (!N->hasAnyUseOfValue(0)) { 10032 // It's not safe to use the two value CombineTo variant here. e.g. 10033 // v1, chain2 = load chain1, loc 10034 // v2, chain3 = load chain2, loc 10035 // v3 = add v2, c 10036 // Now we replace use of chain2 with chain1. This makes the second load 10037 // isomorphic to the one we are deleting, and thus makes this load live. 10038 DEBUG(dbgs() << "\nReplacing.6 "; 10039 N->dump(&DAG); 10040 dbgs() << "\nWith chain: "; 10041 Chain.getNode()->dump(&DAG); 10042 dbgs() << "\n"); 10043 WorklistRemover DeadNodes(*this); 10044 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10045 10046 if (N->use_empty()) 10047 deleteAndRecombine(N); 10048 10049 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10050 } 10051 } else { 10052 // Indexed loads. 10053 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10054 10055 // If this load has an opaque TargetConstant offset, then we cannot split 10056 // the indexing into an add/sub directly (that TargetConstant may not be 10057 // valid for a different type of node, and we cannot convert an opaque 10058 // target constant into a regular constant). 10059 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10060 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10061 10062 if (!N->hasAnyUseOfValue(0) && 10063 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10064 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10065 SDValue Index; 10066 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10067 Index = SplitIndexingFromLoad(LD); 10068 // Try to fold the base pointer arithmetic into subsequent loads and 10069 // stores. 10070 AddUsersToWorklist(N); 10071 } else 10072 Index = DAG.getUNDEF(N->getValueType(1)); 10073 DEBUG(dbgs() << "\nReplacing.7 "; 10074 N->dump(&DAG); 10075 dbgs() << "\nWith: "; 10076 Undef.getNode()->dump(&DAG); 10077 dbgs() << " and 2 other values\n"); 10078 WorklistRemover DeadNodes(*this); 10079 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10080 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10081 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10082 deleteAndRecombine(N); 10083 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10084 } 10085 } 10086 } 10087 10088 // If this load is directly stored, replace the load value with the stored 10089 // value. 10090 // TODO: Handle store large -> read small portion. 10091 // TODO: Handle TRUNCSTORE/LOADEXT 10092 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 10093 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10094 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10095 if (PrevST->getBasePtr() == Ptr && 10096 PrevST->getValue().getValueType() == N->getValueType(0)) 10097 return CombineTo(N, Chain.getOperand(1), Chain); 10098 } 10099 } 10100 10101 // Try to infer better alignment information than the load already has. 10102 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10103 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10104 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10105 SDValue NewLoad = DAG.getExtLoad( 10106 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10107 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10108 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10109 if (NewLoad.getNode() != N) 10110 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10111 } 10112 } 10113 } 10114 10115 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10116 : DAG.getSubtarget().useAA(); 10117 #ifndef NDEBUG 10118 if (CombinerAAOnlyFunc.getNumOccurrences() && 10119 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10120 UseAA = false; 10121 #endif 10122 if (UseAA && LD->isUnindexed()) { 10123 // Walk up chain skipping non-aliasing memory nodes. 10124 SDValue BetterChain = FindBetterChain(N, Chain); 10125 10126 // If there is a better chain. 10127 if (Chain != BetterChain) { 10128 SDValue ReplLoad; 10129 10130 // Replace the chain to void dependency. 10131 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10132 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10133 BetterChain, Ptr, LD->getMemOperand()); 10134 } else { 10135 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10136 LD->getValueType(0), 10137 BetterChain, Ptr, LD->getMemoryVT(), 10138 LD->getMemOperand()); 10139 } 10140 10141 // Create token factor to keep old chain connected. 10142 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10143 MVT::Other, Chain, ReplLoad.getValue(1)); 10144 10145 // Make sure the new and old chains are cleaned up. 10146 AddToWorklist(Token.getNode()); 10147 10148 // Replace uses with load result and token factor. Don't add users 10149 // to work list. 10150 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10151 } 10152 } 10153 10154 // Try transforming N to an indexed load. 10155 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10156 return SDValue(N, 0); 10157 10158 // Try to slice up N to more direct loads if the slices are mapped to 10159 // different register banks or pairing can take place. 10160 if (SliceUpLoad(N)) 10161 return SDValue(N, 0); 10162 10163 return SDValue(); 10164 } 10165 10166 namespace { 10167 /// \brief Helper structure used to slice a load in smaller loads. 10168 /// Basically a slice is obtained from the following sequence: 10169 /// Origin = load Ty1, Base 10170 /// Shift = srl Ty1 Origin, CstTy Amount 10171 /// Inst = trunc Shift to Ty2 10172 /// 10173 /// Then, it will be rewriten into: 10174 /// Slice = load SliceTy, Base + SliceOffset 10175 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10176 /// 10177 /// SliceTy is deduced from the number of bits that are actually used to 10178 /// build Inst. 10179 struct LoadedSlice { 10180 /// \brief Helper structure used to compute the cost of a slice. 10181 struct Cost { 10182 /// Are we optimizing for code size. 10183 bool ForCodeSize; 10184 /// Various cost. 10185 unsigned Loads; 10186 unsigned Truncates; 10187 unsigned CrossRegisterBanksCopies; 10188 unsigned ZExts; 10189 unsigned Shift; 10190 10191 Cost(bool ForCodeSize = false) 10192 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10193 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10194 10195 /// \brief Get the cost of one isolated slice. 10196 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10197 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10198 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10199 EVT TruncType = LS.Inst->getValueType(0); 10200 EVT LoadedType = LS.getLoadedType(); 10201 if (TruncType != LoadedType && 10202 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10203 ZExts = 1; 10204 } 10205 10206 /// \brief Account for slicing gain in the current cost. 10207 /// Slicing provide a few gains like removing a shift or a 10208 /// truncate. This method allows to grow the cost of the original 10209 /// load with the gain from this slice. 10210 void addSliceGain(const LoadedSlice &LS) { 10211 // Each slice saves a truncate. 10212 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10213 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10214 LS.Inst->getValueType(0))) 10215 ++Truncates; 10216 // If there is a shift amount, this slice gets rid of it. 10217 if (LS.Shift) 10218 ++Shift; 10219 // If this slice can merge a cross register bank copy, account for it. 10220 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10221 ++CrossRegisterBanksCopies; 10222 } 10223 10224 Cost &operator+=(const Cost &RHS) { 10225 Loads += RHS.Loads; 10226 Truncates += RHS.Truncates; 10227 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10228 ZExts += RHS.ZExts; 10229 Shift += RHS.Shift; 10230 return *this; 10231 } 10232 10233 bool operator==(const Cost &RHS) const { 10234 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10235 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10236 ZExts == RHS.ZExts && Shift == RHS.Shift; 10237 } 10238 10239 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10240 10241 bool operator<(const Cost &RHS) const { 10242 // Assume cross register banks copies are as expensive as loads. 10243 // FIXME: Do we want some more target hooks? 10244 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10245 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10246 // Unless we are optimizing for code size, consider the 10247 // expensive operation first. 10248 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10249 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10250 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10251 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10252 } 10253 10254 bool operator>(const Cost &RHS) const { return RHS < *this; } 10255 10256 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10257 10258 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10259 }; 10260 // The last instruction that represent the slice. This should be a 10261 // truncate instruction. 10262 SDNode *Inst; 10263 // The original load instruction. 10264 LoadSDNode *Origin; 10265 // The right shift amount in bits from the original load. 10266 unsigned Shift; 10267 // The DAG from which Origin came from. 10268 // This is used to get some contextual information about legal types, etc. 10269 SelectionDAG *DAG; 10270 10271 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10272 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10273 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10274 10275 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10276 /// \return Result is \p BitWidth and has used bits set to 1 and 10277 /// not used bits set to 0. 10278 APInt getUsedBits() const { 10279 // Reproduce the trunc(lshr) sequence: 10280 // - Start from the truncated value. 10281 // - Zero extend to the desired bit width. 10282 // - Shift left. 10283 assert(Origin && "No original load to compare against."); 10284 unsigned BitWidth = Origin->getValueSizeInBits(0); 10285 assert(Inst && "This slice is not bound to an instruction"); 10286 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10287 "Extracted slice is bigger than the whole type!"); 10288 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10289 UsedBits.setAllBits(); 10290 UsedBits = UsedBits.zext(BitWidth); 10291 UsedBits <<= Shift; 10292 return UsedBits; 10293 } 10294 10295 /// \brief Get the size of the slice to be loaded in bytes. 10296 unsigned getLoadedSize() const { 10297 unsigned SliceSize = getUsedBits().countPopulation(); 10298 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10299 return SliceSize / 8; 10300 } 10301 10302 /// \brief Get the type that will be loaded for this slice. 10303 /// Note: This may not be the final type for the slice. 10304 EVT getLoadedType() const { 10305 assert(DAG && "Missing context"); 10306 LLVMContext &Ctxt = *DAG->getContext(); 10307 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10308 } 10309 10310 /// \brief Get the alignment of the load used for this slice. 10311 unsigned getAlignment() const { 10312 unsigned Alignment = Origin->getAlignment(); 10313 unsigned Offset = getOffsetFromBase(); 10314 if (Offset != 0) 10315 Alignment = MinAlign(Alignment, Alignment + Offset); 10316 return Alignment; 10317 } 10318 10319 /// \brief Check if this slice can be rewritten with legal operations. 10320 bool isLegal() const { 10321 // An invalid slice is not legal. 10322 if (!Origin || !Inst || !DAG) 10323 return false; 10324 10325 // Offsets are for indexed load only, we do not handle that. 10326 if (!Origin->getOffset().isUndef()) 10327 return false; 10328 10329 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10330 10331 // Check that the type is legal. 10332 EVT SliceType = getLoadedType(); 10333 if (!TLI.isTypeLegal(SliceType)) 10334 return false; 10335 10336 // Check that the load is legal for this type. 10337 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10338 return false; 10339 10340 // Check that the offset can be computed. 10341 // 1. Check its type. 10342 EVT PtrType = Origin->getBasePtr().getValueType(); 10343 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10344 return false; 10345 10346 // 2. Check that it fits in the immediate. 10347 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10348 return false; 10349 10350 // 3. Check that the computation is legal. 10351 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10352 return false; 10353 10354 // Check that the zext is legal if it needs one. 10355 EVT TruncateType = Inst->getValueType(0); 10356 if (TruncateType != SliceType && 10357 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10358 return false; 10359 10360 return true; 10361 } 10362 10363 /// \brief Get the offset in bytes of this slice in the original chunk of 10364 /// bits. 10365 /// \pre DAG != nullptr. 10366 uint64_t getOffsetFromBase() const { 10367 assert(DAG && "Missing context."); 10368 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10369 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10370 uint64_t Offset = Shift / 8; 10371 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10372 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10373 "The size of the original loaded type is not a multiple of a" 10374 " byte."); 10375 // If Offset is bigger than TySizeInBytes, it means we are loading all 10376 // zeros. This should have been optimized before in the process. 10377 assert(TySizeInBytes > Offset && 10378 "Invalid shift amount for given loaded size"); 10379 if (IsBigEndian) 10380 Offset = TySizeInBytes - Offset - getLoadedSize(); 10381 return Offset; 10382 } 10383 10384 /// \brief Generate the sequence of instructions to load the slice 10385 /// represented by this object and redirect the uses of this slice to 10386 /// this new sequence of instructions. 10387 /// \pre this->Inst && this->Origin are valid Instructions and this 10388 /// object passed the legal check: LoadedSlice::isLegal returned true. 10389 /// \return The last instruction of the sequence used to load the slice. 10390 SDValue loadSlice() const { 10391 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10392 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10393 SDValue BaseAddr = OldBaseAddr; 10394 // Get the offset in that chunk of bytes w.r.t. the endianess. 10395 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10396 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10397 if (Offset) { 10398 // BaseAddr = BaseAddr + Offset. 10399 EVT ArithType = BaseAddr.getValueType(); 10400 SDLoc DL(Origin); 10401 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10402 DAG->getConstant(Offset, DL, ArithType)); 10403 } 10404 10405 // Create the type of the loaded slice according to its size. 10406 EVT SliceType = getLoadedType(); 10407 10408 // Create the load for the slice. 10409 SDValue LastInst = 10410 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10411 Origin->getPointerInfo().getWithOffset(Offset), 10412 getAlignment(), Origin->getMemOperand()->getFlags()); 10413 // If the final type is not the same as the loaded type, this means that 10414 // we have to pad with zero. Create a zero extend for that. 10415 EVT FinalType = Inst->getValueType(0); 10416 if (SliceType != FinalType) 10417 LastInst = 10418 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10419 return LastInst; 10420 } 10421 10422 /// \brief Check if this slice can be merged with an expensive cross register 10423 /// bank copy. E.g., 10424 /// i = load i32 10425 /// f = bitcast i32 i to float 10426 bool canMergeExpensiveCrossRegisterBankCopy() const { 10427 if (!Inst || !Inst->hasOneUse()) 10428 return false; 10429 SDNode *Use = *Inst->use_begin(); 10430 if (Use->getOpcode() != ISD::BITCAST) 10431 return false; 10432 assert(DAG && "Missing context"); 10433 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10434 EVT ResVT = Use->getValueType(0); 10435 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10436 const TargetRegisterClass *ArgRC = 10437 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10438 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10439 return false; 10440 10441 // At this point, we know that we perform a cross-register-bank copy. 10442 // Check if it is expensive. 10443 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10444 // Assume bitcasts are cheap, unless both register classes do not 10445 // explicitly share a common sub class. 10446 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10447 return false; 10448 10449 // Check if it will be merged with the load. 10450 // 1. Check the alignment constraint. 10451 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10452 ResVT.getTypeForEVT(*DAG->getContext())); 10453 10454 if (RequiredAlignment > getAlignment()) 10455 return false; 10456 10457 // 2. Check that the load is a legal operation for that type. 10458 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10459 return false; 10460 10461 // 3. Check that we do not have a zext in the way. 10462 if (Inst->getValueType(0) != getLoadedType()) 10463 return false; 10464 10465 return true; 10466 } 10467 }; 10468 } 10469 10470 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10471 /// \p UsedBits looks like 0..0 1..1 0..0. 10472 static bool areUsedBitsDense(const APInt &UsedBits) { 10473 // If all the bits are one, this is dense! 10474 if (UsedBits.isAllOnesValue()) 10475 return true; 10476 10477 // Get rid of the unused bits on the right. 10478 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10479 // Get rid of the unused bits on the left. 10480 if (NarrowedUsedBits.countLeadingZeros()) 10481 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10482 // Check that the chunk of bits is completely used. 10483 return NarrowedUsedBits.isAllOnesValue(); 10484 } 10485 10486 /// \brief Check whether or not \p First and \p Second are next to each other 10487 /// in memory. This means that there is no hole between the bits loaded 10488 /// by \p First and the bits loaded by \p Second. 10489 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10490 const LoadedSlice &Second) { 10491 assert(First.Origin == Second.Origin && First.Origin && 10492 "Unable to match different memory origins."); 10493 APInt UsedBits = First.getUsedBits(); 10494 assert((UsedBits & Second.getUsedBits()) == 0 && 10495 "Slices are not supposed to overlap."); 10496 UsedBits |= Second.getUsedBits(); 10497 return areUsedBitsDense(UsedBits); 10498 } 10499 10500 /// \brief Adjust the \p GlobalLSCost according to the target 10501 /// paring capabilities and the layout of the slices. 10502 /// \pre \p GlobalLSCost should account for at least as many loads as 10503 /// there is in the slices in \p LoadedSlices. 10504 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10505 LoadedSlice::Cost &GlobalLSCost) { 10506 unsigned NumberOfSlices = LoadedSlices.size(); 10507 // If there is less than 2 elements, no pairing is possible. 10508 if (NumberOfSlices < 2) 10509 return; 10510 10511 // Sort the slices so that elements that are likely to be next to each 10512 // other in memory are next to each other in the list. 10513 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10514 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10515 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10516 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10517 }); 10518 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10519 // First (resp. Second) is the first (resp. Second) potentially candidate 10520 // to be placed in a paired load. 10521 const LoadedSlice *First = nullptr; 10522 const LoadedSlice *Second = nullptr; 10523 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10524 // Set the beginning of the pair. 10525 First = Second) { 10526 10527 Second = &LoadedSlices[CurrSlice]; 10528 10529 // If First is NULL, it means we start a new pair. 10530 // Get to the next slice. 10531 if (!First) 10532 continue; 10533 10534 EVT LoadedType = First->getLoadedType(); 10535 10536 // If the types of the slices are different, we cannot pair them. 10537 if (LoadedType != Second->getLoadedType()) 10538 continue; 10539 10540 // Check if the target supplies paired loads for this type. 10541 unsigned RequiredAlignment = 0; 10542 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10543 // move to the next pair, this type is hopeless. 10544 Second = nullptr; 10545 continue; 10546 } 10547 // Check if we meet the alignment requirement. 10548 if (RequiredAlignment > First->getAlignment()) 10549 continue; 10550 10551 // Check that both loads are next to each other in memory. 10552 if (!areSlicesNextToEachOther(*First, *Second)) 10553 continue; 10554 10555 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10556 --GlobalLSCost.Loads; 10557 // Move to the next pair. 10558 Second = nullptr; 10559 } 10560 } 10561 10562 /// \brief Check the profitability of all involved LoadedSlice. 10563 /// Currently, it is considered profitable if there is exactly two 10564 /// involved slices (1) which are (2) next to each other in memory, and 10565 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10566 /// 10567 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10568 /// the elements themselves. 10569 /// 10570 /// FIXME: When the cost model will be mature enough, we can relax 10571 /// constraints (1) and (2). 10572 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10573 const APInt &UsedBits, bool ForCodeSize) { 10574 unsigned NumberOfSlices = LoadedSlices.size(); 10575 if (StressLoadSlicing) 10576 return NumberOfSlices > 1; 10577 10578 // Check (1). 10579 if (NumberOfSlices != 2) 10580 return false; 10581 10582 // Check (2). 10583 if (!areUsedBitsDense(UsedBits)) 10584 return false; 10585 10586 // Check (3). 10587 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10588 // The original code has one big load. 10589 OrigCost.Loads = 1; 10590 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10591 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10592 // Accumulate the cost of all the slices. 10593 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10594 GlobalSlicingCost += SliceCost; 10595 10596 // Account as cost in the original configuration the gain obtained 10597 // with the current slices. 10598 OrigCost.addSliceGain(LS); 10599 } 10600 10601 // If the target supports paired load, adjust the cost accordingly. 10602 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10603 return OrigCost > GlobalSlicingCost; 10604 } 10605 10606 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10607 /// operations, split it in the various pieces being extracted. 10608 /// 10609 /// This sort of thing is introduced by SROA. 10610 /// This slicing takes care not to insert overlapping loads. 10611 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10612 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10613 if (Level < AfterLegalizeDAG) 10614 return false; 10615 10616 LoadSDNode *LD = cast<LoadSDNode>(N); 10617 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10618 !LD->getValueType(0).isInteger()) 10619 return false; 10620 10621 // Keep track of already used bits to detect overlapping values. 10622 // In that case, we will just abort the transformation. 10623 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10624 10625 SmallVector<LoadedSlice, 4> LoadedSlices; 10626 10627 // Check if this load is used as several smaller chunks of bits. 10628 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10629 // of computation for each trunc. 10630 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10631 UI != UIEnd; ++UI) { 10632 // Skip the uses of the chain. 10633 if (UI.getUse().getResNo() != 0) 10634 continue; 10635 10636 SDNode *User = *UI; 10637 unsigned Shift = 0; 10638 10639 // Check if this is a trunc(lshr). 10640 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10641 isa<ConstantSDNode>(User->getOperand(1))) { 10642 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10643 User = *User->use_begin(); 10644 } 10645 10646 // At this point, User is a Truncate, iff we encountered, trunc or 10647 // trunc(lshr). 10648 if (User->getOpcode() != ISD::TRUNCATE) 10649 return false; 10650 10651 // The width of the type must be a power of 2 and greater than 8-bits. 10652 // Otherwise the load cannot be represented in LLVM IR. 10653 // Moreover, if we shifted with a non-8-bits multiple, the slice 10654 // will be across several bytes. We do not support that. 10655 unsigned Width = User->getValueSizeInBits(0); 10656 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10657 return 0; 10658 10659 // Build the slice for this chain of computations. 10660 LoadedSlice LS(User, LD, Shift, &DAG); 10661 APInt CurrentUsedBits = LS.getUsedBits(); 10662 10663 // Check if this slice overlaps with another. 10664 if ((CurrentUsedBits & UsedBits) != 0) 10665 return false; 10666 // Update the bits used globally. 10667 UsedBits |= CurrentUsedBits; 10668 10669 // Check if the new slice would be legal. 10670 if (!LS.isLegal()) 10671 return false; 10672 10673 // Record the slice. 10674 LoadedSlices.push_back(LS); 10675 } 10676 10677 // Abort slicing if it does not seem to be profitable. 10678 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10679 return false; 10680 10681 ++SlicedLoads; 10682 10683 // Rewrite each chain to use an independent load. 10684 // By construction, each chain can be represented by a unique load. 10685 10686 // Prepare the argument for the new token factor for all the slices. 10687 SmallVector<SDValue, 8> ArgChains; 10688 for (SmallVectorImpl<LoadedSlice>::const_iterator 10689 LSIt = LoadedSlices.begin(), 10690 LSItEnd = LoadedSlices.end(); 10691 LSIt != LSItEnd; ++LSIt) { 10692 SDValue SliceInst = LSIt->loadSlice(); 10693 CombineTo(LSIt->Inst, SliceInst, true); 10694 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10695 SliceInst = SliceInst.getOperand(0); 10696 assert(SliceInst->getOpcode() == ISD::LOAD && 10697 "It takes more than a zext to get to the loaded slice!!"); 10698 ArgChains.push_back(SliceInst.getValue(1)); 10699 } 10700 10701 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10702 ArgChains); 10703 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10704 return true; 10705 } 10706 10707 /// Check to see if V is (and load (ptr), imm), where the load is having 10708 /// specific bytes cleared out. If so, return the byte size being masked out 10709 /// and the shift amount. 10710 static std::pair<unsigned, unsigned> 10711 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10712 std::pair<unsigned, unsigned> Result(0, 0); 10713 10714 // Check for the structure we're looking for. 10715 if (V->getOpcode() != ISD::AND || 10716 !isa<ConstantSDNode>(V->getOperand(1)) || 10717 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10718 return Result; 10719 10720 // Check the chain and pointer. 10721 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10722 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10723 10724 // The store should be chained directly to the load or be an operand of a 10725 // tokenfactor. 10726 if (LD == Chain.getNode()) 10727 ; // ok. 10728 else if (Chain->getOpcode() != ISD::TokenFactor) 10729 return Result; // Fail. 10730 else { 10731 bool isOk = false; 10732 for (const SDValue &ChainOp : Chain->op_values()) 10733 if (ChainOp.getNode() == LD) { 10734 isOk = true; 10735 break; 10736 } 10737 if (!isOk) return Result; 10738 } 10739 10740 // This only handles simple types. 10741 if (V.getValueType() != MVT::i16 && 10742 V.getValueType() != MVT::i32 && 10743 V.getValueType() != MVT::i64) 10744 return Result; 10745 10746 // Check the constant mask. Invert it so that the bits being masked out are 10747 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10748 // follow the sign bit for uniformity. 10749 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10750 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10751 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10752 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10753 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10754 if (NotMaskLZ == 64) return Result; // All zero mask. 10755 10756 // See if we have a continuous run of bits. If so, we have 0*1+0* 10757 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10758 return Result; 10759 10760 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10761 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10762 NotMaskLZ -= 64-V.getValueSizeInBits(); 10763 10764 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10765 switch (MaskedBytes) { 10766 case 1: 10767 case 2: 10768 case 4: break; 10769 default: return Result; // All one mask, or 5-byte mask. 10770 } 10771 10772 // Verify that the first bit starts at a multiple of mask so that the access 10773 // is aligned the same as the access width. 10774 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10775 10776 Result.first = MaskedBytes; 10777 Result.second = NotMaskTZ/8; 10778 return Result; 10779 } 10780 10781 10782 /// Check to see if IVal is something that provides a value as specified by 10783 /// MaskInfo. If so, replace the specified store with a narrower store of 10784 /// truncated IVal. 10785 static SDNode * 10786 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10787 SDValue IVal, StoreSDNode *St, 10788 DAGCombiner *DC) { 10789 unsigned NumBytes = MaskInfo.first; 10790 unsigned ByteShift = MaskInfo.second; 10791 SelectionDAG &DAG = DC->getDAG(); 10792 10793 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10794 // that uses this. If not, this is not a replacement. 10795 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10796 ByteShift*8, (ByteShift+NumBytes)*8); 10797 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10798 10799 // Check that it is legal on the target to do this. It is legal if the new 10800 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10801 // legalization. 10802 MVT VT = MVT::getIntegerVT(NumBytes*8); 10803 if (!DC->isTypeLegal(VT)) 10804 return nullptr; 10805 10806 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10807 // shifted by ByteShift and truncated down to NumBytes. 10808 if (ByteShift) { 10809 SDLoc DL(IVal); 10810 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10811 DAG.getConstant(ByteShift*8, DL, 10812 DC->getShiftAmountTy(IVal.getValueType()))); 10813 } 10814 10815 // Figure out the offset for the store and the alignment of the access. 10816 unsigned StOffset; 10817 unsigned NewAlign = St->getAlignment(); 10818 10819 if (DAG.getDataLayout().isLittleEndian()) 10820 StOffset = ByteShift; 10821 else 10822 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10823 10824 SDValue Ptr = St->getBasePtr(); 10825 if (StOffset) { 10826 SDLoc DL(IVal); 10827 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10828 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10829 NewAlign = MinAlign(NewAlign, StOffset); 10830 } 10831 10832 // Truncate down to the new size. 10833 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10834 10835 ++OpsNarrowed; 10836 return DAG 10837 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10838 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 10839 .getNode(); 10840 } 10841 10842 10843 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10844 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10845 /// narrowing the load and store if it would end up being a win for performance 10846 /// or code size. 10847 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10848 StoreSDNode *ST = cast<StoreSDNode>(N); 10849 if (ST->isVolatile()) 10850 return SDValue(); 10851 10852 SDValue Chain = ST->getChain(); 10853 SDValue Value = ST->getValue(); 10854 SDValue Ptr = ST->getBasePtr(); 10855 EVT VT = Value.getValueType(); 10856 10857 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10858 return SDValue(); 10859 10860 unsigned Opc = Value.getOpcode(); 10861 10862 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10863 // is a byte mask indicating a consecutive number of bytes, check to see if 10864 // Y is known to provide just those bytes. If so, we try to replace the 10865 // load + replace + store sequence with a single (narrower) store, which makes 10866 // the load dead. 10867 if (Opc == ISD::OR) { 10868 std::pair<unsigned, unsigned> MaskedLoad; 10869 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10870 if (MaskedLoad.first) 10871 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10872 Value.getOperand(1), ST,this)) 10873 return SDValue(NewST, 0); 10874 10875 // Or is commutative, so try swapping X and Y. 10876 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10877 if (MaskedLoad.first) 10878 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10879 Value.getOperand(0), ST,this)) 10880 return SDValue(NewST, 0); 10881 } 10882 10883 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10884 Value.getOperand(1).getOpcode() != ISD::Constant) 10885 return SDValue(); 10886 10887 SDValue N0 = Value.getOperand(0); 10888 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10889 Chain == SDValue(N0.getNode(), 1)) { 10890 LoadSDNode *LD = cast<LoadSDNode>(N0); 10891 if (LD->getBasePtr() != Ptr || 10892 LD->getPointerInfo().getAddrSpace() != 10893 ST->getPointerInfo().getAddrSpace()) 10894 return SDValue(); 10895 10896 // Find the type to narrow it the load / op / store to. 10897 SDValue N1 = Value.getOperand(1); 10898 unsigned BitWidth = N1.getValueSizeInBits(); 10899 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10900 if (Opc == ISD::AND) 10901 Imm ^= APInt::getAllOnesValue(BitWidth); 10902 if (Imm == 0 || Imm.isAllOnesValue()) 10903 return SDValue(); 10904 unsigned ShAmt = Imm.countTrailingZeros(); 10905 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10906 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10907 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10908 // The narrowing should be profitable, the load/store operation should be 10909 // legal (or custom) and the store size should be equal to the NewVT width. 10910 while (NewBW < BitWidth && 10911 (NewVT.getStoreSizeInBits() != NewBW || 10912 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10913 !TLI.isNarrowingProfitable(VT, NewVT))) { 10914 NewBW = NextPowerOf2(NewBW); 10915 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10916 } 10917 if (NewBW >= BitWidth) 10918 return SDValue(); 10919 10920 // If the lsb changed does not start at the type bitwidth boundary, 10921 // start at the previous one. 10922 if (ShAmt % NewBW) 10923 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10924 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10925 std::min(BitWidth, ShAmt + NewBW)); 10926 if ((Imm & Mask) == Imm) { 10927 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10928 if (Opc == ISD::AND) 10929 NewImm ^= APInt::getAllOnesValue(NewBW); 10930 uint64_t PtrOff = ShAmt / 8; 10931 // For big endian targets, we need to adjust the offset to the pointer to 10932 // load the correct bytes. 10933 if (DAG.getDataLayout().isBigEndian()) 10934 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10935 10936 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10937 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10938 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10939 return SDValue(); 10940 10941 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10942 Ptr.getValueType(), Ptr, 10943 DAG.getConstant(PtrOff, SDLoc(LD), 10944 Ptr.getValueType())); 10945 SDValue NewLD = 10946 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 10947 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 10948 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10949 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10950 DAG.getConstant(NewImm, SDLoc(Value), 10951 NewVT)); 10952 SDValue NewST = 10953 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 10954 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 10955 10956 AddToWorklist(NewPtr.getNode()); 10957 AddToWorklist(NewLD.getNode()); 10958 AddToWorklist(NewVal.getNode()); 10959 WorklistRemover DeadNodes(*this); 10960 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10961 ++OpsNarrowed; 10962 return NewST; 10963 } 10964 } 10965 10966 return SDValue(); 10967 } 10968 10969 /// For a given floating point load / store pair, if the load value isn't used 10970 /// by any other operations, then consider transforming the pair to integer 10971 /// load / store operations if the target deems the transformation profitable. 10972 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10973 StoreSDNode *ST = cast<StoreSDNode>(N); 10974 SDValue Chain = ST->getChain(); 10975 SDValue Value = ST->getValue(); 10976 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10977 Value.hasOneUse() && 10978 Chain == SDValue(Value.getNode(), 1)) { 10979 LoadSDNode *LD = cast<LoadSDNode>(Value); 10980 EVT VT = LD->getMemoryVT(); 10981 if (!VT.isFloatingPoint() || 10982 VT != ST->getMemoryVT() || 10983 LD->isNonTemporal() || 10984 ST->isNonTemporal() || 10985 LD->getPointerInfo().getAddrSpace() != 0 || 10986 ST->getPointerInfo().getAddrSpace() != 0) 10987 return SDValue(); 10988 10989 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10990 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10991 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10992 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10993 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10994 return SDValue(); 10995 10996 unsigned LDAlign = LD->getAlignment(); 10997 unsigned STAlign = ST->getAlignment(); 10998 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10999 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11000 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11001 return SDValue(); 11002 11003 SDValue NewLD = 11004 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11005 LD->getPointerInfo(), LDAlign); 11006 11007 SDValue NewST = 11008 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11009 ST->getPointerInfo(), STAlign); 11010 11011 AddToWorklist(NewLD.getNode()); 11012 AddToWorklist(NewST.getNode()); 11013 WorklistRemover DeadNodes(*this); 11014 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11015 ++LdStFP2Int; 11016 return NewST; 11017 } 11018 11019 return SDValue(); 11020 } 11021 11022 namespace { 11023 /// Helper struct to parse and store a memory address as base + index + offset. 11024 /// We ignore sign extensions when it is safe to do so. 11025 /// The following two expressions are not equivalent. To differentiate we need 11026 /// to store whether there was a sign extension involved in the index 11027 /// computation. 11028 /// (load (i64 add (i64 copyfromreg %c) 11029 /// (i64 signextend (add (i8 load %index) 11030 /// (i8 1)))) 11031 /// vs 11032 /// 11033 /// (load (i64 add (i64 copyfromreg %c) 11034 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 11035 /// (i32 1))))) 11036 struct BaseIndexOffset { 11037 SDValue Base; 11038 SDValue Index; 11039 int64_t Offset; 11040 bool IsIndexSignExt; 11041 11042 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 11043 11044 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 11045 bool IsIndexSignExt) : 11046 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 11047 11048 bool equalBaseIndex(const BaseIndexOffset &Other) { 11049 return Other.Base == Base && Other.Index == Index && 11050 Other.IsIndexSignExt == IsIndexSignExt; 11051 } 11052 11053 /// Parses tree in Ptr for base, index, offset addresses. 11054 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 11055 bool IsIndexSignExt = false; 11056 11057 // Split up a folded GlobalAddress+Offset into its component parts. 11058 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 11059 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 11060 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 11061 SDLoc(GA), 11062 GA->getValueType(0), 11063 /*Offset=*/0, 11064 /*isTargetGA=*/false, 11065 GA->getTargetFlags()), 11066 SDValue(), 11067 GA->getOffset(), 11068 IsIndexSignExt); 11069 } 11070 11071 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 11072 // instruction, then it could be just the BASE or everything else we don't 11073 // know how to handle. Just use Ptr as BASE and give up. 11074 if (Ptr->getOpcode() != ISD::ADD) 11075 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11076 11077 // We know that we have at least an ADD instruction. Try to pattern match 11078 // the simple case of BASE + OFFSET. 11079 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 11080 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 11081 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 11082 IsIndexSignExt); 11083 } 11084 11085 // Inside a loop the current BASE pointer is calculated using an ADD and a 11086 // MUL instruction. In this case Ptr is the actual BASE pointer. 11087 // (i64 add (i64 %array_ptr) 11088 // (i64 mul (i64 %induction_var) 11089 // (i64 %element_size))) 11090 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11091 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11092 11093 // Look at Base + Index + Offset cases. 11094 SDValue Base = Ptr->getOperand(0); 11095 SDValue IndexOffset = Ptr->getOperand(1); 11096 11097 // Skip signextends. 11098 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11099 IndexOffset = IndexOffset->getOperand(0); 11100 IsIndexSignExt = true; 11101 } 11102 11103 // Either the case of Base + Index (no offset) or something else. 11104 if (IndexOffset->getOpcode() != ISD::ADD) 11105 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11106 11107 // Now we have the case of Base + Index + offset. 11108 SDValue Index = IndexOffset->getOperand(0); 11109 SDValue Offset = IndexOffset->getOperand(1); 11110 11111 if (!isa<ConstantSDNode>(Offset)) 11112 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11113 11114 // Ignore signextends. 11115 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11116 Index = Index->getOperand(0); 11117 IsIndexSignExt = true; 11118 } else IsIndexSignExt = false; 11119 11120 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11121 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11122 } 11123 }; 11124 } // namespace 11125 11126 // This is a helper function for visitMUL to check the profitability 11127 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11128 // MulNode is the original multiply, AddNode is (add x, c1), 11129 // and ConstNode is c2. 11130 // 11131 // If the (add x, c1) has multiple uses, we could increase 11132 // the number of adds if we make this transformation. 11133 // It would only be worth doing this if we can remove a 11134 // multiply in the process. Check for that here. 11135 // To illustrate: 11136 // (A + c1) * c3 11137 // (A + c2) * c3 11138 // We're checking for cases where we have common "c3 * A" expressions. 11139 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11140 SDValue &AddNode, 11141 SDValue &ConstNode) { 11142 APInt Val; 11143 11144 // If the add only has one use, this would be OK to do. 11145 if (AddNode.getNode()->hasOneUse()) 11146 return true; 11147 11148 // Walk all the users of the constant with which we're multiplying. 11149 for (SDNode *Use : ConstNode->uses()) { 11150 11151 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11152 continue; 11153 11154 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11155 SDNode *OtherOp; 11156 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11157 11158 // OtherOp is what we're multiplying against the constant. 11159 if (Use->getOperand(0) == ConstNode) 11160 OtherOp = Use->getOperand(1).getNode(); 11161 else 11162 OtherOp = Use->getOperand(0).getNode(); 11163 11164 // Check to see if multiply is with the same operand of our "add". 11165 // 11166 // ConstNode = CONST 11167 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11168 // ... 11169 // AddNode = (A + c1) <-- MulVar is A. 11170 // = AddNode * ConstNode <-- current visiting instruction. 11171 // 11172 // If we make this transformation, we will have a common 11173 // multiply (ConstNode * A) that we can save. 11174 if (OtherOp == MulVar) 11175 return true; 11176 11177 // Now check to see if a future expansion will give us a common 11178 // multiply. 11179 // 11180 // ConstNode = CONST 11181 // AddNode = (A + c1) 11182 // ... = AddNode * ConstNode <-- current visiting instruction. 11183 // ... 11184 // OtherOp = (A + c2) 11185 // Use = OtherOp * ConstNode <-- visiting Use. 11186 // 11187 // If we make this transformation, we will have a common 11188 // multiply (CONST * A) after we also do the same transformation 11189 // to the "t2" instruction. 11190 if (OtherOp->getOpcode() == ISD::ADD && 11191 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11192 OtherOp->getOperand(0).getNode() == MulVar) 11193 return true; 11194 } 11195 } 11196 11197 // Didn't find a case where this would be profitable. 11198 return false; 11199 } 11200 11201 SDValue DAGCombiner::getMergedConstantVectorStore( 11202 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores, 11203 SmallVectorImpl<SDValue> &Chains, EVT Ty) const { 11204 SmallVector<SDValue, 8> BuildVector; 11205 11206 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11207 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11208 Chains.push_back(St->getChain()); 11209 BuildVector.push_back(St->getValue()); 11210 } 11211 11212 return DAG.getBuildVector(Ty, SL, BuildVector); 11213 } 11214 11215 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11216 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11217 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11218 // Make sure we have something to merge. 11219 if (NumStores < 2) 11220 return false; 11221 11222 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11223 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11224 unsigned LatestNodeUsed = 0; 11225 11226 for (unsigned i=0; i < NumStores; ++i) { 11227 // Find a chain for the new wide-store operand. Notice that some 11228 // of the store nodes that we found may not be selected for inclusion 11229 // in the wide store. The chain we use needs to be the chain of the 11230 // latest store node which is *used* and replaced by the wide store. 11231 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11232 LatestNodeUsed = i; 11233 } 11234 11235 SmallVector<SDValue, 8> Chains; 11236 11237 // The latest Node in the DAG. 11238 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11239 SDLoc DL(StoreNodes[0].MemNode); 11240 11241 SDValue StoredVal; 11242 if (UseVector) { 11243 bool IsVec = MemVT.isVector(); 11244 unsigned Elts = NumStores; 11245 if (IsVec) { 11246 // When merging vector stores, get the total number of elements. 11247 Elts *= MemVT.getVectorNumElements(); 11248 } 11249 // Get the type for the merged vector store. 11250 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11251 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11252 11253 if (IsConstantSrc) { 11254 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11255 } else { 11256 SmallVector<SDValue, 8> Ops; 11257 for (unsigned i = 0; i < NumStores; ++i) { 11258 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11259 SDValue Val = St->getValue(); 11260 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11261 if (Val.getValueType() != MemVT) 11262 return false; 11263 Ops.push_back(Val); 11264 Chains.push_back(St->getChain()); 11265 } 11266 11267 // Build the extracted vector elements back into a vector. 11268 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11269 DL, Ty, Ops); } 11270 } else { 11271 // We should always use a vector store when merging extracted vector 11272 // elements, so this path implies a store of constants. 11273 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11274 11275 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11276 APInt StoreInt(SizeInBits, 0); 11277 11278 // Construct a single integer constant which is made of the smaller 11279 // constant inputs. 11280 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11281 for (unsigned i = 0; i < NumStores; ++i) { 11282 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11283 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11284 Chains.push_back(St->getChain()); 11285 11286 SDValue Val = St->getValue(); 11287 StoreInt <<= ElementSizeBytes * 8; 11288 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11289 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11290 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11291 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11292 } else { 11293 llvm_unreachable("Invalid constant element type"); 11294 } 11295 } 11296 11297 // Create the new Load and Store operations. 11298 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11299 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11300 } 11301 11302 assert(!Chains.empty()); 11303 11304 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11305 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11306 FirstInChain->getBasePtr(), 11307 FirstInChain->getPointerInfo(), 11308 FirstInChain->getAlignment()); 11309 11310 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11311 : DAG.getSubtarget().useAA(); 11312 if (UseAA) { 11313 // Replace all merged stores with the new store. 11314 for (unsigned i = 0; i < NumStores; ++i) 11315 CombineTo(StoreNodes[i].MemNode, NewStore); 11316 } else { 11317 // Replace the last store with the new store. 11318 CombineTo(LatestOp, NewStore); 11319 // Erase all other stores. 11320 for (unsigned i = 0; i < NumStores; ++i) { 11321 if (StoreNodes[i].MemNode == LatestOp) 11322 continue; 11323 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11324 // ReplaceAllUsesWith will replace all uses that existed when it was 11325 // called, but graph optimizations may cause new ones to appear. For 11326 // example, the case in pr14333 looks like 11327 // 11328 // St's chain -> St -> another store -> X 11329 // 11330 // And the only difference from St to the other store is the chain. 11331 // When we change it's chain to be St's chain they become identical, 11332 // get CSEed and the net result is that X is now a use of St. 11333 // Since we know that St is redundant, just iterate. 11334 while (!St->use_empty()) 11335 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11336 deleteAndRecombine(St); 11337 } 11338 } 11339 11340 return true; 11341 } 11342 11343 void DAGCombiner::getStoreMergeAndAliasCandidates( 11344 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11345 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11346 // This holds the base pointer, index, and the offset in bytes from the base 11347 // pointer. 11348 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11349 11350 // We must have a base and an offset. 11351 if (!BasePtr.Base.getNode()) 11352 return; 11353 11354 // Do not handle stores to undef base pointers. 11355 if (BasePtr.Base.isUndef()) 11356 return; 11357 11358 // Walk up the chain and look for nodes with offsets from the same 11359 // base pointer. Stop when reaching an instruction with a different kind 11360 // or instruction which has a different base pointer. 11361 EVT MemVT = St->getMemoryVT(); 11362 unsigned Seq = 0; 11363 StoreSDNode *Index = St; 11364 11365 11366 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11367 : DAG.getSubtarget().useAA(); 11368 11369 if (UseAA) { 11370 // Look at other users of the same chain. Stores on the same chain do not 11371 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11372 // to be on the same chain, so don't bother looking at adjacent chains. 11373 11374 SDValue Chain = St->getChain(); 11375 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11376 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11377 if (I.getOperandNo() != 0) 11378 continue; 11379 11380 if (OtherST->isVolatile() || OtherST->isIndexed()) 11381 continue; 11382 11383 if (OtherST->getMemoryVT() != MemVT) 11384 continue; 11385 11386 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11387 11388 if (Ptr.equalBaseIndex(BasePtr)) 11389 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11390 } 11391 } 11392 11393 return; 11394 } 11395 11396 while (Index) { 11397 // If the chain has more than one use, then we can't reorder the mem ops. 11398 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11399 break; 11400 11401 // Find the base pointer and offset for this memory node. 11402 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11403 11404 // Check that the base pointer is the same as the original one. 11405 if (!Ptr.equalBaseIndex(BasePtr)) 11406 break; 11407 11408 // The memory operands must not be volatile. 11409 if (Index->isVolatile() || Index->isIndexed()) 11410 break; 11411 11412 // No truncation. 11413 if (Index->isTruncatingStore()) 11414 break; 11415 11416 // The stored memory type must be the same. 11417 if (Index->getMemoryVT() != MemVT) 11418 break; 11419 11420 // We do not allow under-aligned stores in order to prevent 11421 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11422 // be irrelevant here; what MATTERS is that we not move memory 11423 // operations that potentially overlap past each-other. 11424 if (Index->getAlignment() < MemVT.getStoreSize()) 11425 break; 11426 11427 // We found a potential memory operand to merge. 11428 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11429 11430 // Find the next memory operand in the chain. If the next operand in the 11431 // chain is a store then move up and continue the scan with the next 11432 // memory operand. If the next operand is a load save it and use alias 11433 // information to check if it interferes with anything. 11434 SDNode *NextInChain = Index->getChain().getNode(); 11435 while (1) { 11436 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11437 // We found a store node. Use it for the next iteration. 11438 Index = STn; 11439 break; 11440 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11441 if (Ldn->isVolatile()) { 11442 Index = nullptr; 11443 break; 11444 } 11445 11446 // Save the load node for later. Continue the scan. 11447 AliasLoadNodes.push_back(Ldn); 11448 NextInChain = Ldn->getChain().getNode(); 11449 continue; 11450 } else { 11451 Index = nullptr; 11452 break; 11453 } 11454 } 11455 } 11456 } 11457 11458 // We need to check that merging these stores does not cause a loop 11459 // in the DAG. Any store candidate may depend on another candidate 11460 // indirectly through its operand (we already consider dependencies 11461 // through the chain). Check in parallel by searching up from 11462 // non-chain operands of candidates. 11463 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11464 SmallVectorImpl<MemOpLink> &StoreNodes) { 11465 SmallPtrSet<const SDNode *, 16> Visited; 11466 SmallVector<const SDNode *, 8> Worklist; 11467 // search ops of store candidates 11468 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11469 SDNode *n = StoreNodes[i].MemNode; 11470 // Potential loops may happen only through non-chain operands 11471 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11472 Worklist.push_back(n->getOperand(j).getNode()); 11473 } 11474 // search through DAG. We can stop early if we find a storenode 11475 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11476 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11477 return false; 11478 } 11479 return true; 11480 } 11481 11482 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11483 if (OptLevel == CodeGenOpt::None) 11484 return false; 11485 11486 EVT MemVT = St->getMemoryVT(); 11487 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11488 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11489 Attribute::NoImplicitFloat); 11490 11491 // This function cannot currently deal with non-byte-sized memory sizes. 11492 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11493 return false; 11494 11495 if (!MemVT.isSimple()) 11496 return false; 11497 11498 // Perform an early exit check. Do not bother looking at stored values that 11499 // are not constants, loads, or extracted vector elements. 11500 SDValue StoredVal = St->getValue(); 11501 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11502 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11503 isa<ConstantFPSDNode>(StoredVal); 11504 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11505 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11506 11507 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11508 return false; 11509 11510 // Don't merge vectors into wider vectors if the source data comes from loads. 11511 // TODO: This restriction can be lifted by using logic similar to the 11512 // ExtractVecSrc case. 11513 if (MemVT.isVector() && IsLoadSrc) 11514 return false; 11515 11516 // Only look at ends of store sequences. 11517 SDValue Chain = SDValue(St, 0); 11518 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11519 return false; 11520 11521 // Save the LoadSDNodes that we find in the chain. 11522 // We need to make sure that these nodes do not interfere with 11523 // any of the store nodes. 11524 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11525 11526 // Save the StoreSDNodes that we find in the chain. 11527 SmallVector<MemOpLink, 8> StoreNodes; 11528 11529 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11530 11531 // Check if there is anything to merge. 11532 if (StoreNodes.size() < 2) 11533 return false; 11534 11535 // only do dep endence check in AA case 11536 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11537 : DAG.getSubtarget().useAA(); 11538 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11539 return false; 11540 11541 // Sort the memory operands according to their distance from the 11542 // base pointer. As a secondary criteria: make sure stores coming 11543 // later in the code come first in the list. This is important for 11544 // the non-UseAA case, because we're merging stores into the FINAL 11545 // store along a chain which potentially contains aliasing stores. 11546 // Thus, if there are multiple stores to the same address, the last 11547 // one can be considered for merging but not the others. 11548 std::sort(StoreNodes.begin(), StoreNodes.end(), 11549 [](MemOpLink LHS, MemOpLink RHS) { 11550 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11551 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11552 LHS.SequenceNum < RHS.SequenceNum); 11553 }); 11554 11555 // Scan the memory operations on the chain and find the first non-consecutive 11556 // store memory address. 11557 unsigned LastConsecutiveStore = 0; 11558 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11559 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11560 11561 // Check that the addresses are consecutive starting from the second 11562 // element in the list of stores. 11563 if (i > 0) { 11564 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11565 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11566 break; 11567 } 11568 11569 // Check if this store interferes with any of the loads that we found. 11570 // If we find a load that alias with this store. Stop the sequence. 11571 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(), 11572 [&](LSBaseSDNode* Ldn) { 11573 return isAlias(Ldn, StoreNodes[i].MemNode); 11574 })) 11575 break; 11576 11577 // Mark this node as useful. 11578 LastConsecutiveStore = i; 11579 } 11580 11581 // The node with the lowest store address. 11582 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11583 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11584 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11585 LLVMContext &Context = *DAG.getContext(); 11586 const DataLayout &DL = DAG.getDataLayout(); 11587 11588 // Store the constants into memory as one consecutive store. 11589 if (IsConstantSrc) { 11590 unsigned LastLegalType = 0; 11591 unsigned LastLegalVectorType = 0; 11592 bool NonZero = false; 11593 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11594 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11595 SDValue StoredVal = St->getValue(); 11596 11597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11598 NonZero |= !C->isNullValue(); 11599 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11600 NonZero |= !C->getConstantFPValue()->isNullValue(); 11601 } else { 11602 // Non-constant. 11603 break; 11604 } 11605 11606 // Find a legal type for the constant store. 11607 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11608 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11609 bool IsFast; 11610 if (TLI.isTypeLegal(StoreTy) && 11611 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11612 FirstStoreAlign, &IsFast) && IsFast) { 11613 LastLegalType = i+1; 11614 // Or check whether a truncstore is legal. 11615 } else if (TLI.getTypeAction(Context, StoreTy) == 11616 TargetLowering::TypePromoteInteger) { 11617 EVT LegalizedStoredValueTy = 11618 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11619 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11620 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11621 FirstStoreAS, FirstStoreAlign, &IsFast) && 11622 IsFast) { 11623 LastLegalType = i + 1; 11624 } 11625 } 11626 11627 // We only use vectors if the constant is known to be zero or the target 11628 // allows it and the function is not marked with the noimplicitfloat 11629 // attribute. 11630 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11631 FirstStoreAS)) && 11632 !NoVectors) { 11633 // Find a legal type for the vector store. 11634 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11635 if (TLI.isTypeLegal(Ty) && 11636 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11637 FirstStoreAlign, &IsFast) && IsFast) 11638 LastLegalVectorType = i + 1; 11639 } 11640 } 11641 11642 // Check if we found a legal integer type to store. 11643 if (LastLegalType == 0 && LastLegalVectorType == 0) 11644 return false; 11645 11646 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11647 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11648 11649 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11650 true, UseVector); 11651 } 11652 11653 // When extracting multiple vector elements, try to store them 11654 // in one vector store rather than a sequence of scalar stores. 11655 if (IsExtractVecSrc) { 11656 unsigned NumStoresToMerge = 0; 11657 bool IsVec = MemVT.isVector(); 11658 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11659 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11660 unsigned StoreValOpcode = St->getValue().getOpcode(); 11661 // This restriction could be loosened. 11662 // Bail out if any stored values are not elements extracted from a vector. 11663 // It should be possible to handle mixed sources, but load sources need 11664 // more careful handling (see the block of code below that handles 11665 // consecutive loads). 11666 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11667 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11668 return false; 11669 11670 // Find a legal type for the vector store. 11671 unsigned Elts = i + 1; 11672 if (IsVec) { 11673 // When merging vector stores, get the total number of elements. 11674 Elts *= MemVT.getVectorNumElements(); 11675 } 11676 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11677 bool IsFast; 11678 if (TLI.isTypeLegal(Ty) && 11679 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11680 FirstStoreAlign, &IsFast) && IsFast) 11681 NumStoresToMerge = i + 1; 11682 } 11683 11684 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11685 false, true); 11686 } 11687 11688 // Below we handle the case of multiple consecutive stores that 11689 // come from multiple consecutive loads. We merge them into a single 11690 // wide load and a single wide store. 11691 11692 // Look for load nodes which are used by the stored values. 11693 SmallVector<MemOpLink, 8> LoadNodes; 11694 11695 // Find acceptable loads. Loads need to have the same chain (token factor), 11696 // must not be zext, volatile, indexed, and they must be consecutive. 11697 BaseIndexOffset LdBasePtr; 11698 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11699 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11700 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11701 if (!Ld) break; 11702 11703 // Loads must only have one use. 11704 if (!Ld->hasNUsesOfValue(1, 0)) 11705 break; 11706 11707 // The memory operands must not be volatile. 11708 if (Ld->isVolatile() || Ld->isIndexed()) 11709 break; 11710 11711 // We do not accept ext loads. 11712 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11713 break; 11714 11715 // The stored memory type must be the same. 11716 if (Ld->getMemoryVT() != MemVT) 11717 break; 11718 11719 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11720 // If this is not the first ptr that we check. 11721 if (LdBasePtr.Base.getNode()) { 11722 // The base ptr must be the same. 11723 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11724 break; 11725 } else { 11726 // Check that all other base pointers are the same as this one. 11727 LdBasePtr = LdPtr; 11728 } 11729 11730 // We found a potential memory operand to merge. 11731 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11732 } 11733 11734 if (LoadNodes.size() < 2) 11735 return false; 11736 11737 // If we have load/store pair instructions and we only have two values, 11738 // don't bother. 11739 unsigned RequiredAlignment; 11740 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11741 St->getAlignment() >= RequiredAlignment) 11742 return false; 11743 11744 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11745 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11746 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11747 11748 // Scan the memory operations on the chain and find the first non-consecutive 11749 // load memory address. These variables hold the index in the store node 11750 // array. 11751 unsigned LastConsecutiveLoad = 0; 11752 // This variable refers to the size and not index in the array. 11753 unsigned LastLegalVectorType = 0; 11754 unsigned LastLegalIntegerType = 0; 11755 StartAddress = LoadNodes[0].OffsetFromBase; 11756 SDValue FirstChain = FirstLoad->getChain(); 11757 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11758 // All loads must share the same chain. 11759 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11760 break; 11761 11762 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11763 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11764 break; 11765 LastConsecutiveLoad = i; 11766 // Find a legal type for the vector store. 11767 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11768 bool IsFastSt, IsFastLd; 11769 if (TLI.isTypeLegal(StoreTy) && 11770 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11771 FirstStoreAlign, &IsFastSt) && IsFastSt && 11772 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11773 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11774 LastLegalVectorType = i + 1; 11775 } 11776 11777 // Find a legal type for the integer store. 11778 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11779 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11780 if (TLI.isTypeLegal(StoreTy) && 11781 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11782 FirstStoreAlign, &IsFastSt) && IsFastSt && 11783 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11784 FirstLoadAlign, &IsFastLd) && IsFastLd) 11785 LastLegalIntegerType = i + 1; 11786 // Or check whether a truncstore and extload is legal. 11787 else if (TLI.getTypeAction(Context, StoreTy) == 11788 TargetLowering::TypePromoteInteger) { 11789 EVT LegalizedStoredValueTy = 11790 TLI.getTypeToTransformTo(Context, StoreTy); 11791 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11792 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11793 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11794 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11795 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11796 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11797 IsFastSt && 11798 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11799 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11800 IsFastLd) 11801 LastLegalIntegerType = i+1; 11802 } 11803 } 11804 11805 // Only use vector types if the vector type is larger than the integer type. 11806 // If they are the same, use integers. 11807 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11808 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11809 11810 // We add +1 here because the LastXXX variables refer to location while 11811 // the NumElem refers to array/index size. 11812 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11813 NumElem = std::min(LastLegalType, NumElem); 11814 11815 if (NumElem < 2) 11816 return false; 11817 11818 // Collect the chains from all merged stores. 11819 SmallVector<SDValue, 8> MergeStoreChains; 11820 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11821 11822 // The latest Node in the DAG. 11823 unsigned LatestNodeUsed = 0; 11824 for (unsigned i=1; i<NumElem; ++i) { 11825 // Find a chain for the new wide-store operand. Notice that some 11826 // of the store nodes that we found may not be selected for inclusion 11827 // in the wide store. The chain we use needs to be the chain of the 11828 // latest store node which is *used* and replaced by the wide store. 11829 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11830 LatestNodeUsed = i; 11831 11832 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11833 } 11834 11835 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11836 11837 // Find if it is better to use vectors or integers to load and store 11838 // to memory. 11839 EVT JointMemOpVT; 11840 if (UseVectorTy) { 11841 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11842 } else { 11843 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11844 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11845 } 11846 11847 SDLoc LoadDL(LoadNodes[0].MemNode); 11848 SDLoc StoreDL(StoreNodes[0].MemNode); 11849 11850 // The merged loads are required to have the same incoming chain, so 11851 // using the first's chain is acceptable. 11852 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 11853 FirstLoad->getBasePtr(), 11854 FirstLoad->getPointerInfo(), FirstLoadAlign); 11855 11856 SDValue NewStoreChain = 11857 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11858 11859 SDValue NewStore = 11860 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11861 FirstInChain->getPointerInfo(), FirstStoreAlign); 11862 11863 // Transfer chain users from old loads to the new load. 11864 for (unsigned i = 0; i < NumElem; ++i) { 11865 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11866 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11867 SDValue(NewLoad.getNode(), 1)); 11868 } 11869 11870 if (UseAA) { 11871 // Replace the all stores with the new store. 11872 for (unsigned i = 0; i < NumElem; ++i) 11873 CombineTo(StoreNodes[i].MemNode, NewStore); 11874 } else { 11875 // Replace the last store with the new store. 11876 CombineTo(LatestOp, NewStore); 11877 // Erase all other stores. 11878 for (unsigned i = 0; i < NumElem; ++i) { 11879 // Remove all Store nodes. 11880 if (StoreNodes[i].MemNode == LatestOp) 11881 continue; 11882 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11883 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11884 deleteAndRecombine(St); 11885 } 11886 } 11887 11888 return true; 11889 } 11890 11891 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11892 SDLoc SL(ST); 11893 SDValue ReplStore; 11894 11895 // Replace the chain to avoid dependency. 11896 if (ST->isTruncatingStore()) { 11897 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11898 ST->getBasePtr(), ST->getMemoryVT(), 11899 ST->getMemOperand()); 11900 } else { 11901 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11902 ST->getMemOperand()); 11903 } 11904 11905 // Create token to keep both nodes around. 11906 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11907 MVT::Other, ST->getChain(), ReplStore); 11908 11909 // Make sure the new and old chains are cleaned up. 11910 AddToWorklist(Token.getNode()); 11911 11912 // Don't add users to work list. 11913 return CombineTo(ST, Token, false); 11914 } 11915 11916 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11917 SDValue Value = ST->getValue(); 11918 if (Value.getOpcode() == ISD::TargetConstantFP) 11919 return SDValue(); 11920 11921 SDLoc DL(ST); 11922 11923 SDValue Chain = ST->getChain(); 11924 SDValue Ptr = ST->getBasePtr(); 11925 11926 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11927 11928 // NOTE: If the original store is volatile, this transform must not increase 11929 // the number of stores. For example, on x86-32 an f64 can be stored in one 11930 // processor operation but an i64 (which is not legal) requires two. So the 11931 // transform should not be done in this case. 11932 11933 SDValue Tmp; 11934 switch (CFP->getSimpleValueType(0).SimpleTy) { 11935 default: 11936 llvm_unreachable("Unknown FP type"); 11937 case MVT::f16: // We don't do this for these yet. 11938 case MVT::f80: 11939 case MVT::f128: 11940 case MVT::ppcf128: 11941 return SDValue(); 11942 case MVT::f32: 11943 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11944 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11945 ; 11946 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11947 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11948 MVT::i32); 11949 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11950 } 11951 11952 return SDValue(); 11953 case MVT::f64: 11954 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11955 !ST->isVolatile()) || 11956 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11957 ; 11958 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11959 getZExtValue(), SDLoc(CFP), MVT::i64); 11960 return DAG.getStore(Chain, DL, Tmp, 11961 Ptr, ST->getMemOperand()); 11962 } 11963 11964 if (!ST->isVolatile() && 11965 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11966 // Many FP stores are not made apparent until after legalize, e.g. for 11967 // argument passing. Since this is so common, custom legalize the 11968 // 64-bit integer store into two 32-bit stores. 11969 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11970 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11971 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11972 if (DAG.getDataLayout().isBigEndian()) 11973 std::swap(Lo, Hi); 11974 11975 unsigned Alignment = ST->getAlignment(); 11976 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 11977 AAMDNodes AAInfo = ST->getAAInfo(); 11978 11979 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 11980 ST->getAlignment(), MMOFlags, AAInfo); 11981 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11982 DAG.getConstant(4, DL, Ptr.getValueType())); 11983 Alignment = MinAlign(Alignment, 4U); 11984 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 11985 ST->getPointerInfo().getWithOffset(4), 11986 Alignment, MMOFlags, AAInfo); 11987 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11988 St0, St1); 11989 } 11990 11991 return SDValue(); 11992 } 11993 } 11994 11995 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11996 StoreSDNode *ST = cast<StoreSDNode>(N); 11997 SDValue Chain = ST->getChain(); 11998 SDValue Value = ST->getValue(); 11999 SDValue Ptr = ST->getBasePtr(); 12000 12001 // If this is a store of a bit convert, store the input value if the 12002 // resultant store does not need a higher alignment than the original. 12003 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12004 ST->isUnindexed()) { 12005 EVT SVT = Value.getOperand(0).getValueType(); 12006 if (((!LegalOperations && !ST->isVolatile()) || 12007 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12008 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12009 unsigned OrigAlign = ST->getAlignment(); 12010 bool Fast = false; 12011 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12012 ST->getAddressSpace(), OrigAlign, &Fast) && 12013 Fast) { 12014 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12015 ST->getPointerInfo(), OrigAlign, 12016 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12017 } 12018 } 12019 } 12020 12021 // Turn 'store undef, Ptr' -> nothing. 12022 if (Value.isUndef() && ST->isUnindexed()) 12023 return Chain; 12024 12025 // Try to infer better alignment information than the store already has. 12026 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12027 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12028 if (Align > ST->getAlignment()) { 12029 SDValue NewStore = 12030 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12031 ST->getMemoryVT(), Align, 12032 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12033 if (NewStore.getNode() != N) 12034 return CombineTo(ST, NewStore, true); 12035 } 12036 } 12037 } 12038 12039 // Try transforming a pair floating point load / store ops to integer 12040 // load / store ops. 12041 if (SDValue NewST = TransformFPLoadStorePair(N)) 12042 return NewST; 12043 12044 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12045 : DAG.getSubtarget().useAA(); 12046 #ifndef NDEBUG 12047 if (CombinerAAOnlyFunc.getNumOccurrences() && 12048 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12049 UseAA = false; 12050 #endif 12051 if (UseAA && ST->isUnindexed()) { 12052 // FIXME: We should do this even without AA enabled. AA will just allow 12053 // FindBetterChain to work in more situations. The problem with this is that 12054 // any combine that expects memory operations to be on consecutive chains 12055 // first needs to be updated to look for users of the same chain. 12056 12057 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12058 // adjacent stores. 12059 if (findBetterNeighborChains(ST)) { 12060 // replaceStoreChain uses CombineTo, which handled all of the worklist 12061 // manipulation. Return the original node to not do anything else. 12062 return SDValue(ST, 0); 12063 } 12064 Chain = ST->getChain(); 12065 } 12066 12067 // Try transforming N to an indexed store. 12068 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12069 return SDValue(N, 0); 12070 12071 // FIXME: is there such a thing as a truncating indexed store? 12072 if (ST->isTruncatingStore() && ST->isUnindexed() && 12073 Value.getValueType().isInteger()) { 12074 // See if we can simplify the input to this truncstore with knowledge that 12075 // only the low bits are being used. For example: 12076 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12077 SDValue Shorter = 12078 GetDemandedBits(Value, 12079 APInt::getLowBitsSet( 12080 Value.getValueType().getScalarType().getSizeInBits(), 12081 ST->getMemoryVT().getScalarType().getSizeInBits())); 12082 AddToWorklist(Value.getNode()); 12083 if (Shorter.getNode()) 12084 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12085 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12086 12087 // Otherwise, see if we can simplify the operation with 12088 // SimplifyDemandedBits, which only works if the value has a single use. 12089 if (SimplifyDemandedBits(Value, 12090 APInt::getLowBitsSet( 12091 Value.getValueType().getScalarType().getSizeInBits(), 12092 ST->getMemoryVT().getScalarType().getSizeInBits()))) 12093 return SDValue(N, 0); 12094 } 12095 12096 // If this is a load followed by a store to the same location, then the store 12097 // is dead/noop. 12098 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12099 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12100 ST->isUnindexed() && !ST->isVolatile() && 12101 // There can't be any side effects between the load and store, such as 12102 // a call or store. 12103 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12104 // The store is dead, remove it. 12105 return Chain; 12106 } 12107 } 12108 12109 // If this is a store followed by a store with the same value to the same 12110 // location, then the store is dead/noop. 12111 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12112 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12113 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12114 ST1->isUnindexed() && !ST1->isVolatile()) { 12115 // The store is dead, remove it. 12116 return Chain; 12117 } 12118 } 12119 12120 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12121 // truncating store. We can do this even if this is already a truncstore. 12122 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12123 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12124 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12125 ST->getMemoryVT())) { 12126 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12127 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12128 } 12129 12130 // Only perform this optimization before the types are legal, because we 12131 // don't want to perform this optimization on every DAGCombine invocation. 12132 if (!LegalTypes) { 12133 bool EverChanged = false; 12134 12135 do { 12136 // There can be multiple store sequences on the same chain. 12137 // Keep trying to merge store sequences until we are unable to do so 12138 // or until we merge the last store on the chain. 12139 bool Changed = MergeConsecutiveStores(ST); 12140 EverChanged |= Changed; 12141 if (!Changed) break; 12142 } while (ST->getOpcode() != ISD::DELETED_NODE); 12143 12144 if (EverChanged) 12145 return SDValue(N, 0); 12146 } 12147 12148 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12149 // 12150 // Make sure to do this only after attempting to merge stores in order to 12151 // avoid changing the types of some subset of stores due to visit order, 12152 // preventing their merging. 12153 if (isa<ConstantFPSDNode>(Value)) { 12154 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12155 return NewSt; 12156 } 12157 12158 return ReduceLoadOpStoreWidth(N); 12159 } 12160 12161 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12162 SDValue InVec = N->getOperand(0); 12163 SDValue InVal = N->getOperand(1); 12164 SDValue EltNo = N->getOperand(2); 12165 SDLoc dl(N); 12166 12167 // If the inserted element is an UNDEF, just use the input vector. 12168 if (InVal.isUndef()) 12169 return InVec; 12170 12171 EVT VT = InVec.getValueType(); 12172 12173 // If we can't generate a legal BUILD_VECTOR, exit 12174 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12175 return SDValue(); 12176 12177 // Check that we know which element is being inserted 12178 if (!isa<ConstantSDNode>(EltNo)) 12179 return SDValue(); 12180 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12181 12182 // Canonicalize insert_vector_elt dag nodes. 12183 // Example: 12184 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12185 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12186 // 12187 // Do this only if the child insert_vector node has one use; also 12188 // do this only if indices are both constants and Idx1 < Idx0. 12189 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12190 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12191 unsigned OtherElt = 12192 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12193 if (Elt < OtherElt) { 12194 // Swap nodes. 12195 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12196 InVec.getOperand(0), InVal, EltNo); 12197 AddToWorklist(NewOp.getNode()); 12198 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12199 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12200 } 12201 } 12202 12203 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12204 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12205 // vector elements. 12206 SmallVector<SDValue, 8> Ops; 12207 // Do not combine these two vectors if the output vector will not replace 12208 // the input vector. 12209 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12210 Ops.append(InVec.getNode()->op_begin(), 12211 InVec.getNode()->op_end()); 12212 } else if (InVec.isUndef()) { 12213 unsigned NElts = VT.getVectorNumElements(); 12214 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12215 } else { 12216 return SDValue(); 12217 } 12218 12219 // Insert the element 12220 if (Elt < Ops.size()) { 12221 // All the operands of BUILD_VECTOR must have the same type; 12222 // we enforce that here. 12223 EVT OpVT = Ops[0].getValueType(); 12224 if (InVal.getValueType() != OpVT) 12225 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12226 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12227 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12228 Ops[Elt] = InVal; 12229 } 12230 12231 // Return the new vector 12232 return DAG.getBuildVector(VT, dl, Ops); 12233 } 12234 12235 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12236 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12237 assert(!OriginalLoad->isVolatile()); 12238 12239 EVT ResultVT = EVE->getValueType(0); 12240 EVT VecEltVT = InVecVT.getVectorElementType(); 12241 unsigned Align = OriginalLoad->getAlignment(); 12242 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12243 VecEltVT.getTypeForEVT(*DAG.getContext())); 12244 12245 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12246 return SDValue(); 12247 12248 Align = NewAlign; 12249 12250 SDValue NewPtr = OriginalLoad->getBasePtr(); 12251 SDValue Offset; 12252 EVT PtrType = NewPtr.getValueType(); 12253 MachinePointerInfo MPI; 12254 SDLoc DL(EVE); 12255 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12256 int Elt = ConstEltNo->getZExtValue(); 12257 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12258 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12259 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12260 } else { 12261 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12262 Offset = DAG.getNode( 12263 ISD::MUL, DL, PtrType, Offset, 12264 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12265 MPI = OriginalLoad->getPointerInfo(); 12266 } 12267 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12268 12269 // The replacement we need to do here is a little tricky: we need to 12270 // replace an extractelement of a load with a load. 12271 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12272 // Note that this replacement assumes that the extractvalue is the only 12273 // use of the load; that's okay because we don't want to perform this 12274 // transformation in other cases anyway. 12275 SDValue Load; 12276 SDValue Chain; 12277 if (ResultVT.bitsGT(VecEltVT)) { 12278 // If the result type of vextract is wider than the load, then issue an 12279 // extending load instead. 12280 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12281 VecEltVT) 12282 ? ISD::ZEXTLOAD 12283 : ISD::EXTLOAD; 12284 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 12285 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 12286 Align, OriginalLoad->getMemOperand()->getFlags(), 12287 OriginalLoad->getAAInfo()); 12288 Chain = Load.getValue(1); 12289 } else { 12290 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 12291 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 12292 OriginalLoad->getAAInfo()); 12293 Chain = Load.getValue(1); 12294 if (ResultVT.bitsLT(VecEltVT)) 12295 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12296 else 12297 Load = DAG.getBitcast(ResultVT, Load); 12298 } 12299 WorklistRemover DeadNodes(*this); 12300 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12301 SDValue To[] = { Load, Chain }; 12302 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12303 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12304 // worklist explicitly as well. 12305 AddToWorklist(Load.getNode()); 12306 AddUsersToWorklist(Load.getNode()); // Add users too 12307 // Make sure to revisit this node to clean it up; it will usually be dead. 12308 AddToWorklist(EVE); 12309 ++OpsNarrowed; 12310 return SDValue(EVE, 0); 12311 } 12312 12313 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12314 // (vextract (scalar_to_vector val, 0) -> val 12315 SDValue InVec = N->getOperand(0); 12316 EVT VT = InVec.getValueType(); 12317 EVT NVT = N->getValueType(0); 12318 12319 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12320 // Check if the result type doesn't match the inserted element type. A 12321 // SCALAR_TO_VECTOR may truncate the inserted element and the 12322 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12323 SDValue InOp = InVec.getOperand(0); 12324 if (InOp.getValueType() != NVT) { 12325 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12326 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12327 } 12328 return InOp; 12329 } 12330 12331 SDValue EltNo = N->getOperand(1); 12332 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12333 12334 // extract_vector_elt (build_vector x, y), 1 -> y 12335 if (ConstEltNo && 12336 InVec.getOpcode() == ISD::BUILD_VECTOR && 12337 TLI.isTypeLegal(VT) && 12338 (InVec.hasOneUse() || 12339 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12340 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12341 EVT InEltVT = Elt.getValueType(); 12342 12343 // Sometimes build_vector's scalar input types do not match result type. 12344 if (NVT == InEltVT) 12345 return Elt; 12346 12347 // TODO: It may be useful to truncate if free if the build_vector implicitly 12348 // converts. 12349 } 12350 12351 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12352 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12353 ConstEltNo->isNullValue() && VT.isInteger()) { 12354 SDValue BCSrc = InVec.getOperand(0); 12355 if (BCSrc.getValueType().isScalarInteger()) 12356 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12357 } 12358 12359 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 12360 // 12361 // This only really matters if the index is non-constant since other combines 12362 // on the constant elements already work. 12363 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 12364 EltNo == InVec.getOperand(2)) { 12365 SDValue Elt = InVec.getOperand(1); 12366 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 12367 } 12368 12369 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12370 // We only perform this optimization before the op legalization phase because 12371 // we may introduce new vector instructions which are not backed by TD 12372 // patterns. For example on AVX, extracting elements from a wide vector 12373 // without using extract_subvector. However, if we can find an underlying 12374 // scalar value, then we can always use that. 12375 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12376 int NumElem = VT.getVectorNumElements(); 12377 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12378 // Find the new index to extract from. 12379 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12380 12381 // Extracting an undef index is undef. 12382 if (OrigElt == -1) 12383 return DAG.getUNDEF(NVT); 12384 12385 // Select the right vector half to extract from. 12386 SDValue SVInVec; 12387 if (OrigElt < NumElem) { 12388 SVInVec = InVec->getOperand(0); 12389 } else { 12390 SVInVec = InVec->getOperand(1); 12391 OrigElt -= NumElem; 12392 } 12393 12394 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12395 SDValue InOp = SVInVec.getOperand(OrigElt); 12396 if (InOp.getValueType() != NVT) { 12397 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12398 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12399 } 12400 12401 return InOp; 12402 } 12403 12404 // FIXME: We should handle recursing on other vector shuffles and 12405 // scalar_to_vector here as well. 12406 12407 if (!LegalOperations) { 12408 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12409 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12410 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12411 } 12412 } 12413 12414 bool BCNumEltsChanged = false; 12415 EVT ExtVT = VT.getVectorElementType(); 12416 EVT LVT = ExtVT; 12417 12418 // If the result of load has to be truncated, then it's not necessarily 12419 // profitable. 12420 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12421 return SDValue(); 12422 12423 if (InVec.getOpcode() == ISD::BITCAST) { 12424 // Don't duplicate a load with other uses. 12425 if (!InVec.hasOneUse()) 12426 return SDValue(); 12427 12428 EVT BCVT = InVec.getOperand(0).getValueType(); 12429 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12430 return SDValue(); 12431 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12432 BCNumEltsChanged = true; 12433 InVec = InVec.getOperand(0); 12434 ExtVT = BCVT.getVectorElementType(); 12435 } 12436 12437 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12438 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12439 ISD::isNormalLoad(InVec.getNode()) && 12440 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12441 SDValue Index = N->getOperand(1); 12442 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 12443 if (!OrigLoad->isVolatile()) { 12444 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12445 OrigLoad); 12446 } 12447 } 12448 } 12449 12450 // Perform only after legalization to ensure build_vector / vector_shuffle 12451 // optimizations have already been done. 12452 if (!LegalOperations) return SDValue(); 12453 12454 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12455 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12456 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12457 12458 if (ConstEltNo) { 12459 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12460 12461 LoadSDNode *LN0 = nullptr; 12462 const ShuffleVectorSDNode *SVN = nullptr; 12463 if (ISD::isNormalLoad(InVec.getNode())) { 12464 LN0 = cast<LoadSDNode>(InVec); 12465 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12466 InVec.getOperand(0).getValueType() == ExtVT && 12467 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12468 // Don't duplicate a load with other uses. 12469 if (!InVec.hasOneUse()) 12470 return SDValue(); 12471 12472 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12473 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12474 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12475 // => 12476 // (load $addr+1*size) 12477 12478 // Don't duplicate a load with other uses. 12479 if (!InVec.hasOneUse()) 12480 return SDValue(); 12481 12482 // If the bit convert changed the number of elements, it is unsafe 12483 // to examine the mask. 12484 if (BCNumEltsChanged) 12485 return SDValue(); 12486 12487 // Select the input vector, guarding against out of range extract vector. 12488 unsigned NumElems = VT.getVectorNumElements(); 12489 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12490 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12491 12492 if (InVec.getOpcode() == ISD::BITCAST) { 12493 // Don't duplicate a load with other uses. 12494 if (!InVec.hasOneUse()) 12495 return SDValue(); 12496 12497 InVec = InVec.getOperand(0); 12498 } 12499 if (ISD::isNormalLoad(InVec.getNode())) { 12500 LN0 = cast<LoadSDNode>(InVec); 12501 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12502 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12503 } 12504 } 12505 12506 // Make sure we found a non-volatile load and the extractelement is 12507 // the only use. 12508 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12509 return SDValue(); 12510 12511 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12512 if (Elt == -1) 12513 return DAG.getUNDEF(LVT); 12514 12515 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12516 } 12517 12518 return SDValue(); 12519 } 12520 12521 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12522 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12523 // We perform this optimization post type-legalization because 12524 // the type-legalizer often scalarizes integer-promoted vectors. 12525 // Performing this optimization before may create bit-casts which 12526 // will be type-legalized to complex code sequences. 12527 // We perform this optimization only before the operation legalizer because we 12528 // may introduce illegal operations. 12529 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12530 return SDValue(); 12531 12532 unsigned NumInScalars = N->getNumOperands(); 12533 SDLoc dl(N); 12534 EVT VT = N->getValueType(0); 12535 12536 // Check to see if this is a BUILD_VECTOR of a bunch of values 12537 // which come from any_extend or zero_extend nodes. If so, we can create 12538 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12539 // optimizations. We do not handle sign-extend because we can't fill the sign 12540 // using shuffles. 12541 EVT SourceType = MVT::Other; 12542 bool AllAnyExt = true; 12543 12544 for (unsigned i = 0; i != NumInScalars; ++i) { 12545 SDValue In = N->getOperand(i); 12546 // Ignore undef inputs. 12547 if (In.isUndef()) continue; 12548 12549 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12550 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12551 12552 // Abort if the element is not an extension. 12553 if (!ZeroExt && !AnyExt) { 12554 SourceType = MVT::Other; 12555 break; 12556 } 12557 12558 // The input is a ZeroExt or AnyExt. Check the original type. 12559 EVT InTy = In.getOperand(0).getValueType(); 12560 12561 // Check that all of the widened source types are the same. 12562 if (SourceType == MVT::Other) 12563 // First time. 12564 SourceType = InTy; 12565 else if (InTy != SourceType) { 12566 // Multiple income types. Abort. 12567 SourceType = MVT::Other; 12568 break; 12569 } 12570 12571 // Check if all of the extends are ANY_EXTENDs. 12572 AllAnyExt &= AnyExt; 12573 } 12574 12575 // In order to have valid types, all of the inputs must be extended from the 12576 // same source type and all of the inputs must be any or zero extend. 12577 // Scalar sizes must be a power of two. 12578 EVT OutScalarTy = VT.getScalarType(); 12579 bool ValidTypes = SourceType != MVT::Other && 12580 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12581 isPowerOf2_32(SourceType.getSizeInBits()); 12582 12583 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12584 // turn into a single shuffle instruction. 12585 if (!ValidTypes) 12586 return SDValue(); 12587 12588 bool isLE = DAG.getDataLayout().isLittleEndian(); 12589 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12590 assert(ElemRatio > 1 && "Invalid element size ratio"); 12591 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12592 DAG.getConstant(0, SDLoc(N), SourceType); 12593 12594 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12595 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12596 12597 // Populate the new build_vector 12598 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12599 SDValue Cast = N->getOperand(i); 12600 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12601 Cast.getOpcode() == ISD::ZERO_EXTEND || 12602 Cast.isUndef()) && "Invalid cast opcode"); 12603 SDValue In; 12604 if (Cast.isUndef()) 12605 In = DAG.getUNDEF(SourceType); 12606 else 12607 In = Cast->getOperand(0); 12608 unsigned Index = isLE ? (i * ElemRatio) : 12609 (i * ElemRatio + (ElemRatio - 1)); 12610 12611 assert(Index < Ops.size() && "Invalid index"); 12612 Ops[Index] = In; 12613 } 12614 12615 // The type of the new BUILD_VECTOR node. 12616 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12617 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12618 "Invalid vector size"); 12619 // Check if the new vector type is legal. 12620 if (!isTypeLegal(VecVT)) return SDValue(); 12621 12622 // Make the new BUILD_VECTOR. 12623 SDValue BV = DAG.getBuildVector(VecVT, dl, Ops); 12624 12625 // The new BUILD_VECTOR node has the potential to be further optimized. 12626 AddToWorklist(BV.getNode()); 12627 // Bitcast to the desired type. 12628 return DAG.getBitcast(VT, BV); 12629 } 12630 12631 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12632 EVT VT = N->getValueType(0); 12633 12634 unsigned NumInScalars = N->getNumOperands(); 12635 SDLoc dl(N); 12636 12637 EVT SrcVT = MVT::Other; 12638 unsigned Opcode = ISD::DELETED_NODE; 12639 unsigned NumDefs = 0; 12640 12641 for (unsigned i = 0; i != NumInScalars; ++i) { 12642 SDValue In = N->getOperand(i); 12643 unsigned Opc = In.getOpcode(); 12644 12645 if (Opc == ISD::UNDEF) 12646 continue; 12647 12648 // If all scalar values are floats and converted from integers. 12649 if (Opcode == ISD::DELETED_NODE && 12650 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12651 Opcode = Opc; 12652 } 12653 12654 if (Opc != Opcode) 12655 return SDValue(); 12656 12657 EVT InVT = In.getOperand(0).getValueType(); 12658 12659 // If all scalar values are typed differently, bail out. It's chosen to 12660 // simplify BUILD_VECTOR of integer types. 12661 if (SrcVT == MVT::Other) 12662 SrcVT = InVT; 12663 if (SrcVT != InVT) 12664 return SDValue(); 12665 NumDefs++; 12666 } 12667 12668 // If the vector has just one element defined, it's not worth to fold it into 12669 // a vectorized one. 12670 if (NumDefs < 2) 12671 return SDValue(); 12672 12673 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12674 && "Should only handle conversion from integer to float."); 12675 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12676 12677 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12678 12679 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12680 return SDValue(); 12681 12682 // Just because the floating-point vector type is legal does not necessarily 12683 // mean that the corresponding integer vector type is. 12684 if (!isTypeLegal(NVT)) 12685 return SDValue(); 12686 12687 SmallVector<SDValue, 8> Opnds; 12688 for (unsigned i = 0; i != NumInScalars; ++i) { 12689 SDValue In = N->getOperand(i); 12690 12691 if (In.isUndef()) 12692 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12693 else 12694 Opnds.push_back(In.getOperand(0)); 12695 } 12696 SDValue BV = DAG.getBuildVector(NVT, dl, Opnds); 12697 AddToWorklist(BV.getNode()); 12698 12699 return DAG.getNode(Opcode, dl, VT, BV); 12700 } 12701 12702 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12703 unsigned NumInScalars = N->getNumOperands(); 12704 SDLoc dl(N); 12705 EVT VT = N->getValueType(0); 12706 12707 // A vector built entirely of undefs is undef. 12708 if (ISD::allOperandsUndef(N)) 12709 return DAG.getUNDEF(VT); 12710 12711 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12712 return V; 12713 12714 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12715 return V; 12716 12717 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12718 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12719 // at most two distinct vectors, turn this into a shuffle node. 12720 12721 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12722 if (!isTypeLegal(VT)) 12723 return SDValue(); 12724 12725 // May only combine to shuffle after legalize if shuffle is legal. 12726 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12727 return SDValue(); 12728 12729 SDValue VecIn1, VecIn2; 12730 bool UsesZeroVector = false; 12731 for (unsigned i = 0; i != NumInScalars; ++i) { 12732 SDValue Op = N->getOperand(i); 12733 // Ignore undef inputs. 12734 if (Op.isUndef()) continue; 12735 12736 // See if we can combine this build_vector into a blend with a zero vector. 12737 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12738 UsesZeroVector = true; 12739 continue; 12740 } 12741 12742 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12743 // constant index, bail out. 12744 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12745 !isa<ConstantSDNode>(Op.getOperand(1))) { 12746 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12747 break; 12748 } 12749 12750 // We allow up to two distinct input vectors. 12751 SDValue ExtractedFromVec = Op.getOperand(0); 12752 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12753 continue; 12754 12755 if (!VecIn1.getNode()) { 12756 VecIn1 = ExtractedFromVec; 12757 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12758 VecIn2 = ExtractedFromVec; 12759 } else { 12760 // Too many inputs. 12761 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12762 break; 12763 } 12764 } 12765 12766 // If everything is good, we can make a shuffle operation. 12767 if (VecIn1.getNode()) { 12768 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12769 SmallVector<int, 8> Mask; 12770 for (unsigned i = 0; i != NumInScalars; ++i) { 12771 unsigned Opcode = N->getOperand(i).getOpcode(); 12772 if (Opcode == ISD::UNDEF) { 12773 Mask.push_back(-1); 12774 continue; 12775 } 12776 12777 // Operands can also be zero. 12778 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12779 assert(UsesZeroVector && 12780 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12781 "Unexpected node found!"); 12782 Mask.push_back(NumInScalars+i); 12783 continue; 12784 } 12785 12786 // If extracting from the first vector, just use the index directly. 12787 SDValue Extract = N->getOperand(i); 12788 SDValue ExtVal = Extract.getOperand(1); 12789 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12790 if (Extract.getOperand(0) == VecIn1) { 12791 Mask.push_back(ExtIndex); 12792 continue; 12793 } 12794 12795 // Otherwise, use InIdx + InputVecSize 12796 Mask.push_back(InNumElements + ExtIndex); 12797 } 12798 12799 // Avoid introducing illegal shuffles with zero. 12800 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12801 return SDValue(); 12802 12803 // We can't generate a shuffle node with mismatched input and output types. 12804 // Attempt to transform a single input vector to the correct type. 12805 if ((VT != VecIn1.getValueType())) { 12806 // If the input vector type has a different base type to the output 12807 // vector type, bail out. 12808 EVT VTElemType = VT.getVectorElementType(); 12809 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12810 (VecIn2.getNode() && 12811 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12812 return SDValue(); 12813 12814 // If the input vector is too small, widen it. 12815 // We only support widening of vectors which are half the size of the 12816 // output registers. For example XMM->YMM widening on X86 with AVX. 12817 EVT VecInT = VecIn1.getValueType(); 12818 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12819 // If we only have one small input, widen it by adding undef values. 12820 if (!VecIn2.getNode()) 12821 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12822 DAG.getUNDEF(VecIn1.getValueType())); 12823 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12824 // If we have two small inputs of the same type, try to concat them. 12825 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12826 VecIn2 = SDValue(nullptr, 0); 12827 } else 12828 return SDValue(); 12829 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12830 // If the input vector is too large, try to split it. 12831 // We don't support having two input vectors that are too large. 12832 // If the zero vector was used, we can not split the vector, 12833 // since we'd need 3 inputs. 12834 if (UsesZeroVector || VecIn2.getNode()) 12835 return SDValue(); 12836 12837 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12838 return SDValue(); 12839 12840 // Try to replace VecIn1 with two extract_subvectors 12841 // No need to update the masks, they should still be correct. 12842 VecIn2 = DAG.getNode( 12843 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12844 DAG.getConstant(VT.getVectorNumElements(), dl, 12845 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12846 VecIn1 = DAG.getNode( 12847 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12848 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12849 } else 12850 return SDValue(); 12851 } 12852 12853 if (UsesZeroVector) 12854 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12855 DAG.getConstantFP(0.0, dl, VT); 12856 else 12857 // If VecIn2 is unused then change it to undef. 12858 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12859 12860 // Check that we were able to transform all incoming values to the same 12861 // type. 12862 if (VecIn2.getValueType() != VecIn1.getValueType() || 12863 VecIn1.getValueType() != VT) 12864 return SDValue(); 12865 12866 // Return the new VECTOR_SHUFFLE node. 12867 SDValue Ops[2]; 12868 Ops[0] = VecIn1; 12869 Ops[1] = VecIn2; 12870 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], Mask); 12871 } 12872 12873 return SDValue(); 12874 } 12875 12876 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12877 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12878 EVT OpVT = N->getOperand(0).getValueType(); 12879 12880 // If the operands are legal vectors, leave them alone. 12881 if (TLI.isTypeLegal(OpVT)) 12882 return SDValue(); 12883 12884 SDLoc DL(N); 12885 EVT VT = N->getValueType(0); 12886 SmallVector<SDValue, 8> Ops; 12887 12888 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12889 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12890 12891 // Keep track of what we encounter. 12892 bool AnyInteger = false; 12893 bool AnyFP = false; 12894 for (const SDValue &Op : N->ops()) { 12895 if (ISD::BITCAST == Op.getOpcode() && 12896 !Op.getOperand(0).getValueType().isVector()) 12897 Ops.push_back(Op.getOperand(0)); 12898 else if (ISD::UNDEF == Op.getOpcode()) 12899 Ops.push_back(ScalarUndef); 12900 else 12901 return SDValue(); 12902 12903 // Note whether we encounter an integer or floating point scalar. 12904 // If it's neither, bail out, it could be something weird like x86mmx. 12905 EVT LastOpVT = Ops.back().getValueType(); 12906 if (LastOpVT.isFloatingPoint()) 12907 AnyFP = true; 12908 else if (LastOpVT.isInteger()) 12909 AnyInteger = true; 12910 else 12911 return SDValue(); 12912 } 12913 12914 // If any of the operands is a floating point scalar bitcast to a vector, 12915 // use floating point types throughout, and bitcast everything. 12916 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12917 if (AnyFP) { 12918 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12919 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12920 if (AnyInteger) { 12921 for (SDValue &Op : Ops) { 12922 if (Op.getValueType() == SVT) 12923 continue; 12924 if (Op.isUndef()) 12925 Op = ScalarUndef; 12926 else 12927 Op = DAG.getBitcast(SVT, Op); 12928 } 12929 } 12930 } 12931 12932 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12933 VT.getSizeInBits() / SVT.getSizeInBits()); 12934 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 12935 } 12936 12937 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12938 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12939 // most two distinct vectors the same size as the result, attempt to turn this 12940 // into a legal shuffle. 12941 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12942 EVT VT = N->getValueType(0); 12943 EVT OpVT = N->getOperand(0).getValueType(); 12944 int NumElts = VT.getVectorNumElements(); 12945 int NumOpElts = OpVT.getVectorNumElements(); 12946 12947 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12948 SmallVector<int, 8> Mask; 12949 12950 for (SDValue Op : N->ops()) { 12951 // Peek through any bitcast. 12952 while (Op.getOpcode() == ISD::BITCAST) 12953 Op = Op.getOperand(0); 12954 12955 // UNDEF nodes convert to UNDEF shuffle mask values. 12956 if (Op.isUndef()) { 12957 Mask.append((unsigned)NumOpElts, -1); 12958 continue; 12959 } 12960 12961 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12962 return SDValue(); 12963 12964 // What vector are we extracting the subvector from and at what index? 12965 SDValue ExtVec = Op.getOperand(0); 12966 12967 // We want the EVT of the original extraction to correctly scale the 12968 // extraction index. 12969 EVT ExtVT = ExtVec.getValueType(); 12970 12971 // Peek through any bitcast. 12972 while (ExtVec.getOpcode() == ISD::BITCAST) 12973 ExtVec = ExtVec.getOperand(0); 12974 12975 // UNDEF nodes convert to UNDEF shuffle mask values. 12976 if (ExtVec.isUndef()) { 12977 Mask.append((unsigned)NumOpElts, -1); 12978 continue; 12979 } 12980 12981 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12982 return SDValue(); 12983 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12984 12985 // Ensure that we are extracting a subvector from a vector the same 12986 // size as the result. 12987 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12988 return SDValue(); 12989 12990 // Scale the subvector index to account for any bitcast. 12991 int NumExtElts = ExtVT.getVectorNumElements(); 12992 if (0 == (NumExtElts % NumElts)) 12993 ExtIdx /= (NumExtElts / NumElts); 12994 else if (0 == (NumElts % NumExtElts)) 12995 ExtIdx *= (NumElts / NumExtElts); 12996 else 12997 return SDValue(); 12998 12999 // At most we can reference 2 inputs in the final shuffle. 13000 if (SV0.isUndef() || SV0 == ExtVec) { 13001 SV0 = ExtVec; 13002 for (int i = 0; i != NumOpElts; ++i) 13003 Mask.push_back(i + ExtIdx); 13004 } else if (SV1.isUndef() || SV1 == ExtVec) { 13005 SV1 = ExtVec; 13006 for (int i = 0; i != NumOpElts; ++i) 13007 Mask.push_back(i + ExtIdx + NumElts); 13008 } else { 13009 return SDValue(); 13010 } 13011 } 13012 13013 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13014 return SDValue(); 13015 13016 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13017 DAG.getBitcast(VT, SV1), Mask); 13018 } 13019 13020 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13021 // If we only have one input vector, we don't need to do any concatenation. 13022 if (N->getNumOperands() == 1) 13023 return N->getOperand(0); 13024 13025 // Check if all of the operands are undefs. 13026 EVT VT = N->getValueType(0); 13027 if (ISD::allOperandsUndef(N)) 13028 return DAG.getUNDEF(VT); 13029 13030 // Optimize concat_vectors where all but the first of the vectors are undef. 13031 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13032 return Op.isUndef(); 13033 })) { 13034 SDValue In = N->getOperand(0); 13035 assert(In.getValueType().isVector() && "Must concat vectors"); 13036 13037 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13038 if (In->getOpcode() == ISD::BITCAST && 13039 !In->getOperand(0)->getValueType(0).isVector()) { 13040 SDValue Scalar = In->getOperand(0); 13041 13042 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13043 // look through the trunc so we can still do the transform: 13044 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13045 if (Scalar->getOpcode() == ISD::TRUNCATE && 13046 !TLI.isTypeLegal(Scalar.getValueType()) && 13047 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13048 Scalar = Scalar->getOperand(0); 13049 13050 EVT SclTy = Scalar->getValueType(0); 13051 13052 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13053 return SDValue(); 13054 13055 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13056 VT.getSizeInBits() / SclTy.getSizeInBits()); 13057 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13058 return SDValue(); 13059 13060 SDLoc dl = SDLoc(N); 13061 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 13062 return DAG.getBitcast(VT, Res); 13063 } 13064 } 13065 13066 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13067 // We have already tested above for an UNDEF only concatenation. 13068 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13069 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13070 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13071 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13072 }; 13073 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13074 SmallVector<SDValue, 8> Opnds; 13075 EVT SVT = VT.getScalarType(); 13076 13077 EVT MinVT = SVT; 13078 if (!SVT.isFloatingPoint()) { 13079 // If BUILD_VECTOR are from built from integer, they may have different 13080 // operand types. Get the smallest type and truncate all operands to it. 13081 bool FoundMinVT = false; 13082 for (const SDValue &Op : N->ops()) 13083 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13084 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13085 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13086 FoundMinVT = true; 13087 } 13088 assert(FoundMinVT && "Concat vector type mismatch"); 13089 } 13090 13091 for (const SDValue &Op : N->ops()) { 13092 EVT OpVT = Op.getValueType(); 13093 unsigned NumElts = OpVT.getVectorNumElements(); 13094 13095 if (ISD::UNDEF == Op.getOpcode()) 13096 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13097 13098 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13099 if (SVT.isFloatingPoint()) { 13100 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13101 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13102 } else { 13103 for (unsigned i = 0; i != NumElts; ++i) 13104 Opnds.push_back( 13105 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13106 } 13107 } 13108 } 13109 13110 assert(VT.getVectorNumElements() == Opnds.size() && 13111 "Concat vector type mismatch"); 13112 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13113 } 13114 13115 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13116 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13117 return V; 13118 13119 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13120 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13121 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13122 return V; 13123 13124 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13125 // nodes often generate nop CONCAT_VECTOR nodes. 13126 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13127 // place the incoming vectors at the exact same location. 13128 SDValue SingleSource = SDValue(); 13129 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13130 13131 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13132 SDValue Op = N->getOperand(i); 13133 13134 if (Op.isUndef()) 13135 continue; 13136 13137 // Check if this is the identity extract: 13138 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13139 return SDValue(); 13140 13141 // Find the single incoming vector for the extract_subvector. 13142 if (SingleSource.getNode()) { 13143 if (Op.getOperand(0) != SingleSource) 13144 return SDValue(); 13145 } else { 13146 SingleSource = Op.getOperand(0); 13147 13148 // Check the source type is the same as the type of the result. 13149 // If not, this concat may extend the vector, so we can not 13150 // optimize it away. 13151 if (SingleSource.getValueType() != N->getValueType(0)) 13152 return SDValue(); 13153 } 13154 13155 unsigned IdentityIndex = i * PartNumElem; 13156 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13157 // The extract index must be constant. 13158 if (!CS) 13159 return SDValue(); 13160 13161 // Check that we are reading from the identity index. 13162 if (CS->getZExtValue() != IdentityIndex) 13163 return SDValue(); 13164 } 13165 13166 if (SingleSource.getNode()) 13167 return SingleSource; 13168 13169 return SDValue(); 13170 } 13171 13172 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13173 EVT NVT = N->getValueType(0); 13174 SDValue V = N->getOperand(0); 13175 13176 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13177 // Combine: 13178 // (extract_subvec (concat V1, V2, ...), i) 13179 // Into: 13180 // Vi if possible 13181 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13182 // type. 13183 if (V->getOperand(0).getValueType() != NVT) 13184 return SDValue(); 13185 unsigned Idx = N->getConstantOperandVal(1); 13186 unsigned NumElems = NVT.getVectorNumElements(); 13187 assert((Idx % NumElems) == 0 && 13188 "IDX in concat is not a multiple of the result vector length."); 13189 return V->getOperand(Idx / NumElems); 13190 } 13191 13192 // Skip bitcasting 13193 if (V->getOpcode() == ISD::BITCAST) 13194 V = V.getOperand(0); 13195 13196 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13197 SDLoc dl(N); 13198 // Handle only simple case where vector being inserted and vector 13199 // being extracted are of same type, and are half size of larger vectors. 13200 EVT BigVT = V->getOperand(0).getValueType(); 13201 EVT SmallVT = V->getOperand(1).getValueType(); 13202 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13203 return SDValue(); 13204 13205 // Only handle cases where both indexes are constants with the same type. 13206 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13207 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13208 13209 if (InsIdx && ExtIdx && 13210 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13211 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13212 // Combine: 13213 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13214 // Into: 13215 // indices are equal or bit offsets are equal => V1 13216 // otherwise => (extract_subvec V1, ExtIdx) 13217 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13218 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13219 return DAG.getBitcast(NVT, V->getOperand(1)); 13220 return DAG.getNode( 13221 ISD::EXTRACT_SUBVECTOR, dl, NVT, 13222 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 13223 N->getOperand(1)); 13224 } 13225 } 13226 13227 return SDValue(); 13228 } 13229 13230 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13231 SDValue V, SelectionDAG &DAG) { 13232 SDLoc DL(V); 13233 EVT VT = V.getValueType(); 13234 13235 switch (V.getOpcode()) { 13236 default: 13237 return V; 13238 13239 case ISD::CONCAT_VECTORS: { 13240 EVT OpVT = V->getOperand(0).getValueType(); 13241 int OpSize = OpVT.getVectorNumElements(); 13242 SmallBitVector OpUsedElements(OpSize, false); 13243 bool FoundSimplification = false; 13244 SmallVector<SDValue, 4> NewOps; 13245 NewOps.reserve(V->getNumOperands()); 13246 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13247 SDValue Op = V->getOperand(i); 13248 bool OpUsed = false; 13249 for (int j = 0; j < OpSize; ++j) 13250 if (UsedElements[i * OpSize + j]) { 13251 OpUsedElements[j] = true; 13252 OpUsed = true; 13253 } 13254 NewOps.push_back( 13255 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13256 : DAG.getUNDEF(OpVT)); 13257 FoundSimplification |= Op == NewOps.back(); 13258 OpUsedElements.reset(); 13259 } 13260 if (FoundSimplification) 13261 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13262 return V; 13263 } 13264 13265 case ISD::INSERT_SUBVECTOR: { 13266 SDValue BaseV = V->getOperand(0); 13267 SDValue SubV = V->getOperand(1); 13268 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13269 if (!IdxN) 13270 return V; 13271 13272 int SubSize = SubV.getValueType().getVectorNumElements(); 13273 int Idx = IdxN->getZExtValue(); 13274 bool SubVectorUsed = false; 13275 SmallBitVector SubUsedElements(SubSize, false); 13276 for (int i = 0; i < SubSize; ++i) 13277 if (UsedElements[i + Idx]) { 13278 SubVectorUsed = true; 13279 SubUsedElements[i] = true; 13280 UsedElements[i + Idx] = false; 13281 } 13282 13283 // Now recurse on both the base and sub vectors. 13284 SDValue SimplifiedSubV = 13285 SubVectorUsed 13286 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13287 : DAG.getUNDEF(SubV.getValueType()); 13288 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13289 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13290 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13291 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13292 return V; 13293 } 13294 } 13295 } 13296 13297 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13298 SDValue N1, SelectionDAG &DAG) { 13299 EVT VT = SVN->getValueType(0); 13300 int NumElts = VT.getVectorNumElements(); 13301 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13302 for (int M : SVN->getMask()) 13303 if (M >= 0 && M < NumElts) 13304 N0UsedElements[M] = true; 13305 else if (M >= NumElts) 13306 N1UsedElements[M - NumElts] = true; 13307 13308 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13309 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13310 if (S0 == N0 && S1 == N1) 13311 return SDValue(); 13312 13313 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13314 } 13315 13316 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13317 // or turn a shuffle of a single concat into simpler shuffle then concat. 13318 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13319 EVT VT = N->getValueType(0); 13320 unsigned NumElts = VT.getVectorNumElements(); 13321 13322 SDValue N0 = N->getOperand(0); 13323 SDValue N1 = N->getOperand(1); 13324 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13325 13326 SmallVector<SDValue, 4> Ops; 13327 EVT ConcatVT = N0.getOperand(0).getValueType(); 13328 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13329 unsigned NumConcats = NumElts / NumElemsPerConcat; 13330 13331 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13332 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13333 // half vector elements. 13334 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13335 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13336 SVN->getMask().end(), [](int i) { return i == -1; })) { 13337 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13338 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13339 N1 = DAG.getUNDEF(ConcatVT); 13340 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13341 } 13342 13343 // Look at every vector that's inserted. We're looking for exact 13344 // subvector-sized copies from a concatenated vector 13345 for (unsigned I = 0; I != NumConcats; ++I) { 13346 // Make sure we're dealing with a copy. 13347 unsigned Begin = I * NumElemsPerConcat; 13348 bool AllUndef = true, NoUndef = true; 13349 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13350 if (SVN->getMaskElt(J) >= 0) 13351 AllUndef = false; 13352 else 13353 NoUndef = false; 13354 } 13355 13356 if (NoUndef) { 13357 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13358 return SDValue(); 13359 13360 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13361 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13362 return SDValue(); 13363 13364 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13365 if (FirstElt < N0.getNumOperands()) 13366 Ops.push_back(N0.getOperand(FirstElt)); 13367 else 13368 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13369 13370 } else if (AllUndef) { 13371 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13372 } else { // Mixed with general masks and undefs, can't do optimization. 13373 return SDValue(); 13374 } 13375 } 13376 13377 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13378 } 13379 13380 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13381 EVT VT = N->getValueType(0); 13382 unsigned NumElts = VT.getVectorNumElements(); 13383 13384 SDValue N0 = N->getOperand(0); 13385 SDValue N1 = N->getOperand(1); 13386 13387 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13388 13389 // Canonicalize shuffle undef, undef -> undef 13390 if (N0.isUndef() && N1.isUndef()) 13391 return DAG.getUNDEF(VT); 13392 13393 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13394 13395 // Canonicalize shuffle v, v -> v, undef 13396 if (N0 == N1) { 13397 SmallVector<int, 8> NewMask; 13398 for (unsigned i = 0; i != NumElts; ++i) { 13399 int Idx = SVN->getMaskElt(i); 13400 if (Idx >= (int)NumElts) Idx -= NumElts; 13401 NewMask.push_back(Idx); 13402 } 13403 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 13404 } 13405 13406 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13407 if (N0.isUndef()) 13408 return DAG.getCommutedVectorShuffle(*SVN); 13409 13410 // Remove references to rhs if it is undef 13411 if (N1.isUndef()) { 13412 bool Changed = false; 13413 SmallVector<int, 8> NewMask; 13414 for (unsigned i = 0; i != NumElts; ++i) { 13415 int Idx = SVN->getMaskElt(i); 13416 if (Idx >= (int)NumElts) { 13417 Idx = -1; 13418 Changed = true; 13419 } 13420 NewMask.push_back(Idx); 13421 } 13422 if (Changed) 13423 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 13424 } 13425 13426 // If it is a splat, check if the argument vector is another splat or a 13427 // build_vector. 13428 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13429 SDNode *V = N0.getNode(); 13430 13431 // If this is a bit convert that changes the element type of the vector but 13432 // not the number of vector elements, look through it. Be careful not to 13433 // look though conversions that change things like v4f32 to v2f64. 13434 if (V->getOpcode() == ISD::BITCAST) { 13435 SDValue ConvInput = V->getOperand(0); 13436 if (ConvInput.getValueType().isVector() && 13437 ConvInput.getValueType().getVectorNumElements() == NumElts) 13438 V = ConvInput.getNode(); 13439 } 13440 13441 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13442 assert(V->getNumOperands() == NumElts && 13443 "BUILD_VECTOR has wrong number of operands"); 13444 SDValue Base; 13445 bool AllSame = true; 13446 for (unsigned i = 0; i != NumElts; ++i) { 13447 if (!V->getOperand(i).isUndef()) { 13448 Base = V->getOperand(i); 13449 break; 13450 } 13451 } 13452 // Splat of <u, u, u, u>, return <u, u, u, u> 13453 if (!Base.getNode()) 13454 return N0; 13455 for (unsigned i = 0; i != NumElts; ++i) { 13456 if (V->getOperand(i) != Base) { 13457 AllSame = false; 13458 break; 13459 } 13460 } 13461 // Splat of <x, x, x, x>, return <x, x, x, x> 13462 if (AllSame) 13463 return N0; 13464 13465 // Canonicalize any other splat as a build_vector. 13466 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13467 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13468 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 13469 13470 // We may have jumped through bitcasts, so the type of the 13471 // BUILD_VECTOR may not match the type of the shuffle. 13472 if (V->getValueType(0) != VT) 13473 NewBV = DAG.getBitcast(VT, NewBV); 13474 return NewBV; 13475 } 13476 } 13477 13478 // There are various patterns used to build up a vector from smaller vectors, 13479 // subvectors, or elements. Scan chains of these and replace unused insertions 13480 // or components with undef. 13481 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13482 return S; 13483 13484 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13485 Level < AfterLegalizeVectorOps && 13486 (N1.isUndef() || 13487 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13488 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13489 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13490 return V; 13491 } 13492 13493 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13494 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13495 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13496 SmallVector<SDValue, 8> Ops; 13497 for (int M : SVN->getMask()) { 13498 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13499 if (M >= 0) { 13500 int Idx = M % NumElts; 13501 SDValue &S = (M < (int)NumElts ? N0 : N1); 13502 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13503 Op = S.getOperand(Idx); 13504 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13505 if (Idx == 0) 13506 Op = S.getOperand(0); 13507 } else { 13508 // Operand can't be combined - bail out. 13509 break; 13510 } 13511 } 13512 Ops.push_back(Op); 13513 } 13514 if (Ops.size() == VT.getVectorNumElements()) { 13515 // BUILD_VECTOR requires all inputs to be of the same type, find the 13516 // maximum type and extend them all. 13517 EVT SVT = VT.getScalarType(); 13518 if (SVT.isInteger()) 13519 for (SDValue &Op : Ops) 13520 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13521 if (SVT != VT.getScalarType()) 13522 for (SDValue &Op : Ops) 13523 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13524 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13525 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13526 return DAG.getBuildVector(VT, SDLoc(N), Ops); 13527 } 13528 } 13529 13530 // If this shuffle only has a single input that is a bitcasted shuffle, 13531 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13532 // back to their original types. 13533 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13534 N1.isUndef() && Level < AfterLegalizeVectorOps && 13535 TLI.isTypeLegal(VT)) { 13536 13537 // Peek through the bitcast only if there is one user. 13538 SDValue BC0 = N0; 13539 while (BC0.getOpcode() == ISD::BITCAST) { 13540 if (!BC0.hasOneUse()) 13541 break; 13542 BC0 = BC0.getOperand(0); 13543 } 13544 13545 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13546 if (Scale == 1) 13547 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13548 13549 SmallVector<int, 8> NewMask; 13550 for (int M : Mask) 13551 for (int s = 0; s != Scale; ++s) 13552 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13553 return NewMask; 13554 }; 13555 13556 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13557 EVT SVT = VT.getScalarType(); 13558 EVT InnerVT = BC0->getValueType(0); 13559 EVT InnerSVT = InnerVT.getScalarType(); 13560 13561 // Determine which shuffle works with the smaller scalar type. 13562 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13563 EVT ScaleSVT = ScaleVT.getScalarType(); 13564 13565 if (TLI.isTypeLegal(ScaleVT) && 13566 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13567 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13568 13569 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13570 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13571 13572 // Scale the shuffle masks to the smaller scalar type. 13573 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13574 SmallVector<int, 8> InnerMask = 13575 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13576 SmallVector<int, 8> OuterMask = 13577 ScaleShuffleMask(SVN->getMask(), OuterScale); 13578 13579 // Merge the shuffle masks. 13580 SmallVector<int, 8> NewMask; 13581 for (int M : OuterMask) 13582 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13583 13584 // Test for shuffle mask legality over both commutations. 13585 SDValue SV0 = BC0->getOperand(0); 13586 SDValue SV1 = BC0->getOperand(1); 13587 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13588 if (!LegalMask) { 13589 std::swap(SV0, SV1); 13590 ShuffleVectorSDNode::commuteMask(NewMask); 13591 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13592 } 13593 13594 if (LegalMask) { 13595 SV0 = DAG.getBitcast(ScaleVT, SV0); 13596 SV1 = DAG.getBitcast(ScaleVT, SV1); 13597 return DAG.getBitcast( 13598 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13599 } 13600 } 13601 } 13602 } 13603 13604 // Canonicalize shuffles according to rules: 13605 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13606 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13607 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13608 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13609 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13610 TLI.isTypeLegal(VT)) { 13611 // The incoming shuffle must be of the same type as the result of the 13612 // current shuffle. 13613 assert(N1->getOperand(0).getValueType() == VT && 13614 "Shuffle types don't match"); 13615 13616 SDValue SV0 = N1->getOperand(0); 13617 SDValue SV1 = N1->getOperand(1); 13618 bool HasSameOp0 = N0 == SV0; 13619 bool IsSV1Undef = SV1.isUndef(); 13620 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13621 // Commute the operands of this shuffle so that next rule 13622 // will trigger. 13623 return DAG.getCommutedVectorShuffle(*SVN); 13624 } 13625 13626 // Try to fold according to rules: 13627 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13628 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13629 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13630 // Don't try to fold shuffles with illegal type. 13631 // Only fold if this shuffle is the only user of the other shuffle. 13632 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13633 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13634 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13635 13636 // The incoming shuffle must be of the same type as the result of the 13637 // current shuffle. 13638 assert(OtherSV->getOperand(0).getValueType() == VT && 13639 "Shuffle types don't match"); 13640 13641 SDValue SV0, SV1; 13642 SmallVector<int, 4> Mask; 13643 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13644 // operand, and SV1 as the second operand. 13645 for (unsigned i = 0; i != NumElts; ++i) { 13646 int Idx = SVN->getMaskElt(i); 13647 if (Idx < 0) { 13648 // Propagate Undef. 13649 Mask.push_back(Idx); 13650 continue; 13651 } 13652 13653 SDValue CurrentVec; 13654 if (Idx < (int)NumElts) { 13655 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13656 // shuffle mask to identify which vector is actually referenced. 13657 Idx = OtherSV->getMaskElt(Idx); 13658 if (Idx < 0) { 13659 // Propagate Undef. 13660 Mask.push_back(Idx); 13661 continue; 13662 } 13663 13664 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13665 : OtherSV->getOperand(1); 13666 } else { 13667 // This shuffle index references an element within N1. 13668 CurrentVec = N1; 13669 } 13670 13671 // Simple case where 'CurrentVec' is UNDEF. 13672 if (CurrentVec.isUndef()) { 13673 Mask.push_back(-1); 13674 continue; 13675 } 13676 13677 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13678 // will be the first or second operand of the combined shuffle. 13679 Idx = Idx % NumElts; 13680 if (!SV0.getNode() || SV0 == CurrentVec) { 13681 // Ok. CurrentVec is the left hand side. 13682 // Update the mask accordingly. 13683 SV0 = CurrentVec; 13684 Mask.push_back(Idx); 13685 continue; 13686 } 13687 13688 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13689 if (SV1.getNode() && SV1 != CurrentVec) 13690 return SDValue(); 13691 13692 // Ok. CurrentVec is the right hand side. 13693 // Update the mask accordingly. 13694 SV1 = CurrentVec; 13695 Mask.push_back(Idx + NumElts); 13696 } 13697 13698 // Check if all indices in Mask are Undef. In case, propagate Undef. 13699 bool isUndefMask = true; 13700 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13701 isUndefMask &= Mask[i] < 0; 13702 13703 if (isUndefMask) 13704 return DAG.getUNDEF(VT); 13705 13706 if (!SV0.getNode()) 13707 SV0 = DAG.getUNDEF(VT); 13708 if (!SV1.getNode()) 13709 SV1 = DAG.getUNDEF(VT); 13710 13711 // Avoid introducing shuffles with illegal mask. 13712 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13713 ShuffleVectorSDNode::commuteMask(Mask); 13714 13715 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13716 return SDValue(); 13717 13718 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13719 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13720 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13721 std::swap(SV0, SV1); 13722 } 13723 13724 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13725 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13726 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13727 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 13728 } 13729 13730 return SDValue(); 13731 } 13732 13733 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13734 SDValue InVal = N->getOperand(0); 13735 EVT VT = N->getValueType(0); 13736 13737 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13738 // with a VECTOR_SHUFFLE. 13739 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13740 SDValue InVec = InVal->getOperand(0); 13741 SDValue EltNo = InVal->getOperand(1); 13742 13743 // FIXME: We could support implicit truncation if the shuffle can be 13744 // scaled to a smaller vector scalar type. 13745 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13746 if (C0 && VT == InVec.getValueType() && 13747 VT.getScalarType() == InVal.getValueType()) { 13748 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13749 int Elt = C0->getZExtValue(); 13750 NewMask[0] = Elt; 13751 13752 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13753 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13754 NewMask); 13755 } 13756 } 13757 13758 return SDValue(); 13759 } 13760 13761 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13762 SDValue N0 = N->getOperand(0); 13763 SDValue N1 = N->getOperand(1); 13764 SDValue N2 = N->getOperand(2); 13765 13766 if (N0.getValueType() != N1.getValueType()) 13767 return SDValue(); 13768 13769 // If the input vector is a concatenation, and the insert replaces 13770 // one of the halves, we can optimize into a single concat_vectors. 13771 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 && 13772 N2.getOpcode() == ISD::Constant) { 13773 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13774 EVT VT = N->getValueType(0); 13775 13776 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13777 // (concat_vectors Z, Y) 13778 if (InsIdx == 0) 13779 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1, 13780 N0.getOperand(1)); 13781 13782 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13783 // (concat_vectors X, Z) 13784 if (InsIdx == VT.getVectorNumElements() / 2) 13785 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0), 13786 N1); 13787 } 13788 13789 return SDValue(); 13790 } 13791 13792 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13793 SDValue N0 = N->getOperand(0); 13794 13795 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13796 if (N0->getOpcode() == ISD::FP16_TO_FP) 13797 return N0->getOperand(0); 13798 13799 return SDValue(); 13800 } 13801 13802 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13803 SDValue N0 = N->getOperand(0); 13804 13805 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13806 if (N0->getOpcode() == ISD::AND) { 13807 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13808 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13809 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13810 N0.getOperand(0)); 13811 } 13812 } 13813 13814 return SDValue(); 13815 } 13816 13817 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13818 /// with the destination vector and a zero vector. 13819 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13820 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13821 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13822 EVT VT = N->getValueType(0); 13823 SDValue LHS = N->getOperand(0); 13824 SDValue RHS = N->getOperand(1); 13825 SDLoc dl(N); 13826 13827 // Make sure we're not running after operation legalization where it 13828 // may have custom lowered the vector shuffles. 13829 if (LegalOperations) 13830 return SDValue(); 13831 13832 if (N->getOpcode() != ISD::AND) 13833 return SDValue(); 13834 13835 if (RHS.getOpcode() == ISD::BITCAST) 13836 RHS = RHS.getOperand(0); 13837 13838 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13839 return SDValue(); 13840 13841 EVT RVT = RHS.getValueType(); 13842 unsigned NumElts = RHS.getNumOperands(); 13843 13844 // Attempt to create a valid clear mask, splitting the mask into 13845 // sub elements and checking to see if each is 13846 // all zeros or all ones - suitable for shuffle masking. 13847 auto BuildClearMask = [&](int Split) { 13848 int NumSubElts = NumElts * Split; 13849 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13850 13851 SmallVector<int, 8> Indices; 13852 for (int i = 0; i != NumSubElts; ++i) { 13853 int EltIdx = i / Split; 13854 int SubIdx = i % Split; 13855 SDValue Elt = RHS.getOperand(EltIdx); 13856 if (Elt.isUndef()) { 13857 Indices.push_back(-1); 13858 continue; 13859 } 13860 13861 APInt Bits; 13862 if (isa<ConstantSDNode>(Elt)) 13863 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13864 else if (isa<ConstantFPSDNode>(Elt)) 13865 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13866 else 13867 return SDValue(); 13868 13869 // Extract the sub element from the constant bit mask. 13870 if (DAG.getDataLayout().isBigEndian()) { 13871 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13872 } else { 13873 Bits = Bits.lshr(SubIdx * NumSubBits); 13874 } 13875 13876 if (Split > 1) 13877 Bits = Bits.trunc(NumSubBits); 13878 13879 if (Bits.isAllOnesValue()) 13880 Indices.push_back(i); 13881 else if (Bits == 0) 13882 Indices.push_back(i + NumSubElts); 13883 else 13884 return SDValue(); 13885 } 13886 13887 // Let's see if the target supports this vector_shuffle. 13888 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13889 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13890 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13891 return SDValue(); 13892 13893 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13894 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13895 DAG.getBitcast(ClearVT, LHS), 13896 Zero, Indices)); 13897 }; 13898 13899 // Determine maximum split level (byte level masking). 13900 int MaxSplit = 1; 13901 if (RVT.getScalarSizeInBits() % 8 == 0) 13902 MaxSplit = RVT.getScalarSizeInBits() / 8; 13903 13904 for (int Split = 1; Split <= MaxSplit; ++Split) 13905 if (RVT.getScalarSizeInBits() % Split == 0) 13906 if (SDValue S = BuildClearMask(Split)) 13907 return S; 13908 13909 return SDValue(); 13910 } 13911 13912 /// Visit a binary vector operation, like ADD. 13913 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13914 assert(N->getValueType(0).isVector() && 13915 "SimplifyVBinOp only works on vectors!"); 13916 13917 SDValue LHS = N->getOperand(0); 13918 SDValue RHS = N->getOperand(1); 13919 SDValue Ops[] = {LHS, RHS}; 13920 13921 // See if we can constant fold the vector operation. 13922 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13923 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13924 return Fold; 13925 13926 // Try to convert a constant mask AND into a shuffle clear mask. 13927 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13928 return Shuffle; 13929 13930 // Type legalization might introduce new shuffles in the DAG. 13931 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13932 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13933 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13934 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13935 LHS.getOperand(1).isUndef() && 13936 RHS.getOperand(1).isUndef()) { 13937 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13938 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13939 13940 if (SVN0->getMask().equals(SVN1->getMask())) { 13941 EVT VT = N->getValueType(0); 13942 SDValue UndefVector = LHS.getOperand(1); 13943 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13944 LHS.getOperand(0), RHS.getOperand(0), 13945 N->getFlags()); 13946 AddUsersToWorklist(N); 13947 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13948 SVN0->getMask()); 13949 } 13950 } 13951 13952 return SDValue(); 13953 } 13954 13955 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 13956 SDValue N2) { 13957 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13958 13959 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13960 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13961 13962 // If we got a simplified select_cc node back from SimplifySelectCC, then 13963 // break it down into a new SETCC node, and a new SELECT node, and then return 13964 // the SELECT node, since we were called with a SELECT node. 13965 if (SCC.getNode()) { 13966 // Check to see if we got a select_cc back (to turn into setcc/select). 13967 // Otherwise, just return whatever node we got back, like fabs. 13968 if (SCC.getOpcode() == ISD::SELECT_CC) { 13969 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13970 N0.getValueType(), 13971 SCC.getOperand(0), SCC.getOperand(1), 13972 SCC.getOperand(4)); 13973 AddToWorklist(SETCC.getNode()); 13974 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13975 SCC.getOperand(2), SCC.getOperand(3)); 13976 } 13977 13978 return SCC; 13979 } 13980 return SDValue(); 13981 } 13982 13983 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13984 /// being selected between, see if we can simplify the select. Callers of this 13985 /// should assume that TheSelect is deleted if this returns true. As such, they 13986 /// should return the appropriate thing (e.g. the node) back to the top-level of 13987 /// the DAG combiner loop to avoid it being looked at. 13988 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13989 SDValue RHS) { 13990 13991 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 13992 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 13993 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13994 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13995 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13996 SDValue Sqrt = RHS; 13997 ISD::CondCode CC; 13998 SDValue CmpLHS; 13999 const ConstantFPSDNode *Zero = nullptr; 14000 14001 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 14002 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 14003 CmpLHS = TheSelect->getOperand(0); 14004 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 14005 } else { 14006 // SELECT or VSELECT 14007 SDValue Cmp = TheSelect->getOperand(0); 14008 if (Cmp.getOpcode() == ISD::SETCC) { 14009 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 14010 CmpLHS = Cmp.getOperand(0); 14011 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 14012 } 14013 } 14014 if (Zero && Zero->isZero() && 14015 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 14016 CC == ISD::SETULT || CC == ISD::SETLT)) { 14017 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14018 CombineTo(TheSelect, Sqrt); 14019 return true; 14020 } 14021 } 14022 } 14023 // Cannot simplify select with vector condition 14024 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 14025 14026 // If this is a select from two identical things, try to pull the operation 14027 // through the select. 14028 if (LHS.getOpcode() != RHS.getOpcode() || 14029 !LHS.hasOneUse() || !RHS.hasOneUse()) 14030 return false; 14031 14032 // If this is a load and the token chain is identical, replace the select 14033 // of two loads with a load through a select of the address to load from. 14034 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 14035 // constants have been dropped into the constant pool. 14036 if (LHS.getOpcode() == ISD::LOAD) { 14037 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 14038 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 14039 14040 // Token chains must be identical. 14041 if (LHS.getOperand(0) != RHS.getOperand(0) || 14042 // Do not let this transformation reduce the number of volatile loads. 14043 LLD->isVolatile() || RLD->isVolatile() || 14044 // FIXME: If either is a pre/post inc/dec load, 14045 // we'd need to split out the address adjustment. 14046 LLD->isIndexed() || RLD->isIndexed() || 14047 // If this is an EXTLOAD, the VT's must match. 14048 LLD->getMemoryVT() != RLD->getMemoryVT() || 14049 // If this is an EXTLOAD, the kind of extension must match. 14050 (LLD->getExtensionType() != RLD->getExtensionType() && 14051 // The only exception is if one of the extensions is anyext. 14052 LLD->getExtensionType() != ISD::EXTLOAD && 14053 RLD->getExtensionType() != ISD::EXTLOAD) || 14054 // FIXME: this discards src value information. This is 14055 // over-conservative. It would be beneficial to be able to remember 14056 // both potential memory locations. Since we are discarding 14057 // src value info, don't do the transformation if the memory 14058 // locations are not in the default address space. 14059 LLD->getPointerInfo().getAddrSpace() != 0 || 14060 RLD->getPointerInfo().getAddrSpace() != 0 || 14061 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 14062 LLD->getBasePtr().getValueType())) 14063 return false; 14064 14065 // Check that the select condition doesn't reach either load. If so, 14066 // folding this will induce a cycle into the DAG. If not, this is safe to 14067 // xform, so create a select of the addresses. 14068 SDValue Addr; 14069 if (TheSelect->getOpcode() == ISD::SELECT) { 14070 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 14071 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 14072 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 14073 return false; 14074 // The loads must not depend on one another. 14075 if (LLD->isPredecessorOf(RLD) || 14076 RLD->isPredecessorOf(LLD)) 14077 return false; 14078 Addr = DAG.getSelect(SDLoc(TheSelect), 14079 LLD->getBasePtr().getValueType(), 14080 TheSelect->getOperand(0), LLD->getBasePtr(), 14081 RLD->getBasePtr()); 14082 } else { // Otherwise SELECT_CC 14083 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14084 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14085 14086 if ((LLD->hasAnyUseOfValue(1) && 14087 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14088 (RLD->hasAnyUseOfValue(1) && 14089 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14090 return false; 14091 14092 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14093 LLD->getBasePtr().getValueType(), 14094 TheSelect->getOperand(0), 14095 TheSelect->getOperand(1), 14096 LLD->getBasePtr(), RLD->getBasePtr(), 14097 TheSelect->getOperand(4)); 14098 } 14099 14100 SDValue Load; 14101 // It is safe to replace the two loads if they have different alignments, 14102 // but the new load must be the minimum (most restrictive) alignment of the 14103 // inputs. 14104 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14105 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 14106 if (!RLD->isInvariant()) 14107 MMOFlags &= ~MachineMemOperand::MOInvariant; 14108 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14109 // FIXME: Discards pointer and AA info. 14110 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 14111 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 14112 MMOFlags); 14113 } else { 14114 // FIXME: Discards pointer and AA info. 14115 Load = DAG.getExtLoad( 14116 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 14117 : LLD->getExtensionType(), 14118 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 14119 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 14120 } 14121 14122 // Users of the select now use the result of the load. 14123 CombineTo(TheSelect, Load); 14124 14125 // Users of the old loads now use the new load's chain. We know the 14126 // old-load value is dead now. 14127 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14128 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14129 return true; 14130 } 14131 14132 return false; 14133 } 14134 14135 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14136 /// where 'cond' is the comparison specified by CC. 14137 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 14138 SDValue N2, SDValue N3, ISD::CondCode CC, 14139 bool NotExtCompare) { 14140 // (x ? y : y) -> y. 14141 if (N2 == N3) return N2; 14142 14143 EVT VT = N2.getValueType(); 14144 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14145 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14146 14147 // Determine if the condition we're dealing with is constant 14148 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14149 N0, N1, CC, DL, false); 14150 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14151 14152 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14153 // fold select_cc true, x, y -> x 14154 // fold select_cc false, x, y -> y 14155 return !SCCC->isNullValue() ? N2 : N3; 14156 } 14157 14158 // Check to see if we can simplify the select into an fabs node 14159 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14160 // Allow either -0.0 or 0.0 14161 if (CFP->isZero()) { 14162 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14163 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14164 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14165 N2 == N3.getOperand(0)) 14166 return DAG.getNode(ISD::FABS, DL, VT, N0); 14167 14168 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14169 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14170 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14171 N2.getOperand(0) == N3) 14172 return DAG.getNode(ISD::FABS, DL, VT, N3); 14173 } 14174 } 14175 14176 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14177 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14178 // in it. This is a win when the constant is not otherwise available because 14179 // it replaces two constant pool loads with one. We only do this if the FP 14180 // type is known to be legal, because if it isn't, then we are before legalize 14181 // types an we want the other legalization to happen first (e.g. to avoid 14182 // messing with soft float) and if the ConstantFP is not legal, because if 14183 // it is legal, we may not need to store the FP constant in a constant pool. 14184 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14185 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14186 if (TLI.isTypeLegal(N2.getValueType()) && 14187 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14188 TargetLowering::Legal && 14189 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14190 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14191 // If both constants have multiple uses, then we won't need to do an 14192 // extra load, they are likely around in registers for other users. 14193 (TV->hasOneUse() || FV->hasOneUse())) { 14194 Constant *Elts[] = { 14195 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14196 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14197 }; 14198 Type *FPTy = Elts[0]->getType(); 14199 const DataLayout &TD = DAG.getDataLayout(); 14200 14201 // Create a ConstantArray of the two constants. 14202 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14203 SDValue CPIdx = 14204 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14205 TD.getPrefTypeAlignment(FPTy)); 14206 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14207 14208 // Get the offsets to the 0 and 1 element of the array so that we can 14209 // select between them. 14210 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14211 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14212 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14213 14214 SDValue Cond = DAG.getSetCC(DL, 14215 getSetCCResultType(N0.getValueType()), 14216 N0, N1, CC); 14217 AddToWorklist(Cond.getNode()); 14218 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14219 Cond, One, Zero); 14220 AddToWorklist(CstOffset.getNode()); 14221 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14222 CstOffset); 14223 AddToWorklist(CPIdx.getNode()); 14224 return DAG.getLoad( 14225 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14226 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14227 Alignment); 14228 } 14229 } 14230 14231 // Check to see if we can perform the "gzip trick", transforming 14232 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14233 if (isNullConstant(N3) && CC == ISD::SETLT && 14234 (isNullConstant(N1) || // (a < 0) ? b : 0 14235 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14236 EVT XType = N0.getValueType(); 14237 EVT AType = N2.getValueType(); 14238 if (XType.bitsGE(AType)) { 14239 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14240 // single-bit constant. 14241 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14242 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14243 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14244 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14245 getShiftAmountTy(N0.getValueType())); 14246 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14247 XType, N0, ShCt); 14248 AddToWorklist(Shift.getNode()); 14249 14250 if (XType.bitsGT(AType)) { 14251 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14252 AddToWorklist(Shift.getNode()); 14253 } 14254 14255 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14256 } 14257 14258 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14259 XType, N0, 14260 DAG.getConstant(XType.getSizeInBits() - 1, 14261 SDLoc(N0), 14262 getShiftAmountTy(N0.getValueType()))); 14263 AddToWorklist(Shift.getNode()); 14264 14265 if (XType.bitsGT(AType)) { 14266 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14267 AddToWorklist(Shift.getNode()); 14268 } 14269 14270 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14271 } 14272 } 14273 14274 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14275 // where y is has a single bit set. 14276 // A plaintext description would be, we can turn the SELECT_CC into an AND 14277 // when the condition can be materialized as an all-ones register. Any 14278 // single bit-test can be materialized as an all-ones register with 14279 // shift-left and shift-right-arith. 14280 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14281 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14282 SDValue AndLHS = N0->getOperand(0); 14283 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14284 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14285 // Shift the tested bit over the sign bit. 14286 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 14287 SDValue ShlAmt = 14288 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14289 getShiftAmountTy(AndLHS.getValueType())); 14290 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14291 14292 // Now arithmetic right shift it all the way over, so the result is either 14293 // all-ones, or zero. 14294 SDValue ShrAmt = 14295 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14296 getShiftAmountTy(Shl.getValueType())); 14297 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14298 14299 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14300 } 14301 } 14302 14303 // fold select C, 16, 0 -> shl C, 4 14304 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14305 TLI.getBooleanContents(N0.getValueType()) == 14306 TargetLowering::ZeroOrOneBooleanContent) { 14307 14308 // If the caller doesn't want us to simplify this into a zext of a compare, 14309 // don't do it. 14310 if (NotExtCompare && N2C->isOne()) 14311 return SDValue(); 14312 14313 // Get a SetCC of the condition 14314 // NOTE: Don't create a SETCC if it's not legal on this target. 14315 if (!LegalOperations || 14316 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14317 SDValue Temp, SCC; 14318 // cast from setcc result type to select result type 14319 if (LegalTypes) { 14320 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14321 N0, N1, CC); 14322 if (N2.getValueType().bitsLT(SCC.getValueType())) 14323 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14324 N2.getValueType()); 14325 else 14326 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14327 N2.getValueType(), SCC); 14328 } else { 14329 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14330 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14331 N2.getValueType(), SCC); 14332 } 14333 14334 AddToWorklist(SCC.getNode()); 14335 AddToWorklist(Temp.getNode()); 14336 14337 if (N2C->isOne()) 14338 return Temp; 14339 14340 // shl setcc result by log2 n2c 14341 return DAG.getNode( 14342 ISD::SHL, DL, N2.getValueType(), Temp, 14343 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14344 getShiftAmountTy(Temp.getValueType()))); 14345 } 14346 } 14347 14348 // Check to see if this is an integer abs. 14349 // select_cc setg[te] X, 0, X, -X -> 14350 // select_cc setgt X, -1, X, -X -> 14351 // select_cc setl[te] X, 0, -X, X -> 14352 // select_cc setlt X, 1, -X, X -> 14353 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14354 if (N1C) { 14355 ConstantSDNode *SubC = nullptr; 14356 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14357 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14358 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14359 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14360 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14361 (N1C->isOne() && CC == ISD::SETLT)) && 14362 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14363 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14364 14365 EVT XType = N0.getValueType(); 14366 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14367 SDLoc DL(N0); 14368 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14369 N0, 14370 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14371 getShiftAmountTy(N0.getValueType()))); 14372 SDValue Add = DAG.getNode(ISD::ADD, DL, 14373 XType, N0, Shift); 14374 AddToWorklist(Shift.getNode()); 14375 AddToWorklist(Add.getNode()); 14376 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14377 } 14378 } 14379 14380 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 14381 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 14382 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 14383 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 14384 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 14385 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 14386 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 14387 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 14388 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 14389 SDValue ValueOnZero = N2; 14390 SDValue Count = N3; 14391 // If the condition is NE instead of E, swap the operands. 14392 if (CC == ISD::SETNE) 14393 std::swap(ValueOnZero, Count); 14394 // Check if the value on zero is a constant equal to the bits in the type. 14395 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 14396 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 14397 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 14398 // legal, combine to just cttz. 14399 if ((Count.getOpcode() == ISD::CTTZ || 14400 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 14401 N0 == Count.getOperand(0) && 14402 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 14403 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 14404 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 14405 // legal, combine to just ctlz. 14406 if ((Count.getOpcode() == ISD::CTLZ || 14407 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 14408 N0 == Count.getOperand(0) && 14409 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 14410 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 14411 } 14412 } 14413 } 14414 14415 return SDValue(); 14416 } 14417 14418 /// This is a stub for TargetLowering::SimplifySetCC. 14419 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 14420 ISD::CondCode Cond, const SDLoc &DL, 14421 bool foldBooleans) { 14422 TargetLowering::DAGCombinerInfo 14423 DagCombineInfo(DAG, Level, false, this); 14424 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14425 } 14426 14427 /// Given an ISD::SDIV node expressing a divide by constant, return 14428 /// a DAG expression to select that will generate the same value by multiplying 14429 /// by a magic number. 14430 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14431 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14432 // when optimising for minimum size, we don't want to expand a div to a mul 14433 // and a shift. 14434 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14435 return SDValue(); 14436 14437 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14438 if (!C) 14439 return SDValue(); 14440 14441 // Avoid division by zero. 14442 if (C->isNullValue()) 14443 return SDValue(); 14444 14445 std::vector<SDNode*> Built; 14446 SDValue S = 14447 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14448 14449 for (SDNode *N : Built) 14450 AddToWorklist(N); 14451 return S; 14452 } 14453 14454 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14455 /// DAG expression that will generate the same value by right shifting. 14456 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14457 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14458 if (!C) 14459 return SDValue(); 14460 14461 // Avoid division by zero. 14462 if (C->isNullValue()) 14463 return SDValue(); 14464 14465 std::vector<SDNode *> Built; 14466 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14467 14468 for (SDNode *N : Built) 14469 AddToWorklist(N); 14470 return S; 14471 } 14472 14473 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14474 /// expression that will generate the same value by multiplying by a magic 14475 /// number. 14476 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14477 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14478 // when optimising for minimum size, we don't want to expand a div to a mul 14479 // and a shift. 14480 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14481 return SDValue(); 14482 14483 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14484 if (!C) 14485 return SDValue(); 14486 14487 // Avoid division by zero. 14488 if (C->isNullValue()) 14489 return SDValue(); 14490 14491 std::vector<SDNode*> Built; 14492 SDValue S = 14493 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14494 14495 for (SDNode *N : Built) 14496 AddToWorklist(N); 14497 return S; 14498 } 14499 14500 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14501 if (Level >= AfterLegalizeDAG) 14502 return SDValue(); 14503 14504 // Expose the DAG combiner to the target combiner implementations. 14505 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14506 14507 unsigned Iterations = 0; 14508 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14509 if (Iterations) { 14510 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14511 // For the reciprocal, we need to find the zero of the function: 14512 // F(X) = A X - 1 [which has a zero at X = 1/A] 14513 // => 14514 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14515 // does not require additional intermediate precision] 14516 EVT VT = Op.getValueType(); 14517 SDLoc DL(Op); 14518 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14519 14520 AddToWorklist(Est.getNode()); 14521 14522 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14523 for (unsigned i = 0; i < Iterations; ++i) { 14524 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14525 AddToWorklist(NewEst.getNode()); 14526 14527 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14528 AddToWorklist(NewEst.getNode()); 14529 14530 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14531 AddToWorklist(NewEst.getNode()); 14532 14533 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14534 AddToWorklist(Est.getNode()); 14535 } 14536 } 14537 return Est; 14538 } 14539 14540 return SDValue(); 14541 } 14542 14543 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14544 /// For the reciprocal sqrt, we need to find the zero of the function: 14545 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14546 /// => 14547 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14548 /// As a result, we precompute A/2 prior to the iteration loop. 14549 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 14550 unsigned Iterations, 14551 SDNodeFlags *Flags, bool Reciprocal) { 14552 EVT VT = Arg.getValueType(); 14553 SDLoc DL(Arg); 14554 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14555 14556 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14557 // this entire sequence requires only one FP constant. 14558 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14559 AddToWorklist(HalfArg.getNode()); 14560 14561 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14562 AddToWorklist(HalfArg.getNode()); 14563 14564 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14565 for (unsigned i = 0; i < Iterations; ++i) { 14566 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14567 AddToWorklist(NewEst.getNode()); 14568 14569 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14570 AddToWorklist(NewEst.getNode()); 14571 14572 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14573 AddToWorklist(NewEst.getNode()); 14574 14575 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14576 AddToWorklist(Est.getNode()); 14577 } 14578 14579 // If non-reciprocal square root is requested, multiply the result by Arg. 14580 if (!Reciprocal) { 14581 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14582 AddToWorklist(Est.getNode()); 14583 } 14584 14585 return Est; 14586 } 14587 14588 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14589 /// For the reciprocal sqrt, we need to find the zero of the function: 14590 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14591 /// => 14592 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14593 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 14594 unsigned Iterations, 14595 SDNodeFlags *Flags, bool Reciprocal) { 14596 EVT VT = Arg.getValueType(); 14597 SDLoc DL(Arg); 14598 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14599 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14600 14601 // This routine must enter the loop below to work correctly 14602 // when (Reciprocal == false). 14603 assert(Iterations > 0); 14604 14605 // Newton iterations for reciprocal square root: 14606 // E = (E * -0.5) * ((A * E) * E + -3.0) 14607 for (unsigned i = 0; i < Iterations; ++i) { 14608 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 14609 AddToWorklist(AE.getNode()); 14610 14611 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 14612 AddToWorklist(AEE.getNode()); 14613 14614 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 14615 AddToWorklist(RHS.getNode()); 14616 14617 // When calculating a square root at the last iteration build: 14618 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 14619 // (notice a common subexpression) 14620 SDValue LHS; 14621 if (Reciprocal || (i + 1) < Iterations) { 14622 // RSQRT: LHS = (E * -0.5) 14623 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14624 } else { 14625 // SQRT: LHS = (A * E) * -0.5 14626 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 14627 } 14628 AddToWorklist(LHS.getNode()); 14629 14630 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 14631 AddToWorklist(Est.getNode()); 14632 } 14633 14634 return Est; 14635 } 14636 14637 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 14638 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 14639 /// Op can be zero. 14640 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 14641 bool Reciprocal) { 14642 if (Level >= AfterLegalizeDAG) 14643 return SDValue(); 14644 14645 // Expose the DAG combiner to the target combiner implementations. 14646 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14647 unsigned Iterations = 0; 14648 bool UseOneConstNR = false; 14649 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14650 AddToWorklist(Est.getNode()); 14651 if (Iterations) { 14652 Est = UseOneConstNR 14653 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 14654 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 14655 } 14656 return Est; 14657 } 14658 14659 return SDValue(); 14660 } 14661 14662 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14663 return buildSqrtEstimateImpl(Op, Flags, true); 14664 } 14665 14666 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14667 SDValue Est = buildSqrtEstimateImpl(Op, Flags, false); 14668 if (!Est) 14669 return SDValue(); 14670 14671 // Unfortunately, Est is now NaN if the input was exactly 0. 14672 // Select out this case and force the answer to 0. 14673 EVT VT = Est.getValueType(); 14674 SDLoc DL(Op); 14675 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 14676 EVT CCVT = getSetCCResultType(VT); 14677 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ); 14678 AddToWorklist(ZeroCmp.getNode()); 14679 14680 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp, 14681 Zero, Est); 14682 AddToWorklist(Est.getNode()); 14683 return Est; 14684 } 14685 14686 /// Return true if base is a frame index, which is known not to alias with 14687 /// anything but itself. Provides base object and offset as results. 14688 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14689 const GlobalValue *&GV, const void *&CV) { 14690 // Assume it is a primitive operation. 14691 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14692 14693 // If it's an adding a simple constant then integrate the offset. 14694 if (Base.getOpcode() == ISD::ADD) { 14695 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14696 Base = Base.getOperand(0); 14697 Offset += C->getZExtValue(); 14698 } 14699 } 14700 14701 // Return the underlying GlobalValue, and update the Offset. Return false 14702 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14703 // by multiple nodes with different offsets. 14704 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14705 GV = G->getGlobal(); 14706 Offset += G->getOffset(); 14707 return false; 14708 } 14709 14710 // Return the underlying Constant value, and update the Offset. Return false 14711 // for ConstantSDNodes since the same constant pool entry may be represented 14712 // by multiple nodes with different offsets. 14713 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14714 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14715 : (const void *)C->getConstVal(); 14716 Offset += C->getOffset(); 14717 return false; 14718 } 14719 // If it's any of the following then it can't alias with anything but itself. 14720 return isa<FrameIndexSDNode>(Base); 14721 } 14722 14723 /// Return true if there is any possibility that the two addresses overlap. 14724 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14725 // If they are the same then they must be aliases. 14726 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14727 14728 // If they are both volatile then they cannot be reordered. 14729 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14730 14731 // If one operation reads from invariant memory, and the other may store, they 14732 // cannot alias. These should really be checking the equivalent of mayWrite, 14733 // but it only matters for memory nodes other than load /store. 14734 if (Op0->isInvariant() && Op1->writeMem()) 14735 return false; 14736 14737 if (Op1->isInvariant() && Op0->writeMem()) 14738 return false; 14739 14740 // Gather base node and offset information. 14741 SDValue Base1, Base2; 14742 int64_t Offset1, Offset2; 14743 const GlobalValue *GV1, *GV2; 14744 const void *CV1, *CV2; 14745 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14746 Base1, Offset1, GV1, CV1); 14747 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14748 Base2, Offset2, GV2, CV2); 14749 14750 // If they have a same base address then check to see if they overlap. 14751 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14752 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14753 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14754 14755 // It is possible for different frame indices to alias each other, mostly 14756 // when tail call optimization reuses return address slots for arguments. 14757 // To catch this case, look up the actual index of frame indices to compute 14758 // the real alias relationship. 14759 if (isFrameIndex1 && isFrameIndex2) { 14760 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14761 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14762 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14763 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14764 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14765 } 14766 14767 // Otherwise, if we know what the bases are, and they aren't identical, then 14768 // we know they cannot alias. 14769 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14770 return false; 14771 14772 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14773 // compared to the size and offset of the access, we may be able to prove they 14774 // do not alias. This check is conservative for now to catch cases created by 14775 // splitting vector types. 14776 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14777 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14778 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14779 Op1->getMemoryVT().getSizeInBits() >> 3) && 14780 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 14781 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14782 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14783 14784 // There is no overlap between these relatively aligned accesses of similar 14785 // size, return no alias. 14786 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14787 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14788 return false; 14789 } 14790 14791 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14792 ? CombinerGlobalAA 14793 : DAG.getSubtarget().useAA(); 14794 #ifndef NDEBUG 14795 if (CombinerAAOnlyFunc.getNumOccurrences() && 14796 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14797 UseAA = false; 14798 #endif 14799 if (UseAA && 14800 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14801 // Use alias analysis information. 14802 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14803 Op1->getSrcValueOffset()); 14804 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14805 Op0->getSrcValueOffset() - MinOffset; 14806 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14807 Op1->getSrcValueOffset() - MinOffset; 14808 AliasResult AAResult = 14809 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14810 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14811 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14812 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14813 if (AAResult == NoAlias) 14814 return false; 14815 } 14816 14817 // Otherwise we have to assume they alias. 14818 return true; 14819 } 14820 14821 /// Walk up chain skipping non-aliasing memory nodes, 14822 /// looking for aliasing nodes and adding them to the Aliases vector. 14823 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14824 SmallVectorImpl<SDValue> &Aliases) { 14825 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14826 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14827 14828 // Get alias information for node. 14829 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14830 14831 // Starting off. 14832 Chains.push_back(OriginalChain); 14833 unsigned Depth = 0; 14834 14835 // Look at each chain and determine if it is an alias. If so, add it to the 14836 // aliases list. If not, then continue up the chain looking for the next 14837 // candidate. 14838 while (!Chains.empty()) { 14839 SDValue Chain = Chains.pop_back_val(); 14840 14841 // For TokenFactor nodes, look at each operand and only continue up the 14842 // chain until we reach the depth limit. 14843 // 14844 // FIXME: The depth check could be made to return the last non-aliasing 14845 // chain we found before we hit a tokenfactor rather than the original 14846 // chain. 14847 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14848 Aliases.clear(); 14849 Aliases.push_back(OriginalChain); 14850 return; 14851 } 14852 14853 // Don't bother if we've been before. 14854 if (!Visited.insert(Chain.getNode()).second) 14855 continue; 14856 14857 switch (Chain.getOpcode()) { 14858 case ISD::EntryToken: 14859 // Entry token is ideal chain operand, but handled in FindBetterChain. 14860 break; 14861 14862 case ISD::LOAD: 14863 case ISD::STORE: { 14864 // Get alias information for Chain. 14865 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14866 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14867 14868 // If chain is alias then stop here. 14869 if (!(IsLoad && IsOpLoad) && 14870 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14871 Aliases.push_back(Chain); 14872 } else { 14873 // Look further up the chain. 14874 Chains.push_back(Chain.getOperand(0)); 14875 ++Depth; 14876 } 14877 break; 14878 } 14879 14880 case ISD::TokenFactor: 14881 // We have to check each of the operands of the token factor for "small" 14882 // token factors, so we queue them up. Adding the operands to the queue 14883 // (stack) in reverse order maintains the original order and increases the 14884 // likelihood that getNode will find a matching token factor (CSE.) 14885 if (Chain.getNumOperands() > 16) { 14886 Aliases.push_back(Chain); 14887 break; 14888 } 14889 for (unsigned n = Chain.getNumOperands(); n;) 14890 Chains.push_back(Chain.getOperand(--n)); 14891 ++Depth; 14892 break; 14893 14894 default: 14895 // For all other instructions we will just have to take what we can get. 14896 Aliases.push_back(Chain); 14897 break; 14898 } 14899 } 14900 } 14901 14902 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14903 /// (aliasing node.) 14904 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14905 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14906 14907 // Accumulate all the aliases to this node. 14908 GatherAllAliases(N, OldChain, Aliases); 14909 14910 // If no operands then chain to entry token. 14911 if (Aliases.size() == 0) 14912 return DAG.getEntryNode(); 14913 14914 // If a single operand then chain to it. We don't need to revisit it. 14915 if (Aliases.size() == 1) 14916 return Aliases[0]; 14917 14918 // Construct a custom tailored token factor. 14919 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14920 } 14921 14922 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 14923 // This holds the base pointer, index, and the offset in bytes from the base 14924 // pointer. 14925 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14926 14927 // We must have a base and an offset. 14928 if (!BasePtr.Base.getNode()) 14929 return false; 14930 14931 // Do not handle stores to undef base pointers. 14932 if (BasePtr.Base.isUndef()) 14933 return false; 14934 14935 SmallVector<StoreSDNode *, 8> ChainedStores; 14936 ChainedStores.push_back(St); 14937 14938 // Walk up the chain and look for nodes with offsets from the same 14939 // base pointer. Stop when reaching an instruction with a different kind 14940 // or instruction which has a different base pointer. 14941 StoreSDNode *Index = St; 14942 while (Index) { 14943 // If the chain has more than one use, then we can't reorder the mem ops. 14944 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14945 break; 14946 14947 if (Index->isVolatile() || Index->isIndexed()) 14948 break; 14949 14950 // Find the base pointer and offset for this memory node. 14951 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 14952 14953 // Check that the base pointer is the same as the original one. 14954 if (!Ptr.equalBaseIndex(BasePtr)) 14955 break; 14956 14957 // Find the next memory operand in the chain. If the next operand in the 14958 // chain is a store then move up and continue the scan with the next 14959 // memory operand. If the next operand is a load save it and use alias 14960 // information to check if it interferes with anything. 14961 SDNode *NextInChain = Index->getChain().getNode(); 14962 while (true) { 14963 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14964 // We found a store node. Use it for the next iteration. 14965 if (STn->isVolatile() || STn->isIndexed()) { 14966 Index = nullptr; 14967 break; 14968 } 14969 ChainedStores.push_back(STn); 14970 Index = STn; 14971 break; 14972 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14973 NextInChain = Ldn->getChain().getNode(); 14974 continue; 14975 } else { 14976 Index = nullptr; 14977 break; 14978 } 14979 } 14980 } 14981 14982 bool MadeChangeToSt = false; 14983 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14984 14985 for (StoreSDNode *ChainedStore : ChainedStores) { 14986 SDValue Chain = ChainedStore->getChain(); 14987 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14988 14989 if (Chain != BetterChain) { 14990 if (ChainedStore == St) 14991 MadeChangeToSt = true; 14992 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14993 } 14994 } 14995 14996 // Do all replacements after finding the replacements to make to avoid making 14997 // the chains more complicated by introducing new TokenFactors. 14998 for (auto Replacement : BetterChains) 14999 replaceStoreChain(Replacement.first, Replacement.second); 15000 15001 return MadeChangeToSt; 15002 } 15003 15004 /// This is the entry point for the file. 15005 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 15006 CodeGenOpt::Level OptLevel) { 15007 /// This is the main entry point to this class. 15008 DAGCombiner(*this, AA, OptLevel).Run(Level); 15009 } 15010