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, 216 SDValue Trunc, SDValue ExtLoad, 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, SDLoc DL, SDValue LHS, SDValue RHS); 333 334 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 335 336 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 337 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 338 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 339 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 340 SDValue N3, ISD::CondCode CC, 341 bool NotExtCompare = false); 342 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 343 SDLoc DL, bool foldBooleans = true); 344 345 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 346 SDValue &CC) const; 347 bool isOneUseSetCC(SDValue N) const; 348 349 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 350 unsigned HiOp); 351 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 352 SDValue CombineExtLoad(SDNode *N); 353 SDValue combineRepeatedFPDivisors(SDNode *N); 354 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 355 SDValue BuildSDIV(SDNode *N); 356 SDValue BuildSDIVPow2(SDNode *N); 357 SDValue BuildUDIV(SDNode *N); 358 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 359 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 360 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 361 SDNodeFlags *Flags); 362 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 363 SDNodeFlags *Flags); 364 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 365 bool DemandHighBits = true); 366 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 367 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 368 SDValue InnerPos, SDValue InnerNeg, 369 unsigned PosOpcode, unsigned NegOpcode, 370 SDLoc DL); 371 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 372 SDValue ReduceLoadWidth(SDNode *N); 373 SDValue ReduceLoadOpStoreWidth(SDNode *N); 374 SDValue TransformFPLoadStorePair(SDNode *N); 375 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 376 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 377 378 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 379 380 /// Walk up chain skipping non-aliasing memory nodes, 381 /// looking for aliasing nodes and adding them to the Aliases vector. 382 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 383 SmallVectorImpl<SDValue> &Aliases); 384 385 /// Return true if there is any possibility that the two addresses overlap. 386 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 387 388 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 389 /// chain (aliasing node.) 390 SDValue FindBetterChain(SDNode *N, SDValue Chain); 391 392 /// Do FindBetterChain for a store and any possibly adjacent stores on 393 /// consecutive chains. 394 bool findBetterNeighborChains(StoreSDNode *St); 395 396 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 397 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 398 399 /// Holds a pointer to an LSBaseSDNode as well as information on where it 400 /// is located in a sequence of memory operations connected by a chain. 401 struct MemOpLink { 402 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 403 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 404 // Ptr to the mem node. 405 LSBaseSDNode *MemNode; 406 // Offset from the base ptr. 407 int64_t OffsetFromBase; 408 // What is the sequence number of this mem node. 409 // Lowest mem operand in the DAG starts at zero. 410 unsigned SequenceNum; 411 }; 412 413 /// This is a helper function for visitMUL to check the profitability 414 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 415 /// MulNode is the original multiply, AddNode is (add x, c1), 416 /// and ConstNode is c2. 417 bool isMulAddWithConstProfitable(SDNode *MulNode, 418 SDValue &AddNode, 419 SDValue &ConstNode); 420 421 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 422 /// constant build_vector of the stored constant values in Stores. 423 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 424 SDLoc SL, 425 ArrayRef<MemOpLink> Stores, 426 SmallVectorImpl<SDValue> &Chains, 427 EVT Ty) const; 428 429 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 430 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 431 /// the type of the loaded value to be extended. LoadedVT returns the type 432 /// of the original loaded value. NarrowLoad returns whether the load would 433 /// need to be narrowed in order to match. 434 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 435 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 436 bool &NarrowLoad); 437 438 /// This is a helper function for MergeConsecutiveStores. When the source 439 /// elements of the consecutive stores are all constants or all extracted 440 /// vector elements, try to merge them into one larger store. 441 /// \return True if a merged store was created. 442 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 443 EVT MemVT, unsigned NumStores, 444 bool IsConstantSrc, bool UseVector); 445 446 /// This is a helper function for MergeConsecutiveStores. 447 /// Stores that may be merged are placed in StoreNodes. 448 /// Loads that may alias with those stores are placed in AliasLoadNodes. 449 void getStoreMergeAndAliasCandidates( 450 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 451 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 452 453 /// Helper function for MergeConsecutiveStores. Checks if 454 /// Candidate stores have indirect dependency through their 455 /// operands. \return True if safe to merge 456 bool checkMergeStoreCandidatesForDependencies( 457 SmallVectorImpl<MemOpLink> &StoreNodes); 458 459 /// Merge consecutive store operations into a wide store. 460 /// This optimization uses wide integers or vectors when possible. 461 /// \return True if some memory operations were changed. 462 bool MergeConsecutiveStores(StoreSDNode *N); 463 464 /// \brief Try to transform a truncation where C is a constant: 465 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 466 /// 467 /// \p N needs to be a truncation and its first operand an AND. Other 468 /// requirements are checked by the function (e.g. that trunc is 469 /// single-use) and if missed an empty SDValue is returned. 470 SDValue distributeTruncateThroughAnd(SDNode *N); 471 472 public: 473 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 474 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 475 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 476 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 477 } 478 479 /// Runs the dag combiner on all nodes in the work list 480 void Run(CombineLevel AtLevel); 481 482 SelectionDAG &getDAG() const { return DAG; } 483 484 /// Returns a type large enough to hold any valid shift amount - before type 485 /// legalization these can be huge. 486 EVT getShiftAmountTy(EVT LHSTy) { 487 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 488 if (LHSTy.isVector()) 489 return LHSTy; 490 auto &DL = DAG.getDataLayout(); 491 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 492 : TLI.getPointerTy(DL); 493 } 494 495 /// This method returns true if we are running before type legalization or 496 /// if the specified VT is legal. 497 bool isTypeLegal(const EVT &VT) { 498 if (!LegalTypes) return true; 499 return TLI.isTypeLegal(VT); 500 } 501 502 /// Convenience wrapper around TargetLowering::getSetCCResultType 503 EVT getSetCCResultType(EVT VT) const { 504 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 505 } 506 }; 507 } 508 509 510 namespace { 511 /// This class is a DAGUpdateListener that removes any deleted 512 /// nodes from the worklist. 513 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 514 DAGCombiner &DC; 515 public: 516 explicit WorklistRemover(DAGCombiner &dc) 517 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 518 519 void NodeDeleted(SDNode *N, SDNode *E) override { 520 DC.removeFromWorklist(N); 521 } 522 }; 523 } 524 525 //===----------------------------------------------------------------------===// 526 // TargetLowering::DAGCombinerInfo implementation 527 //===----------------------------------------------------------------------===// 528 529 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 530 ((DAGCombiner*)DC)->AddToWorklist(N); 531 } 532 533 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 534 ((DAGCombiner*)DC)->removeFromWorklist(N); 535 } 536 537 SDValue TargetLowering::DAGCombinerInfo:: 538 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 539 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 540 } 541 542 SDValue TargetLowering::DAGCombinerInfo:: 543 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 544 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 545 } 546 547 548 SDValue TargetLowering::DAGCombinerInfo:: 549 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 550 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 551 } 552 553 void TargetLowering::DAGCombinerInfo:: 554 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 555 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 556 } 557 558 //===----------------------------------------------------------------------===// 559 // Helper Functions 560 //===----------------------------------------------------------------------===// 561 562 void DAGCombiner::deleteAndRecombine(SDNode *N) { 563 removeFromWorklist(N); 564 565 // If the operands of this node are only used by the node, they will now be 566 // dead. Make sure to re-visit them and recursively delete dead nodes. 567 for (const SDValue &Op : N->ops()) 568 // For an operand generating multiple values, one of the values may 569 // become dead allowing further simplification (e.g. split index 570 // arithmetic from an indexed load). 571 if (Op->hasOneUse() || Op->getNumValues() > 1) 572 AddToWorklist(Op.getNode()); 573 574 DAG.DeleteNode(N); 575 } 576 577 /// Return 1 if we can compute the negated form of the specified expression for 578 /// the same cost as the expression itself, or 2 if we can compute the negated 579 /// form more cheaply than the expression itself. 580 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 581 const TargetLowering &TLI, 582 const TargetOptions *Options, 583 unsigned Depth = 0) { 584 // fneg is removable even if it has multiple uses. 585 if (Op.getOpcode() == ISD::FNEG) return 2; 586 587 // Don't allow anything with multiple uses. 588 if (!Op.hasOneUse()) return 0; 589 590 // Don't recurse exponentially. 591 if (Depth > 6) return 0; 592 593 switch (Op.getOpcode()) { 594 default: return false; 595 case ISD::ConstantFP: 596 // Don't invert constant FP values after legalize. The negated constant 597 // isn't necessarily legal. 598 return LegalOperations ? 0 : 1; 599 case ISD::FADD: 600 // FIXME: determine better conditions for this xform. 601 if (!Options->UnsafeFPMath) return 0; 602 603 // After operation legalization, it might not be legal to create new FSUBs. 604 if (LegalOperations && 605 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 606 return 0; 607 608 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 609 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 610 Options, Depth + 1)) 611 return V; 612 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 613 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 614 Depth + 1); 615 case ISD::FSUB: 616 // We can't turn -(A-B) into B-A when we honor signed zeros. 617 if (!Options->UnsafeFPMath) return 0; 618 619 // fold (fneg (fsub A, B)) -> (fsub B, A) 620 return 1; 621 622 case ISD::FMUL: 623 case ISD::FDIV: 624 if (Options->HonorSignDependentRoundingFPMath()) return 0; 625 626 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 627 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 628 Options, Depth + 1)) 629 return V; 630 631 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 632 Depth + 1); 633 634 case ISD::FP_EXTEND: 635 case ISD::FP_ROUND: 636 case ISD::FSIN: 637 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 638 Depth + 1); 639 } 640 } 641 642 /// If isNegatibleForFree returns true, return the newly negated expression. 643 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 644 bool LegalOperations, unsigned Depth = 0) { 645 const TargetOptions &Options = DAG.getTarget().Options; 646 // fneg is removable even if it has multiple uses. 647 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 648 649 // Don't allow anything with multiple uses. 650 assert(Op.hasOneUse() && "Unknown reuse!"); 651 652 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 653 654 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 655 656 switch (Op.getOpcode()) { 657 default: llvm_unreachable("Unknown code"); 658 case ISD::ConstantFP: { 659 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 660 V.changeSign(); 661 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 662 } 663 case ISD::FADD: 664 // FIXME: determine better conditions for this xform. 665 assert(Options.UnsafeFPMath); 666 667 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 668 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 669 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 670 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 671 GetNegatedExpression(Op.getOperand(0), DAG, 672 LegalOperations, Depth+1), 673 Op.getOperand(1), Flags); 674 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 675 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 676 GetNegatedExpression(Op.getOperand(1), DAG, 677 LegalOperations, Depth+1), 678 Op.getOperand(0), Flags); 679 case ISD::FSUB: 680 // We can't turn -(A-B) into B-A when we honor signed zeros. 681 assert(Options.UnsafeFPMath); 682 683 // fold (fneg (fsub 0, B)) -> B 684 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 685 if (N0CFP->isZero()) 686 return Op.getOperand(1); 687 688 // fold (fneg (fsub A, B)) -> (fsub B, A) 689 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 690 Op.getOperand(1), Op.getOperand(0), Flags); 691 692 case ISD::FMUL: 693 case ISD::FDIV: 694 assert(!Options.HonorSignDependentRoundingFPMath()); 695 696 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 697 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 698 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 699 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 700 GetNegatedExpression(Op.getOperand(0), DAG, 701 LegalOperations, Depth+1), 702 Op.getOperand(1), Flags); 703 704 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 705 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 706 Op.getOperand(0), 707 GetNegatedExpression(Op.getOperand(1), DAG, 708 LegalOperations, Depth+1), Flags); 709 710 case ISD::FP_EXTEND: 711 case ISD::FSIN: 712 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 713 GetNegatedExpression(Op.getOperand(0), DAG, 714 LegalOperations, Depth+1)); 715 case ISD::FP_ROUND: 716 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 717 GetNegatedExpression(Op.getOperand(0), DAG, 718 LegalOperations, Depth+1), 719 Op.getOperand(1)); 720 } 721 } 722 723 // Return true if this node is a setcc, or is a select_cc 724 // that selects between the target values used for true and false, making it 725 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 726 // the appropriate nodes based on the type of node we are checking. This 727 // simplifies life a bit for the callers. 728 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 729 SDValue &CC) const { 730 if (N.getOpcode() == ISD::SETCC) { 731 LHS = N.getOperand(0); 732 RHS = N.getOperand(1); 733 CC = N.getOperand(2); 734 return true; 735 } 736 737 if (N.getOpcode() != ISD::SELECT_CC || 738 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 739 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 740 return false; 741 742 if (TLI.getBooleanContents(N.getValueType()) == 743 TargetLowering::UndefinedBooleanContent) 744 return false; 745 746 LHS = N.getOperand(0); 747 RHS = N.getOperand(1); 748 CC = N.getOperand(4); 749 return true; 750 } 751 752 /// Return true if this is a SetCC-equivalent operation with only one use. 753 /// If this is true, it allows the users to invert the operation for free when 754 /// it is profitable to do so. 755 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 756 SDValue N0, N1, N2; 757 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 758 return true; 759 return false; 760 } 761 762 /// Returns true if N is a BUILD_VECTOR node whose 763 /// elements are all the same constant or undefined. 764 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 765 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 766 if (!C) 767 return false; 768 769 APInt SplatUndef; 770 unsigned SplatBitSize; 771 bool HasAnyUndefs; 772 EVT EltVT = N->getValueType(0).getVectorElementType(); 773 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 774 HasAnyUndefs) && 775 EltVT.getSizeInBits() >= SplatBitSize); 776 } 777 778 // \brief Returns the SDNode if it is a constant float BuildVector 779 // or constant float. 780 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 781 if (isa<ConstantFPSDNode>(N)) 782 return N.getNode(); 783 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 784 return N.getNode(); 785 return nullptr; 786 } 787 788 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 789 // int. 790 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 791 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 792 return CN; 793 794 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 795 BitVector UndefElements; 796 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 797 798 // BuildVectors can truncate their operands. Ignore that case here. 799 // FIXME: We blindly ignore splats which include undef which is overly 800 // pessimistic. 801 if (CN && UndefElements.none() && 802 CN->getValueType(0) == N.getValueType().getScalarType()) 803 return CN; 804 } 805 806 return nullptr; 807 } 808 809 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 810 // float. 811 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 812 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 813 return CN; 814 815 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 816 BitVector UndefElements; 817 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 818 819 if (CN && UndefElements.none()) 820 return CN; 821 } 822 823 return nullptr; 824 } 825 826 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 827 SDValue N0, SDValue N1) { 828 EVT VT = N0.getValueType(); 829 if (N0.getOpcode() == Opc) { 830 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 831 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 832 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 833 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 834 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 835 return SDValue(); 836 } 837 if (N0.hasOneUse()) { 838 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 839 // use 840 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 841 if (!OpNode.getNode()) 842 return SDValue(); 843 AddToWorklist(OpNode.getNode()); 844 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 845 } 846 } 847 } 848 849 if (N1.getOpcode() == Opc) { 850 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 851 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 852 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 853 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 854 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 855 return SDValue(); 856 } 857 if (N1.hasOneUse()) { 858 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 859 // use 860 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 861 if (!OpNode.getNode()) 862 return SDValue(); 863 AddToWorklist(OpNode.getNode()); 864 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 865 } 866 } 867 } 868 869 return SDValue(); 870 } 871 872 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 873 bool AddTo) { 874 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 875 ++NodesCombined; 876 DEBUG(dbgs() << "\nReplacing.1 "; 877 N->dump(&DAG); 878 dbgs() << "\nWith: "; 879 To[0].getNode()->dump(&DAG); 880 dbgs() << " and " << NumTo-1 << " other values\n"); 881 for (unsigned i = 0, e = NumTo; i != e; ++i) 882 assert((!To[i].getNode() || 883 N->getValueType(i) == To[i].getValueType()) && 884 "Cannot combine value to value of different type!"); 885 886 WorklistRemover DeadNodes(*this); 887 DAG.ReplaceAllUsesWith(N, To); 888 if (AddTo) { 889 // Push the new nodes and any users onto the worklist 890 for (unsigned i = 0, e = NumTo; i != e; ++i) { 891 if (To[i].getNode()) { 892 AddToWorklist(To[i].getNode()); 893 AddUsersToWorklist(To[i].getNode()); 894 } 895 } 896 } 897 898 // Finally, if the node is now dead, remove it from the graph. The node 899 // may not be dead if the replacement process recursively simplified to 900 // something else needing this node. 901 if (N->use_empty()) 902 deleteAndRecombine(N); 903 return SDValue(N, 0); 904 } 905 906 void DAGCombiner:: 907 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 908 // Replace all uses. If any nodes become isomorphic to other nodes and 909 // are deleted, make sure to remove them from our worklist. 910 WorklistRemover DeadNodes(*this); 911 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 912 913 // Push the new node and any (possibly new) users onto the worklist. 914 AddToWorklist(TLO.New.getNode()); 915 AddUsersToWorklist(TLO.New.getNode()); 916 917 // Finally, if the node is now dead, remove it from the graph. The node 918 // may not be dead if the replacement process recursively simplified to 919 // something else needing this node. 920 if (TLO.Old.getNode()->use_empty()) 921 deleteAndRecombine(TLO.Old.getNode()); 922 } 923 924 /// Check the specified integer node value to see if it can be simplified or if 925 /// things it uses can be simplified by bit propagation. If so, return true. 926 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 927 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 928 APInt KnownZero, KnownOne; 929 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 930 return false; 931 932 // Revisit the node. 933 AddToWorklist(Op.getNode()); 934 935 // Replace the old value with the new one. 936 ++NodesCombined; 937 DEBUG(dbgs() << "\nReplacing.2 "; 938 TLO.Old.getNode()->dump(&DAG); 939 dbgs() << "\nWith: "; 940 TLO.New.getNode()->dump(&DAG); 941 dbgs() << '\n'); 942 943 CommitTargetLoweringOpt(TLO); 944 return true; 945 } 946 947 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 948 SDLoc dl(Load); 949 EVT VT = Load->getValueType(0); 950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 951 952 DEBUG(dbgs() << "\nReplacing.9 "; 953 Load->dump(&DAG); 954 dbgs() << "\nWith: "; 955 Trunc.getNode()->dump(&DAG); 956 dbgs() << '\n'); 957 WorklistRemover DeadNodes(*this); 958 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 959 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 960 deleteAndRecombine(Load); 961 AddToWorklist(Trunc.getNode()); 962 } 963 964 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 965 Replace = false; 966 SDLoc dl(Op); 967 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 968 LoadSDNode *LD = cast<LoadSDNode>(Op); 969 EVT MemVT = LD->getMemoryVT(); 970 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 971 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 972 : ISD::EXTLOAD) 973 : LD->getExtensionType(); 974 Replace = true; 975 return DAG.getExtLoad(ExtType, dl, PVT, 976 LD->getChain(), LD->getBasePtr(), 977 MemVT, LD->getMemOperand()); 978 } 979 980 unsigned Opc = Op.getOpcode(); 981 switch (Opc) { 982 default: break; 983 case ISD::AssertSext: 984 return DAG.getNode(ISD::AssertSext, dl, PVT, 985 SExtPromoteOperand(Op.getOperand(0), PVT), 986 Op.getOperand(1)); 987 case ISD::AssertZext: 988 return DAG.getNode(ISD::AssertZext, dl, PVT, 989 ZExtPromoteOperand(Op.getOperand(0), PVT), 990 Op.getOperand(1)); 991 case ISD::Constant: { 992 unsigned ExtOpc = 993 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 994 return DAG.getNode(ExtOpc, dl, PVT, Op); 995 } 996 } 997 998 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 999 return SDValue(); 1000 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 1001 } 1002 1003 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1004 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1005 return SDValue(); 1006 EVT OldVT = Op.getValueType(); 1007 SDLoc dl(Op); 1008 bool Replace = false; 1009 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1010 if (!NewOp.getNode()) 1011 return SDValue(); 1012 AddToWorklist(NewOp.getNode()); 1013 1014 if (Replace) 1015 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1016 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1017 DAG.getValueType(OldVT)); 1018 } 1019 1020 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1021 EVT OldVT = Op.getValueType(); 1022 SDLoc dl(Op); 1023 bool Replace = false; 1024 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1025 if (!NewOp.getNode()) 1026 return SDValue(); 1027 AddToWorklist(NewOp.getNode()); 1028 1029 if (Replace) 1030 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1031 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1032 } 1033 1034 /// Promote the specified integer binary operation if the target indicates it is 1035 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1036 /// i32 since i16 instructions are longer. 1037 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1038 if (!LegalOperations) 1039 return SDValue(); 1040 1041 EVT VT = Op.getValueType(); 1042 if (VT.isVector() || !VT.isInteger()) 1043 return SDValue(); 1044 1045 // If operation type is 'undesirable', e.g. i16 on x86, consider 1046 // promoting it. 1047 unsigned Opc = Op.getOpcode(); 1048 if (TLI.isTypeDesirableForOp(Opc, VT)) 1049 return SDValue(); 1050 1051 EVT PVT = VT; 1052 // Consult target whether it is a good idea to promote this operation and 1053 // what's the right type to promote it to. 1054 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1055 assert(PVT != VT && "Don't know what type to promote to!"); 1056 1057 bool Replace0 = false; 1058 SDValue N0 = Op.getOperand(0); 1059 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1060 if (!NN0.getNode()) 1061 return SDValue(); 1062 1063 bool Replace1 = false; 1064 SDValue N1 = Op.getOperand(1); 1065 SDValue NN1; 1066 if (N0 == N1) 1067 NN1 = NN0; 1068 else { 1069 NN1 = PromoteOperand(N1, PVT, Replace1); 1070 if (!NN1.getNode()) 1071 return SDValue(); 1072 } 1073 1074 AddToWorklist(NN0.getNode()); 1075 if (NN1.getNode()) 1076 AddToWorklist(NN1.getNode()); 1077 1078 if (Replace0) 1079 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1080 if (Replace1) 1081 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1082 1083 DEBUG(dbgs() << "\nPromoting "; 1084 Op.getNode()->dump(&DAG)); 1085 SDLoc dl(Op); 1086 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1087 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1088 } 1089 return SDValue(); 1090 } 1091 1092 /// Promote the specified integer shift operation if the target indicates it is 1093 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1094 /// i32 since i16 instructions are longer. 1095 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1096 if (!LegalOperations) 1097 return SDValue(); 1098 1099 EVT VT = Op.getValueType(); 1100 if (VT.isVector() || !VT.isInteger()) 1101 return SDValue(); 1102 1103 // If operation type is 'undesirable', e.g. i16 on x86, consider 1104 // promoting it. 1105 unsigned Opc = Op.getOpcode(); 1106 if (TLI.isTypeDesirableForOp(Opc, VT)) 1107 return SDValue(); 1108 1109 EVT PVT = VT; 1110 // Consult target whether it is a good idea to promote this operation and 1111 // what's the right type to promote it to. 1112 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1113 assert(PVT != VT && "Don't know what type to promote to!"); 1114 1115 bool Replace = false; 1116 SDValue N0 = Op.getOperand(0); 1117 if (Opc == ISD::SRA) 1118 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1119 else if (Opc == ISD::SRL) 1120 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1121 else 1122 N0 = PromoteOperand(N0, PVT, Replace); 1123 if (!N0.getNode()) 1124 return SDValue(); 1125 1126 AddToWorklist(N0.getNode()); 1127 if (Replace) 1128 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1129 1130 DEBUG(dbgs() << "\nPromoting "; 1131 Op.getNode()->dump(&DAG)); 1132 SDLoc dl(Op); 1133 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1134 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1135 } 1136 return SDValue(); 1137 } 1138 1139 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1140 if (!LegalOperations) 1141 return SDValue(); 1142 1143 EVT VT = Op.getValueType(); 1144 if (VT.isVector() || !VT.isInteger()) 1145 return SDValue(); 1146 1147 // If operation type is 'undesirable', e.g. i16 on x86, consider 1148 // promoting it. 1149 unsigned Opc = Op.getOpcode(); 1150 if (TLI.isTypeDesirableForOp(Opc, VT)) 1151 return SDValue(); 1152 1153 EVT PVT = VT; 1154 // Consult target whether it is a good idea to promote this operation and 1155 // what's the right type to promote it to. 1156 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1157 assert(PVT != VT && "Don't know what type to promote to!"); 1158 // fold (aext (aext x)) -> (aext x) 1159 // fold (aext (zext x)) -> (zext x) 1160 // fold (aext (sext x)) -> (sext x) 1161 DEBUG(dbgs() << "\nPromoting "; 1162 Op.getNode()->dump(&DAG)); 1163 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1164 } 1165 return SDValue(); 1166 } 1167 1168 bool DAGCombiner::PromoteLoad(SDValue Op) { 1169 if (!LegalOperations) 1170 return false; 1171 1172 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1173 return false; 1174 1175 EVT VT = Op.getValueType(); 1176 if (VT.isVector() || !VT.isInteger()) 1177 return false; 1178 1179 // If operation type is 'undesirable', e.g. i16 on x86, consider 1180 // promoting it. 1181 unsigned Opc = Op.getOpcode(); 1182 if (TLI.isTypeDesirableForOp(Opc, VT)) 1183 return false; 1184 1185 EVT PVT = VT; 1186 // Consult target whether it is a good idea to promote this operation and 1187 // what's the right type to promote it to. 1188 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1189 assert(PVT != VT && "Don't know what type to promote to!"); 1190 1191 SDLoc dl(Op); 1192 SDNode *N = Op.getNode(); 1193 LoadSDNode *LD = cast<LoadSDNode>(N); 1194 EVT MemVT = LD->getMemoryVT(); 1195 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1196 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1197 : ISD::EXTLOAD) 1198 : LD->getExtensionType(); 1199 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1200 LD->getChain(), LD->getBasePtr(), 1201 MemVT, LD->getMemOperand()); 1202 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1203 1204 DEBUG(dbgs() << "\nPromoting "; 1205 N->dump(&DAG); 1206 dbgs() << "\nTo: "; 1207 Result.getNode()->dump(&DAG); 1208 dbgs() << '\n'); 1209 WorklistRemover DeadNodes(*this); 1210 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1211 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1212 deleteAndRecombine(N); 1213 AddToWorklist(Result.getNode()); 1214 return true; 1215 } 1216 return false; 1217 } 1218 1219 /// \brief Recursively delete a node which has no uses and any operands for 1220 /// which it is the only use. 1221 /// 1222 /// Note that this both deletes the nodes and removes them from the worklist. 1223 /// It also adds any nodes who have had a user deleted to the worklist as they 1224 /// may now have only one use and subject to other combines. 1225 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1226 if (!N->use_empty()) 1227 return false; 1228 1229 SmallSetVector<SDNode *, 16> Nodes; 1230 Nodes.insert(N); 1231 do { 1232 N = Nodes.pop_back_val(); 1233 if (!N) 1234 continue; 1235 1236 if (N->use_empty()) { 1237 for (const SDValue &ChildN : N->op_values()) 1238 Nodes.insert(ChildN.getNode()); 1239 1240 removeFromWorklist(N); 1241 DAG.DeleteNode(N); 1242 } else { 1243 AddToWorklist(N); 1244 } 1245 } while (!Nodes.empty()); 1246 return true; 1247 } 1248 1249 //===----------------------------------------------------------------------===// 1250 // Main DAG Combiner implementation 1251 //===----------------------------------------------------------------------===// 1252 1253 void DAGCombiner::Run(CombineLevel AtLevel) { 1254 // set the instance variables, so that the various visit routines may use it. 1255 Level = AtLevel; 1256 LegalOperations = Level >= AfterLegalizeVectorOps; 1257 LegalTypes = Level >= AfterLegalizeTypes; 1258 1259 // Add all the dag nodes to the worklist. 1260 for (SDNode &Node : DAG.allnodes()) 1261 AddToWorklist(&Node); 1262 1263 // Create a dummy node (which is not added to allnodes), that adds a reference 1264 // to the root node, preventing it from being deleted, and tracking any 1265 // changes of the root. 1266 HandleSDNode Dummy(DAG.getRoot()); 1267 1268 // While the worklist isn't empty, find a node and try to combine it. 1269 while (!WorklistMap.empty()) { 1270 SDNode *N; 1271 // The Worklist holds the SDNodes in order, but it may contain null entries. 1272 do { 1273 N = Worklist.pop_back_val(); 1274 } while (!N); 1275 1276 bool GoodWorklistEntry = WorklistMap.erase(N); 1277 (void)GoodWorklistEntry; 1278 assert(GoodWorklistEntry && 1279 "Found a worklist entry without a corresponding map entry!"); 1280 1281 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1282 // N is deleted from the DAG, since they too may now be dead or may have a 1283 // reduced number of uses, allowing other xforms. 1284 if (recursivelyDeleteUnusedNodes(N)) 1285 continue; 1286 1287 WorklistRemover DeadNodes(*this); 1288 1289 // If this combine is running after legalizing the DAG, re-legalize any 1290 // nodes pulled off the worklist. 1291 if (Level == AfterLegalizeDAG) { 1292 SmallSetVector<SDNode *, 16> UpdatedNodes; 1293 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1294 1295 for (SDNode *LN : UpdatedNodes) { 1296 AddToWorklist(LN); 1297 AddUsersToWorklist(LN); 1298 } 1299 if (!NIsValid) 1300 continue; 1301 } 1302 1303 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1304 1305 // Add any operands of the new node which have not yet been combined to the 1306 // worklist as well. Because the worklist uniques things already, this 1307 // won't repeatedly process the same operand. 1308 CombinedNodes.insert(N); 1309 for (const SDValue &ChildN : N->op_values()) 1310 if (!CombinedNodes.count(ChildN.getNode())) 1311 AddToWorklist(ChildN.getNode()); 1312 1313 SDValue RV = combine(N); 1314 1315 if (!RV.getNode()) 1316 continue; 1317 1318 ++NodesCombined; 1319 1320 // If we get back the same node we passed in, rather than a new node or 1321 // zero, we know that the node must have defined multiple values and 1322 // CombineTo was used. Since CombineTo takes care of the worklist 1323 // mechanics for us, we have no work to do in this case. 1324 if (RV.getNode() == N) 1325 continue; 1326 1327 assert(N->getOpcode() != ISD::DELETED_NODE && 1328 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1329 "Node was deleted but visit returned new node!"); 1330 1331 DEBUG(dbgs() << " ... into: "; 1332 RV.getNode()->dump(&DAG)); 1333 1334 // Transfer debug value. 1335 DAG.TransferDbgValues(SDValue(N, 0), RV); 1336 if (N->getNumValues() == RV.getNode()->getNumValues()) 1337 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1338 else { 1339 assert(N->getValueType(0) == RV.getValueType() && 1340 N->getNumValues() == 1 && "Type mismatch"); 1341 SDValue OpV = RV; 1342 DAG.ReplaceAllUsesWith(N, &OpV); 1343 } 1344 1345 // Push the new node and any users onto the worklist 1346 AddToWorklist(RV.getNode()); 1347 AddUsersToWorklist(RV.getNode()); 1348 1349 // Finally, if the node is now dead, remove it from the graph. The node 1350 // may not be dead if the replacement process recursively simplified to 1351 // something else needing this node. This will also take care of adding any 1352 // operands which have lost a user to the worklist. 1353 recursivelyDeleteUnusedNodes(N); 1354 } 1355 1356 // If the root changed (e.g. it was a dead load, update the root). 1357 DAG.setRoot(Dummy.getValue()); 1358 DAG.RemoveDeadNodes(); 1359 } 1360 1361 SDValue DAGCombiner::visit(SDNode *N) { 1362 switch (N->getOpcode()) { 1363 default: break; 1364 case ISD::TokenFactor: return visitTokenFactor(N); 1365 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1366 case ISD::ADD: return visitADD(N); 1367 case ISD::SUB: return visitSUB(N); 1368 case ISD::ADDC: return visitADDC(N); 1369 case ISD::SUBC: return visitSUBC(N); 1370 case ISD::ADDE: return visitADDE(N); 1371 case ISD::SUBE: return visitSUBE(N); 1372 case ISD::MUL: return visitMUL(N); 1373 case ISD::SDIV: return visitSDIV(N); 1374 case ISD::UDIV: return visitUDIV(N); 1375 case ISD::SREM: 1376 case ISD::UREM: return visitREM(N); 1377 case ISD::MULHU: return visitMULHU(N); 1378 case ISD::MULHS: return visitMULHS(N); 1379 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1380 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1381 case ISD::SMULO: return visitSMULO(N); 1382 case ISD::UMULO: return visitUMULO(N); 1383 case ISD::SMIN: 1384 case ISD::SMAX: 1385 case ISD::UMIN: 1386 case ISD::UMAX: return visitIMINMAX(N); 1387 case ISD::AND: return visitAND(N); 1388 case ISD::OR: return visitOR(N); 1389 case ISD::XOR: return visitXOR(N); 1390 case ISD::SHL: return visitSHL(N); 1391 case ISD::SRA: return visitSRA(N); 1392 case ISD::SRL: return visitSRL(N); 1393 case ISD::ROTR: 1394 case ISD::ROTL: return visitRotate(N); 1395 case ISD::BSWAP: return visitBSWAP(N); 1396 case ISD::BITREVERSE: return visitBITREVERSE(N); 1397 case ISD::CTLZ: return visitCTLZ(N); 1398 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1399 case ISD::CTTZ: return visitCTTZ(N); 1400 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1401 case ISD::CTPOP: return visitCTPOP(N); 1402 case ISD::SELECT: return visitSELECT(N); 1403 case ISD::VSELECT: return visitVSELECT(N); 1404 case ISD::SELECT_CC: return visitSELECT_CC(N); 1405 case ISD::SETCC: return visitSETCC(N); 1406 case ISD::SETCCE: return visitSETCCE(N); 1407 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1408 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1409 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1410 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1411 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1412 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1413 case ISD::TRUNCATE: return visitTRUNCATE(N); 1414 case ISD::BITCAST: return visitBITCAST(N); 1415 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1416 case ISD::FADD: return visitFADD(N); 1417 case ISD::FSUB: return visitFSUB(N); 1418 case ISD::FMUL: return visitFMUL(N); 1419 case ISD::FMA: return visitFMA(N); 1420 case ISD::FDIV: return visitFDIV(N); 1421 case ISD::FREM: return visitFREM(N); 1422 case ISD::FSQRT: return visitFSQRT(N); 1423 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1424 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1425 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1426 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1427 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1428 case ISD::FP_ROUND: return visitFP_ROUND(N); 1429 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1430 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1431 case ISD::FNEG: return visitFNEG(N); 1432 case ISD::FABS: return visitFABS(N); 1433 case ISD::FFLOOR: return visitFFLOOR(N); 1434 case ISD::FMINNUM: return visitFMINNUM(N); 1435 case ISD::FMAXNUM: return visitFMAXNUM(N); 1436 case ISD::FCEIL: return visitFCEIL(N); 1437 case ISD::FTRUNC: return visitFTRUNC(N); 1438 case ISD::BRCOND: return visitBRCOND(N); 1439 case ISD::BR_CC: return visitBR_CC(N); 1440 case ISD::LOAD: return visitLOAD(N); 1441 case ISD::STORE: return visitSTORE(N); 1442 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1443 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1444 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1445 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1446 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1447 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1448 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1449 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1450 case ISD::MGATHER: return visitMGATHER(N); 1451 case ISD::MLOAD: return visitMLOAD(N); 1452 case ISD::MSCATTER: return visitMSCATTER(N); 1453 case ISD::MSTORE: return visitMSTORE(N); 1454 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1455 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1456 } 1457 return SDValue(); 1458 } 1459 1460 SDValue DAGCombiner::combine(SDNode *N) { 1461 SDValue RV = visit(N); 1462 1463 // If nothing happened, try a target-specific DAG combine. 1464 if (!RV.getNode()) { 1465 assert(N->getOpcode() != ISD::DELETED_NODE && 1466 "Node was deleted but visit returned NULL!"); 1467 1468 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1469 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1470 1471 // Expose the DAG combiner to the target combiner impls. 1472 TargetLowering::DAGCombinerInfo 1473 DagCombineInfo(DAG, Level, false, this); 1474 1475 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1476 } 1477 } 1478 1479 // If nothing happened still, try promoting the operation. 1480 if (!RV.getNode()) { 1481 switch (N->getOpcode()) { 1482 default: break; 1483 case ISD::ADD: 1484 case ISD::SUB: 1485 case ISD::MUL: 1486 case ISD::AND: 1487 case ISD::OR: 1488 case ISD::XOR: 1489 RV = PromoteIntBinOp(SDValue(N, 0)); 1490 break; 1491 case ISD::SHL: 1492 case ISD::SRA: 1493 case ISD::SRL: 1494 RV = PromoteIntShiftOp(SDValue(N, 0)); 1495 break; 1496 case ISD::SIGN_EXTEND: 1497 case ISD::ZERO_EXTEND: 1498 case ISD::ANY_EXTEND: 1499 RV = PromoteExtend(SDValue(N, 0)); 1500 break; 1501 case ISD::LOAD: 1502 if (PromoteLoad(SDValue(N, 0))) 1503 RV = SDValue(N, 0); 1504 break; 1505 } 1506 } 1507 1508 // If N is a commutative binary node, try commuting it to enable more 1509 // sdisel CSE. 1510 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1511 N->getNumValues() == 1) { 1512 SDValue N0 = N->getOperand(0); 1513 SDValue N1 = N->getOperand(1); 1514 1515 // Constant operands are canonicalized to RHS. 1516 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1517 SDValue Ops[] = {N1, N0}; 1518 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1519 N->getFlags()); 1520 if (CSENode) 1521 return SDValue(CSENode, 0); 1522 } 1523 } 1524 1525 return RV; 1526 } 1527 1528 /// Given a node, return its input chain if it has one, otherwise return a null 1529 /// sd operand. 1530 static SDValue getInputChainForNode(SDNode *N) { 1531 if (unsigned NumOps = N->getNumOperands()) { 1532 if (N->getOperand(0).getValueType() == MVT::Other) 1533 return N->getOperand(0); 1534 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1535 return N->getOperand(NumOps-1); 1536 for (unsigned i = 1; i < NumOps-1; ++i) 1537 if (N->getOperand(i).getValueType() == MVT::Other) 1538 return N->getOperand(i); 1539 } 1540 return SDValue(); 1541 } 1542 1543 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1544 // If N has two operands, where one has an input chain equal to the other, 1545 // the 'other' chain is redundant. 1546 if (N->getNumOperands() == 2) { 1547 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1548 return N->getOperand(0); 1549 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1550 return N->getOperand(1); 1551 } 1552 1553 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1554 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1555 SmallPtrSet<SDNode*, 16> SeenOps; 1556 bool Changed = false; // If we should replace this token factor. 1557 1558 // Start out with this token factor. 1559 TFs.push_back(N); 1560 1561 // Iterate through token factors. The TFs grows when new token factors are 1562 // encountered. 1563 for (unsigned i = 0; i < TFs.size(); ++i) { 1564 SDNode *TF = TFs[i]; 1565 1566 // Check each of the operands. 1567 for (const SDValue &Op : TF->op_values()) { 1568 1569 switch (Op.getOpcode()) { 1570 case ISD::EntryToken: 1571 // Entry tokens don't need to be added to the list. They are 1572 // redundant. 1573 Changed = true; 1574 break; 1575 1576 case ISD::TokenFactor: 1577 if (Op.hasOneUse() && 1578 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1579 // Queue up for processing. 1580 TFs.push_back(Op.getNode()); 1581 // Clean up in case the token factor is removed. 1582 AddToWorklist(Op.getNode()); 1583 Changed = true; 1584 break; 1585 } 1586 // Fall thru 1587 1588 default: 1589 // Only add if it isn't already in the list. 1590 if (SeenOps.insert(Op.getNode()).second) 1591 Ops.push_back(Op); 1592 else 1593 Changed = true; 1594 break; 1595 } 1596 } 1597 } 1598 1599 SDValue Result; 1600 1601 // If we've changed things around then replace token factor. 1602 if (Changed) { 1603 if (Ops.empty()) { 1604 // The entry token is the only possible outcome. 1605 Result = DAG.getEntryNode(); 1606 } else { 1607 // New and improved token factor. 1608 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1609 } 1610 1611 // Add users to worklist if AA is enabled, since it may introduce 1612 // a lot of new chained token factors while removing memory deps. 1613 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1614 : DAG.getSubtarget().useAA(); 1615 return CombineTo(N, Result, UseAA /*add to worklist*/); 1616 } 1617 1618 return Result; 1619 } 1620 1621 /// MERGE_VALUES can always be eliminated. 1622 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1623 WorklistRemover DeadNodes(*this); 1624 // Replacing results may cause a different MERGE_VALUES to suddenly 1625 // be CSE'd with N, and carry its uses with it. Iterate until no 1626 // uses remain, to ensure that the node can be safely deleted. 1627 // First add the users of this node to the work list so that they 1628 // can be tried again once they have new operands. 1629 AddUsersToWorklist(N); 1630 do { 1631 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1632 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1633 } while (!N->use_empty()); 1634 deleteAndRecombine(N); 1635 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1636 } 1637 1638 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1639 /// ConstantSDNode pointer else nullptr. 1640 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1641 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1642 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1643 } 1644 1645 SDValue DAGCombiner::visitADD(SDNode *N) { 1646 SDValue N0 = N->getOperand(0); 1647 SDValue N1 = N->getOperand(1); 1648 EVT VT = N0.getValueType(); 1649 1650 // fold vector ops 1651 if (VT.isVector()) { 1652 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1653 return FoldedVOp; 1654 1655 // fold (add x, 0) -> x, vector edition 1656 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1657 return N0; 1658 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1659 return N1; 1660 } 1661 1662 // fold (add x, undef) -> undef 1663 if (N0.isUndef()) 1664 return N0; 1665 if (N1.isUndef()) 1666 return N1; 1667 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1668 // canonicalize constant to RHS 1669 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1670 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1671 // fold (add c1, c2) -> c1+c2 1672 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1673 N0.getNode(), N1.getNode()); 1674 } 1675 // fold (add x, 0) -> x 1676 if (isNullConstant(N1)) 1677 return N0; 1678 // fold ((c1-A)+c2) -> (c1+c2)-A 1679 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1680 if (N0.getOpcode() == ISD::SUB) 1681 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1682 SDLoc DL(N); 1683 return DAG.getNode(ISD::SUB, DL, VT, 1684 DAG.getConstant(N1C->getAPIntValue()+ 1685 N0C->getAPIntValue(), DL, VT), 1686 N0.getOperand(1)); 1687 } 1688 } 1689 // reassociate add 1690 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1691 return RADD; 1692 // fold ((0-A) + B) -> B-A 1693 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1695 // fold (A + (0-B)) -> A-B 1696 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1698 // fold (A+(B-A)) -> B 1699 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1700 return N1.getOperand(0); 1701 // fold ((B-A)+A) -> B 1702 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1703 return N0.getOperand(0); 1704 // fold (A+(B-(A+C))) to (B-C) 1705 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1706 N0 == N1.getOperand(1).getOperand(0)) 1707 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1708 N1.getOperand(1).getOperand(1)); 1709 // fold (A+(B-(C+A))) to (B-C) 1710 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1711 N0 == N1.getOperand(1).getOperand(1)) 1712 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1713 N1.getOperand(1).getOperand(0)); 1714 // fold (A+((B-A)+or-C)) to (B+or-C) 1715 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1716 N1.getOperand(0).getOpcode() == ISD::SUB && 1717 N0 == N1.getOperand(0).getOperand(1)) 1718 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1719 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1720 1721 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1722 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1723 SDValue N00 = N0.getOperand(0); 1724 SDValue N01 = N0.getOperand(1); 1725 SDValue N10 = N1.getOperand(0); 1726 SDValue N11 = N1.getOperand(1); 1727 1728 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1729 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1730 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1731 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1732 } 1733 1734 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1735 return SDValue(N, 0); 1736 1737 // fold (a+b) -> (a|b) iff a and b share no bits. 1738 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::OR, VT)) && 1739 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1740 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1741 1742 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1743 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1744 isNullConstant(N1.getOperand(0).getOperand(0))) 1745 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1746 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1747 N1.getOperand(0).getOperand(1), 1748 N1.getOperand(1))); 1749 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1750 isNullConstant(N0.getOperand(0).getOperand(0))) 1751 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1752 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1753 N0.getOperand(0).getOperand(1), 1754 N0.getOperand(1))); 1755 1756 if (N1.getOpcode() == ISD::AND) { 1757 SDValue AndOp0 = N1.getOperand(0); 1758 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1759 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1760 1761 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1762 // and similar xforms where the inner op is either ~0 or 0. 1763 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1764 SDLoc DL(N); 1765 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1766 } 1767 } 1768 1769 // add (sext i1), X -> sub X, (zext i1) 1770 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1771 N0.getOperand(0).getValueType() == MVT::i1 && 1772 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1773 SDLoc DL(N); 1774 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1775 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1776 } 1777 1778 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1779 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1780 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1781 if (TN->getVT() == MVT::i1) { 1782 SDLoc DL(N); 1783 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1784 DAG.getConstant(1, DL, VT)); 1785 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1786 } 1787 } 1788 1789 return SDValue(); 1790 } 1791 1792 SDValue DAGCombiner::visitADDC(SDNode *N) { 1793 SDValue N0 = N->getOperand(0); 1794 SDValue N1 = N->getOperand(1); 1795 EVT VT = N0.getValueType(); 1796 1797 // If the flag result is dead, turn this into an ADD. 1798 if (!N->hasAnyUseOfValue(1)) 1799 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1800 DAG.getNode(ISD::CARRY_FALSE, 1801 SDLoc(N), MVT::Glue)); 1802 1803 // canonicalize constant to RHS. 1804 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1805 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1806 if (N0C && !N1C) 1807 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1808 1809 // fold (addc x, 0) -> x + no carry out 1810 if (isNullConstant(N1)) 1811 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1812 SDLoc(N), MVT::Glue)); 1813 1814 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1815 APInt LHSZero, LHSOne; 1816 APInt RHSZero, RHSOne; 1817 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1818 1819 if (LHSZero.getBoolValue()) { 1820 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1821 1822 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1823 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1824 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1825 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1826 DAG.getNode(ISD::CARRY_FALSE, 1827 SDLoc(N), MVT::Glue)); 1828 } 1829 1830 return SDValue(); 1831 } 1832 1833 SDValue DAGCombiner::visitADDE(SDNode *N) { 1834 SDValue N0 = N->getOperand(0); 1835 SDValue N1 = N->getOperand(1); 1836 SDValue CarryIn = N->getOperand(2); 1837 1838 // canonicalize constant to RHS 1839 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1840 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1841 if (N0C && !N1C) 1842 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1843 N1, N0, CarryIn); 1844 1845 // fold (adde x, y, false) -> (addc x, y) 1846 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1847 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1848 1849 return SDValue(); 1850 } 1851 1852 // Since it may not be valid to emit a fold to zero for vector initializers 1853 // check if we can before folding. 1854 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1855 SelectionDAG &DAG, 1856 bool LegalOperations, bool LegalTypes) { 1857 if (!VT.isVector()) 1858 return DAG.getConstant(0, DL, VT); 1859 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1860 return DAG.getConstant(0, DL, VT); 1861 return SDValue(); 1862 } 1863 1864 SDValue DAGCombiner::visitSUB(SDNode *N) { 1865 SDValue N0 = N->getOperand(0); 1866 SDValue N1 = N->getOperand(1); 1867 EVT VT = N0.getValueType(); 1868 1869 // fold vector ops 1870 if (VT.isVector()) { 1871 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1872 return FoldedVOp; 1873 1874 // fold (sub x, 0) -> x, vector edition 1875 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1876 return N0; 1877 } 1878 1879 // fold (sub x, x) -> 0 1880 // FIXME: Refactor this and xor and other similar operations together. 1881 if (N0 == N1) 1882 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1883 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1884 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1885 // fold (sub c1, c2) -> c1-c2 1886 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1887 N0.getNode(), N1.getNode()); 1888 } 1889 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1890 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1891 // fold (sub x, c) -> (add x, -c) 1892 if (N1C) { 1893 SDLoc DL(N); 1894 return DAG.getNode(ISD::ADD, DL, VT, N0, 1895 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1896 } 1897 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1898 if (isAllOnesConstant(N0)) 1899 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1900 // fold A-(A-B) -> B 1901 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1902 return N1.getOperand(1); 1903 // fold (A+B)-A -> B 1904 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1905 return N0.getOperand(1); 1906 // fold (A+B)-B -> A 1907 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1908 return N0.getOperand(0); 1909 // fold C2-(A+C1) -> (C2-C1)-A 1910 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1911 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1912 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1913 SDLoc DL(N); 1914 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1915 DL, VT); 1916 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1917 N1.getOperand(0)); 1918 } 1919 // fold ((A+(B+or-C))-B) -> A+or-C 1920 if (N0.getOpcode() == ISD::ADD && 1921 (N0.getOperand(1).getOpcode() == ISD::SUB || 1922 N0.getOperand(1).getOpcode() == ISD::ADD) && 1923 N0.getOperand(1).getOperand(0) == N1) 1924 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1925 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1926 // fold ((A+(C+B))-B) -> A+C 1927 if (N0.getOpcode() == ISD::ADD && 1928 N0.getOperand(1).getOpcode() == ISD::ADD && 1929 N0.getOperand(1).getOperand(1) == N1) 1930 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1931 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1932 // fold ((A-(B-C))-C) -> A-B 1933 if (N0.getOpcode() == ISD::SUB && 1934 N0.getOperand(1).getOpcode() == ISD::SUB && 1935 N0.getOperand(1).getOperand(1) == N1) 1936 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1937 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1938 1939 // If either operand of a sub is undef, the result is undef 1940 if (N0.isUndef()) 1941 return N0; 1942 if (N1.isUndef()) 1943 return N1; 1944 1945 // If the relocation model supports it, consider symbol offsets. 1946 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1947 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1948 // fold (sub Sym, c) -> Sym-c 1949 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1950 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1951 GA->getOffset() - 1952 (uint64_t)N1C->getSExtValue()); 1953 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1954 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1955 if (GA->getGlobal() == GB->getGlobal()) 1956 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1957 SDLoc(N), VT); 1958 } 1959 1960 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1961 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1962 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1963 if (TN->getVT() == MVT::i1) { 1964 SDLoc DL(N); 1965 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1966 DAG.getConstant(1, DL, VT)); 1967 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1968 } 1969 } 1970 1971 return SDValue(); 1972 } 1973 1974 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1975 SDValue N0 = N->getOperand(0); 1976 SDValue N1 = N->getOperand(1); 1977 EVT VT = N0.getValueType(); 1978 SDLoc DL(N); 1979 1980 // If the flag result is dead, turn this into an SUB. 1981 if (!N->hasAnyUseOfValue(1)) 1982 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1983 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1984 1985 // fold (subc x, x) -> 0 + no borrow 1986 if (N0 == N1) 1987 return CombineTo(N, DAG.getConstant(0, DL, VT), 1988 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1989 1990 // fold (subc x, 0) -> x + no borrow 1991 if (isNullConstant(N1)) 1992 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1993 1994 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1995 if (isAllOnesConstant(N0)) 1996 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1997 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1998 1999 return SDValue(); 2000 } 2001 2002 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2003 SDValue N0 = N->getOperand(0); 2004 SDValue N1 = N->getOperand(1); 2005 SDValue CarryIn = N->getOperand(2); 2006 2007 // fold (sube x, y, false) -> (subc x, y) 2008 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2009 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2010 2011 return SDValue(); 2012 } 2013 2014 SDValue DAGCombiner::visitMUL(SDNode *N) { 2015 SDValue N0 = N->getOperand(0); 2016 SDValue N1 = N->getOperand(1); 2017 EVT VT = N0.getValueType(); 2018 2019 // fold (mul x, undef) -> 0 2020 if (N0.isUndef() || N1.isUndef()) 2021 return DAG.getConstant(0, SDLoc(N), VT); 2022 2023 bool N0IsConst = false; 2024 bool N1IsConst = false; 2025 bool N1IsOpaqueConst = false; 2026 bool N0IsOpaqueConst = false; 2027 APInt ConstValue0, ConstValue1; 2028 // fold vector ops 2029 if (VT.isVector()) { 2030 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2031 return FoldedVOp; 2032 2033 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2034 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2035 } else { 2036 N0IsConst = isa<ConstantSDNode>(N0); 2037 if (N0IsConst) { 2038 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2039 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2040 } 2041 N1IsConst = isa<ConstantSDNode>(N1); 2042 if (N1IsConst) { 2043 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2044 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2045 } 2046 } 2047 2048 // fold (mul c1, c2) -> c1*c2 2049 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2050 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2051 N0.getNode(), N1.getNode()); 2052 2053 // canonicalize constant to RHS (vector doesn't have to splat) 2054 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2055 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2056 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2057 // fold (mul x, 0) -> 0 2058 if (N1IsConst && ConstValue1 == 0) 2059 return N1; 2060 // We require a splat of the entire scalar bit width for non-contiguous 2061 // bit patterns. 2062 bool IsFullSplat = 2063 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2064 // fold (mul x, 1) -> x 2065 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2066 return N0; 2067 // fold (mul x, -1) -> 0-x 2068 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2069 SDLoc DL(N); 2070 return DAG.getNode(ISD::SUB, DL, VT, 2071 DAG.getConstant(0, DL, VT), N0); 2072 } 2073 // fold (mul x, (1 << c)) -> x << c 2074 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2075 IsFullSplat) { 2076 SDLoc DL(N); 2077 return DAG.getNode(ISD::SHL, DL, VT, N0, 2078 DAG.getConstant(ConstValue1.logBase2(), DL, 2079 getShiftAmountTy(N0.getValueType()))); 2080 } 2081 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2082 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2083 IsFullSplat) { 2084 unsigned Log2Val = (-ConstValue1).logBase2(); 2085 SDLoc DL(N); 2086 // FIXME: If the input is something that is easily negated (e.g. a 2087 // single-use add), we should put the negate there. 2088 return DAG.getNode(ISD::SUB, DL, VT, 2089 DAG.getConstant(0, DL, VT), 2090 DAG.getNode(ISD::SHL, DL, VT, N0, 2091 DAG.getConstant(Log2Val, DL, 2092 getShiftAmountTy(N0.getValueType())))); 2093 } 2094 2095 APInt Val; 2096 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2097 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2098 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2099 isa<ConstantSDNode>(N0.getOperand(1)))) { 2100 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2101 N1, N0.getOperand(1)); 2102 AddToWorklist(C3.getNode()); 2103 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2104 N0.getOperand(0), C3); 2105 } 2106 2107 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2108 // use. 2109 { 2110 SDValue Sh(nullptr,0), Y(nullptr,0); 2111 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2112 if (N0.getOpcode() == ISD::SHL && 2113 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2114 isa<ConstantSDNode>(N0.getOperand(1))) && 2115 N0.getNode()->hasOneUse()) { 2116 Sh = N0; Y = N1; 2117 } else if (N1.getOpcode() == ISD::SHL && 2118 isa<ConstantSDNode>(N1.getOperand(1)) && 2119 N1.getNode()->hasOneUse()) { 2120 Sh = N1; Y = N0; 2121 } 2122 2123 if (Sh.getNode()) { 2124 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2125 Sh.getOperand(0), Y); 2126 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2127 Mul, Sh.getOperand(1)); 2128 } 2129 } 2130 2131 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2132 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2133 N0.getOpcode() == ISD::ADD && 2134 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2135 isMulAddWithConstProfitable(N, N0, N1)) 2136 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2137 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2138 N0.getOperand(0), N1), 2139 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2140 N0.getOperand(1), N1)); 2141 2142 // reassociate mul 2143 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2144 return RMUL; 2145 2146 return SDValue(); 2147 } 2148 2149 /// Return true if divmod libcall is available. 2150 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2151 const TargetLowering &TLI) { 2152 RTLIB::Libcall LC; 2153 EVT NodeType = Node->getValueType(0); 2154 if (!NodeType.isSimple()) 2155 return false; 2156 switch (NodeType.getSimpleVT().SimpleTy) { 2157 default: return false; // No libcall for vector types. 2158 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2159 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2160 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2161 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2162 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2163 } 2164 2165 return TLI.getLibcallName(LC) != nullptr; 2166 } 2167 2168 /// Issue divrem if both quotient and remainder are needed. 2169 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2170 if (Node->use_empty()) 2171 return SDValue(); // This is a dead node, leave it alone. 2172 2173 unsigned Opcode = Node->getOpcode(); 2174 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2175 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2176 2177 // DivMod lib calls can still work on non-legal types if using lib-calls. 2178 EVT VT = Node->getValueType(0); 2179 if (VT.isVector() || !VT.isInteger()) 2180 return SDValue(); 2181 2182 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2183 return SDValue(); 2184 2185 // If DIVREM is going to get expanded into a libcall, 2186 // but there is no libcall available, then don't combine. 2187 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2188 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2189 return SDValue(); 2190 2191 // If div is legal, it's better to do the normal expansion 2192 unsigned OtherOpcode = 0; 2193 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2194 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2195 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2196 return SDValue(); 2197 } else { 2198 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2199 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2200 return SDValue(); 2201 } 2202 2203 SDValue Op0 = Node->getOperand(0); 2204 SDValue Op1 = Node->getOperand(1); 2205 SDValue combined; 2206 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2207 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2208 SDNode *User = *UI; 2209 if (User == Node || User->use_empty()) 2210 continue; 2211 // Convert the other matching node(s), too; 2212 // otherwise, the DIVREM may get target-legalized into something 2213 // target-specific that we won't be able to recognize. 2214 unsigned UserOpc = User->getOpcode(); 2215 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2216 User->getOperand(0) == Op0 && 2217 User->getOperand(1) == Op1) { 2218 if (!combined) { 2219 if (UserOpc == OtherOpcode) { 2220 SDVTList VTs = DAG.getVTList(VT, VT); 2221 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2222 } else if (UserOpc == DivRemOpc) { 2223 combined = SDValue(User, 0); 2224 } else { 2225 assert(UserOpc == Opcode); 2226 continue; 2227 } 2228 } 2229 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2230 CombineTo(User, combined); 2231 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2232 CombineTo(User, combined.getValue(1)); 2233 } 2234 } 2235 return combined; 2236 } 2237 2238 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2239 SDValue N0 = N->getOperand(0); 2240 SDValue N1 = N->getOperand(1); 2241 EVT VT = N->getValueType(0); 2242 2243 // fold vector ops 2244 if (VT.isVector()) 2245 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2246 return FoldedVOp; 2247 2248 SDLoc DL(N); 2249 2250 // fold (sdiv c1, c2) -> c1/c2 2251 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2252 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2253 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2254 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2255 // fold (sdiv X, 1) -> X 2256 if (N1C && N1C->isOne()) 2257 return N0; 2258 // fold (sdiv X, -1) -> 0-X 2259 if (N1C && N1C->isAllOnesValue()) 2260 return DAG.getNode(ISD::SUB, DL, VT, 2261 DAG.getConstant(0, DL, VT), N0); 2262 2263 // If we know the sign bits of both operands are zero, strength reduce to a 2264 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2265 if (!VT.isVector()) { 2266 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2267 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2268 } 2269 2270 // fold (sdiv X, pow2) -> simple ops after legalize 2271 // FIXME: We check for the exact bit here because the generic lowering gives 2272 // better results in that case. The target-specific lowering should learn how 2273 // to handle exact sdivs efficiently. 2274 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2275 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2276 (N1C->getAPIntValue().isPowerOf2() || 2277 (-N1C->getAPIntValue()).isPowerOf2())) { 2278 // Target-specific implementation of sdiv x, pow2. 2279 if (SDValue Res = BuildSDIVPow2(N)) 2280 return Res; 2281 2282 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2283 2284 // Splat the sign bit into the register 2285 SDValue SGN = 2286 DAG.getNode(ISD::SRA, DL, VT, N0, 2287 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2288 getShiftAmountTy(N0.getValueType()))); 2289 AddToWorklist(SGN.getNode()); 2290 2291 // Add (N0 < 0) ? abs2 - 1 : 0; 2292 SDValue SRL = 2293 DAG.getNode(ISD::SRL, DL, VT, SGN, 2294 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2295 getShiftAmountTy(SGN.getValueType()))); 2296 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2297 AddToWorklist(SRL.getNode()); 2298 AddToWorklist(ADD.getNode()); // Divide by pow2 2299 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2300 DAG.getConstant(lg2, DL, 2301 getShiftAmountTy(ADD.getValueType()))); 2302 2303 // If we're dividing by a positive value, we're done. Otherwise, we must 2304 // negate the result. 2305 if (N1C->getAPIntValue().isNonNegative()) 2306 return SRA; 2307 2308 AddToWorklist(SRA.getNode()); 2309 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2310 } 2311 2312 // If integer divide is expensive and we satisfy the requirements, emit an 2313 // alternate sequence. Targets may check function attributes for size/speed 2314 // trade-offs. 2315 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2316 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2317 if (SDValue Op = BuildSDIV(N)) 2318 return Op; 2319 2320 // sdiv, srem -> sdivrem 2321 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2322 // Otherwise, we break the simplification logic in visitREM(). 2323 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2324 if (SDValue DivRem = useDivRem(N)) 2325 return DivRem; 2326 2327 // undef / X -> 0 2328 if (N0.isUndef()) 2329 return DAG.getConstant(0, DL, VT); 2330 // X / undef -> undef 2331 if (N1.isUndef()) 2332 return N1; 2333 2334 return SDValue(); 2335 } 2336 2337 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2338 SDValue N0 = N->getOperand(0); 2339 SDValue N1 = N->getOperand(1); 2340 EVT VT = N->getValueType(0); 2341 2342 // fold vector ops 2343 if (VT.isVector()) 2344 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2345 return FoldedVOp; 2346 2347 SDLoc DL(N); 2348 2349 // fold (udiv c1, c2) -> c1/c2 2350 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2351 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2352 if (N0C && N1C) 2353 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2354 N0C, N1C)) 2355 return Folded; 2356 // fold (udiv x, (1 << c)) -> x >>u c 2357 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2358 return DAG.getNode(ISD::SRL, DL, VT, N0, 2359 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2360 getShiftAmountTy(N0.getValueType()))); 2361 2362 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2363 if (N1.getOpcode() == ISD::SHL) { 2364 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2365 if (SHC->getAPIntValue().isPowerOf2()) { 2366 EVT ADDVT = N1.getOperand(1).getValueType(); 2367 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2368 N1.getOperand(1), 2369 DAG.getConstant(SHC->getAPIntValue() 2370 .logBase2(), 2371 DL, ADDVT)); 2372 AddToWorklist(Add.getNode()); 2373 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2374 } 2375 } 2376 } 2377 2378 // fold (udiv x, c) -> alternate 2379 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2380 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2381 if (SDValue Op = BuildUDIV(N)) 2382 return Op; 2383 2384 // sdiv, srem -> sdivrem 2385 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2386 // Otherwise, we break the simplification logic in visitREM(). 2387 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2388 if (SDValue DivRem = useDivRem(N)) 2389 return DivRem; 2390 2391 // undef / X -> 0 2392 if (N0.isUndef()) 2393 return DAG.getConstant(0, DL, VT); 2394 // X / undef -> undef 2395 if (N1.isUndef()) 2396 return N1; 2397 2398 return SDValue(); 2399 } 2400 2401 // handles ISD::SREM and ISD::UREM 2402 SDValue DAGCombiner::visitREM(SDNode *N) { 2403 unsigned Opcode = N->getOpcode(); 2404 SDValue N0 = N->getOperand(0); 2405 SDValue N1 = N->getOperand(1); 2406 EVT VT = N->getValueType(0); 2407 bool isSigned = (Opcode == ISD::SREM); 2408 SDLoc DL(N); 2409 2410 // fold (rem c1, c2) -> c1%c2 2411 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2412 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2413 if (N0C && N1C) 2414 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2415 return Folded; 2416 2417 if (isSigned) { 2418 // If we know the sign bits of both operands are zero, strength reduce to a 2419 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2420 if (!VT.isVector()) { 2421 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2422 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2423 } 2424 } else { 2425 // fold (urem x, pow2) -> (and x, pow2-1) 2426 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2427 N1C->getAPIntValue().isPowerOf2()) { 2428 return DAG.getNode(ISD::AND, DL, VT, N0, 2429 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2430 } 2431 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2432 if (N1.getOpcode() == ISD::SHL) { 2433 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2434 if (SHC->getAPIntValue().isPowerOf2()) { 2435 SDValue Add = 2436 DAG.getNode(ISD::ADD, DL, VT, N1, 2437 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2438 VT)); 2439 AddToWorklist(Add.getNode()); 2440 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2441 } 2442 } 2443 } 2444 } 2445 2446 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2447 2448 // If X/C can be simplified by the division-by-constant logic, lower 2449 // X%C to the equivalent of X-X/C*C. 2450 // To avoid mangling nodes, this simplification requires that the combine() 2451 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2452 // against this by skipping the simplification if isIntDivCheap(). When 2453 // div is not cheap, combine will not return a DIVREM. Regardless, 2454 // checking cheapness here makes sense since the simplification results in 2455 // fatter code. 2456 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2457 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2458 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2459 AddToWorklist(Div.getNode()); 2460 SDValue OptimizedDiv = combine(Div.getNode()); 2461 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2462 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2463 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2464 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2465 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2466 AddToWorklist(Mul.getNode()); 2467 return Sub; 2468 } 2469 } 2470 2471 // sdiv, srem -> sdivrem 2472 if (SDValue DivRem = useDivRem(N)) 2473 return DivRem.getValue(1); 2474 2475 // undef % X -> 0 2476 if (N0.isUndef()) 2477 return DAG.getConstant(0, DL, VT); 2478 // X % undef -> undef 2479 if (N1.isUndef()) 2480 return N1; 2481 2482 return SDValue(); 2483 } 2484 2485 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2486 SDValue N0 = N->getOperand(0); 2487 SDValue N1 = N->getOperand(1); 2488 EVT VT = N->getValueType(0); 2489 SDLoc DL(N); 2490 2491 // fold (mulhs x, 0) -> 0 2492 if (isNullConstant(N1)) 2493 return N1; 2494 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2495 if (isOneConstant(N1)) { 2496 SDLoc DL(N); 2497 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2498 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2499 DL, 2500 getShiftAmountTy(N0.getValueType()))); 2501 } 2502 // fold (mulhs x, undef) -> 0 2503 if (N0.isUndef() || N1.isUndef()) 2504 return DAG.getConstant(0, SDLoc(N), VT); 2505 2506 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2507 // plus a shift. 2508 if (VT.isSimple() && !VT.isVector()) { 2509 MVT Simple = VT.getSimpleVT(); 2510 unsigned SimpleSize = Simple.getSizeInBits(); 2511 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2512 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2513 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2514 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2515 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2516 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2517 DAG.getConstant(SimpleSize, DL, 2518 getShiftAmountTy(N1.getValueType()))); 2519 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2520 } 2521 } 2522 2523 return SDValue(); 2524 } 2525 2526 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2527 SDValue N0 = N->getOperand(0); 2528 SDValue N1 = N->getOperand(1); 2529 EVT VT = N->getValueType(0); 2530 SDLoc DL(N); 2531 2532 // fold (mulhu x, 0) -> 0 2533 if (isNullConstant(N1)) 2534 return N1; 2535 // fold (mulhu x, 1) -> 0 2536 if (isOneConstant(N1)) 2537 return DAG.getConstant(0, DL, N0.getValueType()); 2538 // fold (mulhu x, undef) -> 0 2539 if (N0.isUndef() || N1.isUndef()) 2540 return DAG.getConstant(0, DL, VT); 2541 2542 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2543 // plus a shift. 2544 if (VT.isSimple() && !VT.isVector()) { 2545 MVT Simple = VT.getSimpleVT(); 2546 unsigned SimpleSize = Simple.getSizeInBits(); 2547 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2548 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2549 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2550 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2551 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2552 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2553 DAG.getConstant(SimpleSize, DL, 2554 getShiftAmountTy(N1.getValueType()))); 2555 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2556 } 2557 } 2558 2559 return SDValue(); 2560 } 2561 2562 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2563 /// give the opcodes for the two computations that are being performed. Return 2564 /// true if a simplification was made. 2565 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2566 unsigned HiOp) { 2567 // If the high half is not needed, just compute the low half. 2568 bool HiExists = N->hasAnyUseOfValue(1); 2569 if (!HiExists && 2570 (!LegalOperations || 2571 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2572 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2573 return CombineTo(N, Res, Res); 2574 } 2575 2576 // If the low half is not needed, just compute the high half. 2577 bool LoExists = N->hasAnyUseOfValue(0); 2578 if (!LoExists && 2579 (!LegalOperations || 2580 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2581 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2582 return CombineTo(N, Res, Res); 2583 } 2584 2585 // If both halves are used, return as it is. 2586 if (LoExists && HiExists) 2587 return SDValue(); 2588 2589 // If the two computed results can be simplified separately, separate them. 2590 if (LoExists) { 2591 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2592 AddToWorklist(Lo.getNode()); 2593 SDValue LoOpt = combine(Lo.getNode()); 2594 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2595 (!LegalOperations || 2596 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2597 return CombineTo(N, LoOpt, LoOpt); 2598 } 2599 2600 if (HiExists) { 2601 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2602 AddToWorklist(Hi.getNode()); 2603 SDValue HiOpt = combine(Hi.getNode()); 2604 if (HiOpt.getNode() && HiOpt != Hi && 2605 (!LegalOperations || 2606 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2607 return CombineTo(N, HiOpt, HiOpt); 2608 } 2609 2610 return SDValue(); 2611 } 2612 2613 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2614 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2615 return Res; 2616 2617 EVT VT = N->getValueType(0); 2618 SDLoc DL(N); 2619 2620 // If the type is twice as wide is legal, transform the mulhu to a wider 2621 // multiply plus a shift. 2622 if (VT.isSimple() && !VT.isVector()) { 2623 MVT Simple = VT.getSimpleVT(); 2624 unsigned SimpleSize = Simple.getSizeInBits(); 2625 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2626 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2627 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2628 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2629 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2630 // Compute the high part as N1. 2631 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2632 DAG.getConstant(SimpleSize, DL, 2633 getShiftAmountTy(Lo.getValueType()))); 2634 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2635 // Compute the low part as N0. 2636 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2637 return CombineTo(N, Lo, Hi); 2638 } 2639 } 2640 2641 return SDValue(); 2642 } 2643 2644 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2645 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2646 return Res; 2647 2648 EVT VT = N->getValueType(0); 2649 SDLoc DL(N); 2650 2651 // If the type is twice as wide is legal, transform the mulhu to a wider 2652 // multiply plus a shift. 2653 if (VT.isSimple() && !VT.isVector()) { 2654 MVT Simple = VT.getSimpleVT(); 2655 unsigned SimpleSize = Simple.getSizeInBits(); 2656 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2657 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2658 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2659 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2660 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2661 // Compute the high part as N1. 2662 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2663 DAG.getConstant(SimpleSize, DL, 2664 getShiftAmountTy(Lo.getValueType()))); 2665 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2666 // Compute the low part as N0. 2667 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2668 return CombineTo(N, Lo, Hi); 2669 } 2670 } 2671 2672 return SDValue(); 2673 } 2674 2675 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2676 // (smulo x, 2) -> (saddo x, x) 2677 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2678 if (C2->getAPIntValue() == 2) 2679 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2680 N->getOperand(0), N->getOperand(0)); 2681 2682 return SDValue(); 2683 } 2684 2685 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2686 // (umulo x, 2) -> (uaddo x, x) 2687 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2688 if (C2->getAPIntValue() == 2) 2689 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2690 N->getOperand(0), N->getOperand(0)); 2691 2692 return SDValue(); 2693 } 2694 2695 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2696 SDValue N0 = N->getOperand(0); 2697 SDValue N1 = N->getOperand(1); 2698 EVT VT = N0.getValueType(); 2699 2700 // fold vector ops 2701 if (VT.isVector()) 2702 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2703 return FoldedVOp; 2704 2705 // fold (add c1, c2) -> c1+c2 2706 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2707 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2708 if (N0C && N1C) 2709 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2710 2711 // canonicalize constant to RHS 2712 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2713 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2714 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2715 2716 return SDValue(); 2717 } 2718 2719 /// If this is a binary operator with two operands of the same opcode, try to 2720 /// simplify it. 2721 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2722 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2723 EVT VT = N0.getValueType(); 2724 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2725 2726 // Bail early if none of these transforms apply. 2727 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2728 2729 // For each of OP in AND/OR/XOR: 2730 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2731 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2732 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2733 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2734 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2735 // 2736 // do not sink logical op inside of a vector extend, since it may combine 2737 // into a vsetcc. 2738 EVT Op0VT = N0.getOperand(0).getValueType(); 2739 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2740 N0.getOpcode() == ISD::SIGN_EXTEND || 2741 N0.getOpcode() == ISD::BSWAP || 2742 // Avoid infinite looping with PromoteIntBinOp. 2743 (N0.getOpcode() == ISD::ANY_EXTEND && 2744 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2745 (N0.getOpcode() == ISD::TRUNCATE && 2746 (!TLI.isZExtFree(VT, Op0VT) || 2747 !TLI.isTruncateFree(Op0VT, VT)) && 2748 TLI.isTypeLegal(Op0VT))) && 2749 !VT.isVector() && 2750 Op0VT == N1.getOperand(0).getValueType() && 2751 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2752 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2753 N0.getOperand(0).getValueType(), 2754 N0.getOperand(0), N1.getOperand(0)); 2755 AddToWorklist(ORNode.getNode()); 2756 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2757 } 2758 2759 // For each of OP in SHL/SRL/SRA/AND... 2760 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2761 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2762 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2763 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2764 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2765 N0.getOperand(1) == N1.getOperand(1)) { 2766 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2767 N0.getOperand(0).getValueType(), 2768 N0.getOperand(0), N1.getOperand(0)); 2769 AddToWorklist(ORNode.getNode()); 2770 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2771 ORNode, N0.getOperand(1)); 2772 } 2773 2774 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2775 // Only perform this optimization up until type legalization, before 2776 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2777 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2778 // we don't want to undo this promotion. 2779 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2780 // on scalars. 2781 if ((N0.getOpcode() == ISD::BITCAST || 2782 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2783 Level <= AfterLegalizeTypes) { 2784 SDValue In0 = N0.getOperand(0); 2785 SDValue In1 = N1.getOperand(0); 2786 EVT In0Ty = In0.getValueType(); 2787 EVT In1Ty = In1.getValueType(); 2788 SDLoc DL(N); 2789 // If both incoming values are integers, and the original types are the 2790 // same. 2791 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2792 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2793 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2794 AddToWorklist(Op.getNode()); 2795 return BC; 2796 } 2797 } 2798 2799 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2800 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2801 // If both shuffles use the same mask, and both shuffle within a single 2802 // vector, then it is worthwhile to move the swizzle after the operation. 2803 // The type-legalizer generates this pattern when loading illegal 2804 // vector types from memory. In many cases this allows additional shuffle 2805 // optimizations. 2806 // There are other cases where moving the shuffle after the xor/and/or 2807 // is profitable even if shuffles don't perform a swizzle. 2808 // If both shuffles use the same mask, and both shuffles have the same first 2809 // or second operand, then it might still be profitable to move the shuffle 2810 // after the xor/and/or operation. 2811 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2812 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2813 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2814 2815 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2816 "Inputs to shuffles are not the same type"); 2817 2818 // Check that both shuffles use the same mask. The masks are known to be of 2819 // the same length because the result vector type is the same. 2820 // Check also that shuffles have only one use to avoid introducing extra 2821 // instructions. 2822 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2823 SVN0->getMask().equals(SVN1->getMask())) { 2824 SDValue ShOp = N0->getOperand(1); 2825 2826 // Don't try to fold this node if it requires introducing a 2827 // build vector of all zeros that might be illegal at this stage. 2828 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2829 if (!LegalTypes) 2830 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2831 else 2832 ShOp = SDValue(); 2833 } 2834 2835 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2836 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2837 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2838 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2839 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2840 N0->getOperand(0), N1->getOperand(0)); 2841 AddToWorklist(NewNode.getNode()); 2842 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2843 &SVN0->getMask()[0]); 2844 } 2845 2846 // Don't try to fold this node if it requires introducing a 2847 // build vector of all zeros that might be illegal at this stage. 2848 ShOp = N0->getOperand(0); 2849 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2850 if (!LegalTypes) 2851 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2852 else 2853 ShOp = SDValue(); 2854 } 2855 2856 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2857 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2858 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2859 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2860 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2861 N0->getOperand(1), N1->getOperand(1)); 2862 AddToWorklist(NewNode.getNode()); 2863 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2864 &SVN0->getMask()[0]); 2865 } 2866 } 2867 } 2868 2869 return SDValue(); 2870 } 2871 2872 /// This contains all DAGCombine rules which reduce two values combined by 2873 /// an And operation to a single value. This makes them reusable in the context 2874 /// of visitSELECT(). Rules involving constants are not included as 2875 /// visitSELECT() already handles those cases. 2876 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2877 SDNode *LocReference) { 2878 EVT VT = N1.getValueType(); 2879 2880 // fold (and x, undef) -> 0 2881 if (N0.isUndef() || N1.isUndef()) 2882 return DAG.getConstant(0, SDLoc(LocReference), VT); 2883 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2884 SDValue LL, LR, RL, RR, CC0, CC1; 2885 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2886 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2887 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2888 2889 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2890 LL.getValueType().isInteger()) { 2891 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2892 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2893 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2894 LR.getValueType(), LL, RL); 2895 AddToWorklist(ORNode.getNode()); 2896 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2897 } 2898 if (isAllOnesConstant(LR)) { 2899 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2900 if (Op1 == ISD::SETEQ) { 2901 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2902 LR.getValueType(), LL, RL); 2903 AddToWorklist(ANDNode.getNode()); 2904 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2905 } 2906 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2907 if (Op1 == ISD::SETGT) { 2908 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2909 LR.getValueType(), LL, RL); 2910 AddToWorklist(ORNode.getNode()); 2911 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2912 } 2913 } 2914 } 2915 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2916 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2917 Op0 == Op1 && LL.getValueType().isInteger() && 2918 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2919 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2920 SDLoc DL(N0); 2921 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2922 LL, DAG.getConstant(1, DL, 2923 LL.getValueType())); 2924 AddToWorklist(ADDNode.getNode()); 2925 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2926 DAG.getConstant(2, DL, LL.getValueType()), 2927 ISD::SETUGE); 2928 } 2929 // canonicalize equivalent to ll == rl 2930 if (LL == RR && LR == RL) { 2931 Op1 = ISD::getSetCCSwappedOperands(Op1); 2932 std::swap(RL, RR); 2933 } 2934 if (LL == RL && LR == RR) { 2935 bool isInteger = LL.getValueType().isInteger(); 2936 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2937 if (Result != ISD::SETCC_INVALID && 2938 (!LegalOperations || 2939 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2940 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2941 EVT CCVT = getSetCCResultType(LL.getValueType()); 2942 if (N0.getValueType() == CCVT || 2943 (!LegalOperations && N0.getValueType() == MVT::i1)) 2944 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2945 LL, LR, Result); 2946 } 2947 } 2948 } 2949 2950 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2951 VT.getSizeInBits() <= 64) { 2952 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2953 APInt ADDC = ADDI->getAPIntValue(); 2954 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2955 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2956 // immediate for an add, but it is legal if its top c2 bits are set, 2957 // transform the ADD so the immediate doesn't need to be materialized 2958 // in a register. 2959 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2960 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2961 SRLI->getZExtValue()); 2962 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2963 ADDC |= Mask; 2964 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2965 SDLoc DL(N0); 2966 SDValue NewAdd = 2967 DAG.getNode(ISD::ADD, DL, VT, 2968 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2969 CombineTo(N0.getNode(), NewAdd); 2970 // Return N so it doesn't get rechecked! 2971 return SDValue(LocReference, 0); 2972 } 2973 } 2974 } 2975 } 2976 } 2977 } 2978 2979 // Reduce bit extract of low half of an integer to the narrower type. 2980 // (and (srl i64:x, K), KMask) -> 2981 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 2982 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 2983 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 2984 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2985 unsigned Size = VT.getSizeInBits(); 2986 const APInt &AndMask = CAnd->getAPIntValue(); 2987 unsigned ShiftBits = CShift->getZExtValue(); 2988 unsigned MaskBits = AndMask.countTrailingOnes(); 2989 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 2990 2991 if (APIntOps::isMask(AndMask) && 2992 // Required bits must not span the two halves of the integer and 2993 // must fit in the half size type. 2994 (ShiftBits + MaskBits <= Size / 2) && 2995 TLI.isNarrowingProfitable(VT, HalfVT) && 2996 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 2997 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 2998 TLI.isTruncateFree(VT, HalfVT) && 2999 TLI.isZExtFree(HalfVT, VT)) { 3000 // The isNarrowingProfitable is to avoid regressions on PPC and 3001 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3002 // on downstream users of this. Those patterns could probably be 3003 // extended to handle extensions mixed in. 3004 3005 SDValue SL(N0); 3006 assert(ShiftBits != 0 && MaskBits <= Size); 3007 3008 // Extracting the highest bit of the low half. 3009 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3010 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3011 N0.getOperand(0)); 3012 3013 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3014 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3015 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3016 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3017 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3018 } 3019 } 3020 } 3021 } 3022 3023 return SDValue(); 3024 } 3025 3026 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3027 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3028 bool &NarrowLoad) { 3029 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3030 3031 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3032 return false; 3033 3034 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3035 LoadedVT = LoadN->getMemoryVT(); 3036 3037 if (ExtVT == LoadedVT && 3038 (!LegalOperations || 3039 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3040 // ZEXTLOAD will match without needing to change the size of the value being 3041 // loaded. 3042 NarrowLoad = false; 3043 return true; 3044 } 3045 3046 // Do not change the width of a volatile load. 3047 if (LoadN->isVolatile()) 3048 return false; 3049 3050 // Do not generate loads of non-round integer types since these can 3051 // be expensive (and would be wrong if the type is not byte sized). 3052 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3053 return false; 3054 3055 if (LegalOperations && 3056 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3057 return false; 3058 3059 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3060 return false; 3061 3062 NarrowLoad = true; 3063 return true; 3064 } 3065 3066 SDValue DAGCombiner::visitAND(SDNode *N) { 3067 SDValue N0 = N->getOperand(0); 3068 SDValue N1 = N->getOperand(1); 3069 EVT VT = N1.getValueType(); 3070 3071 // fold vector ops 3072 if (VT.isVector()) { 3073 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3074 return FoldedVOp; 3075 3076 // fold (and x, 0) -> 0, vector edition 3077 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3078 // do not return N0, because undef node may exist in N0 3079 return DAG.getConstant( 3080 APInt::getNullValue( 3081 N0.getValueType().getScalarType().getSizeInBits()), 3082 SDLoc(N), N0.getValueType()); 3083 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3084 // do not return N1, because undef node may exist in N1 3085 return DAG.getConstant( 3086 APInt::getNullValue( 3087 N1.getValueType().getScalarType().getSizeInBits()), 3088 SDLoc(N), N1.getValueType()); 3089 3090 // fold (and x, -1) -> x, vector edition 3091 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3092 return N1; 3093 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3094 return N0; 3095 } 3096 3097 // fold (and c1, c2) -> c1&c2 3098 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3099 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3100 if (N0C && N1C && !N1C->isOpaque()) 3101 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3102 // canonicalize constant to RHS 3103 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3104 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3105 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3106 // fold (and x, -1) -> x 3107 if (isAllOnesConstant(N1)) 3108 return N0; 3109 // if (and x, c) is known to be zero, return 0 3110 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3111 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3112 APInt::getAllOnesValue(BitWidth))) 3113 return DAG.getConstant(0, SDLoc(N), VT); 3114 // reassociate and 3115 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3116 return RAND; 3117 // fold (and (or x, C), D) -> D if (C & D) == D 3118 if (N1C && N0.getOpcode() == ISD::OR) 3119 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3120 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3121 return N1; 3122 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3123 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3124 SDValue N0Op0 = N0.getOperand(0); 3125 APInt Mask = ~N1C->getAPIntValue(); 3126 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3127 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3128 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3129 N0.getValueType(), N0Op0); 3130 3131 // Replace uses of the AND with uses of the Zero extend node. 3132 CombineTo(N, Zext); 3133 3134 // We actually want to replace all uses of the any_extend with the 3135 // zero_extend, to avoid duplicating things. This will later cause this 3136 // AND to be folded. 3137 CombineTo(N0.getNode(), Zext); 3138 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3139 } 3140 } 3141 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3142 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3143 // already be zero by virtue of the width of the base type of the load. 3144 // 3145 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3146 // more cases. 3147 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3148 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3149 N0.getOperand(0).getOpcode() == ISD::LOAD && 3150 N0.getOperand(0).getResNo() == 0) || 3151 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3152 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3153 N0 : N0.getOperand(0) ); 3154 3155 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3156 // This can be a pure constant or a vector splat, in which case we treat the 3157 // vector as a scalar and use the splat value. 3158 APInt Constant = APInt::getNullValue(1); 3159 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3160 Constant = C->getAPIntValue(); 3161 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3162 APInt SplatValue, SplatUndef; 3163 unsigned SplatBitSize; 3164 bool HasAnyUndefs; 3165 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3166 SplatBitSize, HasAnyUndefs); 3167 if (IsSplat) { 3168 // Undef bits can contribute to a possible optimisation if set, so 3169 // set them. 3170 SplatValue |= SplatUndef; 3171 3172 // The splat value may be something like "0x00FFFFFF", which means 0 for 3173 // the first vector value and FF for the rest, repeating. We need a mask 3174 // that will apply equally to all members of the vector, so AND all the 3175 // lanes of the constant together. 3176 EVT VT = Vector->getValueType(0); 3177 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3178 3179 // If the splat value has been compressed to a bitlength lower 3180 // than the size of the vector lane, we need to re-expand it to 3181 // the lane size. 3182 if (BitWidth > SplatBitSize) 3183 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3184 SplatBitSize < BitWidth; 3185 SplatBitSize = SplatBitSize * 2) 3186 SplatValue |= SplatValue.shl(SplatBitSize); 3187 3188 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3189 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3190 if (SplatBitSize % BitWidth == 0) { 3191 Constant = APInt::getAllOnesValue(BitWidth); 3192 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3193 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3194 } 3195 } 3196 } 3197 3198 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3199 // actually legal and isn't going to get expanded, else this is a false 3200 // optimisation. 3201 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3202 Load->getValueType(0), 3203 Load->getMemoryVT()); 3204 3205 // Resize the constant to the same size as the original memory access before 3206 // extension. If it is still the AllOnesValue then this AND is completely 3207 // unneeded. 3208 Constant = 3209 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3210 3211 bool B; 3212 switch (Load->getExtensionType()) { 3213 default: B = false; break; 3214 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3215 case ISD::ZEXTLOAD: 3216 case ISD::NON_EXTLOAD: B = true; break; 3217 } 3218 3219 if (B && Constant.isAllOnesValue()) { 3220 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3221 // preserve semantics once we get rid of the AND. 3222 SDValue NewLoad(Load, 0); 3223 if (Load->getExtensionType() == ISD::EXTLOAD) { 3224 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3225 Load->getValueType(0), SDLoc(Load), 3226 Load->getChain(), Load->getBasePtr(), 3227 Load->getOffset(), Load->getMemoryVT(), 3228 Load->getMemOperand()); 3229 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3230 if (Load->getNumValues() == 3) { 3231 // PRE/POST_INC loads have 3 values. 3232 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3233 NewLoad.getValue(2) }; 3234 CombineTo(Load, To, 3, true); 3235 } else { 3236 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3237 } 3238 } 3239 3240 // Fold the AND away, taking care not to fold to the old load node if we 3241 // replaced it. 3242 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3243 3244 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3245 } 3246 } 3247 3248 // fold (and (load x), 255) -> (zextload x, i8) 3249 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3250 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3251 if (N1C && (N0.getOpcode() == ISD::LOAD || 3252 (N0.getOpcode() == ISD::ANY_EXTEND && 3253 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3254 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3255 LoadSDNode *LN0 = HasAnyExt 3256 ? cast<LoadSDNode>(N0.getOperand(0)) 3257 : cast<LoadSDNode>(N0); 3258 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3259 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3260 auto NarrowLoad = false; 3261 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3262 EVT ExtVT, LoadedVT; 3263 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3264 NarrowLoad)) { 3265 if (!NarrowLoad) { 3266 SDValue NewLoad = 3267 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3268 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3269 LN0->getMemOperand()); 3270 AddToWorklist(N); 3271 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3272 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3273 } else { 3274 EVT PtrType = LN0->getOperand(1).getValueType(); 3275 3276 unsigned Alignment = LN0->getAlignment(); 3277 SDValue NewPtr = LN0->getBasePtr(); 3278 3279 // For big endian targets, we need to add an offset to the pointer 3280 // to load the correct bytes. For little endian systems, we merely 3281 // need to read fewer bytes from the same pointer. 3282 if (DAG.getDataLayout().isBigEndian()) { 3283 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3284 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3285 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3286 SDLoc DL(LN0); 3287 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3288 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3289 Alignment = MinAlign(Alignment, PtrOff); 3290 } 3291 3292 AddToWorklist(NewPtr.getNode()); 3293 3294 SDValue Load = 3295 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3296 LN0->getChain(), NewPtr, 3297 LN0->getPointerInfo(), 3298 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3299 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3300 AddToWorklist(N); 3301 CombineTo(LN0, Load, Load.getValue(1)); 3302 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3303 } 3304 } 3305 } 3306 } 3307 3308 if (SDValue Combined = visitANDLike(N0, N1, N)) 3309 return Combined; 3310 3311 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3312 if (N0.getOpcode() == N1.getOpcode()) 3313 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3314 return Tmp; 3315 3316 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3317 // fold (and (sra)) -> (and (srl)) when possible. 3318 if (!VT.isVector() && 3319 SimplifyDemandedBits(SDValue(N, 0))) 3320 return SDValue(N, 0); 3321 3322 // fold (zext_inreg (extload x)) -> (zextload x) 3323 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 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 (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3342 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3343 N0.hasOneUse()) { 3344 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3345 EVT MemVT = LN0->getMemoryVT(); 3346 // If we zero all the possible extended bits, then we can turn this into 3347 // a zextload if we are running before legalize or the operation is legal. 3348 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3349 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3350 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3351 ((!LegalOperations && !LN0->isVolatile()) || 3352 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3353 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3354 LN0->getChain(), LN0->getBasePtr(), 3355 MemVT, LN0->getMemOperand()); 3356 AddToWorklist(N); 3357 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3358 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3359 } 3360 } 3361 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3362 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3363 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3364 N0.getOperand(1), false)) 3365 return BSwap; 3366 } 3367 3368 return SDValue(); 3369 } 3370 3371 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3372 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3373 bool DemandHighBits) { 3374 if (!LegalOperations) 3375 return SDValue(); 3376 3377 EVT VT = N->getValueType(0); 3378 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3379 return SDValue(); 3380 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3381 return SDValue(); 3382 3383 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3384 bool LookPassAnd0 = false; 3385 bool LookPassAnd1 = false; 3386 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3387 std::swap(N0, N1); 3388 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3389 std::swap(N0, N1); 3390 if (N0.getOpcode() == ISD::AND) { 3391 if (!N0.getNode()->hasOneUse()) 3392 return SDValue(); 3393 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3394 if (!N01C || N01C->getZExtValue() != 0xFF00) 3395 return SDValue(); 3396 N0 = N0.getOperand(0); 3397 LookPassAnd0 = true; 3398 } 3399 3400 if (N1.getOpcode() == ISD::AND) { 3401 if (!N1.getNode()->hasOneUse()) 3402 return SDValue(); 3403 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3404 if (!N11C || N11C->getZExtValue() != 0xFF) 3405 return SDValue(); 3406 N1 = N1.getOperand(0); 3407 LookPassAnd1 = true; 3408 } 3409 3410 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3411 std::swap(N0, N1); 3412 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3413 return SDValue(); 3414 if (!N0.getNode()->hasOneUse() || 3415 !N1.getNode()->hasOneUse()) 3416 return SDValue(); 3417 3418 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3419 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3420 if (!N01C || !N11C) 3421 return SDValue(); 3422 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3423 return SDValue(); 3424 3425 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3426 SDValue N00 = N0->getOperand(0); 3427 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3428 if (!N00.getNode()->hasOneUse()) 3429 return SDValue(); 3430 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3431 if (!N001C || N001C->getZExtValue() != 0xFF) 3432 return SDValue(); 3433 N00 = N00.getOperand(0); 3434 LookPassAnd0 = true; 3435 } 3436 3437 SDValue N10 = N1->getOperand(0); 3438 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3439 if (!N10.getNode()->hasOneUse()) 3440 return SDValue(); 3441 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3442 if (!N101C || N101C->getZExtValue() != 0xFF00) 3443 return SDValue(); 3444 N10 = N10.getOperand(0); 3445 LookPassAnd1 = true; 3446 } 3447 3448 if (N00 != N10) 3449 return SDValue(); 3450 3451 // Make sure everything beyond the low halfword gets set to zero since the SRL 3452 // 16 will clear the top bits. 3453 unsigned OpSizeInBits = VT.getSizeInBits(); 3454 if (DemandHighBits && OpSizeInBits > 16) { 3455 // If the left-shift isn't masked out then the only way this is a bswap is 3456 // if all bits beyond the low 8 are 0. In that case the entire pattern 3457 // reduces to a left shift anyway: leave it for other parts of the combiner. 3458 if (!LookPassAnd0) 3459 return SDValue(); 3460 3461 // However, if the right shift isn't masked out then it might be because 3462 // it's not needed. See if we can spot that too. 3463 if (!LookPassAnd1 && 3464 !DAG.MaskedValueIsZero( 3465 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3466 return SDValue(); 3467 } 3468 3469 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3470 if (OpSizeInBits > 16) { 3471 SDLoc DL(N); 3472 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3473 DAG.getConstant(OpSizeInBits - 16, DL, 3474 getShiftAmountTy(VT))); 3475 } 3476 return Res; 3477 } 3478 3479 /// Return true if the specified node is an element that makes up a 32-bit 3480 /// packed halfword byteswap. 3481 /// ((x & 0x000000ff) << 8) | 3482 /// ((x & 0x0000ff00) >> 8) | 3483 /// ((x & 0x00ff0000) << 8) | 3484 /// ((x & 0xff000000) >> 8) 3485 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3486 if (!N.getNode()->hasOneUse()) 3487 return false; 3488 3489 unsigned Opc = N.getOpcode(); 3490 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3491 return false; 3492 3493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3494 if (!N1C) 3495 return false; 3496 3497 unsigned Num; 3498 switch (N1C->getZExtValue()) { 3499 default: 3500 return false; 3501 case 0xFF: Num = 0; break; 3502 case 0xFF00: Num = 1; break; 3503 case 0xFF0000: Num = 2; break; 3504 case 0xFF000000: Num = 3; break; 3505 } 3506 3507 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3508 SDValue N0 = N.getOperand(0); 3509 if (Opc == ISD::AND) { 3510 if (Num == 0 || Num == 2) { 3511 // (x >> 8) & 0xff 3512 // (x >> 8) & 0xff0000 3513 if (N0.getOpcode() != ISD::SRL) 3514 return false; 3515 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3516 if (!C || C->getZExtValue() != 8) 3517 return false; 3518 } else { 3519 // (x << 8) & 0xff00 3520 // (x << 8) & 0xff000000 3521 if (N0.getOpcode() != ISD::SHL) 3522 return false; 3523 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3524 if (!C || C->getZExtValue() != 8) 3525 return false; 3526 } 3527 } else if (Opc == ISD::SHL) { 3528 // (x & 0xff) << 8 3529 // (x & 0xff0000) << 8 3530 if (Num != 0 && Num != 2) 3531 return false; 3532 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3533 if (!C || C->getZExtValue() != 8) 3534 return false; 3535 } else { // Opc == ISD::SRL 3536 // (x & 0xff00) >> 8 3537 // (x & 0xff000000) >> 8 3538 if (Num != 1 && Num != 3) 3539 return false; 3540 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3541 if (!C || C->getZExtValue() != 8) 3542 return false; 3543 } 3544 3545 if (Parts[Num]) 3546 return false; 3547 3548 Parts[Num] = N0.getOperand(0).getNode(); 3549 return true; 3550 } 3551 3552 /// Match a 32-bit packed halfword bswap. That is 3553 /// ((x & 0x000000ff) << 8) | 3554 /// ((x & 0x0000ff00) >> 8) | 3555 /// ((x & 0x00ff0000) << 8) | 3556 /// ((x & 0xff000000) >> 8) 3557 /// => (rotl (bswap x), 16) 3558 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3559 if (!LegalOperations) 3560 return SDValue(); 3561 3562 EVT VT = N->getValueType(0); 3563 if (VT != MVT::i32) 3564 return SDValue(); 3565 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3566 return SDValue(); 3567 3568 // Look for either 3569 // (or (or (and), (and)), (or (and), (and))) 3570 // (or (or (or (and), (and)), (and)), (and)) 3571 if (N0.getOpcode() != ISD::OR) 3572 return SDValue(); 3573 SDValue N00 = N0.getOperand(0); 3574 SDValue N01 = N0.getOperand(1); 3575 SDNode *Parts[4] = {}; 3576 3577 if (N1.getOpcode() == ISD::OR && 3578 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3579 // (or (or (and), (and)), (or (and), (and))) 3580 SDValue N000 = N00.getOperand(0); 3581 if (!isBSwapHWordElement(N000, Parts)) 3582 return SDValue(); 3583 3584 SDValue N001 = N00.getOperand(1); 3585 if (!isBSwapHWordElement(N001, Parts)) 3586 return SDValue(); 3587 SDValue N010 = N01.getOperand(0); 3588 if (!isBSwapHWordElement(N010, Parts)) 3589 return SDValue(); 3590 SDValue N011 = N01.getOperand(1); 3591 if (!isBSwapHWordElement(N011, Parts)) 3592 return SDValue(); 3593 } else { 3594 // (or (or (or (and), (and)), (and)), (and)) 3595 if (!isBSwapHWordElement(N1, Parts)) 3596 return SDValue(); 3597 if (!isBSwapHWordElement(N01, Parts)) 3598 return SDValue(); 3599 if (N00.getOpcode() != ISD::OR) 3600 return SDValue(); 3601 SDValue N000 = N00.getOperand(0); 3602 if (!isBSwapHWordElement(N000, Parts)) 3603 return SDValue(); 3604 SDValue N001 = N00.getOperand(1); 3605 if (!isBSwapHWordElement(N001, Parts)) 3606 return SDValue(); 3607 } 3608 3609 // Make sure the parts are all coming from the same node. 3610 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3611 return SDValue(); 3612 3613 SDLoc DL(N); 3614 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3615 SDValue(Parts[0], 0)); 3616 3617 // Result of the bswap should be rotated by 16. If it's not legal, then 3618 // do (x << 16) | (x >> 16). 3619 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3620 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3621 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3622 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3623 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3624 return DAG.getNode(ISD::OR, DL, VT, 3625 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3626 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3627 } 3628 3629 /// This contains all DAGCombine rules which reduce two values combined by 3630 /// an Or operation to a single value \see visitANDLike(). 3631 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3632 EVT VT = N1.getValueType(); 3633 // fold (or x, undef) -> -1 3634 if (!LegalOperations && 3635 (N0.isUndef() || N1.isUndef())) { 3636 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3637 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3638 SDLoc(LocReference), VT); 3639 } 3640 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3641 SDValue LL, LR, RL, RR, CC0, CC1; 3642 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3643 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3644 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3645 3646 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3647 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3648 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3649 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3650 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3651 LR.getValueType(), LL, RL); 3652 AddToWorklist(ORNode.getNode()); 3653 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3654 } 3655 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3656 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3657 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3658 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3659 LR.getValueType(), LL, RL); 3660 AddToWorklist(ANDNode.getNode()); 3661 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3662 } 3663 } 3664 // canonicalize equivalent to ll == rl 3665 if (LL == RR && LR == RL) { 3666 Op1 = ISD::getSetCCSwappedOperands(Op1); 3667 std::swap(RL, RR); 3668 } 3669 if (LL == RL && LR == RR) { 3670 bool isInteger = LL.getValueType().isInteger(); 3671 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3672 if (Result != ISD::SETCC_INVALID && 3673 (!LegalOperations || 3674 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3675 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3676 EVT CCVT = getSetCCResultType(LL.getValueType()); 3677 if (N0.getValueType() == CCVT || 3678 (!LegalOperations && N0.getValueType() == MVT::i1)) 3679 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3680 LL, LR, Result); 3681 } 3682 } 3683 } 3684 3685 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3686 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3687 // Don't increase # computations. 3688 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3689 // We can only do this xform if we know that bits from X that are set in C2 3690 // but not in C1 are already zero. Likewise for Y. 3691 if (const ConstantSDNode *N0O1C = 3692 getAsNonOpaqueConstant(N0.getOperand(1))) { 3693 if (const ConstantSDNode *N1O1C = 3694 getAsNonOpaqueConstant(N1.getOperand(1))) { 3695 // We can only do this xform if we know that bits from X that are set in 3696 // C2 but not in C1 are already zero. Likewise for Y. 3697 const APInt &LHSMask = N0O1C->getAPIntValue(); 3698 const APInt &RHSMask = N1O1C->getAPIntValue(); 3699 3700 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3701 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3702 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3703 N0.getOperand(0), N1.getOperand(0)); 3704 SDLoc DL(LocReference); 3705 return DAG.getNode(ISD::AND, DL, VT, X, 3706 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3707 } 3708 } 3709 } 3710 } 3711 3712 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3713 if (N0.getOpcode() == ISD::AND && 3714 N1.getOpcode() == ISD::AND && 3715 N0.getOperand(0) == N1.getOperand(0) && 3716 // Don't increase # computations. 3717 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3718 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3719 N0.getOperand(1), N1.getOperand(1)); 3720 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3721 } 3722 3723 return SDValue(); 3724 } 3725 3726 SDValue DAGCombiner::visitOR(SDNode *N) { 3727 SDValue N0 = N->getOperand(0); 3728 SDValue N1 = N->getOperand(1); 3729 EVT VT = N1.getValueType(); 3730 3731 // fold vector ops 3732 if (VT.isVector()) { 3733 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3734 return FoldedVOp; 3735 3736 // fold (or x, 0) -> x, vector edition 3737 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3738 return N1; 3739 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3740 return N0; 3741 3742 // fold (or x, -1) -> -1, vector edition 3743 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3744 // do not return N0, because undef node may exist in N0 3745 return DAG.getConstant( 3746 APInt::getAllOnesValue( 3747 N0.getValueType().getScalarType().getSizeInBits()), 3748 SDLoc(N), N0.getValueType()); 3749 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3750 // do not return N1, because undef node may exist in N1 3751 return DAG.getConstant( 3752 APInt::getAllOnesValue( 3753 N1.getValueType().getScalarType().getSizeInBits()), 3754 SDLoc(N), N1.getValueType()); 3755 3756 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3757 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3758 // Do this only if the resulting shuffle is legal. 3759 if (isa<ShuffleVectorSDNode>(N0) && 3760 isa<ShuffleVectorSDNode>(N1) && 3761 // Avoid folding a node with illegal type. 3762 TLI.isTypeLegal(VT) && 3763 N0->getOperand(1) == N1->getOperand(1) && 3764 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3765 bool CanFold = true; 3766 unsigned NumElts = VT.getVectorNumElements(); 3767 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3768 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3769 // We construct two shuffle masks: 3770 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3771 // and N1 as the second operand. 3772 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3773 // and N0 as the second operand. 3774 // We do this because OR is commutable and therefore there might be 3775 // two ways to fold this node into a shuffle. 3776 SmallVector<int,4> Mask1; 3777 SmallVector<int,4> Mask2; 3778 3779 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3780 int M0 = SV0->getMaskElt(i); 3781 int M1 = SV1->getMaskElt(i); 3782 3783 // Both shuffle indexes are undef. Propagate Undef. 3784 if (M0 < 0 && M1 < 0) { 3785 Mask1.push_back(M0); 3786 Mask2.push_back(M0); 3787 continue; 3788 } 3789 3790 if (M0 < 0 || M1 < 0 || 3791 (M0 < (int)NumElts && M1 < (int)NumElts) || 3792 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3793 CanFold = false; 3794 break; 3795 } 3796 3797 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3798 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3799 } 3800 3801 if (CanFold) { 3802 // Fold this sequence only if the resulting shuffle is 'legal'. 3803 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3804 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3805 N1->getOperand(0), &Mask1[0]); 3806 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3807 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3808 N0->getOperand(0), &Mask2[0]); 3809 } 3810 } 3811 } 3812 3813 // fold (or c1, c2) -> c1|c2 3814 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3815 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3816 if (N0C && N1C && !N1C->isOpaque()) 3817 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3818 // canonicalize constant to RHS 3819 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3820 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3821 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3822 // fold (or x, 0) -> x 3823 if (isNullConstant(N1)) 3824 return N0; 3825 // fold (or x, -1) -> -1 3826 if (isAllOnesConstant(N1)) 3827 return N1; 3828 // fold (or x, c) -> c iff (x & ~c) == 0 3829 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3830 return N1; 3831 3832 if (SDValue Combined = visitORLike(N0, N1, N)) 3833 return Combined; 3834 3835 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3836 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3837 return BSwap; 3838 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3839 return BSwap; 3840 3841 // reassociate or 3842 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3843 return ROR; 3844 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3845 // iff (c1 & c2) == 0. 3846 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3847 isa<ConstantSDNode>(N0.getOperand(1))) { 3848 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3849 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3850 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3851 N1C, C1)) 3852 return DAG.getNode( 3853 ISD::AND, SDLoc(N), VT, 3854 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3855 return SDValue(); 3856 } 3857 } 3858 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3859 if (N0.getOpcode() == N1.getOpcode()) 3860 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3861 return Tmp; 3862 3863 // See if this is some rotate idiom. 3864 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3865 return SDValue(Rot, 0); 3866 3867 // Simplify the operands using demanded-bits information. 3868 if (!VT.isVector() && 3869 SimplifyDemandedBits(SDValue(N, 0))) 3870 return SDValue(N, 0); 3871 3872 return SDValue(); 3873 } 3874 3875 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3876 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3877 if (Op.getOpcode() == ISD::AND) { 3878 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3879 Mask = Op.getOperand(1); 3880 Op = Op.getOperand(0); 3881 } else { 3882 return false; 3883 } 3884 } 3885 3886 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3887 Shift = Op; 3888 return true; 3889 } 3890 3891 return false; 3892 } 3893 3894 // Return true if we can prove that, whenever Neg and Pos are both in the 3895 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3896 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3897 // 3898 // (or (shift1 X, Neg), (shift2 X, Pos)) 3899 // 3900 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3901 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3902 // to consider shift amounts with defined behavior. 3903 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3904 // If EltSize is a power of 2 then: 3905 // 3906 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3907 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3908 // 3909 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3910 // for the stronger condition: 3911 // 3912 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3913 // 3914 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3915 // we can just replace Neg with Neg' for the rest of the function. 3916 // 3917 // In other cases we check for the even stronger condition: 3918 // 3919 // Neg == EltSize - Pos [B] 3920 // 3921 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3922 // behavior if Pos == 0 (and consequently Neg == EltSize). 3923 // 3924 // We could actually use [A] whenever EltSize is a power of 2, but the 3925 // only extra cases that it would match are those uninteresting ones 3926 // where Neg and Pos are never in range at the same time. E.g. for 3927 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3928 // as well as (sub 32, Pos), but: 3929 // 3930 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3931 // 3932 // always invokes undefined behavior for 32-bit X. 3933 // 3934 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3935 unsigned MaskLoBits = 0; 3936 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3937 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3938 if (NegC->getAPIntValue() == EltSize - 1) { 3939 Neg = Neg.getOperand(0); 3940 MaskLoBits = Log2_64(EltSize); 3941 } 3942 } 3943 } 3944 3945 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3946 if (Neg.getOpcode() != ISD::SUB) 3947 return false; 3948 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3949 if (!NegC) 3950 return false; 3951 SDValue NegOp1 = Neg.getOperand(1); 3952 3953 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3954 // Pos'. The truncation is redundant for the purpose of the equality. 3955 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3956 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3957 if (PosC->getAPIntValue() == EltSize - 1) 3958 Pos = Pos.getOperand(0); 3959 3960 // The condition we need is now: 3961 // 3962 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3963 // 3964 // If NegOp1 == Pos then we need: 3965 // 3966 // EltSize & Mask == NegC & Mask 3967 // 3968 // (because "x & Mask" is a truncation and distributes through subtraction). 3969 APInt Width; 3970 if (Pos == NegOp1) 3971 Width = NegC->getAPIntValue(); 3972 3973 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3974 // Then the condition we want to prove becomes: 3975 // 3976 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3977 // 3978 // which, again because "x & Mask" is a truncation, becomes: 3979 // 3980 // NegC & Mask == (EltSize - PosC) & Mask 3981 // EltSize & Mask == (NegC + PosC) & Mask 3982 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3983 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3984 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3985 else 3986 return false; 3987 } else 3988 return false; 3989 3990 // Now we just need to check that EltSize & Mask == Width & Mask. 3991 if (MaskLoBits) 3992 // EltSize & Mask is 0 since Mask is EltSize - 1. 3993 return Width.getLoBits(MaskLoBits) == 0; 3994 return Width == EltSize; 3995 } 3996 3997 // A subroutine of MatchRotate used once we have found an OR of two opposite 3998 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3999 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4000 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4001 // Neg with outer conversions stripped away. 4002 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4003 SDValue Neg, SDValue InnerPos, 4004 SDValue InnerNeg, unsigned PosOpcode, 4005 unsigned NegOpcode, SDLoc DL) { 4006 // fold (or (shl x, (*ext y)), 4007 // (srl x, (*ext (sub 32, y)))) -> 4008 // (rotl x, y) or (rotr x, (sub 32, y)) 4009 // 4010 // fold (or (shl x, (*ext (sub 32, y))), 4011 // (srl x, (*ext y))) -> 4012 // (rotr x, y) or (rotl x, (sub 32, y)) 4013 EVT VT = Shifted.getValueType(); 4014 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4015 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4016 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4017 HasPos ? Pos : Neg).getNode(); 4018 } 4019 4020 return nullptr; 4021 } 4022 4023 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4024 // idioms for rotate, and if the target supports rotation instructions, generate 4025 // a rot[lr]. 4026 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 4027 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4028 EVT VT = LHS.getValueType(); 4029 if (!TLI.isTypeLegal(VT)) return nullptr; 4030 4031 // The target must have at least one rotate flavor. 4032 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4033 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4034 if (!HasROTL && !HasROTR) return nullptr; 4035 4036 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4037 SDValue LHSShift; // The shift. 4038 SDValue LHSMask; // AND value if any. 4039 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4040 return nullptr; // Not part of a rotate. 4041 4042 SDValue RHSShift; // The shift. 4043 SDValue RHSMask; // AND value if any. 4044 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4045 return nullptr; // Not part of a rotate. 4046 4047 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4048 return nullptr; // Not shifting the same value. 4049 4050 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4051 return nullptr; // Shifts must disagree. 4052 4053 // Canonicalize shl to left side in a shl/srl pair. 4054 if (RHSShift.getOpcode() == ISD::SHL) { 4055 std::swap(LHS, RHS); 4056 std::swap(LHSShift, RHSShift); 4057 std::swap(LHSMask, RHSMask); 4058 } 4059 4060 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4061 SDValue LHSShiftArg = LHSShift.getOperand(0); 4062 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4063 SDValue RHSShiftArg = RHSShift.getOperand(0); 4064 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4065 4066 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4067 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4068 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4069 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4070 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4071 if ((LShVal + RShVal) != EltSizeInBits) 4072 return nullptr; 4073 4074 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4075 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4076 4077 // If there is an AND of either shifted operand, apply it to the result. 4078 if (LHSMask.getNode() || RHSMask.getNode()) { 4079 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4080 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4081 4082 if (LHSMask.getNode()) { 4083 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4084 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4085 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4086 DAG.getConstant(RHSBits, DL, VT))); 4087 } 4088 if (RHSMask.getNode()) { 4089 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4090 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4091 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4092 DAG.getConstant(LHSBits, DL, VT))); 4093 } 4094 4095 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4096 } 4097 4098 return Rot.getNode(); 4099 } 4100 4101 // If there is a mask here, and we have a variable shift, we can't be sure 4102 // that we're masking out the right stuff. 4103 if (LHSMask.getNode() || RHSMask.getNode()) 4104 return nullptr; 4105 4106 // If the shift amount is sign/zext/any-extended just peel it off. 4107 SDValue LExtOp0 = LHSShiftAmt; 4108 SDValue RExtOp0 = RHSShiftAmt; 4109 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4110 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4111 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4112 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4113 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4114 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4115 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4116 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4117 LExtOp0 = LHSShiftAmt.getOperand(0); 4118 RExtOp0 = RHSShiftAmt.getOperand(0); 4119 } 4120 4121 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4122 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4123 if (TryL) 4124 return TryL; 4125 4126 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4127 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4128 if (TryR) 4129 return TryR; 4130 4131 return nullptr; 4132 } 4133 4134 SDValue DAGCombiner::visitXOR(SDNode *N) { 4135 SDValue N0 = N->getOperand(0); 4136 SDValue N1 = N->getOperand(1); 4137 EVT VT = N0.getValueType(); 4138 4139 // fold vector ops 4140 if (VT.isVector()) { 4141 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4142 return FoldedVOp; 4143 4144 // fold (xor x, 0) -> x, vector edition 4145 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4146 return N1; 4147 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4148 return N0; 4149 } 4150 4151 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4152 if (N0.isUndef() && N1.isUndef()) 4153 return DAG.getConstant(0, SDLoc(N), VT); 4154 // fold (xor x, undef) -> undef 4155 if (N0.isUndef()) 4156 return N0; 4157 if (N1.isUndef()) 4158 return N1; 4159 // fold (xor c1, c2) -> c1^c2 4160 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4161 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4162 if (N0C && N1C) 4163 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4164 // canonicalize constant to RHS 4165 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4166 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4167 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4168 // fold (xor x, 0) -> x 4169 if (isNullConstant(N1)) 4170 return N0; 4171 // reassociate xor 4172 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4173 return RXOR; 4174 4175 // fold !(x cc y) -> (x !cc y) 4176 SDValue LHS, RHS, CC; 4177 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4178 bool isInt = LHS.getValueType().isInteger(); 4179 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4180 isInt); 4181 4182 if (!LegalOperations || 4183 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4184 switch (N0.getOpcode()) { 4185 default: 4186 llvm_unreachable("Unhandled SetCC Equivalent!"); 4187 case ISD::SETCC: 4188 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4189 case ISD::SELECT_CC: 4190 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4191 N0.getOperand(3), NotCC); 4192 } 4193 } 4194 } 4195 4196 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4197 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4198 N0.getNode()->hasOneUse() && 4199 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4200 SDValue V = N0.getOperand(0); 4201 SDLoc DL(N0); 4202 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4203 DAG.getConstant(1, DL, V.getValueType())); 4204 AddToWorklist(V.getNode()); 4205 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4206 } 4207 4208 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4209 if (isOneConstant(N1) && VT == MVT::i1 && 4210 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4211 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4212 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4213 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4214 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4215 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4216 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4217 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4218 } 4219 } 4220 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4221 if (isAllOnesConstant(N1) && 4222 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4223 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4224 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4225 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4226 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4227 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4228 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4229 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4230 } 4231 } 4232 // fold (xor (and x, y), y) -> (and (not x), y) 4233 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4234 N0->getOperand(1) == N1) { 4235 SDValue X = N0->getOperand(0); 4236 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4237 AddToWorklist(NotX.getNode()); 4238 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4239 } 4240 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4241 if (N1C && N0.getOpcode() == ISD::XOR) { 4242 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4243 SDLoc DL(N); 4244 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4245 DAG.getConstant(N1C->getAPIntValue() ^ 4246 N00C->getAPIntValue(), DL, VT)); 4247 } 4248 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4249 SDLoc DL(N); 4250 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4251 DAG.getConstant(N1C->getAPIntValue() ^ 4252 N01C->getAPIntValue(), DL, VT)); 4253 } 4254 } 4255 // fold (xor x, x) -> 0 4256 if (N0 == N1) 4257 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4258 4259 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4260 // Here is a concrete example of this equivalence: 4261 // i16 x == 14 4262 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4263 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4264 // 4265 // => 4266 // 4267 // i16 ~1 == 0b1111111111111110 4268 // i16 rol(~1, 14) == 0b1011111111111111 4269 // 4270 // Some additional tips to help conceptualize this transform: 4271 // - Try to see the operation as placing a single zero in a value of all ones. 4272 // - There exists no value for x which would allow the result to contain zero. 4273 // - Values of x larger than the bitwidth are undefined and do not require a 4274 // consistent result. 4275 // - Pushing the zero left requires shifting one bits in from the right. 4276 // A rotate left of ~1 is a nice way of achieving the desired result. 4277 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4278 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4279 SDLoc DL(N); 4280 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4281 N0.getOperand(1)); 4282 } 4283 4284 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4285 if (N0.getOpcode() == N1.getOpcode()) 4286 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4287 return Tmp; 4288 4289 // Simplify the expression using non-local knowledge. 4290 if (!VT.isVector() && 4291 SimplifyDemandedBits(SDValue(N, 0))) 4292 return SDValue(N, 0); 4293 4294 return SDValue(); 4295 } 4296 4297 /// Handle transforms common to the three shifts, when the shift amount is a 4298 /// constant. 4299 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4300 SDNode *LHS = N->getOperand(0).getNode(); 4301 if (!LHS->hasOneUse()) return SDValue(); 4302 4303 // We want to pull some binops through shifts, so that we have (and (shift)) 4304 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4305 // thing happens with address calculations, so it's important to canonicalize 4306 // it. 4307 bool HighBitSet = false; // Can we transform this if the high bit is set? 4308 4309 switch (LHS->getOpcode()) { 4310 default: return SDValue(); 4311 case ISD::OR: 4312 case ISD::XOR: 4313 HighBitSet = false; // We can only transform sra if the high bit is clear. 4314 break; 4315 case ISD::AND: 4316 HighBitSet = true; // We can only transform sra if the high bit is set. 4317 break; 4318 case ISD::ADD: 4319 if (N->getOpcode() != ISD::SHL) 4320 return SDValue(); // only shl(add) not sr[al](add). 4321 HighBitSet = false; // We can only transform sra if the high bit is clear. 4322 break; 4323 } 4324 4325 // We require the RHS of the binop to be a constant and not opaque as well. 4326 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4327 if (!BinOpCst) return SDValue(); 4328 4329 // FIXME: disable this unless the input to the binop is a shift by a constant. 4330 // If it is not a shift, it pessimizes some common cases like: 4331 // 4332 // void foo(int *X, int i) { X[i & 1235] = 1; } 4333 // int bar(int *X, int i) { return X[i & 255]; } 4334 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4335 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4336 BinOpLHSVal->getOpcode() != ISD::SRA && 4337 BinOpLHSVal->getOpcode() != ISD::SRL) || 4338 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4339 return SDValue(); 4340 4341 EVT VT = N->getValueType(0); 4342 4343 // If this is a signed shift right, and the high bit is modified by the 4344 // logical operation, do not perform the transformation. The highBitSet 4345 // boolean indicates the value of the high bit of the constant which would 4346 // cause it to be modified for this operation. 4347 if (N->getOpcode() == ISD::SRA) { 4348 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4349 if (BinOpRHSSignSet != HighBitSet) 4350 return SDValue(); 4351 } 4352 4353 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4354 return SDValue(); 4355 4356 // Fold the constants, shifting the binop RHS by the shift amount. 4357 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4358 N->getValueType(0), 4359 LHS->getOperand(1), N->getOperand(1)); 4360 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4361 4362 // Create the new shift. 4363 SDValue NewShift = DAG.getNode(N->getOpcode(), 4364 SDLoc(LHS->getOperand(0)), 4365 VT, LHS->getOperand(0), N->getOperand(1)); 4366 4367 // Create the new binop. 4368 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4369 } 4370 4371 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4372 assert(N->getOpcode() == ISD::TRUNCATE); 4373 assert(N->getOperand(0).getOpcode() == ISD::AND); 4374 4375 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4376 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4377 SDValue N01 = N->getOperand(0).getOperand(1); 4378 4379 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4380 if (!N01C->isOpaque()) { 4381 EVT TruncVT = N->getValueType(0); 4382 SDValue N00 = N->getOperand(0).getOperand(0); 4383 APInt TruncC = N01C->getAPIntValue(); 4384 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4385 SDLoc DL(N); 4386 4387 return DAG.getNode(ISD::AND, DL, TruncVT, 4388 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4389 DAG.getConstant(TruncC, DL, TruncVT)); 4390 } 4391 } 4392 } 4393 4394 return SDValue(); 4395 } 4396 4397 SDValue DAGCombiner::visitRotate(SDNode *N) { 4398 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4399 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4400 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4401 if (SDValue NewOp1 = 4402 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4403 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4404 N->getOperand(0), NewOp1); 4405 } 4406 return SDValue(); 4407 } 4408 4409 SDValue DAGCombiner::visitSHL(SDNode *N) { 4410 SDValue N0 = N->getOperand(0); 4411 SDValue N1 = N->getOperand(1); 4412 EVT VT = N0.getValueType(); 4413 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4414 4415 // fold vector ops 4416 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4417 if (VT.isVector()) { 4418 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4419 return FoldedVOp; 4420 4421 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4422 // If setcc produces all-one true value then: 4423 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4424 if (N1CV && N1CV->isConstant()) { 4425 if (N0.getOpcode() == ISD::AND) { 4426 SDValue N00 = N0->getOperand(0); 4427 SDValue N01 = N0->getOperand(1); 4428 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4429 4430 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4431 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4432 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4433 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4434 N01CV, N1CV)) 4435 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4436 } 4437 } else { 4438 N1C = isConstOrConstSplat(N1); 4439 } 4440 } 4441 } 4442 4443 // fold (shl c1, c2) -> c1<<c2 4444 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4445 if (N0C && N1C && !N1C->isOpaque()) 4446 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4447 // fold (shl 0, x) -> 0 4448 if (isNullConstant(N0)) 4449 return N0; 4450 // fold (shl x, c >= size(x)) -> undef 4451 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4452 return DAG.getUNDEF(VT); 4453 // fold (shl x, 0) -> x 4454 if (N1C && N1C->isNullValue()) 4455 return N0; 4456 // fold (shl undef, x) -> 0 4457 if (N0.isUndef()) 4458 return DAG.getConstant(0, SDLoc(N), VT); 4459 // if (shl x, c) is known to be zero, return 0 4460 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4461 APInt::getAllOnesValue(OpSizeInBits))) 4462 return DAG.getConstant(0, SDLoc(N), VT); 4463 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4464 if (N1.getOpcode() == ISD::TRUNCATE && 4465 N1.getOperand(0).getOpcode() == ISD::AND) { 4466 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4467 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4468 } 4469 4470 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4471 return SDValue(N, 0); 4472 4473 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4474 if (N1C && N0.getOpcode() == ISD::SHL) { 4475 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4476 uint64_t c1 = N0C1->getZExtValue(); 4477 uint64_t c2 = N1C->getZExtValue(); 4478 SDLoc DL(N); 4479 if (c1 + c2 >= OpSizeInBits) 4480 return DAG.getConstant(0, DL, VT); 4481 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4482 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4483 } 4484 } 4485 4486 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4487 // For this to be valid, the second form must not preserve any of the bits 4488 // that are shifted out by the inner shift in the first form. This means 4489 // the outer shift size must be >= the number of bits added by the ext. 4490 // As a corollary, we don't care what kind of ext it is. 4491 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4492 N0.getOpcode() == ISD::ANY_EXTEND || 4493 N0.getOpcode() == ISD::SIGN_EXTEND) && 4494 N0.getOperand(0).getOpcode() == ISD::SHL) { 4495 SDValue N0Op0 = N0.getOperand(0); 4496 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4497 uint64_t c1 = N0Op0C1->getZExtValue(); 4498 uint64_t c2 = N1C->getZExtValue(); 4499 EVT InnerShiftVT = N0Op0.getValueType(); 4500 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4501 if (c2 >= OpSizeInBits - InnerShiftSize) { 4502 SDLoc DL(N0); 4503 if (c1 + c2 >= OpSizeInBits) 4504 return DAG.getConstant(0, DL, VT); 4505 return DAG.getNode(ISD::SHL, DL, VT, 4506 DAG.getNode(N0.getOpcode(), DL, VT, 4507 N0Op0->getOperand(0)), 4508 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4509 } 4510 } 4511 } 4512 4513 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4514 // Only fold this if the inner zext has no other uses to avoid increasing 4515 // the total number of instructions. 4516 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4517 N0.getOperand(0).getOpcode() == ISD::SRL) { 4518 SDValue N0Op0 = N0.getOperand(0); 4519 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4520 uint64_t c1 = N0Op0C1->getZExtValue(); 4521 if (c1 < VT.getScalarSizeInBits()) { 4522 uint64_t c2 = N1C->getZExtValue(); 4523 if (c1 == c2) { 4524 SDValue NewOp0 = N0.getOperand(0); 4525 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4526 SDLoc DL(N); 4527 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4528 NewOp0, 4529 DAG.getConstant(c2, DL, CountVT)); 4530 AddToWorklist(NewSHL.getNode()); 4531 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4532 } 4533 } 4534 } 4535 } 4536 4537 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4538 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4539 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4540 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4541 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4542 uint64_t C1 = N0C1->getZExtValue(); 4543 uint64_t C2 = N1C->getZExtValue(); 4544 SDLoc DL(N); 4545 if (C1 <= C2) 4546 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4547 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4548 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4549 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4550 } 4551 } 4552 4553 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4554 // (and (srl x, (sub c1, c2), MASK) 4555 // Only fold this if the inner shift has no other uses -- if it does, folding 4556 // this will increase the total number of instructions. 4557 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4558 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4559 uint64_t c1 = N0C1->getZExtValue(); 4560 if (c1 < OpSizeInBits) { 4561 uint64_t c2 = N1C->getZExtValue(); 4562 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4563 SDValue Shift; 4564 if (c2 > c1) { 4565 Mask = Mask.shl(c2 - c1); 4566 SDLoc DL(N); 4567 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4568 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4569 } else { 4570 Mask = Mask.lshr(c1 - c2); 4571 SDLoc DL(N); 4572 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4573 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4574 } 4575 SDLoc DL(N0); 4576 return DAG.getNode(ISD::AND, DL, VT, Shift, 4577 DAG.getConstant(Mask, DL, VT)); 4578 } 4579 } 4580 } 4581 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4582 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4583 unsigned BitSize = VT.getScalarSizeInBits(); 4584 SDLoc DL(N); 4585 SDValue HiBitsMask = 4586 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4587 BitSize - N1C->getZExtValue()), 4588 DL, VT); 4589 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4590 HiBitsMask); 4591 } 4592 4593 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4594 // Variant of version done on multiply, except mul by a power of 2 is turned 4595 // into a shift. 4596 APInt Val; 4597 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4598 (isa<ConstantSDNode>(N0.getOperand(1)) || 4599 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4600 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4601 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4602 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4603 } 4604 4605 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4606 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4607 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4608 if (SDValue Folded = 4609 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4610 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4611 } 4612 } 4613 4614 if (N1C && !N1C->isOpaque()) 4615 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4616 return NewSHL; 4617 4618 return SDValue(); 4619 } 4620 4621 SDValue DAGCombiner::visitSRA(SDNode *N) { 4622 SDValue N0 = N->getOperand(0); 4623 SDValue N1 = N->getOperand(1); 4624 EVT VT = N0.getValueType(); 4625 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4626 4627 // fold vector ops 4628 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4629 if (VT.isVector()) { 4630 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4631 return FoldedVOp; 4632 4633 N1C = isConstOrConstSplat(N1); 4634 } 4635 4636 // fold (sra c1, c2) -> (sra c1, c2) 4637 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4638 if (N0C && N1C && !N1C->isOpaque()) 4639 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4640 // fold (sra 0, x) -> 0 4641 if (isNullConstant(N0)) 4642 return N0; 4643 // fold (sra -1, x) -> -1 4644 if (isAllOnesConstant(N0)) 4645 return N0; 4646 // fold (sra x, (setge c, size(x))) -> undef 4647 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4648 return DAG.getUNDEF(VT); 4649 // fold (sra x, 0) -> x 4650 if (N1C && N1C->isNullValue()) 4651 return N0; 4652 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4653 // sext_inreg. 4654 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4655 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4656 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4657 if (VT.isVector()) 4658 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4659 ExtVT, VT.getVectorNumElements()); 4660 if ((!LegalOperations || 4661 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4662 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4663 N0.getOperand(0), DAG.getValueType(ExtVT)); 4664 } 4665 4666 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4667 if (N1C && N0.getOpcode() == ISD::SRA) { 4668 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4669 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4670 if (Sum >= OpSizeInBits) 4671 Sum = OpSizeInBits - 1; 4672 SDLoc DL(N); 4673 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4674 DAG.getConstant(Sum, DL, N1.getValueType())); 4675 } 4676 } 4677 4678 // fold (sra (shl X, m), (sub result_size, n)) 4679 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4680 // result_size - n != m. 4681 // If truncate is free for the target sext(shl) is likely to result in better 4682 // code. 4683 if (N0.getOpcode() == ISD::SHL && N1C) { 4684 // Get the two constanst of the shifts, CN0 = m, CN = n. 4685 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4686 if (N01C) { 4687 LLVMContext &Ctx = *DAG.getContext(); 4688 // Determine what the truncate's result bitsize and type would be. 4689 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4690 4691 if (VT.isVector()) 4692 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4693 4694 // Determine the residual right-shift amount. 4695 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4696 4697 // If the shift is not a no-op (in which case this should be just a sign 4698 // extend already), the truncated to type is legal, sign_extend is legal 4699 // on that type, and the truncate to that type is both legal and free, 4700 // perform the transform. 4701 if ((ShiftAmt > 0) && 4702 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4703 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4704 TLI.isTruncateFree(VT, TruncVT)) { 4705 4706 SDLoc DL(N); 4707 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4708 getShiftAmountTy(N0.getOperand(0).getValueType())); 4709 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4710 N0.getOperand(0), Amt); 4711 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4712 Shift); 4713 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4714 N->getValueType(0), Trunc); 4715 } 4716 } 4717 } 4718 4719 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4720 if (N1.getOpcode() == ISD::TRUNCATE && 4721 N1.getOperand(0).getOpcode() == ISD::AND) { 4722 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4723 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4724 } 4725 4726 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4727 // if c1 is equal to the number of bits the trunc removes 4728 if (N0.getOpcode() == ISD::TRUNCATE && 4729 (N0.getOperand(0).getOpcode() == ISD::SRL || 4730 N0.getOperand(0).getOpcode() == ISD::SRA) && 4731 N0.getOperand(0).hasOneUse() && 4732 N0.getOperand(0).getOperand(1).hasOneUse() && 4733 N1C) { 4734 SDValue N0Op0 = N0.getOperand(0); 4735 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4736 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4737 EVT LargeVT = N0Op0.getValueType(); 4738 4739 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4740 SDLoc DL(N); 4741 SDValue Amt = 4742 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4743 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4744 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4745 N0Op0.getOperand(0), Amt); 4746 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4747 } 4748 } 4749 } 4750 4751 // Simplify, based on bits shifted out of the LHS. 4752 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4753 return SDValue(N, 0); 4754 4755 4756 // If the sign bit is known to be zero, switch this to a SRL. 4757 if (DAG.SignBitIsZero(N0)) 4758 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4759 4760 if (N1C && !N1C->isOpaque()) 4761 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4762 return NewSRA; 4763 4764 return SDValue(); 4765 } 4766 4767 SDValue DAGCombiner::visitSRL(SDNode *N) { 4768 SDValue N0 = N->getOperand(0); 4769 SDValue N1 = N->getOperand(1); 4770 EVT VT = N0.getValueType(); 4771 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4772 4773 // fold vector ops 4774 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4775 if (VT.isVector()) { 4776 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4777 return FoldedVOp; 4778 4779 N1C = isConstOrConstSplat(N1); 4780 } 4781 4782 // fold (srl c1, c2) -> c1 >>u c2 4783 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4784 if (N0C && N1C && !N1C->isOpaque()) 4785 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4786 // fold (srl 0, x) -> 0 4787 if (isNullConstant(N0)) 4788 return N0; 4789 // fold (srl x, c >= size(x)) -> undef 4790 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4791 return DAG.getUNDEF(VT); 4792 // fold (srl x, 0) -> x 4793 if (N1C && N1C->isNullValue()) 4794 return N0; 4795 // if (srl x, c) is known to be zero, return 0 4796 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4797 APInt::getAllOnesValue(OpSizeInBits))) 4798 return DAG.getConstant(0, SDLoc(N), VT); 4799 4800 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4801 if (N1C && N0.getOpcode() == ISD::SRL) { 4802 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4803 uint64_t c1 = N01C->getZExtValue(); 4804 uint64_t c2 = N1C->getZExtValue(); 4805 SDLoc DL(N); 4806 if (c1 + c2 >= OpSizeInBits) 4807 return DAG.getConstant(0, DL, VT); 4808 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4809 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4810 } 4811 } 4812 4813 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4814 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4815 N0.getOperand(0).getOpcode() == ISD::SRL && 4816 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4817 uint64_t c1 = 4818 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4819 uint64_t c2 = N1C->getZExtValue(); 4820 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4821 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4822 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4823 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4824 if (c1 + OpSizeInBits == InnerShiftSize) { 4825 SDLoc DL(N0); 4826 if (c1 + c2 >= InnerShiftSize) 4827 return DAG.getConstant(0, DL, VT); 4828 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4829 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4830 N0.getOperand(0)->getOperand(0), 4831 DAG.getConstant(c1 + c2, DL, 4832 ShiftCountVT))); 4833 } 4834 } 4835 4836 // fold (srl (shl x, c), c) -> (and x, cst2) 4837 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4838 unsigned BitSize = N0.getScalarValueSizeInBits(); 4839 if (BitSize <= 64) { 4840 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4841 SDLoc DL(N); 4842 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4843 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4844 } 4845 } 4846 4847 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4848 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4849 // Shifting in all undef bits? 4850 EVT SmallVT = N0.getOperand(0).getValueType(); 4851 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4852 if (N1C->getZExtValue() >= BitSize) 4853 return DAG.getUNDEF(VT); 4854 4855 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4856 uint64_t ShiftAmt = N1C->getZExtValue(); 4857 SDLoc DL0(N0); 4858 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4859 N0.getOperand(0), 4860 DAG.getConstant(ShiftAmt, DL0, 4861 getShiftAmountTy(SmallVT))); 4862 AddToWorklist(SmallShift.getNode()); 4863 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4864 SDLoc DL(N); 4865 return DAG.getNode(ISD::AND, DL, VT, 4866 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4867 DAG.getConstant(Mask, DL, VT)); 4868 } 4869 } 4870 4871 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4872 // bit, which is unmodified by sra. 4873 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4874 if (N0.getOpcode() == ISD::SRA) 4875 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4876 } 4877 4878 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4879 if (N1C && N0.getOpcode() == ISD::CTLZ && 4880 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4881 APInt KnownZero, KnownOne; 4882 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4883 4884 // If any of the input bits are KnownOne, then the input couldn't be all 4885 // zeros, thus the result of the srl will always be zero. 4886 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4887 4888 // If all of the bits input the to ctlz node are known to be zero, then 4889 // the result of the ctlz is "32" and the result of the shift is one. 4890 APInt UnknownBits = ~KnownZero; 4891 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4892 4893 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4894 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4895 // Okay, we know that only that the single bit specified by UnknownBits 4896 // could be set on input to the CTLZ node. If this bit is set, the SRL 4897 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4898 // to an SRL/XOR pair, which is likely to simplify more. 4899 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4900 SDValue Op = N0.getOperand(0); 4901 4902 if (ShAmt) { 4903 SDLoc DL(N0); 4904 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4905 DAG.getConstant(ShAmt, DL, 4906 getShiftAmountTy(Op.getValueType()))); 4907 AddToWorklist(Op.getNode()); 4908 } 4909 4910 SDLoc DL(N); 4911 return DAG.getNode(ISD::XOR, DL, VT, 4912 Op, DAG.getConstant(1, DL, VT)); 4913 } 4914 } 4915 4916 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4917 if (N1.getOpcode() == ISD::TRUNCATE && 4918 N1.getOperand(0).getOpcode() == ISD::AND) { 4919 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4920 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4921 } 4922 4923 // fold operands of srl based on knowledge that the low bits are not 4924 // demanded. 4925 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4926 return SDValue(N, 0); 4927 4928 if (N1C && !N1C->isOpaque()) 4929 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4930 return NewSRL; 4931 4932 // Attempt to convert a srl of a load into a narrower zero-extending load. 4933 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4934 return NarrowLoad; 4935 4936 // Here is a common situation. We want to optimize: 4937 // 4938 // %a = ... 4939 // %b = and i32 %a, 2 4940 // %c = srl i32 %b, 1 4941 // brcond i32 %c ... 4942 // 4943 // into 4944 // 4945 // %a = ... 4946 // %b = and %a, 2 4947 // %c = setcc eq %b, 0 4948 // brcond %c ... 4949 // 4950 // However when after the source operand of SRL is optimized into AND, the SRL 4951 // itself may not be optimized further. Look for it and add the BRCOND into 4952 // the worklist. 4953 if (N->hasOneUse()) { 4954 SDNode *Use = *N->use_begin(); 4955 if (Use->getOpcode() == ISD::BRCOND) 4956 AddToWorklist(Use); 4957 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4958 // Also look pass the truncate. 4959 Use = *Use->use_begin(); 4960 if (Use->getOpcode() == ISD::BRCOND) 4961 AddToWorklist(Use); 4962 } 4963 } 4964 4965 return SDValue(); 4966 } 4967 4968 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4969 SDValue N0 = N->getOperand(0); 4970 EVT VT = N->getValueType(0); 4971 4972 // fold (bswap c1) -> c2 4973 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4974 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4975 // fold (bswap (bswap x)) -> x 4976 if (N0.getOpcode() == ISD::BSWAP) 4977 return N0->getOperand(0); 4978 return SDValue(); 4979 } 4980 4981 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 4982 SDValue N0 = N->getOperand(0); 4983 4984 // fold (bitreverse (bitreverse x)) -> x 4985 if (N0.getOpcode() == ISD::BITREVERSE) 4986 return N0.getOperand(0); 4987 return SDValue(); 4988 } 4989 4990 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4991 SDValue N0 = N->getOperand(0); 4992 EVT VT = N->getValueType(0); 4993 4994 // fold (ctlz c1) -> c2 4995 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4996 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4997 return SDValue(); 4998 } 4999 5000 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5001 SDValue N0 = N->getOperand(0); 5002 EVT VT = N->getValueType(0); 5003 5004 // fold (ctlz_zero_undef c1) -> c2 5005 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5006 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5007 return SDValue(); 5008 } 5009 5010 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5011 SDValue N0 = N->getOperand(0); 5012 EVT VT = N->getValueType(0); 5013 5014 // fold (cttz c1) -> c2 5015 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5016 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5017 return SDValue(); 5018 } 5019 5020 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5021 SDValue N0 = N->getOperand(0); 5022 EVT VT = N->getValueType(0); 5023 5024 // fold (cttz_zero_undef c1) -> c2 5025 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5026 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5027 return SDValue(); 5028 } 5029 5030 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5031 SDValue N0 = N->getOperand(0); 5032 EVT VT = N->getValueType(0); 5033 5034 // fold (ctpop c1) -> c2 5035 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5036 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5037 return SDValue(); 5038 } 5039 5040 5041 /// \brief Generate Min/Max node 5042 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 5043 SDValue True, SDValue False, 5044 ISD::CondCode CC, const TargetLowering &TLI, 5045 SelectionDAG &DAG) { 5046 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5047 return SDValue(); 5048 5049 switch (CC) { 5050 case ISD::SETOLT: 5051 case ISD::SETOLE: 5052 case ISD::SETLT: 5053 case ISD::SETLE: 5054 case ISD::SETULT: 5055 case ISD::SETULE: { 5056 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5057 if (TLI.isOperationLegal(Opcode, VT)) 5058 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5059 return SDValue(); 5060 } 5061 case ISD::SETOGT: 5062 case ISD::SETOGE: 5063 case ISD::SETGT: 5064 case ISD::SETGE: 5065 case ISD::SETUGT: 5066 case ISD::SETUGE: { 5067 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5068 if (TLI.isOperationLegal(Opcode, VT)) 5069 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5070 return SDValue(); 5071 } 5072 default: 5073 return SDValue(); 5074 } 5075 } 5076 5077 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5078 SDValue N0 = N->getOperand(0); 5079 SDValue N1 = N->getOperand(1); 5080 SDValue N2 = N->getOperand(2); 5081 EVT VT = N->getValueType(0); 5082 EVT VT0 = N0.getValueType(); 5083 5084 // fold (select C, X, X) -> X 5085 if (N1 == N2) 5086 return N1; 5087 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5088 // fold (select true, X, Y) -> X 5089 // fold (select false, X, Y) -> Y 5090 return !N0C->isNullValue() ? N1 : N2; 5091 } 5092 // fold (select C, 1, X) -> (or C, X) 5093 if (VT == MVT::i1 && isOneConstant(N1)) 5094 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5095 // fold (select C, 0, 1) -> (xor C, 1) 5096 // We can't do this reliably if integer based booleans have different contents 5097 // to floating point based booleans. This is because we can't tell whether we 5098 // have an integer-based boolean or a floating-point-based boolean unless we 5099 // can find the SETCC that produced it and inspect its operands. This is 5100 // fairly easy if C is the SETCC node, but it can potentially be 5101 // undiscoverable (or not reasonably discoverable). For example, it could be 5102 // in another basic block or it could require searching a complicated 5103 // expression. 5104 if (VT.isInteger() && 5105 (VT0 == MVT::i1 || (VT0.isInteger() && 5106 TLI.getBooleanContents(false, false) == 5107 TLI.getBooleanContents(false, true) && 5108 TLI.getBooleanContents(false, false) == 5109 TargetLowering::ZeroOrOneBooleanContent)) && 5110 isNullConstant(N1) && isOneConstant(N2)) { 5111 SDValue XORNode; 5112 if (VT == VT0) { 5113 SDLoc DL(N); 5114 return DAG.getNode(ISD::XOR, DL, VT0, 5115 N0, DAG.getConstant(1, DL, VT0)); 5116 } 5117 SDLoc DL0(N0); 5118 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5119 N0, DAG.getConstant(1, DL0, VT0)); 5120 AddToWorklist(XORNode.getNode()); 5121 if (VT.bitsGT(VT0)) 5122 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5123 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5124 } 5125 // fold (select C, 0, X) -> (and (not C), X) 5126 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5127 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5128 AddToWorklist(NOTNode.getNode()); 5129 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5130 } 5131 // fold (select C, X, 1) -> (or (not C), X) 5132 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5133 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5134 AddToWorklist(NOTNode.getNode()); 5135 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5136 } 5137 // fold (select C, X, 0) -> (and C, X) 5138 if (VT == MVT::i1 && isNullConstant(N2)) 5139 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5140 // fold (select X, X, Y) -> (or X, Y) 5141 // fold (select X, 1, Y) -> (or X, Y) 5142 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5143 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5144 // fold (select X, Y, X) -> (and X, Y) 5145 // fold (select X, Y, 0) -> (and X, Y) 5146 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5147 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5148 5149 // If we can fold this based on the true/false value, do so. 5150 if (SimplifySelectOps(N, N1, N2)) 5151 return SDValue(N, 0); // Don't revisit N. 5152 5153 if (VT0 == MVT::i1) { 5154 // The code in this block deals with the following 2 equivalences: 5155 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5156 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5157 // The target can specify its prefered form with the 5158 // shouldNormalizeToSelectSequence() callback. However we always transform 5159 // to the right anyway if we find the inner select exists in the DAG anyway 5160 // and we always transform to the left side if we know that we can further 5161 // optimize the combination of the conditions. 5162 bool normalizeToSequence 5163 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5164 // select (and Cond0, Cond1), X, Y 5165 // -> select Cond0, (select Cond1, X, Y), Y 5166 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5167 SDValue Cond0 = N0->getOperand(0); 5168 SDValue Cond1 = N0->getOperand(1); 5169 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5170 N1.getValueType(), Cond1, N1, N2); 5171 if (normalizeToSequence || !InnerSelect.use_empty()) 5172 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5173 InnerSelect, N2); 5174 } 5175 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5176 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5177 SDValue Cond0 = N0->getOperand(0); 5178 SDValue Cond1 = N0->getOperand(1); 5179 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5180 N1.getValueType(), Cond1, N1, N2); 5181 if (normalizeToSequence || !InnerSelect.use_empty()) 5182 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5183 InnerSelect); 5184 } 5185 5186 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5187 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5188 SDValue N1_0 = N1->getOperand(0); 5189 SDValue N1_1 = N1->getOperand(1); 5190 SDValue N1_2 = N1->getOperand(2); 5191 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5192 // Create the actual and node if we can generate good code for it. 5193 if (!normalizeToSequence) { 5194 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5195 N0, N1_0); 5196 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5197 N1_1, N2); 5198 } 5199 // Otherwise see if we can optimize the "and" to a better pattern. 5200 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5201 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5202 N1_1, N2); 5203 } 5204 } 5205 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5206 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5207 SDValue N2_0 = N2->getOperand(0); 5208 SDValue N2_1 = N2->getOperand(1); 5209 SDValue N2_2 = N2->getOperand(2); 5210 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5211 // Create the actual or node if we can generate good code for it. 5212 if (!normalizeToSequence) { 5213 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5214 N0, N2_0); 5215 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5216 N1, N2_2); 5217 } 5218 // Otherwise see if we can optimize to a better pattern. 5219 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5220 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5221 N1, N2_2); 5222 } 5223 } 5224 } 5225 5226 // fold selects based on a setcc into other things, such as min/max/abs 5227 if (N0.getOpcode() == ISD::SETCC) { 5228 // select x, y (fcmp lt x, y) -> fminnum x, y 5229 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5230 // 5231 // This is OK if we don't care about what happens if either operand is a 5232 // NaN. 5233 // 5234 5235 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5236 // no signed zeros as well as no nans. 5237 const TargetOptions &Options = DAG.getTarget().Options; 5238 if (Options.UnsafeFPMath && 5239 VT.isFloatingPoint() && N0.hasOneUse() && 5240 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5241 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5242 5243 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5244 N0.getOperand(1), N1, N2, CC, 5245 TLI, DAG)) 5246 return FMinMax; 5247 } 5248 5249 if ((!LegalOperations && 5250 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5251 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5252 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5253 N0.getOperand(0), N0.getOperand(1), 5254 N1, N2, N0.getOperand(2)); 5255 return SimplifySelect(SDLoc(N), N0, N1, N2); 5256 } 5257 5258 return SDValue(); 5259 } 5260 5261 static 5262 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5263 SDLoc DL(N); 5264 EVT LoVT, HiVT; 5265 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5266 5267 // Split the inputs. 5268 SDValue Lo, Hi, LL, LH, RL, RH; 5269 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5270 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5271 5272 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5273 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5274 5275 return std::make_pair(Lo, Hi); 5276 } 5277 5278 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5279 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5280 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5281 SDLoc dl(N); 5282 SDValue Cond = N->getOperand(0); 5283 SDValue LHS = N->getOperand(1); 5284 SDValue RHS = N->getOperand(2); 5285 EVT VT = N->getValueType(0); 5286 int NumElems = VT.getVectorNumElements(); 5287 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5288 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5289 Cond.getOpcode() == ISD::BUILD_VECTOR); 5290 5291 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5292 // binary ones here. 5293 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5294 return SDValue(); 5295 5296 // We're sure we have an even number of elements due to the 5297 // concat_vectors we have as arguments to vselect. 5298 // Skip BV elements until we find one that's not an UNDEF 5299 // After we find an UNDEF element, keep looping until we get to half the 5300 // length of the BV and see if all the non-undef nodes are the same. 5301 ConstantSDNode *BottomHalf = nullptr; 5302 for (int i = 0; i < NumElems / 2; ++i) { 5303 if (Cond->getOperand(i)->isUndef()) 5304 continue; 5305 5306 if (BottomHalf == nullptr) 5307 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5308 else if (Cond->getOperand(i).getNode() != BottomHalf) 5309 return SDValue(); 5310 } 5311 5312 // Do the same for the second half of the BuildVector 5313 ConstantSDNode *TopHalf = nullptr; 5314 for (int i = NumElems / 2; i < NumElems; ++i) { 5315 if (Cond->getOperand(i)->isUndef()) 5316 continue; 5317 5318 if (TopHalf == nullptr) 5319 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5320 else if (Cond->getOperand(i).getNode() != TopHalf) 5321 return SDValue(); 5322 } 5323 5324 assert(TopHalf && BottomHalf && 5325 "One half of the selector was all UNDEFs and the other was all the " 5326 "same value. This should have been addressed before this function."); 5327 return DAG.getNode( 5328 ISD::CONCAT_VECTORS, dl, VT, 5329 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5330 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5331 } 5332 5333 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5334 5335 if (Level >= AfterLegalizeTypes) 5336 return SDValue(); 5337 5338 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5339 SDValue Mask = MSC->getMask(); 5340 SDValue Data = MSC->getValue(); 5341 SDLoc DL(N); 5342 5343 // If the MSCATTER data type requires splitting and the mask is provided by a 5344 // SETCC, then split both nodes and its operands before legalization. This 5345 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5346 // and enables future optimizations (e.g. min/max pattern matching on X86). 5347 if (Mask.getOpcode() != ISD::SETCC) 5348 return SDValue(); 5349 5350 // Check if any splitting is required. 5351 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5352 TargetLowering::TypeSplitVector) 5353 return SDValue(); 5354 SDValue MaskLo, MaskHi, Lo, Hi; 5355 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5356 5357 EVT LoVT, HiVT; 5358 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5359 5360 SDValue Chain = MSC->getChain(); 5361 5362 EVT MemoryVT = MSC->getMemoryVT(); 5363 unsigned Alignment = MSC->getOriginalAlignment(); 5364 5365 EVT LoMemVT, HiMemVT; 5366 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5367 5368 SDValue DataLo, DataHi; 5369 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5370 5371 SDValue BasePtr = MSC->getBasePtr(); 5372 SDValue IndexLo, IndexHi; 5373 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5374 5375 MachineMemOperand *MMO = DAG.getMachineFunction(). 5376 getMachineMemOperand(MSC->getPointerInfo(), 5377 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5378 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5379 5380 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5381 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5382 DL, OpsLo, MMO); 5383 5384 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5385 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5386 DL, OpsHi, MMO); 5387 5388 AddToWorklist(Lo.getNode()); 5389 AddToWorklist(Hi.getNode()); 5390 5391 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5392 } 5393 5394 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5395 5396 if (Level >= AfterLegalizeTypes) 5397 return SDValue(); 5398 5399 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5400 SDValue Mask = MST->getMask(); 5401 SDValue Data = MST->getValue(); 5402 SDLoc DL(N); 5403 5404 // If the MSTORE data type requires splitting and the mask is provided by a 5405 // SETCC, then split both nodes and its operands before legalization. This 5406 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5407 // and enables future optimizations (e.g. min/max pattern matching on X86). 5408 if (Mask.getOpcode() == ISD::SETCC) { 5409 5410 // Check if any splitting is required. 5411 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5412 TargetLowering::TypeSplitVector) 5413 return SDValue(); 5414 5415 SDValue MaskLo, MaskHi, Lo, Hi; 5416 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5417 5418 EVT LoVT, HiVT; 5419 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5420 5421 SDValue Chain = MST->getChain(); 5422 SDValue Ptr = MST->getBasePtr(); 5423 5424 EVT MemoryVT = MST->getMemoryVT(); 5425 unsigned Alignment = MST->getOriginalAlignment(); 5426 5427 // if Alignment is equal to the vector size, 5428 // take the half of it for the second part 5429 unsigned SecondHalfAlignment = 5430 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5431 Alignment/2 : Alignment; 5432 5433 EVT LoMemVT, HiMemVT; 5434 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5435 5436 SDValue DataLo, DataHi; 5437 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5438 5439 MachineMemOperand *MMO = DAG.getMachineFunction(). 5440 getMachineMemOperand(MST->getPointerInfo(), 5441 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5442 Alignment, MST->getAAInfo(), MST->getRanges()); 5443 5444 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5445 MST->isTruncatingStore()); 5446 5447 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5448 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5449 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5450 5451 MMO = DAG.getMachineFunction(). 5452 getMachineMemOperand(MST->getPointerInfo(), 5453 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5454 SecondHalfAlignment, MST->getAAInfo(), 5455 MST->getRanges()); 5456 5457 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5458 MST->isTruncatingStore()); 5459 5460 AddToWorklist(Lo.getNode()); 5461 AddToWorklist(Hi.getNode()); 5462 5463 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5464 } 5465 return SDValue(); 5466 } 5467 5468 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5469 5470 if (Level >= AfterLegalizeTypes) 5471 return SDValue(); 5472 5473 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5474 SDValue Mask = MGT->getMask(); 5475 SDLoc DL(N); 5476 5477 // If the MGATHER result requires splitting and the mask is provided by a 5478 // SETCC, then split both nodes and its operands before legalization. This 5479 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5480 // and enables future optimizations (e.g. min/max pattern matching on X86). 5481 5482 if (Mask.getOpcode() != ISD::SETCC) 5483 return SDValue(); 5484 5485 EVT VT = N->getValueType(0); 5486 5487 // Check if any splitting is required. 5488 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5489 TargetLowering::TypeSplitVector) 5490 return SDValue(); 5491 5492 SDValue MaskLo, MaskHi, Lo, Hi; 5493 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5494 5495 SDValue Src0 = MGT->getValue(); 5496 SDValue Src0Lo, Src0Hi; 5497 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5498 5499 EVT LoVT, HiVT; 5500 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5501 5502 SDValue Chain = MGT->getChain(); 5503 EVT MemoryVT = MGT->getMemoryVT(); 5504 unsigned Alignment = MGT->getOriginalAlignment(); 5505 5506 EVT LoMemVT, HiMemVT; 5507 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5508 5509 SDValue BasePtr = MGT->getBasePtr(); 5510 SDValue Index = MGT->getIndex(); 5511 SDValue IndexLo, IndexHi; 5512 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5513 5514 MachineMemOperand *MMO = DAG.getMachineFunction(). 5515 getMachineMemOperand(MGT->getPointerInfo(), 5516 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5517 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5518 5519 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5520 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5521 MMO); 5522 5523 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5524 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5525 MMO); 5526 5527 AddToWorklist(Lo.getNode()); 5528 AddToWorklist(Hi.getNode()); 5529 5530 // Build a factor node to remember that this load is independent of the 5531 // other one. 5532 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5533 Hi.getValue(1)); 5534 5535 // Legalized the chain result - switch anything that used the old chain to 5536 // use the new one. 5537 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5538 5539 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5540 5541 SDValue RetOps[] = { GatherRes, Chain }; 5542 return DAG.getMergeValues(RetOps, DL); 5543 } 5544 5545 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5546 5547 if (Level >= AfterLegalizeTypes) 5548 return SDValue(); 5549 5550 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5551 SDValue Mask = MLD->getMask(); 5552 SDLoc DL(N); 5553 5554 // If the MLOAD result requires splitting and the mask is provided by a 5555 // SETCC, then split both nodes and its operands before legalization. This 5556 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5557 // and enables future optimizations (e.g. min/max pattern matching on X86). 5558 5559 if (Mask.getOpcode() == ISD::SETCC) { 5560 EVT VT = N->getValueType(0); 5561 5562 // Check if any splitting is required. 5563 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5564 TargetLowering::TypeSplitVector) 5565 return SDValue(); 5566 5567 SDValue MaskLo, MaskHi, Lo, Hi; 5568 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5569 5570 SDValue Src0 = MLD->getSrc0(); 5571 SDValue Src0Lo, Src0Hi; 5572 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5573 5574 EVT LoVT, HiVT; 5575 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5576 5577 SDValue Chain = MLD->getChain(); 5578 SDValue Ptr = MLD->getBasePtr(); 5579 EVT MemoryVT = MLD->getMemoryVT(); 5580 unsigned Alignment = MLD->getOriginalAlignment(); 5581 5582 // if Alignment is equal to the vector size, 5583 // take the half of it for the second part 5584 unsigned SecondHalfAlignment = 5585 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5586 Alignment/2 : Alignment; 5587 5588 EVT LoMemVT, HiMemVT; 5589 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5590 5591 MachineMemOperand *MMO = DAG.getMachineFunction(). 5592 getMachineMemOperand(MLD->getPointerInfo(), 5593 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5594 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5595 5596 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5597 ISD::NON_EXTLOAD); 5598 5599 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5600 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5601 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5602 5603 MMO = DAG.getMachineFunction(). 5604 getMachineMemOperand(MLD->getPointerInfo(), 5605 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5606 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5607 5608 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5609 ISD::NON_EXTLOAD); 5610 5611 AddToWorklist(Lo.getNode()); 5612 AddToWorklist(Hi.getNode()); 5613 5614 // Build a factor node to remember that this load is independent of the 5615 // other one. 5616 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5617 Hi.getValue(1)); 5618 5619 // Legalized the chain result - switch anything that used the old chain to 5620 // use the new one. 5621 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5622 5623 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5624 5625 SDValue RetOps[] = { LoadRes, Chain }; 5626 return DAG.getMergeValues(RetOps, DL); 5627 } 5628 return SDValue(); 5629 } 5630 5631 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5632 SDValue N0 = N->getOperand(0); 5633 SDValue N1 = N->getOperand(1); 5634 SDValue N2 = N->getOperand(2); 5635 SDLoc DL(N); 5636 5637 // Canonicalize integer abs. 5638 // vselect (setg[te] X, 0), X, -X -> 5639 // vselect (setgt X, -1), X, -X -> 5640 // vselect (setl[te] X, 0), -X, X -> 5641 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5642 if (N0.getOpcode() == ISD::SETCC) { 5643 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5644 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5645 bool isAbs = false; 5646 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5647 5648 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5649 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5650 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5651 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5652 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5653 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5654 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5655 5656 if (isAbs) { 5657 EVT VT = LHS.getValueType(); 5658 SDValue Shift = DAG.getNode( 5659 ISD::SRA, DL, VT, LHS, 5660 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5661 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5662 AddToWorklist(Shift.getNode()); 5663 AddToWorklist(Add.getNode()); 5664 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5665 } 5666 } 5667 5668 if (SimplifySelectOps(N, N1, N2)) 5669 return SDValue(N, 0); // Don't revisit N. 5670 5671 // If the VSELECT result requires splitting and the mask is provided by a 5672 // SETCC, then split both nodes and its operands before legalization. This 5673 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5674 // and enables future optimizations (e.g. min/max pattern matching on X86). 5675 if (N0.getOpcode() == ISD::SETCC) { 5676 EVT VT = N->getValueType(0); 5677 5678 // Check if any splitting is required. 5679 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5680 TargetLowering::TypeSplitVector) 5681 return SDValue(); 5682 5683 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5684 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5685 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5686 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5687 5688 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5689 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5690 5691 // Add the new VSELECT nodes to the work list in case they need to be split 5692 // again. 5693 AddToWorklist(Lo.getNode()); 5694 AddToWorklist(Hi.getNode()); 5695 5696 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5697 } 5698 5699 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5700 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5701 return N1; 5702 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5703 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5704 return N2; 5705 5706 // The ConvertSelectToConcatVector function is assuming both the above 5707 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5708 // and addressed. 5709 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5710 N2.getOpcode() == ISD::CONCAT_VECTORS && 5711 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5712 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5713 return CV; 5714 } 5715 5716 return SDValue(); 5717 } 5718 5719 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5720 SDValue N0 = N->getOperand(0); 5721 SDValue N1 = N->getOperand(1); 5722 SDValue N2 = N->getOperand(2); 5723 SDValue N3 = N->getOperand(3); 5724 SDValue N4 = N->getOperand(4); 5725 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5726 5727 // fold select_cc lhs, rhs, x, x, cc -> x 5728 if (N2 == N3) 5729 return N2; 5730 5731 // Determine if the condition we're dealing with is constant 5732 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5733 CC, SDLoc(N), false)) { 5734 AddToWorklist(SCC.getNode()); 5735 5736 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5737 if (!SCCC->isNullValue()) 5738 return N2; // cond always true -> true val 5739 else 5740 return N3; // cond always false -> false val 5741 } else if (SCC->isUndef()) { 5742 // When the condition is UNDEF, just return the first operand. This is 5743 // coherent the DAG creation, no setcc node is created in this case 5744 return N2; 5745 } else if (SCC.getOpcode() == ISD::SETCC) { 5746 // Fold to a simpler select_cc 5747 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5748 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5749 SCC.getOperand(2)); 5750 } 5751 } 5752 5753 // If we can fold this based on the true/false value, do so. 5754 if (SimplifySelectOps(N, N2, N3)) 5755 return SDValue(N, 0); // Don't revisit N. 5756 5757 // fold select_cc into other things, such as min/max/abs 5758 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5759 } 5760 5761 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5762 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5763 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5764 SDLoc(N)); 5765 } 5766 5767 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5768 SDValue LHS = N->getOperand(0); 5769 SDValue RHS = N->getOperand(1); 5770 SDValue Carry = N->getOperand(2); 5771 SDValue Cond = N->getOperand(3); 5772 5773 // If Carry is false, fold to a regular SETCC. 5774 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5775 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5776 5777 return SDValue(); 5778 } 5779 5780 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5781 /// a build_vector of constants. 5782 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5783 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5784 /// Vector extends are not folded if operations are legal; this is to 5785 /// avoid introducing illegal build_vector dag nodes. 5786 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5787 SelectionDAG &DAG, bool LegalTypes, 5788 bool LegalOperations) { 5789 unsigned Opcode = N->getOpcode(); 5790 SDValue N0 = N->getOperand(0); 5791 EVT VT = N->getValueType(0); 5792 5793 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5794 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5795 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5796 && "Expected EXTEND dag node in input!"); 5797 5798 // fold (sext c1) -> c1 5799 // fold (zext c1) -> c1 5800 // fold (aext c1) -> c1 5801 if (isa<ConstantSDNode>(N0)) 5802 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5803 5804 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5805 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5806 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5807 EVT SVT = VT.getScalarType(); 5808 if (!(VT.isVector() && 5809 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5810 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5811 return nullptr; 5812 5813 // We can fold this node into a build_vector. 5814 unsigned VTBits = SVT.getSizeInBits(); 5815 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5816 SmallVector<SDValue, 8> Elts; 5817 unsigned NumElts = VT.getVectorNumElements(); 5818 SDLoc DL(N); 5819 5820 for (unsigned i=0; i != NumElts; ++i) { 5821 SDValue Op = N0->getOperand(i); 5822 if (Op->isUndef()) { 5823 Elts.push_back(DAG.getUNDEF(SVT)); 5824 continue; 5825 } 5826 5827 SDLoc DL(Op); 5828 // Get the constant value and if needed trunc it to the size of the type. 5829 // Nodes like build_vector might have constants wider than the scalar type. 5830 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5831 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5832 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5833 else 5834 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5835 } 5836 5837 return DAG.getBuildVector(VT, DL, Elts).getNode(); 5838 } 5839 5840 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5841 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5842 // transformation. Returns true if extension are possible and the above 5843 // mentioned transformation is profitable. 5844 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5845 unsigned ExtOpc, 5846 SmallVectorImpl<SDNode *> &ExtendNodes, 5847 const TargetLowering &TLI) { 5848 bool HasCopyToRegUses = false; 5849 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5850 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5851 UE = N0.getNode()->use_end(); 5852 UI != UE; ++UI) { 5853 SDNode *User = *UI; 5854 if (User == N) 5855 continue; 5856 if (UI.getUse().getResNo() != N0.getResNo()) 5857 continue; 5858 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5859 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5860 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5861 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5862 // Sign bits will be lost after a zext. 5863 return false; 5864 bool Add = false; 5865 for (unsigned i = 0; i != 2; ++i) { 5866 SDValue UseOp = User->getOperand(i); 5867 if (UseOp == N0) 5868 continue; 5869 if (!isa<ConstantSDNode>(UseOp)) 5870 return false; 5871 Add = true; 5872 } 5873 if (Add) 5874 ExtendNodes.push_back(User); 5875 continue; 5876 } 5877 // If truncates aren't free and there are users we can't 5878 // extend, it isn't worthwhile. 5879 if (!isTruncFree) 5880 return false; 5881 // Remember if this value is live-out. 5882 if (User->getOpcode() == ISD::CopyToReg) 5883 HasCopyToRegUses = true; 5884 } 5885 5886 if (HasCopyToRegUses) { 5887 bool BothLiveOut = false; 5888 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5889 UI != UE; ++UI) { 5890 SDUse &Use = UI.getUse(); 5891 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5892 BothLiveOut = true; 5893 break; 5894 } 5895 } 5896 if (BothLiveOut) 5897 // Both unextended and extended values are live out. There had better be 5898 // a good reason for the transformation. 5899 return ExtendNodes.size(); 5900 } 5901 return true; 5902 } 5903 5904 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5905 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5906 ISD::NodeType ExtType) { 5907 // Extend SetCC uses if necessary. 5908 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5909 SDNode *SetCC = SetCCs[i]; 5910 SmallVector<SDValue, 4> Ops; 5911 5912 for (unsigned j = 0; j != 2; ++j) { 5913 SDValue SOp = SetCC->getOperand(j); 5914 if (SOp == Trunc) 5915 Ops.push_back(ExtLoad); 5916 else 5917 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5918 } 5919 5920 Ops.push_back(SetCC->getOperand(2)); 5921 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5922 } 5923 } 5924 5925 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5926 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5927 SDValue N0 = N->getOperand(0); 5928 EVT DstVT = N->getValueType(0); 5929 EVT SrcVT = N0.getValueType(); 5930 5931 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5932 N->getOpcode() == ISD::ZERO_EXTEND) && 5933 "Unexpected node type (not an extend)!"); 5934 5935 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5936 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5937 // (v8i32 (sext (v8i16 (load x)))) 5938 // into: 5939 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5940 // (v4i32 (sextload (x + 16))))) 5941 // Where uses of the original load, i.e.: 5942 // (v8i16 (load x)) 5943 // are replaced with: 5944 // (v8i16 (truncate 5945 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5946 // (v4i32 (sextload (x + 16))))))) 5947 // 5948 // This combine is only applicable to illegal, but splittable, vectors. 5949 // All legal types, and illegal non-vector types, are handled elsewhere. 5950 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5951 // 5952 if (N0->getOpcode() != ISD::LOAD) 5953 return SDValue(); 5954 5955 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5956 5957 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5958 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5959 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5960 return SDValue(); 5961 5962 SmallVector<SDNode *, 4> SetCCs; 5963 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5964 return SDValue(); 5965 5966 ISD::LoadExtType ExtType = 5967 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5968 5969 // Try to split the vector types to get down to legal types. 5970 EVT SplitSrcVT = SrcVT; 5971 EVT SplitDstVT = DstVT; 5972 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5973 SplitSrcVT.getVectorNumElements() > 1) { 5974 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5975 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5976 } 5977 5978 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5979 return SDValue(); 5980 5981 SDLoc DL(N); 5982 const unsigned NumSplits = 5983 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5984 const unsigned Stride = SplitSrcVT.getStoreSize(); 5985 SmallVector<SDValue, 4> Loads; 5986 SmallVector<SDValue, 4> Chains; 5987 5988 SDValue BasePtr = LN0->getBasePtr(); 5989 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5990 const unsigned Offset = Idx * Stride; 5991 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5992 5993 SDValue SplitLoad = DAG.getExtLoad( 5994 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5995 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5996 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5997 Align, LN0->getAAInfo()); 5998 5999 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6000 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6001 6002 Loads.push_back(SplitLoad.getValue(0)); 6003 Chains.push_back(SplitLoad.getValue(1)); 6004 } 6005 6006 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6007 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6008 6009 CombineTo(N, NewValue); 6010 6011 // Replace uses of the original load (before extension) 6012 // with a truncate of the concatenated sextloaded vectors. 6013 SDValue Trunc = 6014 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6015 CombineTo(N0.getNode(), Trunc, NewChain); 6016 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6017 (ISD::NodeType)N->getOpcode()); 6018 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6019 } 6020 6021 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6022 SDValue N0 = N->getOperand(0); 6023 EVT VT = N->getValueType(0); 6024 6025 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6026 LegalOperations)) 6027 return SDValue(Res, 0); 6028 6029 // fold (sext (sext x)) -> (sext x) 6030 // fold (sext (aext x)) -> (sext x) 6031 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6032 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 6033 N0.getOperand(0)); 6034 6035 if (N0.getOpcode() == ISD::TRUNCATE) { 6036 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6037 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6038 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6039 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6040 if (NarrowLoad.getNode() != N0.getNode()) { 6041 CombineTo(N0.getNode(), NarrowLoad); 6042 // CombineTo deleted the truncate, if needed, but not what's under it. 6043 AddToWorklist(oye); 6044 } 6045 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6046 } 6047 6048 // See if the value being truncated is already sign extended. If so, just 6049 // eliminate the trunc/sext pair. 6050 SDValue Op = N0.getOperand(0); 6051 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 6052 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 6053 unsigned DestBits = VT.getScalarType().getSizeInBits(); 6054 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6055 6056 if (OpBits == DestBits) { 6057 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6058 // bits, it is already ready. 6059 if (NumSignBits > DestBits-MidBits) 6060 return Op; 6061 } else if (OpBits < DestBits) { 6062 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6063 // bits, just sext from i32. 6064 if (NumSignBits > OpBits-MidBits) 6065 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6066 } else { 6067 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6068 // bits, just truncate to i32. 6069 if (NumSignBits > OpBits-MidBits) 6070 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6071 } 6072 6073 // fold (sext (truncate x)) -> (sextinreg x). 6074 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6075 N0.getValueType())) { 6076 if (OpBits < DestBits) 6077 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6078 else if (OpBits > DestBits) 6079 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6080 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6081 DAG.getValueType(N0.getValueType())); 6082 } 6083 } 6084 6085 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6086 // Only generate vector extloads when 1) they're legal, and 2) they are 6087 // deemed desirable by the target. 6088 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6089 ((!LegalOperations && !VT.isVector() && 6090 !cast<LoadSDNode>(N0)->isVolatile()) || 6091 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6092 bool DoXform = true; 6093 SmallVector<SDNode*, 4> SetCCs; 6094 if (!N0.hasOneUse()) 6095 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6096 if (VT.isVector()) 6097 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6098 if (DoXform) { 6099 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6100 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6101 LN0->getChain(), 6102 LN0->getBasePtr(), N0.getValueType(), 6103 LN0->getMemOperand()); 6104 CombineTo(N, ExtLoad); 6105 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6106 N0.getValueType(), ExtLoad); 6107 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6108 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6109 ISD::SIGN_EXTEND); 6110 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6111 } 6112 } 6113 6114 // fold (sext (load x)) to multiple smaller sextloads. 6115 // Only on illegal but splittable vectors. 6116 if (SDValue ExtLoad = CombineExtLoad(N)) 6117 return ExtLoad; 6118 6119 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6120 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6121 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6122 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6123 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6124 EVT MemVT = LN0->getMemoryVT(); 6125 if ((!LegalOperations && !LN0->isVolatile()) || 6126 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6127 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6128 LN0->getChain(), 6129 LN0->getBasePtr(), MemVT, 6130 LN0->getMemOperand()); 6131 CombineTo(N, ExtLoad); 6132 CombineTo(N0.getNode(), 6133 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6134 N0.getValueType(), ExtLoad), 6135 ExtLoad.getValue(1)); 6136 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6137 } 6138 } 6139 6140 // fold (sext (and/or/xor (load x), cst)) -> 6141 // (and/or/xor (sextload x), (sext cst)) 6142 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6143 N0.getOpcode() == ISD::XOR) && 6144 isa<LoadSDNode>(N0.getOperand(0)) && 6145 N0.getOperand(1).getOpcode() == ISD::Constant && 6146 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6147 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6148 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6149 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6150 bool DoXform = true; 6151 SmallVector<SDNode*, 4> SetCCs; 6152 if (!N0.hasOneUse()) 6153 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6154 SetCCs, TLI); 6155 if (DoXform) { 6156 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6157 LN0->getChain(), LN0->getBasePtr(), 6158 LN0->getMemoryVT(), 6159 LN0->getMemOperand()); 6160 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6161 Mask = Mask.sext(VT.getSizeInBits()); 6162 SDLoc DL(N); 6163 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6164 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6165 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6166 SDLoc(N0.getOperand(0)), 6167 N0.getOperand(0).getValueType(), ExtLoad); 6168 CombineTo(N, And); 6169 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6170 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6171 ISD::SIGN_EXTEND); 6172 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6173 } 6174 } 6175 } 6176 6177 if (N0.getOpcode() == ISD::SETCC) { 6178 EVT N0VT = N0.getOperand(0).getValueType(); 6179 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6180 // Only do this before legalize for now. 6181 if (VT.isVector() && !LegalOperations && 6182 TLI.getBooleanContents(N0VT) == 6183 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6184 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6185 // of the same size as the compared operands. Only optimize sext(setcc()) 6186 // if this is the case. 6187 EVT SVT = getSetCCResultType(N0VT); 6188 6189 // We know that the # elements of the results is the same as the 6190 // # elements of the compare (and the # elements of the compare result 6191 // for that matter). Check to see that they are the same size. If so, 6192 // we know that the element size of the sext'd result matches the 6193 // element size of the compare operands. 6194 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6195 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6196 N0.getOperand(1), 6197 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6198 6199 // If the desired elements are smaller or larger than the source 6200 // elements we can use a matching integer vector type and then 6201 // truncate/sign extend 6202 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6203 if (SVT == MatchingVectorType) { 6204 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6205 N0.getOperand(0), N0.getOperand(1), 6206 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6207 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6208 } 6209 } 6210 6211 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6212 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6213 SDLoc DL(N); 6214 SDValue NegOne = 6215 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6216 if (SDValue SCC = SimplifySelectCC( 6217 DL, N0.getOperand(0), N0.getOperand(1), NegOne, 6218 DAG.getConstant(0, DL, VT), 6219 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6220 return SCC; 6221 6222 if (!VT.isVector()) { 6223 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6224 if (!LegalOperations || 6225 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6226 SDLoc DL(N); 6227 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6228 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6229 N0.getOperand(0), N0.getOperand(1), CC); 6230 return DAG.getSelect(DL, VT, SetCC, 6231 NegOne, DAG.getConstant(0, DL, VT)); 6232 } 6233 } 6234 } 6235 6236 // fold (sext x) -> (zext x) if the sign bit is known zero. 6237 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6238 DAG.SignBitIsZero(N0)) 6239 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6240 6241 return SDValue(); 6242 } 6243 6244 // isTruncateOf - If N is a truncate of some other value, return true, record 6245 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6246 // This function computes KnownZero to avoid a duplicated call to 6247 // computeKnownBits in the caller. 6248 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6249 APInt &KnownZero) { 6250 APInt KnownOne; 6251 if (N->getOpcode() == ISD::TRUNCATE) { 6252 Op = N->getOperand(0); 6253 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6254 return true; 6255 } 6256 6257 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6258 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6259 return false; 6260 6261 SDValue Op0 = N->getOperand(0); 6262 SDValue Op1 = N->getOperand(1); 6263 assert(Op0.getValueType() == Op1.getValueType()); 6264 6265 if (isNullConstant(Op0)) 6266 Op = Op1; 6267 else if (isNullConstant(Op1)) 6268 Op = Op0; 6269 else 6270 return false; 6271 6272 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6273 6274 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6275 return false; 6276 6277 return true; 6278 } 6279 6280 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6281 SDValue N0 = N->getOperand(0); 6282 EVT VT = N->getValueType(0); 6283 6284 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6285 LegalOperations)) 6286 return SDValue(Res, 0); 6287 6288 // fold (zext (zext x)) -> (zext x) 6289 // fold (zext (aext x)) -> (zext x) 6290 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6291 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6292 N0.getOperand(0)); 6293 6294 // fold (zext (truncate x)) -> (zext x) or 6295 // (zext (truncate x)) -> (truncate x) 6296 // This is valid when the truncated bits of x are already zero. 6297 // FIXME: We should extend this to work for vectors too. 6298 SDValue Op; 6299 APInt KnownZero; 6300 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6301 APInt TruncatedBits = 6302 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6303 APInt(Op.getValueSizeInBits(), 0) : 6304 APInt::getBitsSet(Op.getValueSizeInBits(), 6305 N0.getValueSizeInBits(), 6306 std::min(Op.getValueSizeInBits(), 6307 VT.getSizeInBits())); 6308 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6309 if (VT.bitsGT(Op.getValueType())) 6310 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6311 if (VT.bitsLT(Op.getValueType())) 6312 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6313 6314 return Op; 6315 } 6316 } 6317 6318 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6319 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6320 if (N0.getOpcode() == ISD::TRUNCATE) { 6321 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6322 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6323 if (NarrowLoad.getNode() != N0.getNode()) { 6324 CombineTo(N0.getNode(), NarrowLoad); 6325 // CombineTo deleted the truncate, if needed, but not what's under it. 6326 AddToWorklist(oye); 6327 } 6328 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6329 } 6330 } 6331 6332 // fold (zext (truncate x)) -> (and x, mask) 6333 if (N0.getOpcode() == ISD::TRUNCATE) { 6334 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6335 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6336 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6337 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6338 if (NarrowLoad.getNode() != N0.getNode()) { 6339 CombineTo(N0.getNode(), NarrowLoad); 6340 // CombineTo deleted the truncate, if needed, but not what's under it. 6341 AddToWorklist(oye); 6342 } 6343 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6344 } 6345 6346 EVT SrcVT = N0.getOperand(0).getValueType(); 6347 EVT MinVT = N0.getValueType(); 6348 6349 // Try to mask before the extension to avoid having to generate a larger mask, 6350 // possibly over several sub-vectors. 6351 if (SrcVT.bitsLT(VT)) { 6352 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6353 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6354 SDValue Op = N0.getOperand(0); 6355 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6356 AddToWorklist(Op.getNode()); 6357 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6358 } 6359 } 6360 6361 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6362 SDValue Op = N0.getOperand(0); 6363 if (SrcVT.bitsLT(VT)) { 6364 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6365 AddToWorklist(Op.getNode()); 6366 } else if (SrcVT.bitsGT(VT)) { 6367 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6368 AddToWorklist(Op.getNode()); 6369 } 6370 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6371 } 6372 } 6373 6374 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6375 // if either of the casts is not free. 6376 if (N0.getOpcode() == ISD::AND && 6377 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6378 N0.getOperand(1).getOpcode() == ISD::Constant && 6379 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6380 N0.getValueType()) || 6381 !TLI.isZExtFree(N0.getValueType(), VT))) { 6382 SDValue X = N0.getOperand(0).getOperand(0); 6383 if (X.getValueType().bitsLT(VT)) { 6384 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6385 } else if (X.getValueType().bitsGT(VT)) { 6386 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6387 } 6388 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6389 Mask = Mask.zext(VT.getSizeInBits()); 6390 SDLoc DL(N); 6391 return DAG.getNode(ISD::AND, DL, VT, 6392 X, DAG.getConstant(Mask, DL, VT)); 6393 } 6394 6395 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6396 // Only generate vector extloads when 1) they're legal, and 2) they are 6397 // deemed desirable by the target. 6398 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6399 ((!LegalOperations && !VT.isVector() && 6400 !cast<LoadSDNode>(N0)->isVolatile()) || 6401 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6402 bool DoXform = true; 6403 SmallVector<SDNode*, 4> SetCCs; 6404 if (!N0.hasOneUse()) 6405 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6406 if (VT.isVector()) 6407 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6408 if (DoXform) { 6409 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6410 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6411 LN0->getChain(), 6412 LN0->getBasePtr(), N0.getValueType(), 6413 LN0->getMemOperand()); 6414 CombineTo(N, ExtLoad); 6415 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6416 N0.getValueType(), ExtLoad); 6417 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6418 6419 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6420 ISD::ZERO_EXTEND); 6421 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6422 } 6423 } 6424 6425 // fold (zext (load x)) to multiple smaller zextloads. 6426 // Only on illegal but splittable vectors. 6427 if (SDValue ExtLoad = CombineExtLoad(N)) 6428 return ExtLoad; 6429 6430 // fold (zext (and/or/xor (load x), cst)) -> 6431 // (and/or/xor (zextload x), (zext cst)) 6432 // Unless (and (load x) cst) will match as a zextload already and has 6433 // additional users. 6434 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6435 N0.getOpcode() == ISD::XOR) && 6436 isa<LoadSDNode>(N0.getOperand(0)) && 6437 N0.getOperand(1).getOpcode() == ISD::Constant && 6438 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6439 (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) { 6440 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6441 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6442 bool DoXform = true; 6443 SmallVector<SDNode*, 4> SetCCs; 6444 if (!N0.hasOneUse()) { 6445 if (N0.getOpcode() == ISD::AND) { 6446 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6447 auto NarrowLoad = false; 6448 EVT LoadResultTy = AndC->getValueType(0); 6449 EVT ExtVT, LoadedVT; 6450 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6451 NarrowLoad)) 6452 DoXform = false; 6453 } 6454 if (DoXform) 6455 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6456 ISD::ZERO_EXTEND, SetCCs, TLI); 6457 } 6458 if (DoXform) { 6459 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6460 LN0->getChain(), LN0->getBasePtr(), 6461 LN0->getMemoryVT(), 6462 LN0->getMemOperand()); 6463 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6464 Mask = Mask.zext(VT.getSizeInBits()); 6465 SDLoc DL(N); 6466 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6467 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6468 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6469 SDLoc(N0.getOperand(0)), 6470 N0.getOperand(0).getValueType(), ExtLoad); 6471 CombineTo(N, And); 6472 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6473 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6474 ISD::ZERO_EXTEND); 6475 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6476 } 6477 } 6478 } 6479 6480 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6481 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6482 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6483 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6484 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6485 EVT MemVT = LN0->getMemoryVT(); 6486 if ((!LegalOperations && !LN0->isVolatile()) || 6487 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6488 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6489 LN0->getChain(), 6490 LN0->getBasePtr(), MemVT, 6491 LN0->getMemOperand()); 6492 CombineTo(N, ExtLoad); 6493 CombineTo(N0.getNode(), 6494 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6495 ExtLoad), 6496 ExtLoad.getValue(1)); 6497 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6498 } 6499 } 6500 6501 if (N0.getOpcode() == ISD::SETCC) { 6502 if (!LegalOperations && VT.isVector() && 6503 N0.getValueType().getVectorElementType() == MVT::i1) { 6504 EVT N0VT = N0.getOperand(0).getValueType(); 6505 if (getSetCCResultType(N0VT) == N0.getValueType()) 6506 return SDValue(); 6507 6508 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6509 // Only do this before legalize for now. 6510 SDLoc DL(N); 6511 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6512 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6513 // We know that the # elements of the results is the same as the 6514 // # elements of the compare (and the # elements of the compare result 6515 // for that matter). Check to see that they are the same size. If so, 6516 // we know that the element size of the sext'd result matches the 6517 // element size of the compare operands. 6518 return DAG.getNode(ISD::AND, DL, VT, 6519 DAG.getSetCC(DL, VT, N0.getOperand(0), 6520 N0.getOperand(1), 6521 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6522 VecOnes); 6523 6524 // If the desired elements are smaller or larger than the source 6525 // elements we can use a matching integer vector type and then 6526 // truncate/sign extend 6527 EVT MatchingElementType = 6528 EVT::getIntegerVT(*DAG.getContext(), 6529 N0VT.getScalarType().getSizeInBits()); 6530 EVT MatchingVectorType = 6531 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6532 N0VT.getVectorNumElements()); 6533 SDValue VsetCC = 6534 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6535 N0.getOperand(1), 6536 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6537 return DAG.getNode(ISD::AND, DL, VT, 6538 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6539 VecOnes); 6540 } 6541 6542 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6543 SDLoc DL(N); 6544 if (SDValue SCC = SimplifySelectCC( 6545 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6546 DAG.getConstant(0, DL, VT), 6547 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6548 return SCC; 6549 } 6550 6551 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6552 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6553 isa<ConstantSDNode>(N0.getOperand(1)) && 6554 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6555 N0.hasOneUse()) { 6556 SDValue ShAmt = N0.getOperand(1); 6557 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6558 if (N0.getOpcode() == ISD::SHL) { 6559 SDValue InnerZExt = N0.getOperand(0); 6560 // If the original shl may be shifting out bits, do not perform this 6561 // transformation. 6562 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6563 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6564 if (ShAmtVal > KnownZeroBits) 6565 return SDValue(); 6566 } 6567 6568 SDLoc DL(N); 6569 6570 // Ensure that the shift amount is wide enough for the shifted value. 6571 if (VT.getSizeInBits() >= 256) 6572 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6573 6574 return DAG.getNode(N0.getOpcode(), DL, VT, 6575 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6576 ShAmt); 6577 } 6578 6579 return SDValue(); 6580 } 6581 6582 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6583 SDValue N0 = N->getOperand(0); 6584 EVT VT = N->getValueType(0); 6585 6586 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6587 LegalOperations)) 6588 return SDValue(Res, 0); 6589 6590 // fold (aext (aext x)) -> (aext x) 6591 // fold (aext (zext x)) -> (zext x) 6592 // fold (aext (sext x)) -> (sext x) 6593 if (N0.getOpcode() == ISD::ANY_EXTEND || 6594 N0.getOpcode() == ISD::ZERO_EXTEND || 6595 N0.getOpcode() == ISD::SIGN_EXTEND) 6596 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6597 6598 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6599 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6600 if (N0.getOpcode() == ISD::TRUNCATE) { 6601 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6602 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6603 if (NarrowLoad.getNode() != N0.getNode()) { 6604 CombineTo(N0.getNode(), NarrowLoad); 6605 // CombineTo deleted the truncate, if needed, but not what's under it. 6606 AddToWorklist(oye); 6607 } 6608 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6609 } 6610 } 6611 6612 // fold (aext (truncate x)) 6613 if (N0.getOpcode() == ISD::TRUNCATE) { 6614 SDValue TruncOp = N0.getOperand(0); 6615 if (TruncOp.getValueType() == VT) 6616 return TruncOp; // x iff x size == zext size. 6617 if (TruncOp.getValueType().bitsGT(VT)) 6618 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6619 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6620 } 6621 6622 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6623 // if the trunc is not free. 6624 if (N0.getOpcode() == ISD::AND && 6625 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6626 N0.getOperand(1).getOpcode() == ISD::Constant && 6627 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6628 N0.getValueType())) { 6629 SDValue X = N0.getOperand(0).getOperand(0); 6630 if (X.getValueType().bitsLT(VT)) { 6631 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6632 } else if (X.getValueType().bitsGT(VT)) { 6633 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6634 } 6635 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6636 Mask = Mask.zext(VT.getSizeInBits()); 6637 SDLoc DL(N); 6638 return DAG.getNode(ISD::AND, DL, VT, 6639 X, DAG.getConstant(Mask, DL, VT)); 6640 } 6641 6642 // fold (aext (load x)) -> (aext (truncate (extload x))) 6643 // None of the supported targets knows how to perform load and any_ext 6644 // on vectors in one instruction. We only perform this transformation on 6645 // scalars. 6646 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6647 ISD::isUNINDEXEDLoad(N0.getNode()) && 6648 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6649 bool DoXform = true; 6650 SmallVector<SDNode*, 4> SetCCs; 6651 if (!N0.hasOneUse()) 6652 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6653 if (DoXform) { 6654 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6655 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6656 LN0->getChain(), 6657 LN0->getBasePtr(), N0.getValueType(), 6658 LN0->getMemOperand()); 6659 CombineTo(N, ExtLoad); 6660 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6661 N0.getValueType(), ExtLoad); 6662 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6663 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6664 ISD::ANY_EXTEND); 6665 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6666 } 6667 } 6668 6669 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6670 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6671 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6672 if (N0.getOpcode() == ISD::LOAD && 6673 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6674 N0.hasOneUse()) { 6675 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6676 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6677 EVT MemVT = LN0->getMemoryVT(); 6678 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6679 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6680 VT, LN0->getChain(), LN0->getBasePtr(), 6681 MemVT, LN0->getMemOperand()); 6682 CombineTo(N, ExtLoad); 6683 CombineTo(N0.getNode(), 6684 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6685 N0.getValueType(), ExtLoad), 6686 ExtLoad.getValue(1)); 6687 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6688 } 6689 } 6690 6691 if (N0.getOpcode() == ISD::SETCC) { 6692 // For vectors: 6693 // aext(setcc) -> vsetcc 6694 // aext(setcc) -> truncate(vsetcc) 6695 // aext(setcc) -> aext(vsetcc) 6696 // Only do this before legalize for now. 6697 if (VT.isVector() && !LegalOperations) { 6698 EVT N0VT = N0.getOperand(0).getValueType(); 6699 // We know that the # elements of the results is the same as the 6700 // # elements of the compare (and the # elements of the compare result 6701 // for that matter). Check to see that they are the same size. If so, 6702 // we know that the element size of the sext'd result matches the 6703 // element size of the compare operands. 6704 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6705 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6706 N0.getOperand(1), 6707 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6708 // If the desired elements are smaller or larger than the source 6709 // elements we can use a matching integer vector type and then 6710 // truncate/any extend 6711 else { 6712 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6713 SDValue VsetCC = 6714 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6715 N0.getOperand(1), 6716 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6717 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6718 } 6719 } 6720 6721 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6722 SDLoc DL(N); 6723 if (SDValue SCC = SimplifySelectCC( 6724 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6725 DAG.getConstant(0, DL, VT), 6726 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6727 return SCC; 6728 } 6729 6730 return SDValue(); 6731 } 6732 6733 /// See if the specified operand can be simplified with the knowledge that only 6734 /// the bits specified by Mask are used. If so, return the simpler operand, 6735 /// otherwise return a null SDValue. 6736 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6737 switch (V.getOpcode()) { 6738 default: break; 6739 case ISD::Constant: { 6740 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6741 assert(CV && "Const value should be ConstSDNode."); 6742 const APInt &CVal = CV->getAPIntValue(); 6743 APInt NewVal = CVal & Mask; 6744 if (NewVal != CVal) 6745 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6746 break; 6747 } 6748 case ISD::OR: 6749 case ISD::XOR: 6750 // If the LHS or RHS don't contribute bits to the or, drop them. 6751 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6752 return V.getOperand(1); 6753 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6754 return V.getOperand(0); 6755 break; 6756 case ISD::SRL: 6757 // Only look at single-use SRLs. 6758 if (!V.getNode()->hasOneUse()) 6759 break; 6760 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6761 // See if we can recursively simplify the LHS. 6762 unsigned Amt = RHSC->getZExtValue(); 6763 6764 // Watch out for shift count overflow though. 6765 if (Amt >= Mask.getBitWidth()) break; 6766 APInt NewMask = Mask << Amt; 6767 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6768 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6769 SimplifyLHS, V.getOperand(1)); 6770 } 6771 } 6772 return SDValue(); 6773 } 6774 6775 /// If the result of a wider load is shifted to right of N bits and then 6776 /// truncated to a narrower type and where N is a multiple of number of bits of 6777 /// the narrower type, transform it to a narrower load from address + N / num of 6778 /// bits of new type. If the result is to be extended, also fold the extension 6779 /// to form a extending load. 6780 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6781 unsigned Opc = N->getOpcode(); 6782 6783 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6784 SDValue N0 = N->getOperand(0); 6785 EVT VT = N->getValueType(0); 6786 EVT ExtVT = VT; 6787 6788 // This transformation isn't valid for vector loads. 6789 if (VT.isVector()) 6790 return SDValue(); 6791 6792 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6793 // extended to VT. 6794 if (Opc == ISD::SIGN_EXTEND_INREG) { 6795 ExtType = ISD::SEXTLOAD; 6796 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6797 } else if (Opc == ISD::SRL) { 6798 // Another special-case: SRL is basically zero-extending a narrower value. 6799 ExtType = ISD::ZEXTLOAD; 6800 N0 = SDValue(N, 0); 6801 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6802 if (!N01) return SDValue(); 6803 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6804 VT.getSizeInBits() - N01->getZExtValue()); 6805 } 6806 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6807 return SDValue(); 6808 6809 unsigned EVTBits = ExtVT.getSizeInBits(); 6810 6811 // Do not generate loads of non-round integer types since these can 6812 // be expensive (and would be wrong if the type is not byte sized). 6813 if (!ExtVT.isRound()) 6814 return SDValue(); 6815 6816 unsigned ShAmt = 0; 6817 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6818 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6819 ShAmt = N01->getZExtValue(); 6820 // Is the shift amount a multiple of size of VT? 6821 if ((ShAmt & (EVTBits-1)) == 0) { 6822 N0 = N0.getOperand(0); 6823 // Is the load width a multiple of size of VT? 6824 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6825 return SDValue(); 6826 } 6827 6828 // At this point, we must have a load or else we can't do the transform. 6829 if (!isa<LoadSDNode>(N0)) return SDValue(); 6830 6831 // Because a SRL must be assumed to *need* to zero-extend the high bits 6832 // (as opposed to anyext the high bits), we can't combine the zextload 6833 // lowering of SRL and an sextload. 6834 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6835 return SDValue(); 6836 6837 // If the shift amount is larger than the input type then we're not 6838 // accessing any of the loaded bytes. If the load was a zextload/extload 6839 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6840 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6841 return SDValue(); 6842 } 6843 } 6844 6845 // If the load is shifted left (and the result isn't shifted back right), 6846 // we can fold the truncate through the shift. 6847 unsigned ShLeftAmt = 0; 6848 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6849 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6850 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6851 ShLeftAmt = N01->getZExtValue(); 6852 N0 = N0.getOperand(0); 6853 } 6854 } 6855 6856 // If we haven't found a load, we can't narrow it. Don't transform one with 6857 // multiple uses, this would require adding a new load. 6858 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6859 return SDValue(); 6860 6861 // Don't change the width of a volatile load. 6862 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6863 if (LN0->isVolatile()) 6864 return SDValue(); 6865 6866 // Verify that we are actually reducing a load width here. 6867 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6868 return SDValue(); 6869 6870 // For the transform to be legal, the load must produce only two values 6871 // (the value loaded and the chain). Don't transform a pre-increment 6872 // load, for example, which produces an extra value. Otherwise the 6873 // transformation is not equivalent, and the downstream logic to replace 6874 // uses gets things wrong. 6875 if (LN0->getNumValues() > 2) 6876 return SDValue(); 6877 6878 // If the load that we're shrinking is an extload and we're not just 6879 // discarding the extension we can't simply shrink the load. Bail. 6880 // TODO: It would be possible to merge the extensions in some cases. 6881 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6882 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6883 return SDValue(); 6884 6885 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6886 return SDValue(); 6887 6888 EVT PtrType = N0.getOperand(1).getValueType(); 6889 6890 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6891 // It's not possible to generate a constant of extended or untyped type. 6892 return SDValue(); 6893 6894 // For big endian targets, we need to adjust the offset to the pointer to 6895 // load the correct bytes. 6896 if (DAG.getDataLayout().isBigEndian()) { 6897 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6898 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6899 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6900 } 6901 6902 uint64_t PtrOff = ShAmt / 8; 6903 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6904 SDLoc DL(LN0); 6905 // The original load itself didn't wrap, so an offset within it doesn't. 6906 SDNodeFlags Flags; 6907 Flags.setNoUnsignedWrap(true); 6908 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6909 PtrType, LN0->getBasePtr(), 6910 DAG.getConstant(PtrOff, DL, PtrType), 6911 &Flags); 6912 AddToWorklist(NewPtr.getNode()); 6913 6914 SDValue Load; 6915 if (ExtType == ISD::NON_EXTLOAD) 6916 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6917 LN0->getPointerInfo().getWithOffset(PtrOff), 6918 LN0->isVolatile(), LN0->isNonTemporal(), 6919 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6920 else 6921 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6922 LN0->getPointerInfo().getWithOffset(PtrOff), 6923 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6924 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6925 6926 // Replace the old load's chain with the new load's chain. 6927 WorklistRemover DeadNodes(*this); 6928 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6929 6930 // Shift the result left, if we've swallowed a left shift. 6931 SDValue Result = Load; 6932 if (ShLeftAmt != 0) { 6933 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6934 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6935 ShImmTy = VT; 6936 // If the shift amount is as large as the result size (but, presumably, 6937 // no larger than the source) then the useful bits of the result are 6938 // zero; we can't simply return the shortened shift, because the result 6939 // of that operation is undefined. 6940 SDLoc DL(N0); 6941 if (ShLeftAmt >= VT.getSizeInBits()) 6942 Result = DAG.getConstant(0, DL, VT); 6943 else 6944 Result = DAG.getNode(ISD::SHL, DL, VT, 6945 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6946 } 6947 6948 // Return the new loaded value. 6949 return Result; 6950 } 6951 6952 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6953 SDValue N0 = N->getOperand(0); 6954 SDValue N1 = N->getOperand(1); 6955 EVT VT = N->getValueType(0); 6956 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6957 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6958 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6959 6960 if (N0.isUndef()) 6961 return DAG.getUNDEF(VT); 6962 6963 // fold (sext_in_reg c1) -> c1 6964 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6965 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6966 6967 // If the input is already sign extended, just drop the extension. 6968 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6969 return N0; 6970 6971 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6972 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6973 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6974 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6975 N0.getOperand(0), N1); 6976 6977 // fold (sext_in_reg (sext x)) -> (sext x) 6978 // fold (sext_in_reg (aext x)) -> (sext x) 6979 // if x is small enough. 6980 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6981 SDValue N00 = N0.getOperand(0); 6982 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6983 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6984 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6985 } 6986 6987 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6988 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6989 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6990 6991 // fold operands of sext_in_reg based on knowledge that the top bits are not 6992 // demanded. 6993 if (SimplifyDemandedBits(SDValue(N, 0))) 6994 return SDValue(N, 0); 6995 6996 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6997 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6998 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6999 return NarrowLoad; 7000 7001 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7002 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7003 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7004 if (N0.getOpcode() == ISD::SRL) { 7005 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7006 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7007 // We can turn this into an SRA iff the input to the SRL is already sign 7008 // extended enough. 7009 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7010 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7011 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7012 N0.getOperand(0), N0.getOperand(1)); 7013 } 7014 } 7015 7016 // fold (sext_inreg (extload x)) -> (sextload x) 7017 if (ISD::isEXTLoad(N0.getNode()) && 7018 ISD::isUNINDEXEDLoad(N0.getNode()) && 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 AddToWorklist(ExtLoad.getNode()); 7030 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7031 } 7032 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7033 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7034 N0.hasOneUse() && 7035 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7036 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7037 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7038 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7039 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7040 LN0->getChain(), 7041 LN0->getBasePtr(), EVT, 7042 LN0->getMemOperand()); 7043 CombineTo(N, ExtLoad); 7044 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7045 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7046 } 7047 7048 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7049 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7050 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7051 N0.getOperand(1), false)) 7052 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7053 BSwap, N1); 7054 } 7055 7056 return SDValue(); 7057 } 7058 7059 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7060 SDValue N0 = N->getOperand(0); 7061 EVT VT = N->getValueType(0); 7062 7063 if (N0.isUndef()) 7064 return DAG.getUNDEF(VT); 7065 7066 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7067 LegalOperations)) 7068 return SDValue(Res, 0); 7069 7070 return SDValue(); 7071 } 7072 7073 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7074 SDValue N0 = N->getOperand(0); 7075 EVT VT = N->getValueType(0); 7076 7077 if (N0.isUndef()) 7078 return DAG.getUNDEF(VT); 7079 7080 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7081 LegalOperations)) 7082 return SDValue(Res, 0); 7083 7084 return SDValue(); 7085 } 7086 7087 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7088 SDValue N0 = N->getOperand(0); 7089 EVT VT = N->getValueType(0); 7090 bool isLE = DAG.getDataLayout().isLittleEndian(); 7091 7092 // noop truncate 7093 if (N0.getValueType() == N->getValueType(0)) 7094 return N0; 7095 // fold (truncate c1) -> c1 7096 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7097 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7098 // fold (truncate (truncate x)) -> (truncate x) 7099 if (N0.getOpcode() == ISD::TRUNCATE) 7100 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7101 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7102 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7103 N0.getOpcode() == ISD::SIGN_EXTEND || 7104 N0.getOpcode() == ISD::ANY_EXTEND) { 7105 // if the source is smaller than the dest, we still need an extend. 7106 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7107 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7108 // if the source is larger than the dest, than we just need the truncate. 7109 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7110 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7111 // if the source and dest are the same type, we can drop both the extend 7112 // and the truncate. 7113 return N0.getOperand(0); 7114 } 7115 7116 // Fold extract-and-trunc into a narrow extract. For example: 7117 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7118 // i32 y = TRUNCATE(i64 x) 7119 // -- becomes -- 7120 // v16i8 b = BITCAST (v2i64 val) 7121 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7122 // 7123 // Note: We only run this optimization after type legalization (which often 7124 // creates this pattern) and before operation legalization after which 7125 // we need to be more careful about the vector instructions that we generate. 7126 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7127 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7128 7129 EVT VecTy = N0.getOperand(0).getValueType(); 7130 EVT ExTy = N0.getValueType(); 7131 EVT TrTy = N->getValueType(0); 7132 7133 unsigned NumElem = VecTy.getVectorNumElements(); 7134 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7135 7136 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7137 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7138 7139 SDValue EltNo = N0->getOperand(1); 7140 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7141 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7142 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7143 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7144 7145 SDLoc DL(N); 7146 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7147 DAG.getBitcast(NVT, N0.getOperand(0)), 7148 DAG.getConstant(Index, DL, IndexTy)); 7149 } 7150 } 7151 7152 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7153 if (N0.getOpcode() == ISD::SELECT) { 7154 EVT SrcVT = N0.getValueType(); 7155 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7156 TLI.isTruncateFree(SrcVT, VT)) { 7157 SDLoc SL(N0); 7158 SDValue Cond = N0.getOperand(0); 7159 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7160 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7161 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7162 } 7163 } 7164 7165 // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2 7166 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7167 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7168 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7169 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7170 uint64_t Amt = CAmt->getZExtValue(); 7171 unsigned Size = VT.getSizeInBits(); 7172 7173 if (Amt < Size / 2) { 7174 SDLoc SL(N); 7175 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7176 7177 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7178 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7179 DAG.getConstant(Amt, SL, AmtVT)); 7180 } 7181 } 7182 } 7183 7184 // Fold a series of buildvector, bitcast, and truncate if possible. 7185 // For example fold 7186 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7187 // (2xi32 (buildvector x, y)). 7188 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7189 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7190 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7191 N0.getOperand(0).hasOneUse()) { 7192 7193 SDValue BuildVect = N0.getOperand(0); 7194 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7195 EVT TruncVecEltTy = VT.getVectorElementType(); 7196 7197 // Check that the element types match. 7198 if (BuildVectEltTy == TruncVecEltTy) { 7199 // Now we only need to compute the offset of the truncated elements. 7200 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7201 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7202 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7203 7204 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7205 "Invalid number of elements"); 7206 7207 SmallVector<SDValue, 8> Opnds; 7208 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7209 Opnds.push_back(BuildVect.getOperand(i)); 7210 7211 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7212 } 7213 } 7214 7215 // See if we can simplify the input to this truncate through knowledge that 7216 // only the low bits are being used. 7217 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7218 // Currently we only perform this optimization on scalars because vectors 7219 // may have different active low bits. 7220 if (!VT.isVector()) { 7221 if (SDValue Shorter = 7222 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7223 VT.getSizeInBits()))) 7224 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7225 } 7226 // fold (truncate (load x)) -> (smaller load x) 7227 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7228 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7229 if (SDValue Reduced = ReduceLoadWidth(N)) 7230 return Reduced; 7231 7232 // Handle the case where the load remains an extending load even 7233 // after truncation. 7234 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7235 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7236 if (!LN0->isVolatile() && 7237 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7238 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7239 VT, LN0->getChain(), LN0->getBasePtr(), 7240 LN0->getMemoryVT(), 7241 LN0->getMemOperand()); 7242 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7243 return NewLoad; 7244 } 7245 } 7246 } 7247 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7248 // where ... are all 'undef'. 7249 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7250 SmallVector<EVT, 8> VTs; 7251 SDValue V; 7252 unsigned Idx = 0; 7253 unsigned NumDefs = 0; 7254 7255 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7256 SDValue X = N0.getOperand(i); 7257 if (!X.isUndef()) { 7258 V = X; 7259 Idx = i; 7260 NumDefs++; 7261 } 7262 // Stop if more than one members are non-undef. 7263 if (NumDefs > 1) 7264 break; 7265 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7266 VT.getVectorElementType(), 7267 X.getValueType().getVectorNumElements())); 7268 } 7269 7270 if (NumDefs == 0) 7271 return DAG.getUNDEF(VT); 7272 7273 if (NumDefs == 1) { 7274 assert(V.getNode() && "The single defined operand is empty!"); 7275 SmallVector<SDValue, 8> Opnds; 7276 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7277 if (i != Idx) { 7278 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7279 continue; 7280 } 7281 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7282 AddToWorklist(NV.getNode()); 7283 Opnds.push_back(NV); 7284 } 7285 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7286 } 7287 } 7288 7289 // Fold truncate of a bitcast of a vector to an extract of the low vector 7290 // element. 7291 // 7292 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7293 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7294 SDValue VecSrc = N0.getOperand(0); 7295 EVT SrcVT = VecSrc.getValueType(); 7296 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7297 (!LegalOperations || 7298 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7299 SDLoc SL(N); 7300 7301 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7302 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7303 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7304 } 7305 } 7306 7307 // Simplify the operands using demanded-bits information. 7308 if (!VT.isVector() && 7309 SimplifyDemandedBits(SDValue(N, 0))) 7310 return SDValue(N, 0); 7311 7312 return SDValue(); 7313 } 7314 7315 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7316 SDValue Elt = N->getOperand(i); 7317 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7318 return Elt.getNode(); 7319 return Elt.getOperand(Elt.getResNo()).getNode(); 7320 } 7321 7322 /// build_pair (load, load) -> load 7323 /// if load locations are consecutive. 7324 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7325 assert(N->getOpcode() == ISD::BUILD_PAIR); 7326 7327 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7328 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7329 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7330 LD1->getAddressSpace() != LD2->getAddressSpace()) 7331 return SDValue(); 7332 EVT LD1VT = LD1->getValueType(0); 7333 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7334 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7335 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7336 unsigned Align = LD1->getAlignment(); 7337 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7338 VT.getTypeForEVT(*DAG.getContext())); 7339 7340 if (NewAlign <= Align && 7341 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7342 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7343 LD1->getBasePtr(), LD1->getPointerInfo(), 7344 false, false, false, Align); 7345 } 7346 7347 return SDValue(); 7348 } 7349 7350 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7351 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7352 // and Lo parts; on big-endian machines it doesn't. 7353 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7354 } 7355 7356 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7357 SDValue N0 = N->getOperand(0); 7358 EVT VT = N->getValueType(0); 7359 7360 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7361 // Only do this before legalize, since afterward the target may be depending 7362 // on the bitconvert. 7363 // First check to see if this is all constant. 7364 if (!LegalTypes && 7365 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7366 VT.isVector()) { 7367 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7368 7369 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7370 assert(!DestEltVT.isVector() && 7371 "Element type of vector ValueType must not be vector!"); 7372 if (isSimple) 7373 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7374 } 7375 7376 // If the input is a constant, let getNode fold it. 7377 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7378 // If we can't allow illegal operations, we need to check that this is just 7379 // a fp -> int or int -> conversion and that the resulting operation will 7380 // be legal. 7381 if (!LegalOperations || 7382 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7383 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7384 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7385 TLI.isOperationLegal(ISD::Constant, VT))) 7386 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7387 } 7388 7389 // (conv (conv x, t1), t2) -> (conv x, t2) 7390 if (N0.getOpcode() == ISD::BITCAST) 7391 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7392 N0.getOperand(0)); 7393 7394 // fold (conv (load x)) -> (load (conv*)x) 7395 // If the resultant load doesn't need a higher alignment than the original! 7396 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7397 // Do not change the width of a volatile load. 7398 !cast<LoadSDNode>(N0)->isVolatile() && 7399 // Do not remove the cast if the types differ in endian layout. 7400 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7401 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7402 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7403 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7404 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7405 unsigned OrigAlign = LN0->getAlignment(); 7406 7407 bool Fast = false; 7408 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7409 LN0->getAddressSpace(), OrigAlign, &Fast) && 7410 Fast) { 7411 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7412 LN0->getBasePtr(), LN0->getPointerInfo(), 7413 LN0->isVolatile(), LN0->isNonTemporal(), 7414 LN0->isInvariant(), OrigAlign, 7415 LN0->getAAInfo()); 7416 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7417 return Load; 7418 } 7419 } 7420 7421 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7422 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7423 // 7424 // For ppc_fp128: 7425 // fold (bitcast (fneg x)) -> 7426 // flipbit = signbit 7427 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7428 // 7429 // fold (bitcast (fabs x)) -> 7430 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7431 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7432 // This often reduces constant pool loads. 7433 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7434 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7435 N0.getNode()->hasOneUse() && VT.isInteger() && 7436 !VT.isVector() && !N0.getValueType().isVector()) { 7437 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7438 N0.getOperand(0)); 7439 AddToWorklist(NewConv.getNode()); 7440 7441 SDLoc DL(N); 7442 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7443 assert(VT.getSizeInBits() == 128); 7444 SDValue SignBit = DAG.getConstant( 7445 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7446 SDValue FlipBit; 7447 if (N0.getOpcode() == ISD::FNEG) { 7448 FlipBit = SignBit; 7449 AddToWorklist(FlipBit.getNode()); 7450 } else { 7451 assert(N0.getOpcode() == ISD::FABS); 7452 SDValue Hi = 7453 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7454 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7455 SDLoc(NewConv))); 7456 AddToWorklist(Hi.getNode()); 7457 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7458 AddToWorklist(FlipBit.getNode()); 7459 } 7460 SDValue FlipBits = 7461 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7462 AddToWorklist(FlipBits.getNode()); 7463 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7464 } 7465 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7466 if (N0.getOpcode() == ISD::FNEG) 7467 return DAG.getNode(ISD::XOR, DL, VT, 7468 NewConv, DAG.getConstant(SignBit, DL, VT)); 7469 assert(N0.getOpcode() == ISD::FABS); 7470 return DAG.getNode(ISD::AND, DL, VT, 7471 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7472 } 7473 7474 // fold (bitconvert (fcopysign cst, x)) -> 7475 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7476 // Note that we don't handle (copysign x, cst) because this can always be 7477 // folded to an fneg or fabs. 7478 // 7479 // For ppc_fp128: 7480 // fold (bitcast (fcopysign cst, x)) -> 7481 // flipbit = (and (extract_element 7482 // (xor (bitcast cst), (bitcast x)), 0), 7483 // signbit) 7484 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7485 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7486 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7487 VT.isInteger() && !VT.isVector()) { 7488 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7489 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7490 if (isTypeLegal(IntXVT)) { 7491 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7492 IntXVT, N0.getOperand(1)); 7493 AddToWorklist(X.getNode()); 7494 7495 // If X has a different width than the result/lhs, sext it or truncate it. 7496 unsigned VTWidth = VT.getSizeInBits(); 7497 if (OrigXWidth < VTWidth) { 7498 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7499 AddToWorklist(X.getNode()); 7500 } else if (OrigXWidth > VTWidth) { 7501 // To get the sign bit in the right place, we have to shift it right 7502 // before truncating. 7503 SDLoc DL(X); 7504 X = DAG.getNode(ISD::SRL, DL, 7505 X.getValueType(), X, 7506 DAG.getConstant(OrigXWidth-VTWidth, DL, 7507 X.getValueType())); 7508 AddToWorklist(X.getNode()); 7509 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7510 AddToWorklist(X.getNode()); 7511 } 7512 7513 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7514 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7515 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7516 AddToWorklist(Cst.getNode()); 7517 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7518 AddToWorklist(X.getNode()); 7519 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7520 AddToWorklist(XorResult.getNode()); 7521 SDValue XorResult64 = DAG.getNode( 7522 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7523 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7524 SDLoc(XorResult))); 7525 AddToWorklist(XorResult64.getNode()); 7526 SDValue FlipBit = 7527 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7528 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7529 AddToWorklist(FlipBit.getNode()); 7530 SDValue FlipBits = 7531 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7532 AddToWorklist(FlipBits.getNode()); 7533 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7534 } 7535 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7536 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7537 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7538 AddToWorklist(X.getNode()); 7539 7540 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7541 VT, N0.getOperand(0)); 7542 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7543 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7544 AddToWorklist(Cst.getNode()); 7545 7546 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7547 } 7548 } 7549 7550 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7551 if (N0.getOpcode() == ISD::BUILD_PAIR) 7552 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7553 return CombineLD; 7554 7555 // Remove double bitcasts from shuffles - this is often a legacy of 7556 // XformToShuffleWithZero being used to combine bitmaskings (of 7557 // float vectors bitcast to integer vectors) into shuffles. 7558 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7559 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7560 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7561 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7562 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7563 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7564 7565 // If operands are a bitcast, peek through if it casts the original VT. 7566 // If operands are a constant, just bitcast back to original VT. 7567 auto PeekThroughBitcast = [&](SDValue Op) { 7568 if (Op.getOpcode() == ISD::BITCAST && 7569 Op.getOperand(0).getValueType() == VT) 7570 return SDValue(Op.getOperand(0)); 7571 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7572 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7573 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7574 return SDValue(); 7575 }; 7576 7577 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7578 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7579 if (!(SV0 && SV1)) 7580 return SDValue(); 7581 7582 int MaskScale = 7583 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7584 SmallVector<int, 8> NewMask; 7585 for (int M : SVN->getMask()) 7586 for (int i = 0; i != MaskScale; ++i) 7587 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7588 7589 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7590 if (!LegalMask) { 7591 std::swap(SV0, SV1); 7592 ShuffleVectorSDNode::commuteMask(NewMask); 7593 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7594 } 7595 7596 if (LegalMask) 7597 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7598 } 7599 7600 return SDValue(); 7601 } 7602 7603 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7604 EVT VT = N->getValueType(0); 7605 return CombineConsecutiveLoads(N, VT); 7606 } 7607 7608 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7609 /// operands. DstEltVT indicates the destination element value type. 7610 SDValue DAGCombiner:: 7611 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7612 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7613 7614 // If this is already the right type, we're done. 7615 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7616 7617 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7618 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7619 7620 // If this is a conversion of N elements of one type to N elements of another 7621 // type, convert each element. This handles FP<->INT cases. 7622 if (SrcBitSize == DstBitSize) { 7623 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7624 BV->getValueType(0).getVectorNumElements()); 7625 7626 // Due to the FP element handling below calling this routine recursively, 7627 // we can end up with a scalar-to-vector node here. 7628 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7629 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7630 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7631 DstEltVT, BV->getOperand(0))); 7632 7633 SmallVector<SDValue, 8> Ops; 7634 for (SDValue Op : BV->op_values()) { 7635 // If the vector element type is not legal, the BUILD_VECTOR operands 7636 // are promoted and implicitly truncated. Make that explicit here. 7637 if (Op.getValueType() != SrcEltVT) 7638 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7639 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7640 DstEltVT, Op)); 7641 AddToWorklist(Ops.back().getNode()); 7642 } 7643 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 7644 } 7645 7646 // Otherwise, we're growing or shrinking the elements. To avoid having to 7647 // handle annoying details of growing/shrinking FP values, we convert them to 7648 // int first. 7649 if (SrcEltVT.isFloatingPoint()) { 7650 // Convert the input float vector to a int vector where the elements are the 7651 // same sizes. 7652 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7653 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7654 SrcEltVT = IntVT; 7655 } 7656 7657 // Now we know the input is an integer vector. If the output is a FP type, 7658 // convert to integer first, then to FP of the right size. 7659 if (DstEltVT.isFloatingPoint()) { 7660 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7661 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7662 7663 // Next, convert to FP elements of the same size. 7664 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7665 } 7666 7667 SDLoc DL(BV); 7668 7669 // Okay, we know the src/dst types are both integers of differing types. 7670 // Handling growing first. 7671 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7672 if (SrcBitSize < DstBitSize) { 7673 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7674 7675 SmallVector<SDValue, 8> Ops; 7676 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7677 i += NumInputsPerOutput) { 7678 bool isLE = DAG.getDataLayout().isLittleEndian(); 7679 APInt NewBits = APInt(DstBitSize, 0); 7680 bool EltIsUndef = true; 7681 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7682 // Shift the previously computed bits over. 7683 NewBits <<= SrcBitSize; 7684 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7685 if (Op.isUndef()) continue; 7686 EltIsUndef = false; 7687 7688 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7689 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7690 } 7691 7692 if (EltIsUndef) 7693 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7694 else 7695 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7696 } 7697 7698 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7699 return DAG.getBuildVector(VT, DL, Ops); 7700 } 7701 7702 // Finally, this must be the case where we are shrinking elements: each input 7703 // turns into multiple outputs. 7704 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7705 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7706 NumOutputsPerInput*BV->getNumOperands()); 7707 SmallVector<SDValue, 8> Ops; 7708 7709 for (const SDValue &Op : BV->op_values()) { 7710 if (Op.isUndef()) { 7711 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7712 continue; 7713 } 7714 7715 APInt OpVal = cast<ConstantSDNode>(Op)-> 7716 getAPIntValue().zextOrTrunc(SrcBitSize); 7717 7718 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7719 APInt ThisVal = OpVal.trunc(DstBitSize); 7720 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7721 OpVal = OpVal.lshr(DstBitSize); 7722 } 7723 7724 // For big endian targets, swap the order of the pieces of each element. 7725 if (DAG.getDataLayout().isBigEndian()) 7726 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7727 } 7728 7729 return DAG.getBuildVector(VT, DL, Ops); 7730 } 7731 7732 /// Try to perform FMA combining on a given FADD node. 7733 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7734 SDValue N0 = N->getOperand(0); 7735 SDValue N1 = N->getOperand(1); 7736 EVT VT = N->getValueType(0); 7737 SDLoc SL(N); 7738 7739 const TargetOptions &Options = DAG.getTarget().Options; 7740 bool AllowFusion = 7741 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7742 7743 // Floating-point multiply-add with intermediate rounding. 7744 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7745 7746 // Floating-point multiply-add without intermediate rounding. 7747 bool HasFMA = 7748 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7749 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7750 7751 // No valid opcode, do not combine. 7752 if (!HasFMAD && !HasFMA) 7753 return SDValue(); 7754 7755 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7756 ; 7757 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7758 return SDValue(); 7759 7760 // Always prefer FMAD to FMA for precision. 7761 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7762 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7763 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7764 7765 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7766 // prefer to fold the multiply with fewer uses. 7767 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7768 N1.getOpcode() == ISD::FMUL) { 7769 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7770 std::swap(N0, N1); 7771 } 7772 7773 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7774 if (N0.getOpcode() == ISD::FMUL && 7775 (Aggressive || N0->hasOneUse())) { 7776 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7777 N0.getOperand(0), N0.getOperand(1), N1); 7778 } 7779 7780 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7781 // Note: Commutes FADD operands. 7782 if (N1.getOpcode() == ISD::FMUL && 7783 (Aggressive || N1->hasOneUse())) { 7784 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7785 N1.getOperand(0), N1.getOperand(1), N0); 7786 } 7787 7788 // Look through FP_EXTEND nodes to do more combining. 7789 if (AllowFusion && LookThroughFPExt) { 7790 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7791 if (N0.getOpcode() == ISD::FP_EXTEND) { 7792 SDValue N00 = N0.getOperand(0); 7793 if (N00.getOpcode() == ISD::FMUL) 7794 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7795 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7796 N00.getOperand(0)), 7797 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7798 N00.getOperand(1)), N1); 7799 } 7800 7801 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7802 // Note: Commutes FADD operands. 7803 if (N1.getOpcode() == ISD::FP_EXTEND) { 7804 SDValue N10 = N1.getOperand(0); 7805 if (N10.getOpcode() == ISD::FMUL) 7806 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7807 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7808 N10.getOperand(0)), 7809 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7810 N10.getOperand(1)), N0); 7811 } 7812 } 7813 7814 // More folding opportunities when target permits. 7815 if ((AllowFusion || HasFMAD) && Aggressive) { 7816 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7817 if (N0.getOpcode() == PreferredFusedOpcode && 7818 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7819 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7820 N0.getOperand(0), N0.getOperand(1), 7821 DAG.getNode(PreferredFusedOpcode, SL, VT, 7822 N0.getOperand(2).getOperand(0), 7823 N0.getOperand(2).getOperand(1), 7824 N1)); 7825 } 7826 7827 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7828 if (N1->getOpcode() == PreferredFusedOpcode && 7829 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7830 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7831 N1.getOperand(0), N1.getOperand(1), 7832 DAG.getNode(PreferredFusedOpcode, SL, VT, 7833 N1.getOperand(2).getOperand(0), 7834 N1.getOperand(2).getOperand(1), 7835 N0)); 7836 } 7837 7838 if (AllowFusion && LookThroughFPExt) { 7839 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7840 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7841 auto FoldFAddFMAFPExtFMul = [&] ( 7842 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7843 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7844 DAG.getNode(PreferredFusedOpcode, SL, VT, 7845 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7846 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7847 Z)); 7848 }; 7849 if (N0.getOpcode() == PreferredFusedOpcode) { 7850 SDValue N02 = N0.getOperand(2); 7851 if (N02.getOpcode() == ISD::FP_EXTEND) { 7852 SDValue N020 = N02.getOperand(0); 7853 if (N020.getOpcode() == ISD::FMUL) 7854 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7855 N020.getOperand(0), N020.getOperand(1), 7856 N1); 7857 } 7858 } 7859 7860 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7861 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7862 // FIXME: This turns two single-precision and one double-precision 7863 // operation into two double-precision operations, which might not be 7864 // interesting for all targets, especially GPUs. 7865 auto FoldFAddFPExtFMAFMul = [&] ( 7866 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7867 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7868 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7869 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7870 DAG.getNode(PreferredFusedOpcode, SL, VT, 7871 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7872 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7873 Z)); 7874 }; 7875 if (N0.getOpcode() == ISD::FP_EXTEND) { 7876 SDValue N00 = N0.getOperand(0); 7877 if (N00.getOpcode() == PreferredFusedOpcode) { 7878 SDValue N002 = N00.getOperand(2); 7879 if (N002.getOpcode() == ISD::FMUL) 7880 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7881 N002.getOperand(0), N002.getOperand(1), 7882 N1); 7883 } 7884 } 7885 7886 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7887 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7888 if (N1.getOpcode() == PreferredFusedOpcode) { 7889 SDValue N12 = N1.getOperand(2); 7890 if (N12.getOpcode() == ISD::FP_EXTEND) { 7891 SDValue N120 = N12.getOperand(0); 7892 if (N120.getOpcode() == ISD::FMUL) 7893 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7894 N120.getOperand(0), N120.getOperand(1), 7895 N0); 7896 } 7897 } 7898 7899 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7900 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7901 // FIXME: This turns two single-precision and one double-precision 7902 // operation into two double-precision operations, which might not be 7903 // interesting for all targets, especially GPUs. 7904 if (N1.getOpcode() == ISD::FP_EXTEND) { 7905 SDValue N10 = N1.getOperand(0); 7906 if (N10.getOpcode() == PreferredFusedOpcode) { 7907 SDValue N102 = N10.getOperand(2); 7908 if (N102.getOpcode() == ISD::FMUL) 7909 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7910 N102.getOperand(0), N102.getOperand(1), 7911 N0); 7912 } 7913 } 7914 } 7915 } 7916 7917 return SDValue(); 7918 } 7919 7920 /// Try to perform FMA combining on a given FSUB node. 7921 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7922 SDValue N0 = N->getOperand(0); 7923 SDValue N1 = N->getOperand(1); 7924 EVT VT = N->getValueType(0); 7925 SDLoc SL(N); 7926 7927 const TargetOptions &Options = DAG.getTarget().Options; 7928 bool AllowFusion = 7929 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7930 7931 // Floating-point multiply-add with intermediate rounding. 7932 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7933 7934 // Floating-point multiply-add without intermediate rounding. 7935 bool HasFMA = 7936 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7937 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7938 7939 // No valid opcode, do not combine. 7940 if (!HasFMAD && !HasFMA) 7941 return SDValue(); 7942 7943 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7944 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7945 return SDValue(); 7946 7947 // Always prefer FMAD to FMA for precision. 7948 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7949 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7950 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7951 7952 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7953 if (N0.getOpcode() == ISD::FMUL && 7954 (Aggressive || N0->hasOneUse())) { 7955 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7956 N0.getOperand(0), N0.getOperand(1), 7957 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7958 } 7959 7960 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7961 // Note: Commutes FSUB operands. 7962 if (N1.getOpcode() == ISD::FMUL && 7963 (Aggressive || N1->hasOneUse())) 7964 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7965 DAG.getNode(ISD::FNEG, SL, VT, 7966 N1.getOperand(0)), 7967 N1.getOperand(1), N0); 7968 7969 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7970 if (N0.getOpcode() == ISD::FNEG && 7971 N0.getOperand(0).getOpcode() == ISD::FMUL && 7972 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7973 SDValue N00 = N0.getOperand(0).getOperand(0); 7974 SDValue N01 = N0.getOperand(0).getOperand(1); 7975 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7976 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7977 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7978 } 7979 7980 // Look through FP_EXTEND nodes to do more combining. 7981 if (AllowFusion && LookThroughFPExt) { 7982 // fold (fsub (fpext (fmul x, y)), z) 7983 // -> (fma (fpext x), (fpext y), (fneg z)) 7984 if (N0.getOpcode() == ISD::FP_EXTEND) { 7985 SDValue N00 = N0.getOperand(0); 7986 if (N00.getOpcode() == ISD::FMUL) 7987 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7988 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7989 N00.getOperand(0)), 7990 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7991 N00.getOperand(1)), 7992 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7993 } 7994 7995 // fold (fsub x, (fpext (fmul y, z))) 7996 // -> (fma (fneg (fpext y)), (fpext z), x) 7997 // Note: Commutes FSUB operands. 7998 if (N1.getOpcode() == ISD::FP_EXTEND) { 7999 SDValue N10 = N1.getOperand(0); 8000 if (N10.getOpcode() == ISD::FMUL) 8001 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8002 DAG.getNode(ISD::FNEG, SL, VT, 8003 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8004 N10.getOperand(0))), 8005 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8006 N10.getOperand(1)), 8007 N0); 8008 } 8009 8010 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8011 // -> (fneg (fma (fpext x), (fpext y), z)) 8012 // Note: This could be removed with appropriate canonicalization of the 8013 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8014 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8015 // from implementing the canonicalization in visitFSUB. 8016 if (N0.getOpcode() == ISD::FP_EXTEND) { 8017 SDValue N00 = N0.getOperand(0); 8018 if (N00.getOpcode() == ISD::FNEG) { 8019 SDValue N000 = N00.getOperand(0); 8020 if (N000.getOpcode() == ISD::FMUL) { 8021 return DAG.getNode(ISD::FNEG, SL, VT, 8022 DAG.getNode(PreferredFusedOpcode, SL, VT, 8023 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8024 N000.getOperand(0)), 8025 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8026 N000.getOperand(1)), 8027 N1)); 8028 } 8029 } 8030 } 8031 8032 // fold (fsub (fneg (fpext (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::FNEG) { 8039 SDValue N00 = N0.getOperand(0); 8040 if (N00.getOpcode() == ISD::FP_EXTEND) { 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 } 8055 8056 // More folding opportunities when target permits. 8057 if ((AllowFusion || HasFMAD) && Aggressive) { 8058 // fold (fsub (fma x, y, (fmul u, v)), z) 8059 // -> (fma x, y (fma u, v, (fneg z))) 8060 if (N0.getOpcode() == PreferredFusedOpcode && 8061 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8062 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8063 N0.getOperand(0), N0.getOperand(1), 8064 DAG.getNode(PreferredFusedOpcode, SL, VT, 8065 N0.getOperand(2).getOperand(0), 8066 N0.getOperand(2).getOperand(1), 8067 DAG.getNode(ISD::FNEG, SL, VT, 8068 N1))); 8069 } 8070 8071 // fold (fsub x, (fma y, z, (fmul u, v))) 8072 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8073 if (N1.getOpcode() == PreferredFusedOpcode && 8074 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8075 SDValue N20 = N1.getOperand(2).getOperand(0); 8076 SDValue N21 = N1.getOperand(2).getOperand(1); 8077 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8078 DAG.getNode(ISD::FNEG, SL, VT, 8079 N1.getOperand(0)), 8080 N1.getOperand(1), 8081 DAG.getNode(PreferredFusedOpcode, SL, VT, 8082 DAG.getNode(ISD::FNEG, SL, VT, N20), 8083 8084 N21, N0)); 8085 } 8086 8087 if (AllowFusion && LookThroughFPExt) { 8088 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8089 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8090 if (N0.getOpcode() == PreferredFusedOpcode) { 8091 SDValue N02 = N0.getOperand(2); 8092 if (N02.getOpcode() == ISD::FP_EXTEND) { 8093 SDValue N020 = N02.getOperand(0); 8094 if (N020.getOpcode() == ISD::FMUL) 8095 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8096 N0.getOperand(0), N0.getOperand(1), 8097 DAG.getNode(PreferredFusedOpcode, SL, VT, 8098 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8099 N020.getOperand(0)), 8100 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8101 N020.getOperand(1)), 8102 DAG.getNode(ISD::FNEG, SL, VT, 8103 N1))); 8104 } 8105 } 8106 8107 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8108 // -> (fma (fpext x), (fpext y), 8109 // (fma (fpext u), (fpext v), (fneg z))) 8110 // FIXME: This turns two single-precision and one double-precision 8111 // operation into two double-precision operations, which might not be 8112 // interesting for all targets, especially GPUs. 8113 if (N0.getOpcode() == ISD::FP_EXTEND) { 8114 SDValue N00 = N0.getOperand(0); 8115 if (N00.getOpcode() == PreferredFusedOpcode) { 8116 SDValue N002 = N00.getOperand(2); 8117 if (N002.getOpcode() == ISD::FMUL) 8118 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8119 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8120 N00.getOperand(0)), 8121 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8122 N00.getOperand(1)), 8123 DAG.getNode(PreferredFusedOpcode, SL, VT, 8124 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8125 N002.getOperand(0)), 8126 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8127 N002.getOperand(1)), 8128 DAG.getNode(ISD::FNEG, SL, VT, 8129 N1))); 8130 } 8131 } 8132 8133 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8134 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8135 if (N1.getOpcode() == PreferredFusedOpcode && 8136 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8137 SDValue N120 = N1.getOperand(2).getOperand(0); 8138 if (N120.getOpcode() == ISD::FMUL) { 8139 SDValue N1200 = N120.getOperand(0); 8140 SDValue N1201 = N120.getOperand(1); 8141 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8142 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8143 N1.getOperand(1), 8144 DAG.getNode(PreferredFusedOpcode, SL, VT, 8145 DAG.getNode(ISD::FNEG, SL, VT, 8146 DAG.getNode(ISD::FP_EXTEND, SL, 8147 VT, N1200)), 8148 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8149 N1201), 8150 N0)); 8151 } 8152 } 8153 8154 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8155 // -> (fma (fneg (fpext y)), (fpext z), 8156 // (fma (fneg (fpext u)), (fpext v), x)) 8157 // FIXME: This turns two single-precision and one double-precision 8158 // operation into two double-precision operations, which might not be 8159 // interesting for all targets, especially GPUs. 8160 if (N1.getOpcode() == ISD::FP_EXTEND && 8161 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8162 SDValue N100 = N1.getOperand(0).getOperand(0); 8163 SDValue N101 = N1.getOperand(0).getOperand(1); 8164 SDValue N102 = N1.getOperand(0).getOperand(2); 8165 if (N102.getOpcode() == ISD::FMUL) { 8166 SDValue N1020 = N102.getOperand(0); 8167 SDValue N1021 = N102.getOperand(1); 8168 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8169 DAG.getNode(ISD::FNEG, SL, VT, 8170 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8171 N100)), 8172 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8173 DAG.getNode(PreferredFusedOpcode, SL, VT, 8174 DAG.getNode(ISD::FNEG, SL, VT, 8175 DAG.getNode(ISD::FP_EXTEND, SL, 8176 VT, N1020)), 8177 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8178 N1021), 8179 N0)); 8180 } 8181 } 8182 } 8183 } 8184 8185 return SDValue(); 8186 } 8187 8188 /// Try to perform FMA combining on a given FMUL node. 8189 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8190 SDValue N0 = N->getOperand(0); 8191 SDValue N1 = N->getOperand(1); 8192 EVT VT = N->getValueType(0); 8193 SDLoc SL(N); 8194 8195 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8196 8197 const TargetOptions &Options = DAG.getTarget().Options; 8198 bool AllowFusion = 8199 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8200 8201 // Floating-point multiply-add with intermediate rounding. 8202 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8203 8204 // Floating-point multiply-add without intermediate rounding. 8205 bool HasFMA = 8206 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8207 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8208 8209 // No valid opcode, do not combine. 8210 if (!HasFMAD && !HasFMA) 8211 return SDValue(); 8212 8213 // Always prefer FMAD to FMA for precision. 8214 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8215 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8216 8217 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8218 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8219 auto FuseFADD = [&](SDValue X, SDValue Y) { 8220 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8221 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8222 if (XC1 && XC1->isExactlyValue(+1.0)) 8223 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8224 if (XC1 && XC1->isExactlyValue(-1.0)) 8225 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8226 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8227 } 8228 return SDValue(); 8229 }; 8230 8231 if (SDValue FMA = FuseFADD(N0, N1)) 8232 return FMA; 8233 if (SDValue FMA = FuseFADD(N1, N0)) 8234 return FMA; 8235 8236 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8237 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8238 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8239 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8240 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8241 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8242 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8243 if (XC0 && XC0->isExactlyValue(+1.0)) 8244 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8245 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8246 Y); 8247 if (XC0 && XC0->isExactlyValue(-1.0)) 8248 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8249 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8250 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8251 8252 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8253 if (XC1 && XC1->isExactlyValue(+1.0)) 8254 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8255 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8256 if (XC1 && XC1->isExactlyValue(-1.0)) 8257 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8258 } 8259 return SDValue(); 8260 }; 8261 8262 if (SDValue FMA = FuseFSUB(N0, N1)) 8263 return FMA; 8264 if (SDValue FMA = FuseFSUB(N1, N0)) 8265 return FMA; 8266 8267 return SDValue(); 8268 } 8269 8270 SDValue DAGCombiner::visitFADD(SDNode *N) { 8271 SDValue N0 = N->getOperand(0); 8272 SDValue N1 = N->getOperand(1); 8273 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8274 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8275 EVT VT = N->getValueType(0); 8276 SDLoc DL(N); 8277 const TargetOptions &Options = DAG.getTarget().Options; 8278 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8279 8280 // fold vector ops 8281 if (VT.isVector()) 8282 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8283 return FoldedVOp; 8284 8285 // fold (fadd c1, c2) -> c1 + c2 8286 if (N0CFP && N1CFP) 8287 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8288 8289 // canonicalize constant to RHS 8290 if (N0CFP && !N1CFP) 8291 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8292 8293 // fold (fadd A, (fneg B)) -> (fsub A, B) 8294 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8295 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8296 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8297 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8298 8299 // fold (fadd (fneg A), B) -> (fsub B, A) 8300 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8301 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8302 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8303 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8304 8305 // If 'unsafe math' is enabled, fold lots of things. 8306 if (Options.UnsafeFPMath) { 8307 // No FP constant should be created after legalization as Instruction 8308 // Selection pass has a hard time dealing with FP constants. 8309 bool AllowNewConst = (Level < AfterLegalizeDAG); 8310 8311 // fold (fadd A, 0) -> A 8312 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8313 if (N1C->isZero()) 8314 return N0; 8315 8316 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8317 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8318 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8319 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8320 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8321 Flags), 8322 Flags); 8323 8324 // If allowed, fold (fadd (fneg x), x) -> 0.0 8325 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8326 return DAG.getConstantFP(0.0, DL, VT); 8327 8328 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8329 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8330 return DAG.getConstantFP(0.0, DL, VT); 8331 8332 // We can fold chains of FADD's of the same value into multiplications. 8333 // This transform is not safe in general because we are reducing the number 8334 // of rounding steps. 8335 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8336 if (N0.getOpcode() == ISD::FMUL) { 8337 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8338 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8339 8340 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8341 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8342 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8343 DAG.getConstantFP(1.0, DL, VT), Flags); 8344 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8345 } 8346 8347 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8348 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8349 N1.getOperand(0) == N1.getOperand(1) && 8350 N0.getOperand(0) == N1.getOperand(0)) { 8351 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8352 DAG.getConstantFP(2.0, DL, VT), Flags); 8353 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8354 } 8355 } 8356 8357 if (N1.getOpcode() == ISD::FMUL) { 8358 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8359 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8360 8361 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8362 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8363 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8364 DAG.getConstantFP(1.0, DL, VT), Flags); 8365 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8366 } 8367 8368 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8369 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8370 N0.getOperand(0) == N0.getOperand(1) && 8371 N1.getOperand(0) == N0.getOperand(0)) { 8372 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8373 DAG.getConstantFP(2.0, DL, VT), Flags); 8374 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8375 } 8376 } 8377 8378 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8379 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8380 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8381 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8382 (N0.getOperand(0) == N1)) { 8383 return DAG.getNode(ISD::FMUL, DL, VT, 8384 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8385 } 8386 } 8387 8388 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8389 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8390 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8391 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8392 N1.getOperand(0) == N0) { 8393 return DAG.getNode(ISD::FMUL, DL, VT, 8394 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8395 } 8396 } 8397 8398 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8399 if (AllowNewConst && 8400 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8401 N0.getOperand(0) == N0.getOperand(1) && 8402 N1.getOperand(0) == N1.getOperand(1) && 8403 N0.getOperand(0) == N1.getOperand(0)) { 8404 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8405 DAG.getConstantFP(4.0, DL, VT), Flags); 8406 } 8407 } 8408 } // enable-unsafe-fp-math 8409 8410 // FADD -> FMA combines: 8411 if (SDValue Fused = visitFADDForFMACombine(N)) { 8412 AddToWorklist(Fused.getNode()); 8413 return Fused; 8414 } 8415 return SDValue(); 8416 } 8417 8418 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8419 SDValue N0 = N->getOperand(0); 8420 SDValue N1 = N->getOperand(1); 8421 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8422 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8423 EVT VT = N->getValueType(0); 8424 SDLoc dl(N); 8425 const TargetOptions &Options = DAG.getTarget().Options; 8426 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8427 8428 // fold vector ops 8429 if (VT.isVector()) 8430 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8431 return FoldedVOp; 8432 8433 // fold (fsub c1, c2) -> c1-c2 8434 if (N0CFP && N1CFP) 8435 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8436 8437 // fold (fsub A, (fneg B)) -> (fadd A, B) 8438 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8439 return DAG.getNode(ISD::FADD, dl, VT, N0, 8440 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8441 8442 // If 'unsafe math' is enabled, fold lots of things. 8443 if (Options.UnsafeFPMath) { 8444 // (fsub A, 0) -> A 8445 if (N1CFP && N1CFP->isZero()) 8446 return N0; 8447 8448 // (fsub 0, B) -> -B 8449 if (N0CFP && N0CFP->isZero()) { 8450 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8451 return GetNegatedExpression(N1, DAG, LegalOperations); 8452 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8453 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8454 } 8455 8456 // (fsub x, x) -> 0.0 8457 if (N0 == N1) 8458 return DAG.getConstantFP(0.0f, dl, VT); 8459 8460 // (fsub x, (fadd x, y)) -> (fneg y) 8461 // (fsub x, (fadd y, x)) -> (fneg y) 8462 if (N1.getOpcode() == ISD::FADD) { 8463 SDValue N10 = N1->getOperand(0); 8464 SDValue N11 = N1->getOperand(1); 8465 8466 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8467 return GetNegatedExpression(N11, DAG, LegalOperations); 8468 8469 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8470 return GetNegatedExpression(N10, DAG, LegalOperations); 8471 } 8472 } 8473 8474 // FSUB -> FMA combines: 8475 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8476 AddToWorklist(Fused.getNode()); 8477 return Fused; 8478 } 8479 8480 return SDValue(); 8481 } 8482 8483 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8484 SDValue N0 = N->getOperand(0); 8485 SDValue N1 = N->getOperand(1); 8486 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8487 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8488 EVT VT = N->getValueType(0); 8489 SDLoc DL(N); 8490 const TargetOptions &Options = DAG.getTarget().Options; 8491 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8492 8493 // fold vector ops 8494 if (VT.isVector()) { 8495 // This just handles C1 * C2 for vectors. Other vector folds are below. 8496 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8497 return FoldedVOp; 8498 } 8499 8500 // fold (fmul c1, c2) -> c1*c2 8501 if (N0CFP && N1CFP) 8502 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8503 8504 // canonicalize constant to RHS 8505 if (isConstantFPBuildVectorOrConstantFP(N0) && 8506 !isConstantFPBuildVectorOrConstantFP(N1)) 8507 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8508 8509 // fold (fmul A, 1.0) -> A 8510 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8511 return N0; 8512 8513 if (Options.UnsafeFPMath) { 8514 // fold (fmul A, 0) -> 0 8515 if (N1CFP && N1CFP->isZero()) 8516 return N1; 8517 8518 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8519 if (N0.getOpcode() == ISD::FMUL) { 8520 // Fold scalars or any vector constants (not just splats). 8521 // This fold is done in general by InstCombine, but extra fmul insts 8522 // may have been generated during lowering. 8523 SDValue N00 = N0.getOperand(0); 8524 SDValue N01 = N0.getOperand(1); 8525 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8526 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8527 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8528 8529 // Check 1: Make sure that the first operand of the inner multiply is NOT 8530 // a constant. Otherwise, we may induce infinite looping. 8531 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8532 // Check 2: Make sure that the second operand of the inner multiply and 8533 // the second operand of the outer multiply are constants. 8534 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8535 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8536 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8537 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8538 } 8539 } 8540 } 8541 8542 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8543 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8544 // during an early run of DAGCombiner can prevent folding with fmuls 8545 // inserted during lowering. 8546 if (N0.getOpcode() == ISD::FADD && 8547 (N0.getOperand(0) == N0.getOperand(1)) && 8548 N0.hasOneUse()) { 8549 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8550 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8551 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8552 } 8553 } 8554 8555 // fold (fmul X, 2.0) -> (fadd X, X) 8556 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8557 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8558 8559 // fold (fmul X, -1.0) -> (fneg X) 8560 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8561 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8562 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8563 8564 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8565 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8566 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8567 // Both can be negated for free, check to see if at least one is cheaper 8568 // negated. 8569 if (LHSNeg == 2 || RHSNeg == 2) 8570 return DAG.getNode(ISD::FMUL, DL, VT, 8571 GetNegatedExpression(N0, DAG, LegalOperations), 8572 GetNegatedExpression(N1, DAG, LegalOperations), 8573 Flags); 8574 } 8575 } 8576 8577 // FMUL -> FMA combines: 8578 if (SDValue Fused = visitFMULForFMACombine(N)) { 8579 AddToWorklist(Fused.getNode()); 8580 return Fused; 8581 } 8582 8583 return SDValue(); 8584 } 8585 8586 SDValue DAGCombiner::visitFMA(SDNode *N) { 8587 SDValue N0 = N->getOperand(0); 8588 SDValue N1 = N->getOperand(1); 8589 SDValue N2 = N->getOperand(2); 8590 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8591 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8592 EVT VT = N->getValueType(0); 8593 SDLoc dl(N); 8594 const TargetOptions &Options = DAG.getTarget().Options; 8595 8596 // Constant fold FMA. 8597 if (isa<ConstantFPSDNode>(N0) && 8598 isa<ConstantFPSDNode>(N1) && 8599 isa<ConstantFPSDNode>(N2)) { 8600 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8601 } 8602 8603 if (Options.UnsafeFPMath) { 8604 if (N0CFP && N0CFP->isZero()) 8605 return N2; 8606 if (N1CFP && N1CFP->isZero()) 8607 return N2; 8608 } 8609 // TODO: The FMA node should have flags that propagate to these nodes. 8610 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8611 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8612 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8613 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8614 8615 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8616 if (isConstantFPBuildVectorOrConstantFP(N0) && 8617 !isConstantFPBuildVectorOrConstantFP(N1)) 8618 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8619 8620 // TODO: FMA nodes should have flags that propagate to the created nodes. 8621 // For now, create a Flags object for use with all unsafe math transforms. 8622 SDNodeFlags Flags; 8623 Flags.setUnsafeAlgebra(true); 8624 8625 if (Options.UnsafeFPMath) { 8626 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8627 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8628 isConstantFPBuildVectorOrConstantFP(N1) && 8629 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8630 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8631 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8632 &Flags), &Flags); 8633 } 8634 8635 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8636 if (N0.getOpcode() == ISD::FMUL && 8637 isConstantFPBuildVectorOrConstantFP(N1) && 8638 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8639 return DAG.getNode(ISD::FMA, dl, VT, 8640 N0.getOperand(0), 8641 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8642 &Flags), 8643 N2); 8644 } 8645 } 8646 8647 // (fma x, 1, y) -> (fadd x, y) 8648 // (fma x, -1, y) -> (fadd (fneg x), y) 8649 if (N1CFP) { 8650 if (N1CFP->isExactlyValue(1.0)) 8651 // TODO: The FMA node should have flags that propagate to this node. 8652 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8653 8654 if (N1CFP->isExactlyValue(-1.0) && 8655 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8656 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8657 AddToWorklist(RHSNeg.getNode()); 8658 // TODO: The FMA node should have flags that propagate to this node. 8659 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8660 } 8661 } 8662 8663 if (Options.UnsafeFPMath) { 8664 // (fma x, c, x) -> (fmul x, (c+1)) 8665 if (N1CFP && N0 == N2) { 8666 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8667 DAG.getNode(ISD::FADD, dl, VT, 8668 N1, DAG.getConstantFP(1.0, dl, VT), 8669 &Flags), &Flags); 8670 } 8671 8672 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8673 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8674 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8675 DAG.getNode(ISD::FADD, dl, VT, 8676 N1, DAG.getConstantFP(-1.0, dl, VT), 8677 &Flags), &Flags); 8678 } 8679 } 8680 8681 return SDValue(); 8682 } 8683 8684 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8685 // reciprocal. 8686 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8687 // Notice that this is not always beneficial. One reason is different target 8688 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8689 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8690 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8691 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8692 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8693 const SDNodeFlags *Flags = N->getFlags(); 8694 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8695 return SDValue(); 8696 8697 // Skip if current node is a reciprocal. 8698 SDValue N0 = N->getOperand(0); 8699 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8700 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8701 return SDValue(); 8702 8703 // Exit early if the target does not want this transform or if there can't 8704 // possibly be enough uses of the divisor to make the transform worthwhile. 8705 SDValue N1 = N->getOperand(1); 8706 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8707 if (!MinUses || N1->use_size() < MinUses) 8708 return SDValue(); 8709 8710 // Find all FDIV users of the same divisor. 8711 // Use a set because duplicates may be present in the user list. 8712 SetVector<SDNode *> Users; 8713 for (auto *U : N1->uses()) { 8714 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8715 // This division is eligible for optimization only if global unsafe math 8716 // is enabled or if this division allows reciprocal formation. 8717 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8718 Users.insert(U); 8719 } 8720 } 8721 8722 // Now that we have the actual number of divisor uses, make sure it meets 8723 // the minimum threshold specified by the target. 8724 if (Users.size() < MinUses) 8725 return SDValue(); 8726 8727 EVT VT = N->getValueType(0); 8728 SDLoc DL(N); 8729 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8730 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8731 8732 // Dividend / Divisor -> Dividend * Reciprocal 8733 for (auto *U : Users) { 8734 SDValue Dividend = U->getOperand(0); 8735 if (Dividend != FPOne) { 8736 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8737 Reciprocal, Flags); 8738 CombineTo(U, NewNode); 8739 } else if (U != Reciprocal.getNode()) { 8740 // In the absence of fast-math-flags, this user node is always the 8741 // same node as Reciprocal, but with FMF they may be different nodes. 8742 CombineTo(U, Reciprocal); 8743 } 8744 } 8745 return SDValue(N, 0); // N was replaced. 8746 } 8747 8748 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8749 SDValue N0 = N->getOperand(0); 8750 SDValue N1 = N->getOperand(1); 8751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8752 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8753 EVT VT = N->getValueType(0); 8754 SDLoc DL(N); 8755 const TargetOptions &Options = DAG.getTarget().Options; 8756 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8757 8758 // fold vector ops 8759 if (VT.isVector()) 8760 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8761 return FoldedVOp; 8762 8763 // fold (fdiv c1, c2) -> c1/c2 8764 if (N0CFP && N1CFP) 8765 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8766 8767 if (Options.UnsafeFPMath) { 8768 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8769 if (N1CFP) { 8770 // Compute the reciprocal 1.0 / c2. 8771 APFloat N1APF = N1CFP->getValueAPF(); 8772 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8773 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8774 // Only do the transform if the reciprocal is a legal fp immediate that 8775 // isn't too nasty (eg NaN, denormal, ...). 8776 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8777 (!LegalOperations || 8778 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8779 // backend)... we should handle this gracefully after Legalize. 8780 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8781 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8782 TLI.isFPImmLegal(Recip, VT))) 8783 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8784 DAG.getConstantFP(Recip, DL, VT), Flags); 8785 } 8786 8787 // If this FDIV is part of a reciprocal square root, it may be folded 8788 // into a target-specific square root estimate instruction. 8789 if (N1.getOpcode() == ISD::FSQRT) { 8790 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8791 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8792 } 8793 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8794 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8795 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8796 Flags)) { 8797 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8798 AddToWorklist(RV.getNode()); 8799 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8800 } 8801 } else if (N1.getOpcode() == ISD::FP_ROUND && 8802 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8803 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8804 Flags)) { 8805 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8806 AddToWorklist(RV.getNode()); 8807 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8808 } 8809 } else if (N1.getOpcode() == ISD::FMUL) { 8810 // Look through an FMUL. Even though this won't remove the FDIV directly, 8811 // it's still worthwhile to get rid of the FSQRT if possible. 8812 SDValue SqrtOp; 8813 SDValue OtherOp; 8814 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8815 SqrtOp = N1.getOperand(0); 8816 OtherOp = N1.getOperand(1); 8817 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8818 SqrtOp = N1.getOperand(1); 8819 OtherOp = N1.getOperand(0); 8820 } 8821 if (SqrtOp.getNode()) { 8822 // We found a FSQRT, so try to make this fold: 8823 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8824 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8825 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8826 AddToWorklist(RV.getNode()); 8827 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8828 } 8829 } 8830 } 8831 8832 // Fold into a reciprocal estimate and multiply instead of a real divide. 8833 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8834 AddToWorklist(RV.getNode()); 8835 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8836 } 8837 } 8838 8839 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8840 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8841 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8842 // Both can be negated for free, check to see if at least one is cheaper 8843 // negated. 8844 if (LHSNeg == 2 || RHSNeg == 2) 8845 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8846 GetNegatedExpression(N0, DAG, LegalOperations), 8847 GetNegatedExpression(N1, DAG, LegalOperations), 8848 Flags); 8849 } 8850 } 8851 8852 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8853 return CombineRepeatedDivisors; 8854 8855 return SDValue(); 8856 } 8857 8858 SDValue DAGCombiner::visitFREM(SDNode *N) { 8859 SDValue N0 = N->getOperand(0); 8860 SDValue N1 = N->getOperand(1); 8861 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8862 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8863 EVT VT = N->getValueType(0); 8864 8865 // fold (frem c1, c2) -> fmod(c1,c2) 8866 if (N0CFP && N1CFP) 8867 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8868 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8869 8870 return SDValue(); 8871 } 8872 8873 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8874 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8875 return SDValue(); 8876 8877 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8878 // For now, create a Flags object for use with all unsafe math transforms. 8879 SDNodeFlags Flags; 8880 Flags.setUnsafeAlgebra(true); 8881 8882 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8883 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8884 if (!RV) 8885 return SDValue(); 8886 8887 EVT VT = RV.getValueType(); 8888 SDLoc DL(N); 8889 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8890 AddToWorklist(RV.getNode()); 8891 8892 // Unfortunately, RV is now NaN if the input was exactly 0. 8893 // Select out this case and force the answer to 0. 8894 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8895 EVT CCVT = getSetCCResultType(VT); 8896 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8897 AddToWorklist(ZeroCmp.getNode()); 8898 AddToWorklist(RV.getNode()); 8899 8900 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8901 ZeroCmp, Zero, RV); 8902 } 8903 8904 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8905 /// copysign(x, fp_round(y)) -> copysign(x, y) 8906 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8907 SDValue N1 = N->getOperand(1); 8908 if ((N1.getOpcode() == ISD::FP_EXTEND || 8909 N1.getOpcode() == ISD::FP_ROUND)) { 8910 // Do not optimize out type conversion of f128 type yet. 8911 // For some targets like x86_64, configuration is changed to keep one f128 8912 // value in one SSE register, but instruction selection cannot handle 8913 // FCOPYSIGN on SSE registers yet. 8914 EVT N1VT = N1->getValueType(0); 8915 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8916 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8917 } 8918 return false; 8919 } 8920 8921 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8922 SDValue N0 = N->getOperand(0); 8923 SDValue N1 = N->getOperand(1); 8924 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8925 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8926 EVT VT = N->getValueType(0); 8927 8928 if (N0CFP && N1CFP) // Constant fold 8929 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8930 8931 if (N1CFP) { 8932 const APFloat& V = N1CFP->getValueAPF(); 8933 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8934 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8935 if (!V.isNegative()) { 8936 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8937 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8938 } else { 8939 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8940 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8941 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8942 } 8943 } 8944 8945 // copysign(fabs(x), y) -> copysign(x, y) 8946 // copysign(fneg(x), y) -> copysign(x, y) 8947 // copysign(copysign(x,z), y) -> copysign(x, y) 8948 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8949 N0.getOpcode() == ISD::FCOPYSIGN) 8950 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8951 N0.getOperand(0), N1); 8952 8953 // copysign(x, abs(y)) -> abs(x) 8954 if (N1.getOpcode() == ISD::FABS) 8955 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8956 8957 // copysign(x, copysign(y,z)) -> copysign(x, z) 8958 if (N1.getOpcode() == ISD::FCOPYSIGN) 8959 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8960 N0, N1.getOperand(1)); 8961 8962 // copysign(x, fp_extend(y)) -> copysign(x, y) 8963 // copysign(x, fp_round(y)) -> copysign(x, y) 8964 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 8965 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8966 N0, N1.getOperand(0)); 8967 8968 return SDValue(); 8969 } 8970 8971 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8972 SDValue N0 = N->getOperand(0); 8973 EVT VT = N->getValueType(0); 8974 EVT OpVT = N0.getValueType(); 8975 8976 // fold (sint_to_fp c1) -> c1fp 8977 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8978 // ...but only if the target supports immediate floating-point values 8979 (!LegalOperations || 8980 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8981 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8982 8983 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8984 // but UINT_TO_FP is legal on this target, try to convert. 8985 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8986 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8987 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8988 if (DAG.SignBitIsZero(N0)) 8989 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8990 } 8991 8992 // The next optimizations are desirable only if SELECT_CC can be lowered. 8993 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8994 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8995 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8996 !VT.isVector() && 8997 (!LegalOperations || 8998 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8999 SDLoc DL(N); 9000 SDValue Ops[] = 9001 { N0.getOperand(0), N0.getOperand(1), 9002 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9003 N0.getOperand(2) }; 9004 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9005 } 9006 9007 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9008 // (select_cc x, y, 1.0, 0.0,, cc) 9009 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9010 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9011 (!LegalOperations || 9012 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9013 SDLoc DL(N); 9014 SDValue Ops[] = 9015 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9016 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9017 N0.getOperand(0).getOperand(2) }; 9018 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9019 } 9020 } 9021 9022 return SDValue(); 9023 } 9024 9025 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9026 SDValue N0 = N->getOperand(0); 9027 EVT VT = N->getValueType(0); 9028 EVT OpVT = N0.getValueType(); 9029 9030 // fold (uint_to_fp c1) -> c1fp 9031 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9032 // ...but only if the target supports immediate floating-point values 9033 (!LegalOperations || 9034 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9035 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9036 9037 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9038 // but SINT_TO_FP is legal on this target, try to convert. 9039 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9040 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9041 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9042 if (DAG.SignBitIsZero(N0)) 9043 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9044 } 9045 9046 // The next optimizations are desirable only if SELECT_CC can be lowered. 9047 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9048 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9049 9050 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9051 (!LegalOperations || 9052 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9053 SDLoc DL(N); 9054 SDValue Ops[] = 9055 { N0.getOperand(0), N0.getOperand(1), 9056 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9057 N0.getOperand(2) }; 9058 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9059 } 9060 } 9061 9062 return SDValue(); 9063 } 9064 9065 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9066 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9067 SDValue N0 = N->getOperand(0); 9068 EVT VT = N->getValueType(0); 9069 9070 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9071 return SDValue(); 9072 9073 SDValue Src = N0.getOperand(0); 9074 EVT SrcVT = Src.getValueType(); 9075 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9076 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9077 9078 // We can safely assume the conversion won't overflow the output range, 9079 // because (for example) (uint8_t)18293.f is undefined behavior. 9080 9081 // Since we can assume the conversion won't overflow, our decision as to 9082 // whether the input will fit in the float should depend on the minimum 9083 // of the input range and output range. 9084 9085 // This means this is also safe for a signed input and unsigned output, since 9086 // a negative input would lead to undefined behavior. 9087 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9088 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9089 unsigned ActualSize = std::min(InputSize, OutputSize); 9090 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9091 9092 // We can only fold away the float conversion if the input range can be 9093 // represented exactly in the float range. 9094 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9095 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9096 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9097 : ISD::ZERO_EXTEND; 9098 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9099 } 9100 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9101 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9102 return DAG.getBitcast(VT, Src); 9103 } 9104 return SDValue(); 9105 } 9106 9107 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9108 SDValue N0 = N->getOperand(0); 9109 EVT VT = N->getValueType(0); 9110 9111 // fold (fp_to_sint c1fp) -> c1 9112 if (isConstantFPBuildVectorOrConstantFP(N0)) 9113 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9114 9115 return FoldIntToFPToInt(N, DAG); 9116 } 9117 9118 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9119 SDValue N0 = N->getOperand(0); 9120 EVT VT = N->getValueType(0); 9121 9122 // fold (fp_to_uint c1fp) -> c1 9123 if (isConstantFPBuildVectorOrConstantFP(N0)) 9124 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9125 9126 return FoldIntToFPToInt(N, DAG); 9127 } 9128 9129 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9130 SDValue N0 = N->getOperand(0); 9131 SDValue N1 = N->getOperand(1); 9132 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9133 EVT VT = N->getValueType(0); 9134 9135 // fold (fp_round c1fp) -> c1fp 9136 if (N0CFP) 9137 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9138 9139 // fold (fp_round (fp_extend x)) -> x 9140 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9141 return N0.getOperand(0); 9142 9143 // fold (fp_round (fp_round x)) -> (fp_round x) 9144 if (N0.getOpcode() == ISD::FP_ROUND) { 9145 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9146 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9147 9148 // Skip this folding if it results in an fp_round from f80 to f16. 9149 // 9150 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9151 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9152 // instructions from f32 or f64. Moreover, the first (value-preserving) 9153 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9154 // x86. 9155 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9156 return SDValue(); 9157 9158 // If the first fp_round isn't a value preserving truncation, it might 9159 // introduce a tie in the second fp_round, that wouldn't occur in the 9160 // single-step fp_round we want to fold to. 9161 // In other words, double rounding isn't the same as rounding. 9162 // Also, this is a value preserving truncation iff both fp_round's are. 9163 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9164 SDLoc DL(N); 9165 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9166 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9167 } 9168 } 9169 9170 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9171 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9172 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9173 N0.getOperand(0), N1); 9174 AddToWorklist(Tmp.getNode()); 9175 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9176 Tmp, N0.getOperand(1)); 9177 } 9178 9179 return SDValue(); 9180 } 9181 9182 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9183 SDValue N0 = N->getOperand(0); 9184 EVT VT = N->getValueType(0); 9185 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9186 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9187 9188 // fold (fp_round_inreg c1fp) -> c1fp 9189 if (N0CFP && isTypeLegal(EVT)) { 9190 SDLoc DL(N); 9191 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9192 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9193 } 9194 9195 return SDValue(); 9196 } 9197 9198 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9199 SDValue N0 = N->getOperand(0); 9200 EVT VT = N->getValueType(0); 9201 9202 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9203 if (N->hasOneUse() && 9204 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9205 return SDValue(); 9206 9207 // fold (fp_extend c1fp) -> c1fp 9208 if (isConstantFPBuildVectorOrConstantFP(N0)) 9209 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9210 9211 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9212 if (N0.getOpcode() == ISD::FP16_TO_FP && 9213 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9214 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9215 9216 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9217 // value of X. 9218 if (N0.getOpcode() == ISD::FP_ROUND 9219 && N0.getNode()->getConstantOperandVal(1) == 1) { 9220 SDValue In = N0.getOperand(0); 9221 if (In.getValueType() == VT) return In; 9222 if (VT.bitsLT(In.getValueType())) 9223 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9224 In, N0.getOperand(1)); 9225 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9226 } 9227 9228 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9229 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9230 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9231 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9232 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9233 LN0->getChain(), 9234 LN0->getBasePtr(), N0.getValueType(), 9235 LN0->getMemOperand()); 9236 CombineTo(N, ExtLoad); 9237 CombineTo(N0.getNode(), 9238 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9239 N0.getValueType(), ExtLoad, 9240 DAG.getIntPtrConstant(1, SDLoc(N0))), 9241 ExtLoad.getValue(1)); 9242 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9243 } 9244 9245 return SDValue(); 9246 } 9247 9248 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9249 SDValue N0 = N->getOperand(0); 9250 EVT VT = N->getValueType(0); 9251 9252 // fold (fceil c1) -> fceil(c1) 9253 if (isConstantFPBuildVectorOrConstantFP(N0)) 9254 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9255 9256 return SDValue(); 9257 } 9258 9259 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9260 SDValue N0 = N->getOperand(0); 9261 EVT VT = N->getValueType(0); 9262 9263 // fold (ftrunc c1) -> ftrunc(c1) 9264 if (isConstantFPBuildVectorOrConstantFP(N0)) 9265 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9266 9267 return SDValue(); 9268 } 9269 9270 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9271 SDValue N0 = N->getOperand(0); 9272 EVT VT = N->getValueType(0); 9273 9274 // fold (ffloor c1) -> ffloor(c1) 9275 if (isConstantFPBuildVectorOrConstantFP(N0)) 9276 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9277 9278 return SDValue(); 9279 } 9280 9281 // FIXME: FNEG and FABS have a lot in common; refactor. 9282 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9283 SDValue N0 = N->getOperand(0); 9284 EVT VT = N->getValueType(0); 9285 9286 // Constant fold FNEG. 9287 if (isConstantFPBuildVectorOrConstantFP(N0)) 9288 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9289 9290 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9291 &DAG.getTarget().Options)) 9292 return GetNegatedExpression(N0, DAG, LegalOperations); 9293 9294 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9295 // constant pool values. 9296 if (!TLI.isFNegFree(VT) && 9297 N0.getOpcode() == ISD::BITCAST && 9298 N0.getNode()->hasOneUse()) { 9299 SDValue Int = N0.getOperand(0); 9300 EVT IntVT = Int.getValueType(); 9301 if (IntVT.isInteger() && !IntVT.isVector()) { 9302 APInt SignMask; 9303 if (N0.getValueType().isVector()) { 9304 // For a vector, get a mask such as 0x80... per scalar element 9305 // and splat it. 9306 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9307 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9308 } else { 9309 // For a scalar, just generate 0x80... 9310 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9311 } 9312 SDLoc DL0(N0); 9313 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9314 DAG.getConstant(SignMask, DL0, IntVT)); 9315 AddToWorklist(Int.getNode()); 9316 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9317 } 9318 } 9319 9320 // (fneg (fmul c, x)) -> (fmul -c, x) 9321 if (N0.getOpcode() == ISD::FMUL && 9322 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9323 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9324 if (CFP1) { 9325 APFloat CVal = CFP1->getValueAPF(); 9326 CVal.changeSign(); 9327 if (Level >= AfterLegalizeDAG && 9328 (TLI.isFPImmLegal(CVal, VT) || 9329 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9330 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9331 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9332 N0.getOperand(1)), 9333 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9334 } 9335 } 9336 9337 return SDValue(); 9338 } 9339 9340 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9341 SDValue N0 = N->getOperand(0); 9342 SDValue N1 = N->getOperand(1); 9343 EVT VT = N->getValueType(0); 9344 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9345 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9346 9347 if (N0CFP && N1CFP) { 9348 const APFloat &C0 = N0CFP->getValueAPF(); 9349 const APFloat &C1 = N1CFP->getValueAPF(); 9350 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9351 } 9352 9353 // Canonicalize to constant on RHS. 9354 if (isConstantFPBuildVectorOrConstantFP(N0) && 9355 !isConstantFPBuildVectorOrConstantFP(N1)) 9356 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9357 9358 return SDValue(); 9359 } 9360 9361 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9362 SDValue N0 = N->getOperand(0); 9363 SDValue N1 = N->getOperand(1); 9364 EVT VT = N->getValueType(0); 9365 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9366 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9367 9368 if (N0CFP && N1CFP) { 9369 const APFloat &C0 = N0CFP->getValueAPF(); 9370 const APFloat &C1 = N1CFP->getValueAPF(); 9371 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9372 } 9373 9374 // Canonicalize to constant on RHS. 9375 if (isConstantFPBuildVectorOrConstantFP(N0) && 9376 !isConstantFPBuildVectorOrConstantFP(N1)) 9377 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9378 9379 return SDValue(); 9380 } 9381 9382 SDValue DAGCombiner::visitFABS(SDNode *N) { 9383 SDValue N0 = N->getOperand(0); 9384 EVT VT = N->getValueType(0); 9385 9386 // fold (fabs c1) -> fabs(c1) 9387 if (isConstantFPBuildVectorOrConstantFP(N0)) 9388 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9389 9390 // fold (fabs (fabs x)) -> (fabs x) 9391 if (N0.getOpcode() == ISD::FABS) 9392 return N->getOperand(0); 9393 9394 // fold (fabs (fneg x)) -> (fabs x) 9395 // fold (fabs (fcopysign x, y)) -> (fabs x) 9396 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9397 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9398 9399 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9400 // constant pool values. 9401 if (!TLI.isFAbsFree(VT) && 9402 N0.getOpcode() == ISD::BITCAST && 9403 N0.getNode()->hasOneUse()) { 9404 SDValue Int = N0.getOperand(0); 9405 EVT IntVT = Int.getValueType(); 9406 if (IntVT.isInteger() && !IntVT.isVector()) { 9407 APInt SignMask; 9408 if (N0.getValueType().isVector()) { 9409 // For a vector, get a mask such as 0x7f... per scalar element 9410 // and splat it. 9411 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9412 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9413 } else { 9414 // For a scalar, just generate 0x7f... 9415 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9416 } 9417 SDLoc DL(N0); 9418 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9419 DAG.getConstant(SignMask, DL, IntVT)); 9420 AddToWorklist(Int.getNode()); 9421 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9422 } 9423 } 9424 9425 return SDValue(); 9426 } 9427 9428 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9429 SDValue Chain = N->getOperand(0); 9430 SDValue N1 = N->getOperand(1); 9431 SDValue N2 = N->getOperand(2); 9432 9433 // If N is a constant we could fold this into a fallthrough or unconditional 9434 // branch. However that doesn't happen very often in normal code, because 9435 // Instcombine/SimplifyCFG should have handled the available opportunities. 9436 // If we did this folding here, it would be necessary to update the 9437 // MachineBasicBlock CFG, which is awkward. 9438 9439 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9440 // on the target. 9441 if (N1.getOpcode() == ISD::SETCC && 9442 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9443 N1.getOperand(0).getValueType())) { 9444 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9445 Chain, N1.getOperand(2), 9446 N1.getOperand(0), N1.getOperand(1), N2); 9447 } 9448 9449 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9450 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9451 (N1.getOperand(0).hasOneUse() && 9452 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9453 SDNode *Trunc = nullptr; 9454 if (N1.getOpcode() == ISD::TRUNCATE) { 9455 // Look pass the truncate. 9456 Trunc = N1.getNode(); 9457 N1 = N1.getOperand(0); 9458 } 9459 9460 // Match this pattern so that we can generate simpler code: 9461 // 9462 // %a = ... 9463 // %b = and i32 %a, 2 9464 // %c = srl i32 %b, 1 9465 // brcond i32 %c ... 9466 // 9467 // into 9468 // 9469 // %a = ... 9470 // %b = and i32 %a, 2 9471 // %c = setcc eq %b, 0 9472 // brcond %c ... 9473 // 9474 // This applies only when the AND constant value has one bit set and the 9475 // SRL constant is equal to the log2 of the AND constant. The back-end is 9476 // smart enough to convert the result into a TEST/JMP sequence. 9477 SDValue Op0 = N1.getOperand(0); 9478 SDValue Op1 = N1.getOperand(1); 9479 9480 if (Op0.getOpcode() == ISD::AND && 9481 Op1.getOpcode() == ISD::Constant) { 9482 SDValue AndOp1 = Op0.getOperand(1); 9483 9484 if (AndOp1.getOpcode() == ISD::Constant) { 9485 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9486 9487 if (AndConst.isPowerOf2() && 9488 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9489 SDLoc DL(N); 9490 SDValue SetCC = 9491 DAG.getSetCC(DL, 9492 getSetCCResultType(Op0.getValueType()), 9493 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9494 ISD::SETNE); 9495 9496 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9497 MVT::Other, Chain, SetCC, N2); 9498 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9499 // will convert it back to (X & C1) >> C2. 9500 CombineTo(N, NewBRCond, false); 9501 // Truncate is dead. 9502 if (Trunc) 9503 deleteAndRecombine(Trunc); 9504 // Replace the uses of SRL with SETCC 9505 WorklistRemover DeadNodes(*this); 9506 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9507 deleteAndRecombine(N1.getNode()); 9508 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9509 } 9510 } 9511 } 9512 9513 if (Trunc) 9514 // Restore N1 if the above transformation doesn't match. 9515 N1 = N->getOperand(1); 9516 } 9517 9518 // Transform br(xor(x, y)) -> br(x != y) 9519 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9520 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9521 SDNode *TheXor = N1.getNode(); 9522 SDValue Op0 = TheXor->getOperand(0); 9523 SDValue Op1 = TheXor->getOperand(1); 9524 if (Op0.getOpcode() == Op1.getOpcode()) { 9525 // Avoid missing important xor optimizations. 9526 if (SDValue Tmp = visitXOR(TheXor)) { 9527 if (Tmp.getNode() != TheXor) { 9528 DEBUG(dbgs() << "\nReplacing.8 "; 9529 TheXor->dump(&DAG); 9530 dbgs() << "\nWith: "; 9531 Tmp.getNode()->dump(&DAG); 9532 dbgs() << '\n'); 9533 WorklistRemover DeadNodes(*this); 9534 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9535 deleteAndRecombine(TheXor); 9536 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9537 MVT::Other, Chain, Tmp, N2); 9538 } 9539 9540 // visitXOR has changed XOR's operands or replaced the XOR completely, 9541 // bail out. 9542 return SDValue(N, 0); 9543 } 9544 } 9545 9546 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9547 bool Equal = false; 9548 if (isOneConstant(Op0) && Op0.hasOneUse() && 9549 Op0.getOpcode() == ISD::XOR) { 9550 TheXor = Op0.getNode(); 9551 Equal = true; 9552 } 9553 9554 EVT SetCCVT = N1.getValueType(); 9555 if (LegalTypes) 9556 SetCCVT = getSetCCResultType(SetCCVT); 9557 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9558 SetCCVT, 9559 Op0, Op1, 9560 Equal ? ISD::SETEQ : ISD::SETNE); 9561 // Replace the uses of XOR with SETCC 9562 WorklistRemover DeadNodes(*this); 9563 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9564 deleteAndRecombine(N1.getNode()); 9565 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9566 MVT::Other, Chain, SetCC, N2); 9567 } 9568 } 9569 9570 return SDValue(); 9571 } 9572 9573 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9574 // 9575 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9576 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9577 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9578 9579 // If N is a constant we could fold this into a fallthrough or unconditional 9580 // branch. However that doesn't happen very often in normal code, because 9581 // Instcombine/SimplifyCFG should have handled the available opportunities. 9582 // If we did this folding here, it would be necessary to update the 9583 // MachineBasicBlock CFG, which is awkward. 9584 9585 // Use SimplifySetCC to simplify SETCC's. 9586 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9587 CondLHS, CondRHS, CC->get(), SDLoc(N), 9588 false); 9589 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9590 9591 // fold to a simpler setcc 9592 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9593 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9594 N->getOperand(0), Simp.getOperand(2), 9595 Simp.getOperand(0), Simp.getOperand(1), 9596 N->getOperand(4)); 9597 9598 return SDValue(); 9599 } 9600 9601 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9602 /// and that N may be folded in the load / store addressing mode. 9603 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9604 SelectionDAG &DAG, 9605 const TargetLowering &TLI) { 9606 EVT VT; 9607 unsigned AS; 9608 9609 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9610 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9611 return false; 9612 VT = LD->getMemoryVT(); 9613 AS = LD->getAddressSpace(); 9614 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9615 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9616 return false; 9617 VT = ST->getMemoryVT(); 9618 AS = ST->getAddressSpace(); 9619 } else 9620 return false; 9621 9622 TargetLowering::AddrMode AM; 9623 if (N->getOpcode() == ISD::ADD) { 9624 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9625 if (Offset) 9626 // [reg +/- imm] 9627 AM.BaseOffs = Offset->getSExtValue(); 9628 else 9629 // [reg +/- reg] 9630 AM.Scale = 1; 9631 } else if (N->getOpcode() == ISD::SUB) { 9632 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9633 if (Offset) 9634 // [reg +/- imm] 9635 AM.BaseOffs = -Offset->getSExtValue(); 9636 else 9637 // [reg +/- reg] 9638 AM.Scale = 1; 9639 } else 9640 return false; 9641 9642 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9643 VT.getTypeForEVT(*DAG.getContext()), AS); 9644 } 9645 9646 /// Try turning a load/store into a pre-indexed load/store when the base 9647 /// pointer is an add or subtract and it has other uses besides the load/store. 9648 /// After the transformation, the new indexed load/store has effectively folded 9649 /// the add/subtract in and all of its other uses are redirected to the 9650 /// new load/store. 9651 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9652 if (Level < AfterLegalizeDAG) 9653 return false; 9654 9655 bool isLoad = true; 9656 SDValue Ptr; 9657 EVT VT; 9658 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9659 if (LD->isIndexed()) 9660 return false; 9661 VT = LD->getMemoryVT(); 9662 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9663 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9664 return false; 9665 Ptr = LD->getBasePtr(); 9666 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9667 if (ST->isIndexed()) 9668 return false; 9669 VT = ST->getMemoryVT(); 9670 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9671 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9672 return false; 9673 Ptr = ST->getBasePtr(); 9674 isLoad = false; 9675 } else { 9676 return false; 9677 } 9678 9679 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9680 // out. There is no reason to make this a preinc/predec. 9681 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9682 Ptr.getNode()->hasOneUse()) 9683 return false; 9684 9685 // Ask the target to do addressing mode selection. 9686 SDValue BasePtr; 9687 SDValue Offset; 9688 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9689 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9690 return false; 9691 9692 // Backends without true r+i pre-indexed forms may need to pass a 9693 // constant base with a variable offset so that constant coercion 9694 // will work with the patterns in canonical form. 9695 bool Swapped = false; 9696 if (isa<ConstantSDNode>(BasePtr)) { 9697 std::swap(BasePtr, Offset); 9698 Swapped = true; 9699 } 9700 9701 // Don't create a indexed load / store with zero offset. 9702 if (isNullConstant(Offset)) 9703 return false; 9704 9705 // Try turning it into a pre-indexed load / store except when: 9706 // 1) The new base ptr is a frame index. 9707 // 2) If N is a store and the new base ptr is either the same as or is a 9708 // predecessor of the value being stored. 9709 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9710 // that would create a cycle. 9711 // 4) All uses are load / store ops that use it as old base ptr. 9712 9713 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9714 // (plus the implicit offset) to a register to preinc anyway. 9715 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9716 return false; 9717 9718 // Check #2. 9719 if (!isLoad) { 9720 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9721 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9722 return false; 9723 } 9724 9725 // Caches for hasPredecessorHelper. 9726 SmallPtrSet<const SDNode *, 32> Visited; 9727 SmallVector<const SDNode *, 16> Worklist; 9728 Worklist.push_back(N); 9729 9730 // If the offset is a constant, there may be other adds of constants that 9731 // can be folded with this one. We should do this to avoid having to keep 9732 // a copy of the original base pointer. 9733 SmallVector<SDNode *, 16> OtherUses; 9734 if (isa<ConstantSDNode>(Offset)) 9735 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9736 UE = BasePtr.getNode()->use_end(); 9737 UI != UE; ++UI) { 9738 SDUse &Use = UI.getUse(); 9739 // Skip the use that is Ptr and uses of other results from BasePtr's 9740 // node (important for nodes that return multiple results). 9741 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9742 continue; 9743 9744 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9745 continue; 9746 9747 if (Use.getUser()->getOpcode() != ISD::ADD && 9748 Use.getUser()->getOpcode() != ISD::SUB) { 9749 OtherUses.clear(); 9750 break; 9751 } 9752 9753 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9754 if (!isa<ConstantSDNode>(Op1)) { 9755 OtherUses.clear(); 9756 break; 9757 } 9758 9759 // FIXME: In some cases, we can be smarter about this. 9760 if (Op1.getValueType() != Offset.getValueType()) { 9761 OtherUses.clear(); 9762 break; 9763 } 9764 9765 OtherUses.push_back(Use.getUser()); 9766 } 9767 9768 if (Swapped) 9769 std::swap(BasePtr, Offset); 9770 9771 // Now check for #3 and #4. 9772 bool RealUse = false; 9773 9774 for (SDNode *Use : Ptr.getNode()->uses()) { 9775 if (Use == N) 9776 continue; 9777 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9778 return false; 9779 9780 // If Ptr may be folded in addressing mode of other use, then it's 9781 // not profitable to do this transformation. 9782 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9783 RealUse = true; 9784 } 9785 9786 if (!RealUse) 9787 return false; 9788 9789 SDValue Result; 9790 if (isLoad) 9791 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9792 BasePtr, Offset, AM); 9793 else 9794 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9795 BasePtr, Offset, AM); 9796 ++PreIndexedNodes; 9797 ++NodesCombined; 9798 DEBUG(dbgs() << "\nReplacing.4 "; 9799 N->dump(&DAG); 9800 dbgs() << "\nWith: "; 9801 Result.getNode()->dump(&DAG); 9802 dbgs() << '\n'); 9803 WorklistRemover DeadNodes(*this); 9804 if (isLoad) { 9805 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9806 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9807 } else { 9808 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9809 } 9810 9811 // Finally, since the node is now dead, remove it from the graph. 9812 deleteAndRecombine(N); 9813 9814 if (Swapped) 9815 std::swap(BasePtr, Offset); 9816 9817 // Replace other uses of BasePtr that can be updated to use Ptr 9818 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9819 unsigned OffsetIdx = 1; 9820 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9821 OffsetIdx = 0; 9822 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9823 BasePtr.getNode() && "Expected BasePtr operand"); 9824 9825 // We need to replace ptr0 in the following expression: 9826 // x0 * offset0 + y0 * ptr0 = t0 9827 // knowing that 9828 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9829 // 9830 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9831 // indexed load/store and the expresion that needs to be re-written. 9832 // 9833 // Therefore, we have: 9834 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9835 9836 ConstantSDNode *CN = 9837 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9838 int X0, X1, Y0, Y1; 9839 APInt Offset0 = CN->getAPIntValue(); 9840 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9841 9842 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9843 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9844 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9845 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9846 9847 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9848 9849 APInt CNV = Offset0; 9850 if (X0 < 0) CNV = -CNV; 9851 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9852 else CNV = CNV - Offset1; 9853 9854 SDLoc DL(OtherUses[i]); 9855 9856 // We can now generate the new expression. 9857 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9858 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9859 9860 SDValue NewUse = DAG.getNode(Opcode, 9861 DL, 9862 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9863 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9864 deleteAndRecombine(OtherUses[i]); 9865 } 9866 9867 // Replace the uses of Ptr with uses of the updated base value. 9868 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9869 deleteAndRecombine(Ptr.getNode()); 9870 9871 return true; 9872 } 9873 9874 /// Try to combine a load/store with a add/sub of the base pointer node into a 9875 /// post-indexed load/store. The transformation folded the add/subtract into the 9876 /// new indexed load/store effectively and all of its uses are redirected to the 9877 /// new load/store. 9878 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9879 if (Level < AfterLegalizeDAG) 9880 return false; 9881 9882 bool isLoad = true; 9883 SDValue Ptr; 9884 EVT VT; 9885 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9886 if (LD->isIndexed()) 9887 return false; 9888 VT = LD->getMemoryVT(); 9889 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9890 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9891 return false; 9892 Ptr = LD->getBasePtr(); 9893 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9894 if (ST->isIndexed()) 9895 return false; 9896 VT = ST->getMemoryVT(); 9897 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9898 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9899 return false; 9900 Ptr = ST->getBasePtr(); 9901 isLoad = false; 9902 } else { 9903 return false; 9904 } 9905 9906 if (Ptr.getNode()->hasOneUse()) 9907 return false; 9908 9909 for (SDNode *Op : Ptr.getNode()->uses()) { 9910 if (Op == N || 9911 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9912 continue; 9913 9914 SDValue BasePtr; 9915 SDValue Offset; 9916 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9917 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9918 // Don't create a indexed load / store with zero offset. 9919 if (isNullConstant(Offset)) 9920 continue; 9921 9922 // Try turning it into a post-indexed load / store except when 9923 // 1) All uses are load / store ops that use it as base ptr (and 9924 // it may be folded as addressing mmode). 9925 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9926 // nor a successor of N. Otherwise, if Op is folded that would 9927 // create a cycle. 9928 9929 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9930 continue; 9931 9932 // Check for #1. 9933 bool TryNext = false; 9934 for (SDNode *Use : BasePtr.getNode()->uses()) { 9935 if (Use == Ptr.getNode()) 9936 continue; 9937 9938 // If all the uses are load / store addresses, then don't do the 9939 // transformation. 9940 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9941 bool RealUse = false; 9942 for (SDNode *UseUse : Use->uses()) { 9943 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9944 RealUse = true; 9945 } 9946 9947 if (!RealUse) { 9948 TryNext = true; 9949 break; 9950 } 9951 } 9952 } 9953 9954 if (TryNext) 9955 continue; 9956 9957 // Check for #2 9958 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9959 SDValue Result = isLoad 9960 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9961 BasePtr, Offset, AM) 9962 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9963 BasePtr, Offset, AM); 9964 ++PostIndexedNodes; 9965 ++NodesCombined; 9966 DEBUG(dbgs() << "\nReplacing.5 "; 9967 N->dump(&DAG); 9968 dbgs() << "\nWith: "; 9969 Result.getNode()->dump(&DAG); 9970 dbgs() << '\n'); 9971 WorklistRemover DeadNodes(*this); 9972 if (isLoad) { 9973 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9974 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9975 } else { 9976 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9977 } 9978 9979 // Finally, since the node is now dead, remove it from the graph. 9980 deleteAndRecombine(N); 9981 9982 // Replace the uses of Use with uses of the updated base value. 9983 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9984 Result.getValue(isLoad ? 1 : 0)); 9985 deleteAndRecombine(Op); 9986 return true; 9987 } 9988 } 9989 } 9990 9991 return false; 9992 } 9993 9994 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9995 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9996 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9997 assert(AM != ISD::UNINDEXED); 9998 SDValue BP = LD->getOperand(1); 9999 SDValue Inc = LD->getOperand(2); 10000 10001 // Some backends use TargetConstants for load offsets, but don't expect 10002 // TargetConstants in general ADD nodes. We can convert these constants into 10003 // regular Constants (if the constant is not opaque). 10004 assert((Inc.getOpcode() != ISD::TargetConstant || 10005 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10006 "Cannot split out indexing using opaque target constants"); 10007 if (Inc.getOpcode() == ISD::TargetConstant) { 10008 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10009 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10010 ConstInc->getValueType(0)); 10011 } 10012 10013 unsigned Opc = 10014 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10015 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10016 } 10017 10018 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10019 LoadSDNode *LD = cast<LoadSDNode>(N); 10020 SDValue Chain = LD->getChain(); 10021 SDValue Ptr = LD->getBasePtr(); 10022 10023 // If load is not volatile and there are no uses of the loaded value (and 10024 // the updated indexed value in case of indexed loads), change uses of the 10025 // chain value into uses of the chain input (i.e. delete the dead load). 10026 if (!LD->isVolatile()) { 10027 if (N->getValueType(1) == MVT::Other) { 10028 // Unindexed loads. 10029 if (!N->hasAnyUseOfValue(0)) { 10030 // It's not safe to use the two value CombineTo variant here. e.g. 10031 // v1, chain2 = load chain1, loc 10032 // v2, chain3 = load chain2, loc 10033 // v3 = add v2, c 10034 // Now we replace use of chain2 with chain1. This makes the second load 10035 // isomorphic to the one we are deleting, and thus makes this load live. 10036 DEBUG(dbgs() << "\nReplacing.6 "; 10037 N->dump(&DAG); 10038 dbgs() << "\nWith chain: "; 10039 Chain.getNode()->dump(&DAG); 10040 dbgs() << "\n"); 10041 WorklistRemover DeadNodes(*this); 10042 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10043 10044 if (N->use_empty()) 10045 deleteAndRecombine(N); 10046 10047 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10048 } 10049 } else { 10050 // Indexed loads. 10051 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10052 10053 // If this load has an opaque TargetConstant offset, then we cannot split 10054 // the indexing into an add/sub directly (that TargetConstant may not be 10055 // valid for a different type of node, and we cannot convert an opaque 10056 // target constant into a regular constant). 10057 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10058 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10059 10060 if (!N->hasAnyUseOfValue(0) && 10061 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10062 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10063 SDValue Index; 10064 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10065 Index = SplitIndexingFromLoad(LD); 10066 // Try to fold the base pointer arithmetic into subsequent loads and 10067 // stores. 10068 AddUsersToWorklist(N); 10069 } else 10070 Index = DAG.getUNDEF(N->getValueType(1)); 10071 DEBUG(dbgs() << "\nReplacing.7 "; 10072 N->dump(&DAG); 10073 dbgs() << "\nWith: "; 10074 Undef.getNode()->dump(&DAG); 10075 dbgs() << " and 2 other values\n"); 10076 WorklistRemover DeadNodes(*this); 10077 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10078 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10079 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10080 deleteAndRecombine(N); 10081 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10082 } 10083 } 10084 } 10085 10086 // If this load is directly stored, replace the load value with the stored 10087 // value. 10088 // TODO: Handle store large -> read small portion. 10089 // TODO: Handle TRUNCSTORE/LOADEXT 10090 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 10091 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10092 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10093 if (PrevST->getBasePtr() == Ptr && 10094 PrevST->getValue().getValueType() == N->getValueType(0)) 10095 return CombineTo(N, Chain.getOperand(1), Chain); 10096 } 10097 } 10098 10099 // Try to infer better alignment information than the load already has. 10100 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10101 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10102 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10103 SDValue NewLoad = 10104 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 10105 LD->getValueType(0), 10106 Chain, Ptr, LD->getPointerInfo(), 10107 LD->getMemoryVT(), 10108 LD->isVolatile(), LD->isNonTemporal(), 10109 LD->isInvariant(), Align, LD->getAAInfo()); 10110 if (NewLoad.getNode() != N) 10111 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10112 } 10113 } 10114 } 10115 10116 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10117 : DAG.getSubtarget().useAA(); 10118 #ifndef NDEBUG 10119 if (CombinerAAOnlyFunc.getNumOccurrences() && 10120 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10121 UseAA = false; 10122 #endif 10123 if (UseAA && LD->isUnindexed()) { 10124 // Walk up chain skipping non-aliasing memory nodes. 10125 SDValue BetterChain = FindBetterChain(N, Chain); 10126 10127 // If there is a better chain. 10128 if (Chain != BetterChain) { 10129 SDValue ReplLoad; 10130 10131 // Replace the chain to void dependency. 10132 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10133 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10134 BetterChain, Ptr, LD->getMemOperand()); 10135 } else { 10136 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10137 LD->getValueType(0), 10138 BetterChain, Ptr, LD->getMemoryVT(), 10139 LD->getMemOperand()); 10140 } 10141 10142 // Create token factor to keep old chain connected. 10143 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10144 MVT::Other, Chain, ReplLoad.getValue(1)); 10145 10146 // Make sure the new and old chains are cleaned up. 10147 AddToWorklist(Token.getNode()); 10148 10149 // Replace uses with load result and token factor. Don't add users 10150 // to work list. 10151 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10152 } 10153 } 10154 10155 // Try transforming N to an indexed load. 10156 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10157 return SDValue(N, 0); 10158 10159 // Try to slice up N to more direct loads if the slices are mapped to 10160 // different register banks or pairing can take place. 10161 if (SliceUpLoad(N)) 10162 return SDValue(N, 0); 10163 10164 return SDValue(); 10165 } 10166 10167 namespace { 10168 /// \brief Helper structure used to slice a load in smaller loads. 10169 /// Basically a slice is obtained from the following sequence: 10170 /// Origin = load Ty1, Base 10171 /// Shift = srl Ty1 Origin, CstTy Amount 10172 /// Inst = trunc Shift to Ty2 10173 /// 10174 /// Then, it will be rewriten into: 10175 /// Slice = load SliceTy, Base + SliceOffset 10176 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10177 /// 10178 /// SliceTy is deduced from the number of bits that are actually used to 10179 /// build Inst. 10180 struct LoadedSlice { 10181 /// \brief Helper structure used to compute the cost of a slice. 10182 struct Cost { 10183 /// Are we optimizing for code size. 10184 bool ForCodeSize; 10185 /// Various cost. 10186 unsigned Loads; 10187 unsigned Truncates; 10188 unsigned CrossRegisterBanksCopies; 10189 unsigned ZExts; 10190 unsigned Shift; 10191 10192 Cost(bool ForCodeSize = false) 10193 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10194 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10195 10196 /// \brief Get the cost of one isolated slice. 10197 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10198 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10199 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10200 EVT TruncType = LS.Inst->getValueType(0); 10201 EVT LoadedType = LS.getLoadedType(); 10202 if (TruncType != LoadedType && 10203 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10204 ZExts = 1; 10205 } 10206 10207 /// \brief Account for slicing gain in the current cost. 10208 /// Slicing provide a few gains like removing a shift or a 10209 /// truncate. This method allows to grow the cost of the original 10210 /// load with the gain from this slice. 10211 void addSliceGain(const LoadedSlice &LS) { 10212 // Each slice saves a truncate. 10213 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10214 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10215 LS.Inst->getValueType(0))) 10216 ++Truncates; 10217 // If there is a shift amount, this slice gets rid of it. 10218 if (LS.Shift) 10219 ++Shift; 10220 // If this slice can merge a cross register bank copy, account for it. 10221 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10222 ++CrossRegisterBanksCopies; 10223 } 10224 10225 Cost &operator+=(const Cost &RHS) { 10226 Loads += RHS.Loads; 10227 Truncates += RHS.Truncates; 10228 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10229 ZExts += RHS.ZExts; 10230 Shift += RHS.Shift; 10231 return *this; 10232 } 10233 10234 bool operator==(const Cost &RHS) const { 10235 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10236 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10237 ZExts == RHS.ZExts && Shift == RHS.Shift; 10238 } 10239 10240 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10241 10242 bool operator<(const Cost &RHS) const { 10243 // Assume cross register banks copies are as expensive as loads. 10244 // FIXME: Do we want some more target hooks? 10245 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10246 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10247 // Unless we are optimizing for code size, consider the 10248 // expensive operation first. 10249 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10250 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10251 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10252 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10253 } 10254 10255 bool operator>(const Cost &RHS) const { return RHS < *this; } 10256 10257 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10258 10259 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10260 }; 10261 // The last instruction that represent the slice. This should be a 10262 // truncate instruction. 10263 SDNode *Inst; 10264 // The original load instruction. 10265 LoadSDNode *Origin; 10266 // The right shift amount in bits from the original load. 10267 unsigned Shift; 10268 // The DAG from which Origin came from. 10269 // This is used to get some contextual information about legal types, etc. 10270 SelectionDAG *DAG; 10271 10272 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10273 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10274 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10275 10276 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10277 /// \return Result is \p BitWidth and has used bits set to 1 and 10278 /// not used bits set to 0. 10279 APInt getUsedBits() const { 10280 // Reproduce the trunc(lshr) sequence: 10281 // - Start from the truncated value. 10282 // - Zero extend to the desired bit width. 10283 // - Shift left. 10284 assert(Origin && "No original load to compare against."); 10285 unsigned BitWidth = Origin->getValueSizeInBits(0); 10286 assert(Inst && "This slice is not bound to an instruction"); 10287 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10288 "Extracted slice is bigger than the whole type!"); 10289 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10290 UsedBits.setAllBits(); 10291 UsedBits = UsedBits.zext(BitWidth); 10292 UsedBits <<= Shift; 10293 return UsedBits; 10294 } 10295 10296 /// \brief Get the size of the slice to be loaded in bytes. 10297 unsigned getLoadedSize() const { 10298 unsigned SliceSize = getUsedBits().countPopulation(); 10299 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10300 return SliceSize / 8; 10301 } 10302 10303 /// \brief Get the type that will be loaded for this slice. 10304 /// Note: This may not be the final type for the slice. 10305 EVT getLoadedType() const { 10306 assert(DAG && "Missing context"); 10307 LLVMContext &Ctxt = *DAG->getContext(); 10308 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10309 } 10310 10311 /// \brief Get the alignment of the load used for this slice. 10312 unsigned getAlignment() const { 10313 unsigned Alignment = Origin->getAlignment(); 10314 unsigned Offset = getOffsetFromBase(); 10315 if (Offset != 0) 10316 Alignment = MinAlign(Alignment, Alignment + Offset); 10317 return Alignment; 10318 } 10319 10320 /// \brief Check if this slice can be rewritten with legal operations. 10321 bool isLegal() const { 10322 // An invalid slice is not legal. 10323 if (!Origin || !Inst || !DAG) 10324 return false; 10325 10326 // Offsets are for indexed load only, we do not handle that. 10327 if (!Origin->getOffset().isUndef()) 10328 return false; 10329 10330 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10331 10332 // Check that the type is legal. 10333 EVT SliceType = getLoadedType(); 10334 if (!TLI.isTypeLegal(SliceType)) 10335 return false; 10336 10337 // Check that the load is legal for this type. 10338 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10339 return false; 10340 10341 // Check that the offset can be computed. 10342 // 1. Check its type. 10343 EVT PtrType = Origin->getBasePtr().getValueType(); 10344 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10345 return false; 10346 10347 // 2. Check that it fits in the immediate. 10348 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10349 return false; 10350 10351 // 3. Check that the computation is legal. 10352 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10353 return false; 10354 10355 // Check that the zext is legal if it needs one. 10356 EVT TruncateType = Inst->getValueType(0); 10357 if (TruncateType != SliceType && 10358 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10359 return false; 10360 10361 return true; 10362 } 10363 10364 /// \brief Get the offset in bytes of this slice in the original chunk of 10365 /// bits. 10366 /// \pre DAG != nullptr. 10367 uint64_t getOffsetFromBase() const { 10368 assert(DAG && "Missing context."); 10369 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10370 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10371 uint64_t Offset = Shift / 8; 10372 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10373 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10374 "The size of the original loaded type is not a multiple of a" 10375 " byte."); 10376 // If Offset is bigger than TySizeInBytes, it means we are loading all 10377 // zeros. This should have been optimized before in the process. 10378 assert(TySizeInBytes > Offset && 10379 "Invalid shift amount for given loaded size"); 10380 if (IsBigEndian) 10381 Offset = TySizeInBytes - Offset - getLoadedSize(); 10382 return Offset; 10383 } 10384 10385 /// \brief Generate the sequence of instructions to load the slice 10386 /// represented by this object and redirect the uses of this slice to 10387 /// this new sequence of instructions. 10388 /// \pre this->Inst && this->Origin are valid Instructions and this 10389 /// object passed the legal check: LoadedSlice::isLegal returned true. 10390 /// \return The last instruction of the sequence used to load the slice. 10391 SDValue loadSlice() const { 10392 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10393 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10394 SDValue BaseAddr = OldBaseAddr; 10395 // Get the offset in that chunk of bytes w.r.t. the endianess. 10396 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10397 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10398 if (Offset) { 10399 // BaseAddr = BaseAddr + Offset. 10400 EVT ArithType = BaseAddr.getValueType(); 10401 SDLoc DL(Origin); 10402 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10403 DAG->getConstant(Offset, DL, ArithType)); 10404 } 10405 10406 // Create the type of the loaded slice according to its size. 10407 EVT SliceType = getLoadedType(); 10408 10409 // Create the load for the slice. 10410 SDValue LastInst = DAG->getLoad( 10411 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10412 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10413 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10414 // If the final type is not the same as the loaded type, this means that 10415 // we have to pad with zero. Create a zero extend for that. 10416 EVT FinalType = Inst->getValueType(0); 10417 if (SliceType != FinalType) 10418 LastInst = 10419 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10420 return LastInst; 10421 } 10422 10423 /// \brief Check if this slice can be merged with an expensive cross register 10424 /// bank copy. E.g., 10425 /// i = load i32 10426 /// f = bitcast i32 i to float 10427 bool canMergeExpensiveCrossRegisterBankCopy() const { 10428 if (!Inst || !Inst->hasOneUse()) 10429 return false; 10430 SDNode *Use = *Inst->use_begin(); 10431 if (Use->getOpcode() != ISD::BITCAST) 10432 return false; 10433 assert(DAG && "Missing context"); 10434 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10435 EVT ResVT = Use->getValueType(0); 10436 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10437 const TargetRegisterClass *ArgRC = 10438 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10439 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10440 return false; 10441 10442 // At this point, we know that we perform a cross-register-bank copy. 10443 // Check if it is expensive. 10444 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10445 // Assume bitcasts are cheap, unless both register classes do not 10446 // explicitly share a common sub class. 10447 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10448 return false; 10449 10450 // Check if it will be merged with the load. 10451 // 1. Check the alignment constraint. 10452 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10453 ResVT.getTypeForEVT(*DAG->getContext())); 10454 10455 if (RequiredAlignment > getAlignment()) 10456 return false; 10457 10458 // 2. Check that the load is a legal operation for that type. 10459 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10460 return false; 10461 10462 // 3. Check that we do not have a zext in the way. 10463 if (Inst->getValueType(0) != getLoadedType()) 10464 return false; 10465 10466 return true; 10467 } 10468 }; 10469 } 10470 10471 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10472 /// \p UsedBits looks like 0..0 1..1 0..0. 10473 static bool areUsedBitsDense(const APInt &UsedBits) { 10474 // If all the bits are one, this is dense! 10475 if (UsedBits.isAllOnesValue()) 10476 return true; 10477 10478 // Get rid of the unused bits on the right. 10479 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10480 // Get rid of the unused bits on the left. 10481 if (NarrowedUsedBits.countLeadingZeros()) 10482 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10483 // Check that the chunk of bits is completely used. 10484 return NarrowedUsedBits.isAllOnesValue(); 10485 } 10486 10487 /// \brief Check whether or not \p First and \p Second are next to each other 10488 /// in memory. This means that there is no hole between the bits loaded 10489 /// by \p First and the bits loaded by \p Second. 10490 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10491 const LoadedSlice &Second) { 10492 assert(First.Origin == Second.Origin && First.Origin && 10493 "Unable to match different memory origins."); 10494 APInt UsedBits = First.getUsedBits(); 10495 assert((UsedBits & Second.getUsedBits()) == 0 && 10496 "Slices are not supposed to overlap."); 10497 UsedBits |= Second.getUsedBits(); 10498 return areUsedBitsDense(UsedBits); 10499 } 10500 10501 /// \brief Adjust the \p GlobalLSCost according to the target 10502 /// paring capabilities and the layout of the slices. 10503 /// \pre \p GlobalLSCost should account for at least as many loads as 10504 /// there is in the slices in \p LoadedSlices. 10505 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10506 LoadedSlice::Cost &GlobalLSCost) { 10507 unsigned NumberOfSlices = LoadedSlices.size(); 10508 // If there is less than 2 elements, no pairing is possible. 10509 if (NumberOfSlices < 2) 10510 return; 10511 10512 // Sort the slices so that elements that are likely to be next to each 10513 // other in memory are next to each other in the list. 10514 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10515 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10516 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10517 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10518 }); 10519 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10520 // First (resp. Second) is the first (resp. Second) potentially candidate 10521 // to be placed in a paired load. 10522 const LoadedSlice *First = nullptr; 10523 const LoadedSlice *Second = nullptr; 10524 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10525 // Set the beginning of the pair. 10526 First = Second) { 10527 10528 Second = &LoadedSlices[CurrSlice]; 10529 10530 // If First is NULL, it means we start a new pair. 10531 // Get to the next slice. 10532 if (!First) 10533 continue; 10534 10535 EVT LoadedType = First->getLoadedType(); 10536 10537 // If the types of the slices are different, we cannot pair them. 10538 if (LoadedType != Second->getLoadedType()) 10539 continue; 10540 10541 // Check if the target supplies paired loads for this type. 10542 unsigned RequiredAlignment = 0; 10543 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10544 // move to the next pair, this type is hopeless. 10545 Second = nullptr; 10546 continue; 10547 } 10548 // Check if we meet the alignment requirement. 10549 if (RequiredAlignment > First->getAlignment()) 10550 continue; 10551 10552 // Check that both loads are next to each other in memory. 10553 if (!areSlicesNextToEachOther(*First, *Second)) 10554 continue; 10555 10556 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10557 --GlobalLSCost.Loads; 10558 // Move to the next pair. 10559 Second = nullptr; 10560 } 10561 } 10562 10563 /// \brief Check the profitability of all involved LoadedSlice. 10564 /// Currently, it is considered profitable if there is exactly two 10565 /// involved slices (1) which are (2) next to each other in memory, and 10566 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10567 /// 10568 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10569 /// the elements themselves. 10570 /// 10571 /// FIXME: When the cost model will be mature enough, we can relax 10572 /// constraints (1) and (2). 10573 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10574 const APInt &UsedBits, bool ForCodeSize) { 10575 unsigned NumberOfSlices = LoadedSlices.size(); 10576 if (StressLoadSlicing) 10577 return NumberOfSlices > 1; 10578 10579 // Check (1). 10580 if (NumberOfSlices != 2) 10581 return false; 10582 10583 // Check (2). 10584 if (!areUsedBitsDense(UsedBits)) 10585 return false; 10586 10587 // Check (3). 10588 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10589 // The original code has one big load. 10590 OrigCost.Loads = 1; 10591 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10592 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10593 // Accumulate the cost of all the slices. 10594 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10595 GlobalSlicingCost += SliceCost; 10596 10597 // Account as cost in the original configuration the gain obtained 10598 // with the current slices. 10599 OrigCost.addSliceGain(LS); 10600 } 10601 10602 // If the target supports paired load, adjust the cost accordingly. 10603 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10604 return OrigCost > GlobalSlicingCost; 10605 } 10606 10607 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10608 /// operations, split it in the various pieces being extracted. 10609 /// 10610 /// This sort of thing is introduced by SROA. 10611 /// This slicing takes care not to insert overlapping loads. 10612 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10613 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10614 if (Level < AfterLegalizeDAG) 10615 return false; 10616 10617 LoadSDNode *LD = cast<LoadSDNode>(N); 10618 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10619 !LD->getValueType(0).isInteger()) 10620 return false; 10621 10622 // Keep track of already used bits to detect overlapping values. 10623 // In that case, we will just abort the transformation. 10624 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10625 10626 SmallVector<LoadedSlice, 4> LoadedSlices; 10627 10628 // Check if this load is used as several smaller chunks of bits. 10629 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10630 // of computation for each trunc. 10631 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10632 UI != UIEnd; ++UI) { 10633 // Skip the uses of the chain. 10634 if (UI.getUse().getResNo() != 0) 10635 continue; 10636 10637 SDNode *User = *UI; 10638 unsigned Shift = 0; 10639 10640 // Check if this is a trunc(lshr). 10641 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10642 isa<ConstantSDNode>(User->getOperand(1))) { 10643 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10644 User = *User->use_begin(); 10645 } 10646 10647 // At this point, User is a Truncate, iff we encountered, trunc or 10648 // trunc(lshr). 10649 if (User->getOpcode() != ISD::TRUNCATE) 10650 return false; 10651 10652 // The width of the type must be a power of 2 and greater than 8-bits. 10653 // Otherwise the load cannot be represented in LLVM IR. 10654 // Moreover, if we shifted with a non-8-bits multiple, the slice 10655 // will be across several bytes. We do not support that. 10656 unsigned Width = User->getValueSizeInBits(0); 10657 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10658 return 0; 10659 10660 // Build the slice for this chain of computations. 10661 LoadedSlice LS(User, LD, Shift, &DAG); 10662 APInt CurrentUsedBits = LS.getUsedBits(); 10663 10664 // Check if this slice overlaps with another. 10665 if ((CurrentUsedBits & UsedBits) != 0) 10666 return false; 10667 // Update the bits used globally. 10668 UsedBits |= CurrentUsedBits; 10669 10670 // Check if the new slice would be legal. 10671 if (!LS.isLegal()) 10672 return false; 10673 10674 // Record the slice. 10675 LoadedSlices.push_back(LS); 10676 } 10677 10678 // Abort slicing if it does not seem to be profitable. 10679 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10680 return false; 10681 10682 ++SlicedLoads; 10683 10684 // Rewrite each chain to use an independent load. 10685 // By construction, each chain can be represented by a unique load. 10686 10687 // Prepare the argument for the new token factor for all the slices. 10688 SmallVector<SDValue, 8> ArgChains; 10689 for (SmallVectorImpl<LoadedSlice>::const_iterator 10690 LSIt = LoadedSlices.begin(), 10691 LSItEnd = LoadedSlices.end(); 10692 LSIt != LSItEnd; ++LSIt) { 10693 SDValue SliceInst = LSIt->loadSlice(); 10694 CombineTo(LSIt->Inst, SliceInst, true); 10695 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10696 SliceInst = SliceInst.getOperand(0); 10697 assert(SliceInst->getOpcode() == ISD::LOAD && 10698 "It takes more than a zext to get to the loaded slice!!"); 10699 ArgChains.push_back(SliceInst.getValue(1)); 10700 } 10701 10702 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10703 ArgChains); 10704 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10705 return true; 10706 } 10707 10708 /// Check to see if V is (and load (ptr), imm), where the load is having 10709 /// specific bytes cleared out. If so, return the byte size being masked out 10710 /// and the shift amount. 10711 static std::pair<unsigned, unsigned> 10712 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10713 std::pair<unsigned, unsigned> Result(0, 0); 10714 10715 // Check for the structure we're looking for. 10716 if (V->getOpcode() != ISD::AND || 10717 !isa<ConstantSDNode>(V->getOperand(1)) || 10718 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10719 return Result; 10720 10721 // Check the chain and pointer. 10722 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10723 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10724 10725 // The store should be chained directly to the load or be an operand of a 10726 // tokenfactor. 10727 if (LD == Chain.getNode()) 10728 ; // ok. 10729 else if (Chain->getOpcode() != ISD::TokenFactor) 10730 return Result; // Fail. 10731 else { 10732 bool isOk = false; 10733 for (const SDValue &ChainOp : Chain->op_values()) 10734 if (ChainOp.getNode() == LD) { 10735 isOk = true; 10736 break; 10737 } 10738 if (!isOk) return Result; 10739 } 10740 10741 // This only handles simple types. 10742 if (V.getValueType() != MVT::i16 && 10743 V.getValueType() != MVT::i32 && 10744 V.getValueType() != MVT::i64) 10745 return Result; 10746 10747 // Check the constant mask. Invert it so that the bits being masked out are 10748 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10749 // follow the sign bit for uniformity. 10750 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10751 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10752 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10753 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10754 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10755 if (NotMaskLZ == 64) return Result; // All zero mask. 10756 10757 // See if we have a continuous run of bits. If so, we have 0*1+0* 10758 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10759 return Result; 10760 10761 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10762 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10763 NotMaskLZ -= 64-V.getValueSizeInBits(); 10764 10765 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10766 switch (MaskedBytes) { 10767 case 1: 10768 case 2: 10769 case 4: break; 10770 default: return Result; // All one mask, or 5-byte mask. 10771 } 10772 10773 // Verify that the first bit starts at a multiple of mask so that the access 10774 // is aligned the same as the access width. 10775 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10776 10777 Result.first = MaskedBytes; 10778 Result.second = NotMaskTZ/8; 10779 return Result; 10780 } 10781 10782 10783 /// Check to see if IVal is something that provides a value as specified by 10784 /// MaskInfo. If so, replace the specified store with a narrower store of 10785 /// truncated IVal. 10786 static SDNode * 10787 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10788 SDValue IVal, StoreSDNode *St, 10789 DAGCombiner *DC) { 10790 unsigned NumBytes = MaskInfo.first; 10791 unsigned ByteShift = MaskInfo.second; 10792 SelectionDAG &DAG = DC->getDAG(); 10793 10794 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10795 // that uses this. If not, this is not a replacement. 10796 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10797 ByteShift*8, (ByteShift+NumBytes)*8); 10798 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10799 10800 // Check that it is legal on the target to do this. It is legal if the new 10801 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10802 // legalization. 10803 MVT VT = MVT::getIntegerVT(NumBytes*8); 10804 if (!DC->isTypeLegal(VT)) 10805 return nullptr; 10806 10807 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10808 // shifted by ByteShift and truncated down to NumBytes. 10809 if (ByteShift) { 10810 SDLoc DL(IVal); 10811 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10812 DAG.getConstant(ByteShift*8, DL, 10813 DC->getShiftAmountTy(IVal.getValueType()))); 10814 } 10815 10816 // Figure out the offset for the store and the alignment of the access. 10817 unsigned StOffset; 10818 unsigned NewAlign = St->getAlignment(); 10819 10820 if (DAG.getDataLayout().isLittleEndian()) 10821 StOffset = ByteShift; 10822 else 10823 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10824 10825 SDValue Ptr = St->getBasePtr(); 10826 if (StOffset) { 10827 SDLoc DL(IVal); 10828 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10829 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10830 NewAlign = MinAlign(NewAlign, StOffset); 10831 } 10832 10833 // Truncate down to the new size. 10834 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10835 10836 ++OpsNarrowed; 10837 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10838 St->getPointerInfo().getWithOffset(StOffset), 10839 false, false, NewAlign).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 = DAG.getLoad(NewVT, SDLoc(N0), 10946 LD->getChain(), NewPtr, 10947 LD->getPointerInfo().getWithOffset(PtrOff), 10948 LD->isVolatile(), LD->isNonTemporal(), 10949 LD->isInvariant(), NewAlign, 10950 LD->getAAInfo()); 10951 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10952 DAG.getConstant(NewImm, SDLoc(Value), 10953 NewVT)); 10954 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10955 NewVal, NewPtr, 10956 ST->getPointerInfo().getWithOffset(PtrOff), 10957 false, false, NewAlign); 10958 10959 AddToWorklist(NewPtr.getNode()); 10960 AddToWorklist(NewLD.getNode()); 10961 AddToWorklist(NewVal.getNode()); 10962 WorklistRemover DeadNodes(*this); 10963 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10964 ++OpsNarrowed; 10965 return NewST; 10966 } 10967 } 10968 10969 return SDValue(); 10970 } 10971 10972 /// For a given floating point load / store pair, if the load value isn't used 10973 /// by any other operations, then consider transforming the pair to integer 10974 /// load / store operations if the target deems the transformation profitable. 10975 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10976 StoreSDNode *ST = cast<StoreSDNode>(N); 10977 SDValue Chain = ST->getChain(); 10978 SDValue Value = ST->getValue(); 10979 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10980 Value.hasOneUse() && 10981 Chain == SDValue(Value.getNode(), 1)) { 10982 LoadSDNode *LD = cast<LoadSDNode>(Value); 10983 EVT VT = LD->getMemoryVT(); 10984 if (!VT.isFloatingPoint() || 10985 VT != ST->getMemoryVT() || 10986 LD->isNonTemporal() || 10987 ST->isNonTemporal() || 10988 LD->getPointerInfo().getAddrSpace() != 0 || 10989 ST->getPointerInfo().getAddrSpace() != 0) 10990 return SDValue(); 10991 10992 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10993 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10994 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10995 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10996 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10997 return SDValue(); 10998 10999 unsigned LDAlign = LD->getAlignment(); 11000 unsigned STAlign = ST->getAlignment(); 11001 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11002 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11003 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11004 return SDValue(); 11005 11006 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 11007 LD->getChain(), LD->getBasePtr(), 11008 LD->getPointerInfo(), 11009 false, false, false, LDAlign); 11010 11011 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 11012 NewLD, ST->getBasePtr(), 11013 ST->getPointerInfo(), 11014 false, false, STAlign); 11015 11016 AddToWorklist(NewLD.getNode()); 11017 AddToWorklist(NewST.getNode()); 11018 WorklistRemover DeadNodes(*this); 11019 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11020 ++LdStFP2Int; 11021 return NewST; 11022 } 11023 11024 return SDValue(); 11025 } 11026 11027 namespace { 11028 /// Helper struct to parse and store a memory address as base + index + offset. 11029 /// We ignore sign extensions when it is safe to do so. 11030 /// The following two expressions are not equivalent. To differentiate we need 11031 /// to store whether there was a sign extension involved in the index 11032 /// computation. 11033 /// (load (i64 add (i64 copyfromreg %c) 11034 /// (i64 signextend (add (i8 load %index) 11035 /// (i8 1)))) 11036 /// vs 11037 /// 11038 /// (load (i64 add (i64 copyfromreg %c) 11039 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 11040 /// (i32 1))))) 11041 struct BaseIndexOffset { 11042 SDValue Base; 11043 SDValue Index; 11044 int64_t Offset; 11045 bool IsIndexSignExt; 11046 11047 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 11048 11049 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 11050 bool IsIndexSignExt) : 11051 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 11052 11053 bool equalBaseIndex(const BaseIndexOffset &Other) { 11054 return Other.Base == Base && Other.Index == Index && 11055 Other.IsIndexSignExt == IsIndexSignExt; 11056 } 11057 11058 /// Parses tree in Ptr for base, index, offset addresses. 11059 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 11060 bool IsIndexSignExt = false; 11061 11062 // Split up a folded GlobalAddress+Offset into its component parts. 11063 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 11064 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 11065 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 11066 SDLoc(GA), 11067 GA->getValueType(0), 11068 /*Offset=*/0, 11069 /*isTargetGA=*/false, 11070 GA->getTargetFlags()), 11071 SDValue(), 11072 GA->getOffset(), 11073 IsIndexSignExt); 11074 } 11075 11076 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 11077 // instruction, then it could be just the BASE or everything else we don't 11078 // know how to handle. Just use Ptr as BASE and give up. 11079 if (Ptr->getOpcode() != ISD::ADD) 11080 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11081 11082 // We know that we have at least an ADD instruction. Try to pattern match 11083 // the simple case of BASE + OFFSET. 11084 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 11085 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 11086 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 11087 IsIndexSignExt); 11088 } 11089 11090 // Inside a loop the current BASE pointer is calculated using an ADD and a 11091 // MUL instruction. In this case Ptr is the actual BASE pointer. 11092 // (i64 add (i64 %array_ptr) 11093 // (i64 mul (i64 %induction_var) 11094 // (i64 %element_size))) 11095 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11096 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11097 11098 // Look at Base + Index + Offset cases. 11099 SDValue Base = Ptr->getOperand(0); 11100 SDValue IndexOffset = Ptr->getOperand(1); 11101 11102 // Skip signextends. 11103 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11104 IndexOffset = IndexOffset->getOperand(0); 11105 IsIndexSignExt = true; 11106 } 11107 11108 // Either the case of Base + Index (no offset) or something else. 11109 if (IndexOffset->getOpcode() != ISD::ADD) 11110 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11111 11112 // Now we have the case of Base + Index + offset. 11113 SDValue Index = IndexOffset->getOperand(0); 11114 SDValue Offset = IndexOffset->getOperand(1); 11115 11116 if (!isa<ConstantSDNode>(Offset)) 11117 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11118 11119 // Ignore signextends. 11120 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11121 Index = Index->getOperand(0); 11122 IsIndexSignExt = true; 11123 } else IsIndexSignExt = false; 11124 11125 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11126 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11127 } 11128 }; 11129 } // namespace 11130 11131 // This is a helper function for visitMUL to check the profitability 11132 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11133 // MulNode is the original multiply, AddNode is (add x, c1), 11134 // and ConstNode is c2. 11135 // 11136 // If the (add x, c1) has multiple uses, we could increase 11137 // the number of adds if we make this transformation. 11138 // It would only be worth doing this if we can remove a 11139 // multiply in the process. Check for that here. 11140 // To illustrate: 11141 // (A + c1) * c3 11142 // (A + c2) * c3 11143 // We're checking for cases where we have common "c3 * A" expressions. 11144 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11145 SDValue &AddNode, 11146 SDValue &ConstNode) { 11147 APInt Val; 11148 11149 // If the add only has one use, this would be OK to do. 11150 if (AddNode.getNode()->hasOneUse()) 11151 return true; 11152 11153 // Walk all the users of the constant with which we're multiplying. 11154 for (SDNode *Use : ConstNode->uses()) { 11155 11156 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11157 continue; 11158 11159 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11160 SDNode *OtherOp; 11161 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11162 11163 // OtherOp is what we're multiplying against the constant. 11164 if (Use->getOperand(0) == ConstNode) 11165 OtherOp = Use->getOperand(1).getNode(); 11166 else 11167 OtherOp = Use->getOperand(0).getNode(); 11168 11169 // Check to see if multiply is with the same operand of our "add". 11170 // 11171 // ConstNode = CONST 11172 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11173 // ... 11174 // AddNode = (A + c1) <-- MulVar is A. 11175 // = AddNode * ConstNode <-- current visiting instruction. 11176 // 11177 // If we make this transformation, we will have a common 11178 // multiply (ConstNode * A) that we can save. 11179 if (OtherOp == MulVar) 11180 return true; 11181 11182 // Now check to see if a future expansion will give us a common 11183 // multiply. 11184 // 11185 // ConstNode = CONST 11186 // AddNode = (A + c1) 11187 // ... = AddNode * ConstNode <-- current visiting instruction. 11188 // ... 11189 // OtherOp = (A + c2) 11190 // Use = OtherOp * ConstNode <-- visiting Use. 11191 // 11192 // If we make this transformation, we will have a common 11193 // multiply (CONST * A) after we also do the same transformation 11194 // to the "t2" instruction. 11195 if (OtherOp->getOpcode() == ISD::ADD && 11196 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11197 OtherOp->getOperand(0).getNode() == MulVar) 11198 return true; 11199 } 11200 } 11201 11202 // Didn't find a case where this would be profitable. 11203 return false; 11204 } 11205 11206 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 11207 SDLoc SL, 11208 ArrayRef<MemOpLink> Stores, 11209 SmallVectorImpl<SDValue> &Chains, 11210 EVT Ty) const { 11211 SmallVector<SDValue, 8> BuildVector; 11212 11213 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11214 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11215 Chains.push_back(St->getChain()); 11216 BuildVector.push_back(St->getValue()); 11217 } 11218 11219 return DAG.getBuildVector(Ty, SL, BuildVector); 11220 } 11221 11222 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11223 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11224 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11225 // Make sure we have something to merge. 11226 if (NumStores < 2) 11227 return false; 11228 11229 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11230 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11231 unsigned LatestNodeUsed = 0; 11232 11233 for (unsigned i=0; i < NumStores; ++i) { 11234 // Find a chain for the new wide-store operand. Notice that some 11235 // of the store nodes that we found may not be selected for inclusion 11236 // in the wide store. The chain we use needs to be the chain of the 11237 // latest store node which is *used* and replaced by the wide store. 11238 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11239 LatestNodeUsed = i; 11240 } 11241 11242 SmallVector<SDValue, 8> Chains; 11243 11244 // The latest Node in the DAG. 11245 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11246 SDLoc DL(StoreNodes[0].MemNode); 11247 11248 SDValue StoredVal; 11249 if (UseVector) { 11250 bool IsVec = MemVT.isVector(); 11251 unsigned Elts = NumStores; 11252 if (IsVec) { 11253 // When merging vector stores, get the total number of elements. 11254 Elts *= MemVT.getVectorNumElements(); 11255 } 11256 // Get the type for the merged vector store. 11257 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11258 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11259 11260 if (IsConstantSrc) { 11261 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11262 } else { 11263 SmallVector<SDValue, 8> Ops; 11264 for (unsigned i = 0; i < NumStores; ++i) { 11265 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11266 SDValue Val = St->getValue(); 11267 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11268 if (Val.getValueType() != MemVT) 11269 return false; 11270 Ops.push_back(Val); 11271 Chains.push_back(St->getChain()); 11272 } 11273 11274 // Build the extracted vector elements back into a vector. 11275 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11276 DL, Ty, Ops); } 11277 } else { 11278 // We should always use a vector store when merging extracted vector 11279 // elements, so this path implies a store of constants. 11280 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11281 11282 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11283 APInt StoreInt(SizeInBits, 0); 11284 11285 // Construct a single integer constant which is made of the smaller 11286 // constant inputs. 11287 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11288 for (unsigned i = 0; i < NumStores; ++i) { 11289 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11290 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11291 Chains.push_back(St->getChain()); 11292 11293 SDValue Val = St->getValue(); 11294 StoreInt <<= ElementSizeBytes * 8; 11295 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11296 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11297 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11298 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11299 } else { 11300 llvm_unreachable("Invalid constant element type"); 11301 } 11302 } 11303 11304 // Create the new Load and Store operations. 11305 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11306 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11307 } 11308 11309 assert(!Chains.empty()); 11310 11311 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11312 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11313 FirstInChain->getBasePtr(), 11314 FirstInChain->getPointerInfo(), 11315 false, false, 11316 FirstInChain->getAlignment()); 11317 11318 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11319 : DAG.getSubtarget().useAA(); 11320 if (UseAA) { 11321 // Replace all merged stores with the new store. 11322 for (unsigned i = 0; i < NumStores; ++i) 11323 CombineTo(StoreNodes[i].MemNode, NewStore); 11324 } else { 11325 // Replace the last store with the new store. 11326 CombineTo(LatestOp, NewStore); 11327 // Erase all other stores. 11328 for (unsigned i = 0; i < NumStores; ++i) { 11329 if (StoreNodes[i].MemNode == LatestOp) 11330 continue; 11331 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11332 // ReplaceAllUsesWith will replace all uses that existed when it was 11333 // called, but graph optimizations may cause new ones to appear. For 11334 // example, the case in pr14333 looks like 11335 // 11336 // St's chain -> St -> another store -> X 11337 // 11338 // And the only difference from St to the other store is the chain. 11339 // When we change it's chain to be St's chain they become identical, 11340 // get CSEed and the net result is that X is now a use of St. 11341 // Since we know that St is redundant, just iterate. 11342 while (!St->use_empty()) 11343 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11344 deleteAndRecombine(St); 11345 } 11346 } 11347 11348 return true; 11349 } 11350 11351 void DAGCombiner::getStoreMergeAndAliasCandidates( 11352 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11353 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11354 // This holds the base pointer, index, and the offset in bytes from the base 11355 // pointer. 11356 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11357 11358 // We must have a base and an offset. 11359 if (!BasePtr.Base.getNode()) 11360 return; 11361 11362 // Do not handle stores to undef base pointers. 11363 if (BasePtr.Base.isUndef()) 11364 return; 11365 11366 // Walk up the chain and look for nodes with offsets from the same 11367 // base pointer. Stop when reaching an instruction with a different kind 11368 // or instruction which has a different base pointer. 11369 EVT MemVT = St->getMemoryVT(); 11370 unsigned Seq = 0; 11371 StoreSDNode *Index = St; 11372 11373 11374 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11375 : DAG.getSubtarget().useAA(); 11376 11377 if (UseAA) { 11378 // Look at other users of the same chain. Stores on the same chain do not 11379 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11380 // to be on the same chain, so don't bother looking at adjacent chains. 11381 11382 SDValue Chain = St->getChain(); 11383 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11384 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11385 if (I.getOperandNo() != 0) 11386 continue; 11387 11388 if (OtherST->isVolatile() || OtherST->isIndexed()) 11389 continue; 11390 11391 if (OtherST->getMemoryVT() != MemVT) 11392 continue; 11393 11394 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11395 11396 if (Ptr.equalBaseIndex(BasePtr)) 11397 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11398 } 11399 } 11400 11401 return; 11402 } 11403 11404 while (Index) { 11405 // If the chain has more than one use, then we can't reorder the mem ops. 11406 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11407 break; 11408 11409 // Find the base pointer and offset for this memory node. 11410 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11411 11412 // Check that the base pointer is the same as the original one. 11413 if (!Ptr.equalBaseIndex(BasePtr)) 11414 break; 11415 11416 // The memory operands must not be volatile. 11417 if (Index->isVolatile() || Index->isIndexed()) 11418 break; 11419 11420 // No truncation. 11421 if (Index->isTruncatingStore()) 11422 break; 11423 11424 // The stored memory type must be the same. 11425 if (Index->getMemoryVT() != MemVT) 11426 break; 11427 11428 // We do not allow under-aligned stores in order to prevent 11429 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11430 // be irrelevant here; what MATTERS is that we not move memory 11431 // operations that potentially overlap past each-other. 11432 if (Index->getAlignment() < MemVT.getStoreSize()) 11433 break; 11434 11435 // We found a potential memory operand to merge. 11436 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11437 11438 // Find the next memory operand in the chain. If the next operand in the 11439 // chain is a store then move up and continue the scan with the next 11440 // memory operand. If the next operand is a load save it and use alias 11441 // information to check if it interferes with anything. 11442 SDNode *NextInChain = Index->getChain().getNode(); 11443 while (1) { 11444 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11445 // We found a store node. Use it for the next iteration. 11446 Index = STn; 11447 break; 11448 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11449 if (Ldn->isVolatile()) { 11450 Index = nullptr; 11451 break; 11452 } 11453 11454 // Save the load node for later. Continue the scan. 11455 AliasLoadNodes.push_back(Ldn); 11456 NextInChain = Ldn->getChain().getNode(); 11457 continue; 11458 } else { 11459 Index = nullptr; 11460 break; 11461 } 11462 } 11463 } 11464 } 11465 11466 // We need to check that merging these stores does not cause a loop 11467 // in the DAG. Any store candidate may depend on another candidate 11468 // indirectly through its operand (we already consider dependencies 11469 // through the chain). Check in parallel by searching up from 11470 // non-chain operands of candidates. 11471 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11472 SmallVectorImpl<MemOpLink> &StoreNodes) { 11473 SmallPtrSet<const SDNode *, 16> Visited; 11474 SmallVector<const SDNode *, 8> Worklist; 11475 // search ops of store candidates 11476 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11477 SDNode *n = StoreNodes[i].MemNode; 11478 // Potential loops may happen only through non-chain operands 11479 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11480 Worklist.push_back(n->getOperand(j).getNode()); 11481 } 11482 // search through DAG. We can stop early if we find a storenode 11483 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11484 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11485 return false; 11486 } 11487 return true; 11488 } 11489 11490 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11491 if (OptLevel == CodeGenOpt::None) 11492 return false; 11493 11494 EVT MemVT = St->getMemoryVT(); 11495 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11496 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11497 Attribute::NoImplicitFloat); 11498 11499 // This function cannot currently deal with non-byte-sized memory sizes. 11500 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11501 return false; 11502 11503 if (!MemVT.isSimple()) 11504 return false; 11505 11506 // Perform an early exit check. Do not bother looking at stored values that 11507 // are not constants, loads, or extracted vector elements. 11508 SDValue StoredVal = St->getValue(); 11509 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11510 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11511 isa<ConstantFPSDNode>(StoredVal); 11512 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11513 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11514 11515 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11516 return false; 11517 11518 // Don't merge vectors into wider vectors if the source data comes from loads. 11519 // TODO: This restriction can be lifted by using logic similar to the 11520 // ExtractVecSrc case. 11521 if (MemVT.isVector() && IsLoadSrc) 11522 return false; 11523 11524 // Only look at ends of store sequences. 11525 SDValue Chain = SDValue(St, 0); 11526 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11527 return false; 11528 11529 // Save the LoadSDNodes that we find in the chain. 11530 // We need to make sure that these nodes do not interfere with 11531 // any of the store nodes. 11532 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11533 11534 // Save the StoreSDNodes that we find in the chain. 11535 SmallVector<MemOpLink, 8> StoreNodes; 11536 11537 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11538 11539 // Check if there is anything to merge. 11540 if (StoreNodes.size() < 2) 11541 return false; 11542 11543 // only do dep endence check in AA case 11544 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11545 : DAG.getSubtarget().useAA(); 11546 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11547 return false; 11548 11549 // Sort the memory operands according to their distance from the 11550 // base pointer. As a secondary criteria: make sure stores coming 11551 // later in the code come first in the list. This is important for 11552 // the non-UseAA case, because we're merging stores into the FINAL 11553 // store along a chain which potentially contains aliasing stores. 11554 // Thus, if there are multiple stores to the same address, the last 11555 // one can be considered for merging but not the others. 11556 std::sort(StoreNodes.begin(), StoreNodes.end(), 11557 [](MemOpLink LHS, MemOpLink RHS) { 11558 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11559 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11560 LHS.SequenceNum < RHS.SequenceNum); 11561 }); 11562 11563 // Scan the memory operations on the chain and find the first non-consecutive 11564 // store memory address. 11565 unsigned LastConsecutiveStore = 0; 11566 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11567 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11568 11569 // Check that the addresses are consecutive starting from the second 11570 // element in the list of stores. 11571 if (i > 0) { 11572 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11573 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11574 break; 11575 } 11576 11577 // Check if this store interferes with any of the loads that we found. 11578 // If we find a load that alias with this store. Stop the sequence. 11579 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(), 11580 [&](LSBaseSDNode* Ldn) { 11581 return isAlias(Ldn, StoreNodes[i].MemNode); 11582 })) 11583 break; 11584 11585 // Mark this node as useful. 11586 LastConsecutiveStore = i; 11587 } 11588 11589 // The node with the lowest store address. 11590 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11591 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11592 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11593 LLVMContext &Context = *DAG.getContext(); 11594 const DataLayout &DL = DAG.getDataLayout(); 11595 11596 // Store the constants into memory as one consecutive store. 11597 if (IsConstantSrc) { 11598 unsigned LastLegalType = 0; 11599 unsigned LastLegalVectorType = 0; 11600 bool NonZero = false; 11601 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11602 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11603 SDValue StoredVal = St->getValue(); 11604 11605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11606 NonZero |= !C->isNullValue(); 11607 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11608 NonZero |= !C->getConstantFPValue()->isNullValue(); 11609 } else { 11610 // Non-constant. 11611 break; 11612 } 11613 11614 // Find a legal type for the constant store. 11615 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11616 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11617 bool IsFast; 11618 if (TLI.isTypeLegal(StoreTy) && 11619 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11620 FirstStoreAlign, &IsFast) && IsFast) { 11621 LastLegalType = i+1; 11622 // Or check whether a truncstore is legal. 11623 } else if (TLI.getTypeAction(Context, StoreTy) == 11624 TargetLowering::TypePromoteInteger) { 11625 EVT LegalizedStoredValueTy = 11626 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11627 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11628 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11629 FirstStoreAS, FirstStoreAlign, &IsFast) && 11630 IsFast) { 11631 LastLegalType = i + 1; 11632 } 11633 } 11634 11635 // We only use vectors if the constant is known to be zero or the target 11636 // allows it and the function is not marked with the noimplicitfloat 11637 // attribute. 11638 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11639 FirstStoreAS)) && 11640 !NoVectors) { 11641 // Find a legal type for the vector store. 11642 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11643 if (TLI.isTypeLegal(Ty) && 11644 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11645 FirstStoreAlign, &IsFast) && IsFast) 11646 LastLegalVectorType = i + 1; 11647 } 11648 } 11649 11650 // Check if we found a legal integer type to store. 11651 if (LastLegalType == 0 && LastLegalVectorType == 0) 11652 return false; 11653 11654 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11655 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11656 11657 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11658 true, UseVector); 11659 } 11660 11661 // When extracting multiple vector elements, try to store them 11662 // in one vector store rather than a sequence of scalar stores. 11663 if (IsExtractVecSrc) { 11664 unsigned NumStoresToMerge = 0; 11665 bool IsVec = MemVT.isVector(); 11666 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11667 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11668 unsigned StoreValOpcode = St->getValue().getOpcode(); 11669 // This restriction could be loosened. 11670 // Bail out if any stored values are not elements extracted from a vector. 11671 // It should be possible to handle mixed sources, but load sources need 11672 // more careful handling (see the block of code below that handles 11673 // consecutive loads). 11674 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11675 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11676 return false; 11677 11678 // Find a legal type for the vector store. 11679 unsigned Elts = i + 1; 11680 if (IsVec) { 11681 // When merging vector stores, get the total number of elements. 11682 Elts *= MemVT.getVectorNumElements(); 11683 } 11684 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11685 bool IsFast; 11686 if (TLI.isTypeLegal(Ty) && 11687 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11688 FirstStoreAlign, &IsFast) && IsFast) 11689 NumStoresToMerge = i + 1; 11690 } 11691 11692 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11693 false, true); 11694 } 11695 11696 // Below we handle the case of multiple consecutive stores that 11697 // come from multiple consecutive loads. We merge them into a single 11698 // wide load and a single wide store. 11699 11700 // Look for load nodes which are used by the stored values. 11701 SmallVector<MemOpLink, 8> LoadNodes; 11702 11703 // Find acceptable loads. Loads need to have the same chain (token factor), 11704 // must not be zext, volatile, indexed, and they must be consecutive. 11705 BaseIndexOffset LdBasePtr; 11706 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11707 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11708 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11709 if (!Ld) break; 11710 11711 // Loads must only have one use. 11712 if (!Ld->hasNUsesOfValue(1, 0)) 11713 break; 11714 11715 // The memory operands must not be volatile. 11716 if (Ld->isVolatile() || Ld->isIndexed()) 11717 break; 11718 11719 // We do not accept ext loads. 11720 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11721 break; 11722 11723 // The stored memory type must be the same. 11724 if (Ld->getMemoryVT() != MemVT) 11725 break; 11726 11727 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11728 // If this is not the first ptr that we check. 11729 if (LdBasePtr.Base.getNode()) { 11730 // The base ptr must be the same. 11731 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11732 break; 11733 } else { 11734 // Check that all other base pointers are the same as this one. 11735 LdBasePtr = LdPtr; 11736 } 11737 11738 // We found a potential memory operand to merge. 11739 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11740 } 11741 11742 if (LoadNodes.size() < 2) 11743 return false; 11744 11745 // If we have load/store pair instructions and we only have two values, 11746 // don't bother. 11747 unsigned RequiredAlignment; 11748 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11749 St->getAlignment() >= RequiredAlignment) 11750 return false; 11751 11752 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11753 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11754 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11755 11756 // Scan the memory operations on the chain and find the first non-consecutive 11757 // load memory address. These variables hold the index in the store node 11758 // array. 11759 unsigned LastConsecutiveLoad = 0; 11760 // This variable refers to the size and not index in the array. 11761 unsigned LastLegalVectorType = 0; 11762 unsigned LastLegalIntegerType = 0; 11763 StartAddress = LoadNodes[0].OffsetFromBase; 11764 SDValue FirstChain = FirstLoad->getChain(); 11765 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11766 // All loads must share the same chain. 11767 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11768 break; 11769 11770 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11771 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11772 break; 11773 LastConsecutiveLoad = i; 11774 // Find a legal type for the vector store. 11775 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11776 bool IsFastSt, IsFastLd; 11777 if (TLI.isTypeLegal(StoreTy) && 11778 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11779 FirstStoreAlign, &IsFastSt) && IsFastSt && 11780 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11781 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11782 LastLegalVectorType = i + 1; 11783 } 11784 11785 // Find a legal type for the integer store. 11786 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11787 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11788 if (TLI.isTypeLegal(StoreTy) && 11789 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11790 FirstStoreAlign, &IsFastSt) && IsFastSt && 11791 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11792 FirstLoadAlign, &IsFastLd) && IsFastLd) 11793 LastLegalIntegerType = i + 1; 11794 // Or check whether a truncstore and extload is legal. 11795 else if (TLI.getTypeAction(Context, StoreTy) == 11796 TargetLowering::TypePromoteInteger) { 11797 EVT LegalizedStoredValueTy = 11798 TLI.getTypeToTransformTo(Context, StoreTy); 11799 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11800 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11801 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11802 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11803 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11804 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11805 IsFastSt && 11806 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11807 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11808 IsFastLd) 11809 LastLegalIntegerType = i+1; 11810 } 11811 } 11812 11813 // Only use vector types if the vector type is larger than the integer type. 11814 // If they are the same, use integers. 11815 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11816 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11817 11818 // We add +1 here because the LastXXX variables refer to location while 11819 // the NumElem refers to array/index size. 11820 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11821 NumElem = std::min(LastLegalType, NumElem); 11822 11823 if (NumElem < 2) 11824 return false; 11825 11826 // Collect the chains from all merged stores. 11827 SmallVector<SDValue, 8> MergeStoreChains; 11828 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11829 11830 // The latest Node in the DAG. 11831 unsigned LatestNodeUsed = 0; 11832 for (unsigned i=1; i<NumElem; ++i) { 11833 // Find a chain for the new wide-store operand. Notice that some 11834 // of the store nodes that we found may not be selected for inclusion 11835 // in the wide store. The chain we use needs to be the chain of the 11836 // latest store node which is *used* and replaced by the wide store. 11837 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11838 LatestNodeUsed = i; 11839 11840 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11841 } 11842 11843 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11844 11845 // Find if it is better to use vectors or integers to load and store 11846 // to memory. 11847 EVT JointMemOpVT; 11848 if (UseVectorTy) { 11849 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11850 } else { 11851 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11852 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11853 } 11854 11855 SDLoc LoadDL(LoadNodes[0].MemNode); 11856 SDLoc StoreDL(StoreNodes[0].MemNode); 11857 11858 // The merged loads are required to have the same incoming chain, so 11859 // using the first's chain is acceptable. 11860 SDValue NewLoad = DAG.getLoad( 11861 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11862 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11863 11864 SDValue NewStoreChain = 11865 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11866 11867 SDValue NewStore = DAG.getStore( 11868 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11869 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11870 11871 // Transfer chain users from old loads to the new load. 11872 for (unsigned i = 0; i < NumElem; ++i) { 11873 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11874 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11875 SDValue(NewLoad.getNode(), 1)); 11876 } 11877 11878 if (UseAA) { 11879 // Replace the all stores with the new store. 11880 for (unsigned i = 0; i < NumElem; ++i) 11881 CombineTo(StoreNodes[i].MemNode, NewStore); 11882 } else { 11883 // Replace the last store with the new store. 11884 CombineTo(LatestOp, NewStore); 11885 // Erase all other stores. 11886 for (unsigned i = 0; i < NumElem; ++i) { 11887 // Remove all Store nodes. 11888 if (StoreNodes[i].MemNode == LatestOp) 11889 continue; 11890 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11891 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11892 deleteAndRecombine(St); 11893 } 11894 } 11895 11896 return true; 11897 } 11898 11899 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11900 SDLoc SL(ST); 11901 SDValue ReplStore; 11902 11903 // Replace the chain to avoid dependency. 11904 if (ST->isTruncatingStore()) { 11905 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11906 ST->getBasePtr(), ST->getMemoryVT(), 11907 ST->getMemOperand()); 11908 } else { 11909 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11910 ST->getMemOperand()); 11911 } 11912 11913 // Create token to keep both nodes around. 11914 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11915 MVT::Other, ST->getChain(), ReplStore); 11916 11917 // Make sure the new and old chains are cleaned up. 11918 AddToWorklist(Token.getNode()); 11919 11920 // Don't add users to work list. 11921 return CombineTo(ST, Token, false); 11922 } 11923 11924 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11925 SDValue Value = ST->getValue(); 11926 if (Value.getOpcode() == ISD::TargetConstantFP) 11927 return SDValue(); 11928 11929 SDLoc DL(ST); 11930 11931 SDValue Chain = ST->getChain(); 11932 SDValue Ptr = ST->getBasePtr(); 11933 11934 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11935 11936 // NOTE: If the original store is volatile, this transform must not increase 11937 // the number of stores. For example, on x86-32 an f64 can be stored in one 11938 // processor operation but an i64 (which is not legal) requires two. So the 11939 // transform should not be done in this case. 11940 11941 SDValue Tmp; 11942 switch (CFP->getSimpleValueType(0).SimpleTy) { 11943 default: 11944 llvm_unreachable("Unknown FP type"); 11945 case MVT::f16: // We don't do this for these yet. 11946 case MVT::f80: 11947 case MVT::f128: 11948 case MVT::ppcf128: 11949 return SDValue(); 11950 case MVT::f32: 11951 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11952 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11953 ; 11954 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11955 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11956 MVT::i32); 11957 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11958 } 11959 11960 return SDValue(); 11961 case MVT::f64: 11962 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11963 !ST->isVolatile()) || 11964 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11965 ; 11966 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11967 getZExtValue(), SDLoc(CFP), MVT::i64); 11968 return DAG.getStore(Chain, DL, Tmp, 11969 Ptr, ST->getMemOperand()); 11970 } 11971 11972 if (!ST->isVolatile() && 11973 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11974 // Many FP stores are not made apparent until after legalize, e.g. for 11975 // argument passing. Since this is so common, custom legalize the 11976 // 64-bit integer store into two 32-bit stores. 11977 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11978 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11979 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11980 if (DAG.getDataLayout().isBigEndian()) 11981 std::swap(Lo, Hi); 11982 11983 unsigned Alignment = ST->getAlignment(); 11984 bool isVolatile = ST->isVolatile(); 11985 bool isNonTemporal = ST->isNonTemporal(); 11986 AAMDNodes AAInfo = ST->getAAInfo(); 11987 11988 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11989 Ptr, ST->getPointerInfo(), 11990 isVolatile, isNonTemporal, 11991 ST->getAlignment(), AAInfo); 11992 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11993 DAG.getConstant(4, DL, Ptr.getValueType())); 11994 Alignment = MinAlign(Alignment, 4U); 11995 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11996 Ptr, ST->getPointerInfo().getWithOffset(4), 11997 isVolatile, isNonTemporal, 11998 Alignment, AAInfo); 11999 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12000 St0, St1); 12001 } 12002 12003 return SDValue(); 12004 } 12005 } 12006 12007 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12008 StoreSDNode *ST = cast<StoreSDNode>(N); 12009 SDValue Chain = ST->getChain(); 12010 SDValue Value = ST->getValue(); 12011 SDValue Ptr = ST->getBasePtr(); 12012 12013 // If this is a store of a bit convert, store the input value if the 12014 // resultant store does not need a higher alignment than the original. 12015 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12016 ST->isUnindexed()) { 12017 EVT SVT = Value.getOperand(0).getValueType(); 12018 if (((!LegalOperations && !ST->isVolatile()) || 12019 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12020 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12021 unsigned OrigAlign = ST->getAlignment(); 12022 bool Fast = false; 12023 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12024 ST->getAddressSpace(), OrigAlign, &Fast) && 12025 Fast) { 12026 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 12027 Ptr, ST->getPointerInfo(), ST->isVolatile(), 12028 ST->isNonTemporal(), OrigAlign, 12029 ST->getAAInfo()); 12030 } 12031 } 12032 } 12033 12034 // Turn 'store undef, Ptr' -> nothing. 12035 if (Value.isUndef() && ST->isUnindexed()) 12036 return Chain; 12037 12038 // Try to infer better alignment information than the store already has. 12039 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12040 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12041 if (Align > ST->getAlignment()) { 12042 SDValue NewStore = 12043 DAG.getTruncStore(Chain, SDLoc(N), Value, 12044 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 12045 ST->isVolatile(), ST->isNonTemporal(), Align, 12046 ST->getAAInfo()); 12047 if (NewStore.getNode() != N) 12048 return CombineTo(ST, NewStore, true); 12049 } 12050 } 12051 } 12052 12053 // Try transforming a pair floating point load / store ops to integer 12054 // load / store ops. 12055 if (SDValue NewST = TransformFPLoadStorePair(N)) 12056 return NewST; 12057 12058 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12059 : DAG.getSubtarget().useAA(); 12060 #ifndef NDEBUG 12061 if (CombinerAAOnlyFunc.getNumOccurrences() && 12062 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12063 UseAA = false; 12064 #endif 12065 if (UseAA && ST->isUnindexed()) { 12066 // FIXME: We should do this even without AA enabled. AA will just allow 12067 // FindBetterChain to work in more situations. The problem with this is that 12068 // any combine that expects memory operations to be on consecutive chains 12069 // first needs to be updated to look for users of the same chain. 12070 12071 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12072 // adjacent stores. 12073 if (findBetterNeighborChains(ST)) { 12074 // replaceStoreChain uses CombineTo, which handled all of the worklist 12075 // manipulation. Return the original node to not do anything else. 12076 return SDValue(ST, 0); 12077 } 12078 } 12079 12080 // Try transforming N to an indexed store. 12081 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12082 return SDValue(N, 0); 12083 12084 // FIXME: is there such a thing as a truncating indexed store? 12085 if (ST->isTruncatingStore() && ST->isUnindexed() && 12086 Value.getValueType().isInteger()) { 12087 // See if we can simplify the input to this truncstore with knowledge that 12088 // only the low bits are being used. For example: 12089 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12090 SDValue Shorter = 12091 GetDemandedBits(Value, 12092 APInt::getLowBitsSet( 12093 Value.getValueType().getScalarType().getSizeInBits(), 12094 ST->getMemoryVT().getScalarType().getSizeInBits())); 12095 AddToWorklist(Value.getNode()); 12096 if (Shorter.getNode()) 12097 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12098 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12099 12100 // Otherwise, see if we can simplify the operation with 12101 // SimplifyDemandedBits, which only works if the value has a single use. 12102 if (SimplifyDemandedBits(Value, 12103 APInt::getLowBitsSet( 12104 Value.getValueType().getScalarType().getSizeInBits(), 12105 ST->getMemoryVT().getScalarType().getSizeInBits()))) 12106 return SDValue(N, 0); 12107 } 12108 12109 // If this is a load followed by a store to the same location, then the store 12110 // is dead/noop. 12111 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12112 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12113 ST->isUnindexed() && !ST->isVolatile() && 12114 // There can't be any side effects between the load and store, such as 12115 // a call or store. 12116 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12117 // The store is dead, remove it. 12118 return Chain; 12119 } 12120 } 12121 12122 // If this is a store followed by a store with the same value to the same 12123 // location, then the store is dead/noop. 12124 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12125 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12126 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12127 ST1->isUnindexed() && !ST1->isVolatile()) { 12128 // The store is dead, remove it. 12129 return Chain; 12130 } 12131 } 12132 12133 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12134 // truncating store. We can do this even if this is already a truncstore. 12135 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12136 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12137 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12138 ST->getMemoryVT())) { 12139 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12140 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12141 } 12142 12143 // Only perform this optimization before the types are legal, because we 12144 // don't want to perform this optimization on every DAGCombine invocation. 12145 if (!LegalTypes) { 12146 bool EverChanged = false; 12147 12148 do { 12149 // There can be multiple store sequences on the same chain. 12150 // Keep trying to merge store sequences until we are unable to do so 12151 // or until we merge the last store on the chain. 12152 bool Changed = MergeConsecutiveStores(ST); 12153 EverChanged |= Changed; 12154 if (!Changed) break; 12155 } while (ST->getOpcode() != ISD::DELETED_NODE); 12156 12157 if (EverChanged) 12158 return SDValue(N, 0); 12159 } 12160 12161 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12162 // 12163 // Make sure to do this only after attempting to merge stores in order to 12164 // avoid changing the types of some subset of stores due to visit order, 12165 // preventing their merging. 12166 if (isa<ConstantFPSDNode>(Value)) { 12167 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12168 return NewSt; 12169 } 12170 12171 return ReduceLoadOpStoreWidth(N); 12172 } 12173 12174 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12175 SDValue InVec = N->getOperand(0); 12176 SDValue InVal = N->getOperand(1); 12177 SDValue EltNo = N->getOperand(2); 12178 SDLoc dl(N); 12179 12180 // If the inserted element is an UNDEF, just use the input vector. 12181 if (InVal.isUndef()) 12182 return InVec; 12183 12184 EVT VT = InVec.getValueType(); 12185 12186 // If we can't generate a legal BUILD_VECTOR, exit 12187 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12188 return SDValue(); 12189 12190 // Check that we know which element is being inserted 12191 if (!isa<ConstantSDNode>(EltNo)) 12192 return SDValue(); 12193 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12194 12195 // Canonicalize insert_vector_elt dag nodes. 12196 // Example: 12197 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12198 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12199 // 12200 // Do this only if the child insert_vector node has one use; also 12201 // do this only if indices are both constants and Idx1 < Idx0. 12202 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12203 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12204 unsigned OtherElt = 12205 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12206 if (Elt < OtherElt) { 12207 // Swap nodes. 12208 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12209 InVec.getOperand(0), InVal, EltNo); 12210 AddToWorklist(NewOp.getNode()); 12211 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12212 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12213 } 12214 } 12215 12216 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12217 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12218 // vector elements. 12219 SmallVector<SDValue, 8> Ops; 12220 // Do not combine these two vectors if the output vector will not replace 12221 // the input vector. 12222 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12223 Ops.append(InVec.getNode()->op_begin(), 12224 InVec.getNode()->op_end()); 12225 } else if (InVec.isUndef()) { 12226 unsigned NElts = VT.getVectorNumElements(); 12227 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12228 } else { 12229 return SDValue(); 12230 } 12231 12232 // Insert the element 12233 if (Elt < Ops.size()) { 12234 // All the operands of BUILD_VECTOR must have the same type; 12235 // we enforce that here. 12236 EVT OpVT = Ops[0].getValueType(); 12237 if (InVal.getValueType() != OpVT) 12238 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12239 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12240 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12241 Ops[Elt] = InVal; 12242 } 12243 12244 // Return the new vector 12245 return DAG.getBuildVector(VT, dl, Ops); 12246 } 12247 12248 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12249 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12250 EVT ResultVT = EVE->getValueType(0); 12251 EVT VecEltVT = InVecVT.getVectorElementType(); 12252 unsigned Align = OriginalLoad->getAlignment(); 12253 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12254 VecEltVT.getTypeForEVT(*DAG.getContext())); 12255 12256 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12257 return SDValue(); 12258 12259 Align = NewAlign; 12260 12261 SDValue NewPtr = OriginalLoad->getBasePtr(); 12262 SDValue Offset; 12263 EVT PtrType = NewPtr.getValueType(); 12264 MachinePointerInfo MPI; 12265 SDLoc DL(EVE); 12266 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12267 int Elt = ConstEltNo->getZExtValue(); 12268 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12269 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12270 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12271 } else { 12272 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12273 Offset = DAG.getNode( 12274 ISD::MUL, DL, PtrType, Offset, 12275 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12276 MPI = OriginalLoad->getPointerInfo(); 12277 } 12278 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12279 12280 // The replacement we need to do here is a little tricky: we need to 12281 // replace an extractelement of a load with a load. 12282 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12283 // Note that this replacement assumes that the extractvalue is the only 12284 // use of the load; that's okay because we don't want to perform this 12285 // transformation in other cases anyway. 12286 SDValue Load; 12287 SDValue Chain; 12288 if (ResultVT.bitsGT(VecEltVT)) { 12289 // If the result type of vextract is wider than the load, then issue an 12290 // extending load instead. 12291 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12292 VecEltVT) 12293 ? ISD::ZEXTLOAD 12294 : ISD::EXTLOAD; 12295 Load = DAG.getExtLoad( 12296 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 12297 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12298 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12299 Chain = Load.getValue(1); 12300 } else { 12301 Load = DAG.getLoad( 12302 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 12303 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12304 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12305 Chain = Load.getValue(1); 12306 if (ResultVT.bitsLT(VecEltVT)) 12307 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12308 else 12309 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 12310 } 12311 WorklistRemover DeadNodes(*this); 12312 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12313 SDValue To[] = { Load, Chain }; 12314 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12315 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12316 // worklist explicitly as well. 12317 AddToWorklist(Load.getNode()); 12318 AddUsersToWorklist(Load.getNode()); // Add users too 12319 // Make sure to revisit this node to clean it up; it will usually be dead. 12320 AddToWorklist(EVE); 12321 ++OpsNarrowed; 12322 return SDValue(EVE, 0); 12323 } 12324 12325 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12326 // (vextract (scalar_to_vector val, 0) -> val 12327 SDValue InVec = N->getOperand(0); 12328 EVT VT = InVec.getValueType(); 12329 EVT NVT = N->getValueType(0); 12330 12331 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12332 // Check if the result type doesn't match the inserted element type. A 12333 // SCALAR_TO_VECTOR may truncate the inserted element and the 12334 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12335 SDValue InOp = InVec.getOperand(0); 12336 if (InOp.getValueType() != NVT) { 12337 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12338 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12339 } 12340 return InOp; 12341 } 12342 12343 SDValue EltNo = N->getOperand(1); 12344 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12345 12346 // extract_vector_elt (build_vector x, y), 1 -> y 12347 if (ConstEltNo && 12348 InVec.getOpcode() == ISD::BUILD_VECTOR && 12349 TLI.isTypeLegal(VT) && 12350 (InVec.hasOneUse() || 12351 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12352 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12353 EVT InEltVT = Elt.getValueType(); 12354 12355 // Sometimes build_vector's scalar input types do not match result type. 12356 if (NVT == InEltVT) 12357 return Elt; 12358 12359 // TODO: It may be useful to truncate if free if the build_vector implicitly 12360 // converts. 12361 } 12362 12363 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12364 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12365 ConstEltNo->isNullValue() && VT.isInteger()) { 12366 SDValue BCSrc = InVec.getOperand(0); 12367 if (BCSrc.getValueType().isScalarInteger()) 12368 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12369 } 12370 12371 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12372 // We only perform this optimization before the op legalization phase because 12373 // we may introduce new vector instructions which are not backed by TD 12374 // patterns. For example on AVX, extracting elements from a wide vector 12375 // without using extract_subvector. However, if we can find an underlying 12376 // scalar value, then we can always use that. 12377 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12378 int NumElem = VT.getVectorNumElements(); 12379 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12380 // Find the new index to extract from. 12381 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12382 12383 // Extracting an undef index is undef. 12384 if (OrigElt == -1) 12385 return DAG.getUNDEF(NVT); 12386 12387 // Select the right vector half to extract from. 12388 SDValue SVInVec; 12389 if (OrigElt < NumElem) { 12390 SVInVec = InVec->getOperand(0); 12391 } else { 12392 SVInVec = InVec->getOperand(1); 12393 OrigElt -= NumElem; 12394 } 12395 12396 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12397 SDValue InOp = SVInVec.getOperand(OrigElt); 12398 if (InOp.getValueType() != NVT) { 12399 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12400 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12401 } 12402 12403 return InOp; 12404 } 12405 12406 // FIXME: We should handle recursing on other vector shuffles and 12407 // scalar_to_vector here as well. 12408 12409 if (!LegalOperations) { 12410 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12411 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12412 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12413 } 12414 } 12415 12416 bool BCNumEltsChanged = false; 12417 EVT ExtVT = VT.getVectorElementType(); 12418 EVT LVT = ExtVT; 12419 12420 // If the result of load has to be truncated, then it's not necessarily 12421 // profitable. 12422 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12423 return SDValue(); 12424 12425 if (InVec.getOpcode() == ISD::BITCAST) { 12426 // Don't duplicate a load with other uses. 12427 if (!InVec.hasOneUse()) 12428 return SDValue(); 12429 12430 EVT BCVT = InVec.getOperand(0).getValueType(); 12431 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12432 return SDValue(); 12433 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12434 BCNumEltsChanged = true; 12435 InVec = InVec.getOperand(0); 12436 ExtVT = BCVT.getVectorElementType(); 12437 } 12438 12439 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12440 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12441 ISD::isNormalLoad(InVec.getNode()) && 12442 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12443 SDValue Index = N->getOperand(1); 12444 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 12445 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12446 OrigLoad); 12447 } 12448 12449 // Perform only after legalization to ensure build_vector / vector_shuffle 12450 // optimizations have already been done. 12451 if (!LegalOperations) return SDValue(); 12452 12453 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12454 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12455 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12456 12457 if (ConstEltNo) { 12458 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12459 12460 LoadSDNode *LN0 = nullptr; 12461 const ShuffleVectorSDNode *SVN = nullptr; 12462 if (ISD::isNormalLoad(InVec.getNode())) { 12463 LN0 = cast<LoadSDNode>(InVec); 12464 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12465 InVec.getOperand(0).getValueType() == ExtVT && 12466 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12467 // Don't duplicate a load with other uses. 12468 if (!InVec.hasOneUse()) 12469 return SDValue(); 12470 12471 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12472 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12473 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12474 // => 12475 // (load $addr+1*size) 12476 12477 // Don't duplicate a load with other uses. 12478 if (!InVec.hasOneUse()) 12479 return SDValue(); 12480 12481 // If the bit convert changed the number of elements, it is unsafe 12482 // to examine the mask. 12483 if (BCNumEltsChanged) 12484 return SDValue(); 12485 12486 // Select the input vector, guarding against out of range extract vector. 12487 unsigned NumElems = VT.getVectorNumElements(); 12488 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12489 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12490 12491 if (InVec.getOpcode() == ISD::BITCAST) { 12492 // Don't duplicate a load with other uses. 12493 if (!InVec.hasOneUse()) 12494 return SDValue(); 12495 12496 InVec = InVec.getOperand(0); 12497 } 12498 if (ISD::isNormalLoad(InVec.getNode())) { 12499 LN0 = cast<LoadSDNode>(InVec); 12500 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12501 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12502 } 12503 } 12504 12505 // Make sure we found a non-volatile load and the extractelement is 12506 // the only use. 12507 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12508 return SDValue(); 12509 12510 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12511 if (Elt == -1) 12512 return DAG.getUNDEF(LVT); 12513 12514 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12515 } 12516 12517 return SDValue(); 12518 } 12519 12520 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12521 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12522 // We perform this optimization post type-legalization because 12523 // the type-legalizer often scalarizes integer-promoted vectors. 12524 // Performing this optimization before may create bit-casts which 12525 // will be type-legalized to complex code sequences. 12526 // We perform this optimization only before the operation legalizer because we 12527 // may introduce illegal operations. 12528 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12529 return SDValue(); 12530 12531 unsigned NumInScalars = N->getNumOperands(); 12532 SDLoc dl(N); 12533 EVT VT = N->getValueType(0); 12534 12535 // Check to see if this is a BUILD_VECTOR of a bunch of values 12536 // which come from any_extend or zero_extend nodes. If so, we can create 12537 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12538 // optimizations. We do not handle sign-extend because we can't fill the sign 12539 // using shuffles. 12540 EVT SourceType = MVT::Other; 12541 bool AllAnyExt = true; 12542 12543 for (unsigned i = 0; i != NumInScalars; ++i) { 12544 SDValue In = N->getOperand(i); 12545 // Ignore undef inputs. 12546 if (In.isUndef()) continue; 12547 12548 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12549 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12550 12551 // Abort if the element is not an extension. 12552 if (!ZeroExt && !AnyExt) { 12553 SourceType = MVT::Other; 12554 break; 12555 } 12556 12557 // The input is a ZeroExt or AnyExt. Check the original type. 12558 EVT InTy = In.getOperand(0).getValueType(); 12559 12560 // Check that all of the widened source types are the same. 12561 if (SourceType == MVT::Other) 12562 // First time. 12563 SourceType = InTy; 12564 else if (InTy != SourceType) { 12565 // Multiple income types. Abort. 12566 SourceType = MVT::Other; 12567 break; 12568 } 12569 12570 // Check if all of the extends are ANY_EXTENDs. 12571 AllAnyExt &= AnyExt; 12572 } 12573 12574 // In order to have valid types, all of the inputs must be extended from the 12575 // same source type and all of the inputs must be any or zero extend. 12576 // Scalar sizes must be a power of two. 12577 EVT OutScalarTy = VT.getScalarType(); 12578 bool ValidTypes = SourceType != MVT::Other && 12579 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12580 isPowerOf2_32(SourceType.getSizeInBits()); 12581 12582 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12583 // turn into a single shuffle instruction. 12584 if (!ValidTypes) 12585 return SDValue(); 12586 12587 bool isLE = DAG.getDataLayout().isLittleEndian(); 12588 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12589 assert(ElemRatio > 1 && "Invalid element size ratio"); 12590 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12591 DAG.getConstant(0, SDLoc(N), SourceType); 12592 12593 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12594 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12595 12596 // Populate the new build_vector 12597 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12598 SDValue Cast = N->getOperand(i); 12599 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12600 Cast.getOpcode() == ISD::ZERO_EXTEND || 12601 Cast.isUndef()) && "Invalid cast opcode"); 12602 SDValue In; 12603 if (Cast.isUndef()) 12604 In = DAG.getUNDEF(SourceType); 12605 else 12606 In = Cast->getOperand(0); 12607 unsigned Index = isLE ? (i * ElemRatio) : 12608 (i * ElemRatio + (ElemRatio - 1)); 12609 12610 assert(Index < Ops.size() && "Invalid index"); 12611 Ops[Index] = In; 12612 } 12613 12614 // The type of the new BUILD_VECTOR node. 12615 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12616 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12617 "Invalid vector size"); 12618 // Check if the new vector type is legal. 12619 if (!isTypeLegal(VecVT)) return SDValue(); 12620 12621 // Make the new BUILD_VECTOR. 12622 SDValue BV = DAG.getBuildVector(VecVT, dl, Ops); 12623 12624 // The new BUILD_VECTOR node has the potential to be further optimized. 12625 AddToWorklist(BV.getNode()); 12626 // Bitcast to the desired type. 12627 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12628 } 12629 12630 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12631 EVT VT = N->getValueType(0); 12632 12633 unsigned NumInScalars = N->getNumOperands(); 12634 SDLoc dl(N); 12635 12636 EVT SrcVT = MVT::Other; 12637 unsigned Opcode = ISD::DELETED_NODE; 12638 unsigned NumDefs = 0; 12639 12640 for (unsigned i = 0; i != NumInScalars; ++i) { 12641 SDValue In = N->getOperand(i); 12642 unsigned Opc = In.getOpcode(); 12643 12644 if (Opc == ISD::UNDEF) 12645 continue; 12646 12647 // If all scalar values are floats and converted from integers. 12648 if (Opcode == ISD::DELETED_NODE && 12649 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12650 Opcode = Opc; 12651 } 12652 12653 if (Opc != Opcode) 12654 return SDValue(); 12655 12656 EVT InVT = In.getOperand(0).getValueType(); 12657 12658 // If all scalar values are typed differently, bail out. It's chosen to 12659 // simplify BUILD_VECTOR of integer types. 12660 if (SrcVT == MVT::Other) 12661 SrcVT = InVT; 12662 if (SrcVT != InVT) 12663 return SDValue(); 12664 NumDefs++; 12665 } 12666 12667 // If the vector has just one element defined, it's not worth to fold it into 12668 // a vectorized one. 12669 if (NumDefs < 2) 12670 return SDValue(); 12671 12672 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12673 && "Should only handle conversion from integer to float."); 12674 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12675 12676 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12677 12678 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12679 return SDValue(); 12680 12681 // Just because the floating-point vector type is legal does not necessarily 12682 // mean that the corresponding integer vector type is. 12683 if (!isTypeLegal(NVT)) 12684 return SDValue(); 12685 12686 SmallVector<SDValue, 8> Opnds; 12687 for (unsigned i = 0; i != NumInScalars; ++i) { 12688 SDValue In = N->getOperand(i); 12689 12690 if (In.isUndef()) 12691 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12692 else 12693 Opnds.push_back(In.getOperand(0)); 12694 } 12695 SDValue BV = DAG.getBuildVector(NVT, dl, Opnds); 12696 AddToWorklist(BV.getNode()); 12697 12698 return DAG.getNode(Opcode, dl, VT, BV); 12699 } 12700 12701 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12702 unsigned NumInScalars = N->getNumOperands(); 12703 SDLoc dl(N); 12704 EVT VT = N->getValueType(0); 12705 12706 // A vector built entirely of undefs is undef. 12707 if (ISD::allOperandsUndef(N)) 12708 return DAG.getUNDEF(VT); 12709 12710 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12711 return V; 12712 12713 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12714 return V; 12715 12716 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12717 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12718 // at most two distinct vectors, turn this into a shuffle node. 12719 12720 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12721 if (!isTypeLegal(VT)) 12722 return SDValue(); 12723 12724 // May only combine to shuffle after legalize if shuffle is legal. 12725 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12726 return SDValue(); 12727 12728 SDValue VecIn1, VecIn2; 12729 bool UsesZeroVector = false; 12730 for (unsigned i = 0; i != NumInScalars; ++i) { 12731 SDValue Op = N->getOperand(i); 12732 // Ignore undef inputs. 12733 if (Op.isUndef()) continue; 12734 12735 // See if we can combine this build_vector into a blend with a zero vector. 12736 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12737 UsesZeroVector = true; 12738 continue; 12739 } 12740 12741 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12742 // constant index, bail out. 12743 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12744 !isa<ConstantSDNode>(Op.getOperand(1))) { 12745 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12746 break; 12747 } 12748 12749 // We allow up to two distinct input vectors. 12750 SDValue ExtractedFromVec = Op.getOperand(0); 12751 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12752 continue; 12753 12754 if (!VecIn1.getNode()) { 12755 VecIn1 = ExtractedFromVec; 12756 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12757 VecIn2 = ExtractedFromVec; 12758 } else { 12759 // Too many inputs. 12760 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12761 break; 12762 } 12763 } 12764 12765 // If everything is good, we can make a shuffle operation. 12766 if (VecIn1.getNode()) { 12767 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12768 SmallVector<int, 8> Mask; 12769 for (unsigned i = 0; i != NumInScalars; ++i) { 12770 unsigned Opcode = N->getOperand(i).getOpcode(); 12771 if (Opcode == ISD::UNDEF) { 12772 Mask.push_back(-1); 12773 continue; 12774 } 12775 12776 // Operands can also be zero. 12777 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12778 assert(UsesZeroVector && 12779 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12780 "Unexpected node found!"); 12781 Mask.push_back(NumInScalars+i); 12782 continue; 12783 } 12784 12785 // If extracting from the first vector, just use the index directly. 12786 SDValue Extract = N->getOperand(i); 12787 SDValue ExtVal = Extract.getOperand(1); 12788 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12789 if (Extract.getOperand(0) == VecIn1) { 12790 Mask.push_back(ExtIndex); 12791 continue; 12792 } 12793 12794 // Otherwise, use InIdx + InputVecSize 12795 Mask.push_back(InNumElements + ExtIndex); 12796 } 12797 12798 // Avoid introducing illegal shuffles with zero. 12799 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12800 return SDValue(); 12801 12802 // We can't generate a shuffle node with mismatched input and output types. 12803 // Attempt to transform a single input vector to the correct type. 12804 if ((VT != VecIn1.getValueType())) { 12805 // If the input vector type has a different base type to the output 12806 // vector type, bail out. 12807 EVT VTElemType = VT.getVectorElementType(); 12808 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12809 (VecIn2.getNode() && 12810 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12811 return SDValue(); 12812 12813 // If the input vector is too small, widen it. 12814 // We only support widening of vectors which are half the size of the 12815 // output registers. For example XMM->YMM widening on X86 with AVX. 12816 EVT VecInT = VecIn1.getValueType(); 12817 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12818 // If we only have one small input, widen it by adding undef values. 12819 if (!VecIn2.getNode()) 12820 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12821 DAG.getUNDEF(VecIn1.getValueType())); 12822 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12823 // If we have two small inputs of the same type, try to concat them. 12824 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12825 VecIn2 = SDValue(nullptr, 0); 12826 } else 12827 return SDValue(); 12828 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12829 // If the input vector is too large, try to split it. 12830 // We don't support having two input vectors that are too large. 12831 // If the zero vector was used, we can not split the vector, 12832 // since we'd need 3 inputs. 12833 if (UsesZeroVector || VecIn2.getNode()) 12834 return SDValue(); 12835 12836 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12837 return SDValue(); 12838 12839 // Try to replace VecIn1 with two extract_subvectors 12840 // No need to update the masks, they should still be correct. 12841 VecIn2 = DAG.getNode( 12842 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12843 DAG.getConstant(VT.getVectorNumElements(), dl, 12844 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12845 VecIn1 = DAG.getNode( 12846 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12847 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12848 } else 12849 return SDValue(); 12850 } 12851 12852 if (UsesZeroVector) 12853 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12854 DAG.getConstantFP(0.0, dl, VT); 12855 else 12856 // If VecIn2 is unused then change it to undef. 12857 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12858 12859 // Check that we were able to transform all incoming values to the same 12860 // type. 12861 if (VecIn2.getValueType() != VecIn1.getValueType() || 12862 VecIn1.getValueType() != VT) 12863 return SDValue(); 12864 12865 // Return the new VECTOR_SHUFFLE node. 12866 SDValue Ops[2]; 12867 Ops[0] = VecIn1; 12868 Ops[1] = VecIn2; 12869 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12870 } 12871 12872 return SDValue(); 12873 } 12874 12875 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12876 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12877 EVT OpVT = N->getOperand(0).getValueType(); 12878 12879 // If the operands are legal vectors, leave them alone. 12880 if (TLI.isTypeLegal(OpVT)) 12881 return SDValue(); 12882 12883 SDLoc DL(N); 12884 EVT VT = N->getValueType(0); 12885 SmallVector<SDValue, 8> Ops; 12886 12887 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12888 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12889 12890 // Keep track of what we encounter. 12891 bool AnyInteger = false; 12892 bool AnyFP = false; 12893 for (const SDValue &Op : N->ops()) { 12894 if (ISD::BITCAST == Op.getOpcode() && 12895 !Op.getOperand(0).getValueType().isVector()) 12896 Ops.push_back(Op.getOperand(0)); 12897 else if (ISD::UNDEF == Op.getOpcode()) 12898 Ops.push_back(ScalarUndef); 12899 else 12900 return SDValue(); 12901 12902 // Note whether we encounter an integer or floating point scalar. 12903 // If it's neither, bail out, it could be something weird like x86mmx. 12904 EVT LastOpVT = Ops.back().getValueType(); 12905 if (LastOpVT.isFloatingPoint()) 12906 AnyFP = true; 12907 else if (LastOpVT.isInteger()) 12908 AnyInteger = true; 12909 else 12910 return SDValue(); 12911 } 12912 12913 // If any of the operands is a floating point scalar bitcast to a vector, 12914 // use floating point types throughout, and bitcast everything. 12915 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12916 if (AnyFP) { 12917 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12918 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12919 if (AnyInteger) { 12920 for (SDValue &Op : Ops) { 12921 if (Op.getValueType() == SVT) 12922 continue; 12923 if (Op.isUndef()) 12924 Op = ScalarUndef; 12925 else 12926 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12927 } 12928 } 12929 } 12930 12931 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12932 VT.getSizeInBits() / SVT.getSizeInBits()); 12933 return DAG.getNode(ISD::BITCAST, DL, VT, 12934 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.getNode(ISD::BITCAST, dl, 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 bool AllBuildVectorsOrUndefs = 13074 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 13075 if (AllBuildVectorsOrUndefs) { 13076 SmallVector<SDValue, 8> Opnds; 13077 EVT SVT = VT.getScalarType(); 13078 13079 EVT MinVT = SVT; 13080 if (!SVT.isFloatingPoint()) { 13081 // If BUILD_VECTOR are from built from integer, they may have different 13082 // operand types. Get the smallest type and truncate all operands to it. 13083 bool FoundMinVT = false; 13084 for (const SDValue &Op : N->ops()) 13085 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13086 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13087 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13088 FoundMinVT = true; 13089 } 13090 assert(FoundMinVT && "Concat vector type mismatch"); 13091 } 13092 13093 for (const SDValue &Op : N->ops()) { 13094 EVT OpVT = Op.getValueType(); 13095 unsigned NumElts = OpVT.getVectorNumElements(); 13096 13097 if (ISD::UNDEF == Op.getOpcode()) 13098 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13099 13100 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13101 if (SVT.isFloatingPoint()) { 13102 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13103 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13104 } else { 13105 for (unsigned i = 0; i != NumElts; ++i) 13106 Opnds.push_back( 13107 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13108 } 13109 } 13110 } 13111 13112 assert(VT.getVectorNumElements() == Opnds.size() && 13113 "Concat vector type mismatch"); 13114 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13115 } 13116 13117 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13118 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13119 return V; 13120 13121 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13122 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13123 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13124 return V; 13125 13126 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13127 // nodes often generate nop CONCAT_VECTOR nodes. 13128 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13129 // place the incoming vectors at the exact same location. 13130 SDValue SingleSource = SDValue(); 13131 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13132 13133 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13134 SDValue Op = N->getOperand(i); 13135 13136 if (Op.isUndef()) 13137 continue; 13138 13139 // Check if this is the identity extract: 13140 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13141 return SDValue(); 13142 13143 // Find the single incoming vector for the extract_subvector. 13144 if (SingleSource.getNode()) { 13145 if (Op.getOperand(0) != SingleSource) 13146 return SDValue(); 13147 } else { 13148 SingleSource = Op.getOperand(0); 13149 13150 // Check the source type is the same as the type of the result. 13151 // If not, this concat may extend the vector, so we can not 13152 // optimize it away. 13153 if (SingleSource.getValueType() != N->getValueType(0)) 13154 return SDValue(); 13155 } 13156 13157 unsigned IdentityIndex = i * PartNumElem; 13158 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13159 // The extract index must be constant. 13160 if (!CS) 13161 return SDValue(); 13162 13163 // Check that we are reading from the identity index. 13164 if (CS->getZExtValue() != IdentityIndex) 13165 return SDValue(); 13166 } 13167 13168 if (SingleSource.getNode()) 13169 return SingleSource; 13170 13171 return SDValue(); 13172 } 13173 13174 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13175 EVT NVT = N->getValueType(0); 13176 SDValue V = N->getOperand(0); 13177 13178 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13179 // Combine: 13180 // (extract_subvec (concat V1, V2, ...), i) 13181 // Into: 13182 // Vi if possible 13183 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13184 // type. 13185 if (V->getOperand(0).getValueType() != NVT) 13186 return SDValue(); 13187 unsigned Idx = N->getConstantOperandVal(1); 13188 unsigned NumElems = NVT.getVectorNumElements(); 13189 assert((Idx % NumElems) == 0 && 13190 "IDX in concat is not a multiple of the result vector length."); 13191 return V->getOperand(Idx / NumElems); 13192 } 13193 13194 // Skip bitcasting 13195 if (V->getOpcode() == ISD::BITCAST) 13196 V = V.getOperand(0); 13197 13198 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13199 SDLoc dl(N); 13200 // Handle only simple case where vector being inserted and vector 13201 // being extracted are of same type, and are half size of larger vectors. 13202 EVT BigVT = V->getOperand(0).getValueType(); 13203 EVT SmallVT = V->getOperand(1).getValueType(); 13204 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13205 return SDValue(); 13206 13207 // Only handle cases where both indexes are constants with the same type. 13208 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13209 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13210 13211 if (InsIdx && ExtIdx && 13212 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13213 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13214 // Combine: 13215 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13216 // Into: 13217 // indices are equal or bit offsets are equal => V1 13218 // otherwise => (extract_subvec V1, ExtIdx) 13219 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13220 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13221 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 13222 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 13223 DAG.getNode(ISD::BITCAST, dl, 13224 N->getOperand(0).getValueType(), 13225 V->getOperand(0)), N->getOperand(1)); 13226 } 13227 } 13228 13229 return SDValue(); 13230 } 13231 13232 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13233 SDValue V, SelectionDAG &DAG) { 13234 SDLoc DL(V); 13235 EVT VT = V.getValueType(); 13236 13237 switch (V.getOpcode()) { 13238 default: 13239 return V; 13240 13241 case ISD::CONCAT_VECTORS: { 13242 EVT OpVT = V->getOperand(0).getValueType(); 13243 int OpSize = OpVT.getVectorNumElements(); 13244 SmallBitVector OpUsedElements(OpSize, false); 13245 bool FoundSimplification = false; 13246 SmallVector<SDValue, 4> NewOps; 13247 NewOps.reserve(V->getNumOperands()); 13248 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13249 SDValue Op = V->getOperand(i); 13250 bool OpUsed = false; 13251 for (int j = 0; j < OpSize; ++j) 13252 if (UsedElements[i * OpSize + j]) { 13253 OpUsedElements[j] = true; 13254 OpUsed = true; 13255 } 13256 NewOps.push_back( 13257 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13258 : DAG.getUNDEF(OpVT)); 13259 FoundSimplification |= Op == NewOps.back(); 13260 OpUsedElements.reset(); 13261 } 13262 if (FoundSimplification) 13263 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13264 return V; 13265 } 13266 13267 case ISD::INSERT_SUBVECTOR: { 13268 SDValue BaseV = V->getOperand(0); 13269 SDValue SubV = V->getOperand(1); 13270 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13271 if (!IdxN) 13272 return V; 13273 13274 int SubSize = SubV.getValueType().getVectorNumElements(); 13275 int Idx = IdxN->getZExtValue(); 13276 bool SubVectorUsed = false; 13277 SmallBitVector SubUsedElements(SubSize, false); 13278 for (int i = 0; i < SubSize; ++i) 13279 if (UsedElements[i + Idx]) { 13280 SubVectorUsed = true; 13281 SubUsedElements[i] = true; 13282 UsedElements[i + Idx] = false; 13283 } 13284 13285 // Now recurse on both the base and sub vectors. 13286 SDValue SimplifiedSubV = 13287 SubVectorUsed 13288 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13289 : DAG.getUNDEF(SubV.getValueType()); 13290 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13291 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13292 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13293 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13294 return V; 13295 } 13296 } 13297 } 13298 13299 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13300 SDValue N1, SelectionDAG &DAG) { 13301 EVT VT = SVN->getValueType(0); 13302 int NumElts = VT.getVectorNumElements(); 13303 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13304 for (int M : SVN->getMask()) 13305 if (M >= 0 && M < NumElts) 13306 N0UsedElements[M] = true; 13307 else if (M >= NumElts) 13308 N1UsedElements[M - NumElts] = true; 13309 13310 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13311 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13312 if (S0 == N0 && S1 == N1) 13313 return SDValue(); 13314 13315 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13316 } 13317 13318 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13319 // or turn a shuffle of a single concat into simpler shuffle then concat. 13320 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13321 EVT VT = N->getValueType(0); 13322 unsigned NumElts = VT.getVectorNumElements(); 13323 13324 SDValue N0 = N->getOperand(0); 13325 SDValue N1 = N->getOperand(1); 13326 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13327 13328 SmallVector<SDValue, 4> Ops; 13329 EVT ConcatVT = N0.getOperand(0).getValueType(); 13330 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13331 unsigned NumConcats = NumElts / NumElemsPerConcat; 13332 13333 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13334 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13335 // half vector elements. 13336 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13337 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13338 SVN->getMask().end(), [](int i) { return i == -1; })) { 13339 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13340 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13341 N1 = DAG.getUNDEF(ConcatVT); 13342 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13343 } 13344 13345 // Look at every vector that's inserted. We're looking for exact 13346 // subvector-sized copies from a concatenated vector 13347 for (unsigned I = 0; I != NumConcats; ++I) { 13348 // Make sure we're dealing with a copy. 13349 unsigned Begin = I * NumElemsPerConcat; 13350 bool AllUndef = true, NoUndef = true; 13351 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13352 if (SVN->getMaskElt(J) >= 0) 13353 AllUndef = false; 13354 else 13355 NoUndef = false; 13356 } 13357 13358 if (NoUndef) { 13359 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13360 return SDValue(); 13361 13362 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13363 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13364 return SDValue(); 13365 13366 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13367 if (FirstElt < N0.getNumOperands()) 13368 Ops.push_back(N0.getOperand(FirstElt)); 13369 else 13370 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13371 13372 } else if (AllUndef) { 13373 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13374 } else { // Mixed with general masks and undefs, can't do optimization. 13375 return SDValue(); 13376 } 13377 } 13378 13379 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13380 } 13381 13382 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13383 EVT VT = N->getValueType(0); 13384 unsigned NumElts = VT.getVectorNumElements(); 13385 13386 SDValue N0 = N->getOperand(0); 13387 SDValue N1 = N->getOperand(1); 13388 13389 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13390 13391 // Canonicalize shuffle undef, undef -> undef 13392 if (N0.isUndef() && N1.isUndef()) 13393 return DAG.getUNDEF(VT); 13394 13395 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13396 13397 // Canonicalize shuffle v, v -> v, undef 13398 if (N0 == N1) { 13399 SmallVector<int, 8> NewMask; 13400 for (unsigned i = 0; i != NumElts; ++i) { 13401 int Idx = SVN->getMaskElt(i); 13402 if (Idx >= (int)NumElts) Idx -= NumElts; 13403 NewMask.push_back(Idx); 13404 } 13405 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 13406 &NewMask[0]); 13407 } 13408 13409 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13410 if (N0.isUndef()) { 13411 SmallVector<int, 8> NewMask; 13412 for (unsigned i = 0; i != NumElts; ++i) { 13413 int Idx = SVN->getMaskElt(i); 13414 if (Idx >= 0) { 13415 if (Idx >= (int)NumElts) 13416 Idx -= NumElts; 13417 else 13418 Idx = -1; // remove reference to lhs 13419 } 13420 NewMask.push_back(Idx); 13421 } 13422 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 13423 &NewMask[0]); 13424 } 13425 13426 // Remove references to rhs if it is undef 13427 if (N1.isUndef()) { 13428 bool Changed = false; 13429 SmallVector<int, 8> NewMask; 13430 for (unsigned i = 0; i != NumElts; ++i) { 13431 int Idx = SVN->getMaskElt(i); 13432 if (Idx >= (int)NumElts) { 13433 Idx = -1; 13434 Changed = true; 13435 } 13436 NewMask.push_back(Idx); 13437 } 13438 if (Changed) 13439 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 13440 } 13441 13442 // If it is a splat, check if the argument vector is another splat or a 13443 // build_vector. 13444 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13445 SDNode *V = N0.getNode(); 13446 13447 // If this is a bit convert that changes the element type of the vector but 13448 // not the number of vector elements, look through it. Be careful not to 13449 // look though conversions that change things like v4f32 to v2f64. 13450 if (V->getOpcode() == ISD::BITCAST) { 13451 SDValue ConvInput = V->getOperand(0); 13452 if (ConvInput.getValueType().isVector() && 13453 ConvInput.getValueType().getVectorNumElements() == NumElts) 13454 V = ConvInput.getNode(); 13455 } 13456 13457 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13458 assert(V->getNumOperands() == NumElts && 13459 "BUILD_VECTOR has wrong number of operands"); 13460 SDValue Base; 13461 bool AllSame = true; 13462 for (unsigned i = 0; i != NumElts; ++i) { 13463 if (!V->getOperand(i).isUndef()) { 13464 Base = V->getOperand(i); 13465 break; 13466 } 13467 } 13468 // Splat of <u, u, u, u>, return <u, u, u, u> 13469 if (!Base.getNode()) 13470 return N0; 13471 for (unsigned i = 0; i != NumElts; ++i) { 13472 if (V->getOperand(i) != Base) { 13473 AllSame = false; 13474 break; 13475 } 13476 } 13477 // Splat of <x, x, x, x>, return <x, x, x, x> 13478 if (AllSame) 13479 return N0; 13480 13481 // Canonicalize any other splat as a build_vector. 13482 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13483 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13484 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 13485 13486 // We may have jumped through bitcasts, so the type of the 13487 // BUILD_VECTOR may not match the type of the shuffle. 13488 if (V->getValueType(0) != VT) 13489 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13490 return NewBV; 13491 } 13492 } 13493 13494 // There are various patterns used to build up a vector from smaller vectors, 13495 // subvectors, or elements. Scan chains of these and replace unused insertions 13496 // or components with undef. 13497 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13498 return S; 13499 13500 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13501 Level < AfterLegalizeVectorOps && 13502 (N1.isUndef() || 13503 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13504 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13505 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13506 return V; 13507 } 13508 13509 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13510 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13511 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13512 SmallVector<SDValue, 8> Ops; 13513 for (int M : SVN->getMask()) { 13514 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13515 if (M >= 0) { 13516 int Idx = M % NumElts; 13517 SDValue &S = (M < (int)NumElts ? N0 : N1); 13518 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13519 Op = S.getOperand(Idx); 13520 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13521 if (Idx == 0) 13522 Op = S.getOperand(0); 13523 } else { 13524 // Operand can't be combined - bail out. 13525 break; 13526 } 13527 } 13528 Ops.push_back(Op); 13529 } 13530 if (Ops.size() == VT.getVectorNumElements()) { 13531 // BUILD_VECTOR requires all inputs to be of the same type, find the 13532 // maximum type and extend them all. 13533 EVT SVT = VT.getScalarType(); 13534 if (SVT.isInteger()) 13535 for (SDValue &Op : Ops) 13536 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13537 if (SVT != VT.getScalarType()) 13538 for (SDValue &Op : Ops) 13539 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13540 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13541 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13542 return DAG.getBuildVector(VT, SDLoc(N), Ops); 13543 } 13544 } 13545 13546 // If this shuffle only has a single input that is a bitcasted shuffle, 13547 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13548 // back to their original types. 13549 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13550 N1.isUndef() && Level < AfterLegalizeVectorOps && 13551 TLI.isTypeLegal(VT)) { 13552 13553 // Peek through the bitcast only if there is one user. 13554 SDValue BC0 = N0; 13555 while (BC0.getOpcode() == ISD::BITCAST) { 13556 if (!BC0.hasOneUse()) 13557 break; 13558 BC0 = BC0.getOperand(0); 13559 } 13560 13561 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13562 if (Scale == 1) 13563 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13564 13565 SmallVector<int, 8> NewMask; 13566 for (int M : Mask) 13567 for (int s = 0; s != Scale; ++s) 13568 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13569 return NewMask; 13570 }; 13571 13572 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13573 EVT SVT = VT.getScalarType(); 13574 EVT InnerVT = BC0->getValueType(0); 13575 EVT InnerSVT = InnerVT.getScalarType(); 13576 13577 // Determine which shuffle works with the smaller scalar type. 13578 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13579 EVT ScaleSVT = ScaleVT.getScalarType(); 13580 13581 if (TLI.isTypeLegal(ScaleVT) && 13582 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13583 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13584 13585 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13586 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13587 13588 // Scale the shuffle masks to the smaller scalar type. 13589 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13590 SmallVector<int, 8> InnerMask = 13591 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13592 SmallVector<int, 8> OuterMask = 13593 ScaleShuffleMask(SVN->getMask(), OuterScale); 13594 13595 // Merge the shuffle masks. 13596 SmallVector<int, 8> NewMask; 13597 for (int M : OuterMask) 13598 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13599 13600 // Test for shuffle mask legality over both commutations. 13601 SDValue SV0 = BC0->getOperand(0); 13602 SDValue SV1 = BC0->getOperand(1); 13603 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13604 if (!LegalMask) { 13605 std::swap(SV0, SV1); 13606 ShuffleVectorSDNode::commuteMask(NewMask); 13607 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13608 } 13609 13610 if (LegalMask) { 13611 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13612 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13613 return DAG.getNode( 13614 ISD::BITCAST, SDLoc(N), VT, 13615 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13616 } 13617 } 13618 } 13619 } 13620 13621 // Canonicalize shuffles according to rules: 13622 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13623 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13624 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13625 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13626 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13627 TLI.isTypeLegal(VT)) { 13628 // The incoming shuffle must be of the same type as the result of the 13629 // current shuffle. 13630 assert(N1->getOperand(0).getValueType() == VT && 13631 "Shuffle types don't match"); 13632 13633 SDValue SV0 = N1->getOperand(0); 13634 SDValue SV1 = N1->getOperand(1); 13635 bool HasSameOp0 = N0 == SV0; 13636 bool IsSV1Undef = SV1.isUndef(); 13637 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13638 // Commute the operands of this shuffle so that next rule 13639 // will trigger. 13640 return DAG.getCommutedVectorShuffle(*SVN); 13641 } 13642 13643 // Try to fold according to rules: 13644 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13645 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13646 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13647 // Don't try to fold shuffles with illegal type. 13648 // Only fold if this shuffle is the only user of the other shuffle. 13649 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13650 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13651 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13652 13653 // The incoming shuffle must be of the same type as the result of the 13654 // current shuffle. 13655 assert(OtherSV->getOperand(0).getValueType() == VT && 13656 "Shuffle types don't match"); 13657 13658 SDValue SV0, SV1; 13659 SmallVector<int, 4> Mask; 13660 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13661 // operand, and SV1 as the second operand. 13662 for (unsigned i = 0; i != NumElts; ++i) { 13663 int Idx = SVN->getMaskElt(i); 13664 if (Idx < 0) { 13665 // Propagate Undef. 13666 Mask.push_back(Idx); 13667 continue; 13668 } 13669 13670 SDValue CurrentVec; 13671 if (Idx < (int)NumElts) { 13672 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13673 // shuffle mask to identify which vector is actually referenced. 13674 Idx = OtherSV->getMaskElt(Idx); 13675 if (Idx < 0) { 13676 // Propagate Undef. 13677 Mask.push_back(Idx); 13678 continue; 13679 } 13680 13681 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13682 : OtherSV->getOperand(1); 13683 } else { 13684 // This shuffle index references an element within N1. 13685 CurrentVec = N1; 13686 } 13687 13688 // Simple case where 'CurrentVec' is UNDEF. 13689 if (CurrentVec.isUndef()) { 13690 Mask.push_back(-1); 13691 continue; 13692 } 13693 13694 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13695 // will be the first or second operand of the combined shuffle. 13696 Idx = Idx % NumElts; 13697 if (!SV0.getNode() || SV0 == CurrentVec) { 13698 // Ok. CurrentVec is the left hand side. 13699 // Update the mask accordingly. 13700 SV0 = CurrentVec; 13701 Mask.push_back(Idx); 13702 continue; 13703 } 13704 13705 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13706 if (SV1.getNode() && SV1 != CurrentVec) 13707 return SDValue(); 13708 13709 // Ok. CurrentVec is the right hand side. 13710 // Update the mask accordingly. 13711 SV1 = CurrentVec; 13712 Mask.push_back(Idx + NumElts); 13713 } 13714 13715 // Check if all indices in Mask are Undef. In case, propagate Undef. 13716 bool isUndefMask = true; 13717 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13718 isUndefMask &= Mask[i] < 0; 13719 13720 if (isUndefMask) 13721 return DAG.getUNDEF(VT); 13722 13723 if (!SV0.getNode()) 13724 SV0 = DAG.getUNDEF(VT); 13725 if (!SV1.getNode()) 13726 SV1 = DAG.getUNDEF(VT); 13727 13728 // Avoid introducing shuffles with illegal mask. 13729 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13730 ShuffleVectorSDNode::commuteMask(Mask); 13731 13732 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13733 return SDValue(); 13734 13735 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13736 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13737 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13738 std::swap(SV0, SV1); 13739 } 13740 13741 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13742 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13743 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13744 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13745 } 13746 13747 return SDValue(); 13748 } 13749 13750 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13751 SDValue InVal = N->getOperand(0); 13752 EVT VT = N->getValueType(0); 13753 13754 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13755 // with a VECTOR_SHUFFLE. 13756 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13757 SDValue InVec = InVal->getOperand(0); 13758 SDValue EltNo = InVal->getOperand(1); 13759 13760 // FIXME: We could support implicit truncation if the shuffle can be 13761 // scaled to a smaller vector scalar type. 13762 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13763 if (C0 && VT == InVec.getValueType() && 13764 VT.getScalarType() == InVal.getValueType()) { 13765 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13766 int Elt = C0->getZExtValue(); 13767 NewMask[0] = Elt; 13768 13769 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13770 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13771 NewMask); 13772 } 13773 } 13774 13775 return SDValue(); 13776 } 13777 13778 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13779 SDValue N0 = N->getOperand(0); 13780 SDValue N2 = N->getOperand(2); 13781 13782 // If the input vector is a concatenation, and the insert replaces 13783 // one of the halves, we can optimize into a single concat_vectors. 13784 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13785 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13786 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13787 EVT VT = N->getValueType(0); 13788 13789 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13790 // (concat_vectors Z, Y) 13791 if (InsIdx == 0) 13792 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13793 N->getOperand(1), N0.getOperand(1)); 13794 13795 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13796 // (concat_vectors X, Z) 13797 if (InsIdx == VT.getVectorNumElements()/2) 13798 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13799 N0.getOperand(0), N->getOperand(1)); 13800 } 13801 13802 return SDValue(); 13803 } 13804 13805 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13806 SDValue N0 = N->getOperand(0); 13807 13808 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13809 if (N0->getOpcode() == ISD::FP16_TO_FP) 13810 return N0->getOperand(0); 13811 13812 return SDValue(); 13813 } 13814 13815 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13816 SDValue N0 = N->getOperand(0); 13817 13818 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13819 if (N0->getOpcode() == ISD::AND) { 13820 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13821 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13822 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13823 N0.getOperand(0)); 13824 } 13825 } 13826 13827 return SDValue(); 13828 } 13829 13830 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13831 /// with the destination vector and a zero vector. 13832 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13833 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13834 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13835 EVT VT = N->getValueType(0); 13836 SDValue LHS = N->getOperand(0); 13837 SDValue RHS = N->getOperand(1); 13838 SDLoc dl(N); 13839 13840 // Make sure we're not running after operation legalization where it 13841 // may have custom lowered the vector shuffles. 13842 if (LegalOperations) 13843 return SDValue(); 13844 13845 if (N->getOpcode() != ISD::AND) 13846 return SDValue(); 13847 13848 if (RHS.getOpcode() == ISD::BITCAST) 13849 RHS = RHS.getOperand(0); 13850 13851 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13852 return SDValue(); 13853 13854 EVT RVT = RHS.getValueType(); 13855 unsigned NumElts = RHS.getNumOperands(); 13856 13857 // Attempt to create a valid clear mask, splitting the mask into 13858 // sub elements and checking to see if each is 13859 // all zeros or all ones - suitable for shuffle masking. 13860 auto BuildClearMask = [&](int Split) { 13861 int NumSubElts = NumElts * Split; 13862 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13863 13864 SmallVector<int, 8> Indices; 13865 for (int i = 0; i != NumSubElts; ++i) { 13866 int EltIdx = i / Split; 13867 int SubIdx = i % Split; 13868 SDValue Elt = RHS.getOperand(EltIdx); 13869 if (Elt.isUndef()) { 13870 Indices.push_back(-1); 13871 continue; 13872 } 13873 13874 APInt Bits; 13875 if (isa<ConstantSDNode>(Elt)) 13876 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13877 else if (isa<ConstantFPSDNode>(Elt)) 13878 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13879 else 13880 return SDValue(); 13881 13882 // Extract the sub element from the constant bit mask. 13883 if (DAG.getDataLayout().isBigEndian()) { 13884 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13885 } else { 13886 Bits = Bits.lshr(SubIdx * NumSubBits); 13887 } 13888 13889 if (Split > 1) 13890 Bits = Bits.trunc(NumSubBits); 13891 13892 if (Bits.isAllOnesValue()) 13893 Indices.push_back(i); 13894 else if (Bits == 0) 13895 Indices.push_back(i + NumSubElts); 13896 else 13897 return SDValue(); 13898 } 13899 13900 // Let's see if the target supports this vector_shuffle. 13901 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13902 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13903 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13904 return SDValue(); 13905 13906 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13907 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13908 DAG.getBitcast(ClearVT, LHS), 13909 Zero, &Indices[0])); 13910 }; 13911 13912 // Determine maximum split level (byte level masking). 13913 int MaxSplit = 1; 13914 if (RVT.getScalarSizeInBits() % 8 == 0) 13915 MaxSplit = RVT.getScalarSizeInBits() / 8; 13916 13917 for (int Split = 1; Split <= MaxSplit; ++Split) 13918 if (RVT.getScalarSizeInBits() % Split == 0) 13919 if (SDValue S = BuildClearMask(Split)) 13920 return S; 13921 13922 return SDValue(); 13923 } 13924 13925 /// Visit a binary vector operation, like ADD. 13926 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13927 assert(N->getValueType(0).isVector() && 13928 "SimplifyVBinOp only works on vectors!"); 13929 13930 SDValue LHS = N->getOperand(0); 13931 SDValue RHS = N->getOperand(1); 13932 SDValue Ops[] = {LHS, RHS}; 13933 13934 // See if we can constant fold the vector operation. 13935 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13936 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13937 return Fold; 13938 13939 // Try to convert a constant mask AND into a shuffle clear mask. 13940 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13941 return Shuffle; 13942 13943 // Type legalization might introduce new shuffles in the DAG. 13944 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13945 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13946 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13947 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13948 LHS.getOperand(1).isUndef() && 13949 RHS.getOperand(1).isUndef()) { 13950 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13951 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13952 13953 if (SVN0->getMask().equals(SVN1->getMask())) { 13954 EVT VT = N->getValueType(0); 13955 SDValue UndefVector = LHS.getOperand(1); 13956 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13957 LHS.getOperand(0), RHS.getOperand(0), 13958 N->getFlags()); 13959 AddUsersToWorklist(N); 13960 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13961 &SVN0->getMask()[0]); 13962 } 13963 } 13964 13965 return SDValue(); 13966 } 13967 13968 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13969 SDValue N1, SDValue N2){ 13970 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13971 13972 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13973 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13974 13975 // If we got a simplified select_cc node back from SimplifySelectCC, then 13976 // break it down into a new SETCC node, and a new SELECT node, and then return 13977 // the SELECT node, since we were called with a SELECT node. 13978 if (SCC.getNode()) { 13979 // Check to see if we got a select_cc back (to turn into setcc/select). 13980 // Otherwise, just return whatever node we got back, like fabs. 13981 if (SCC.getOpcode() == ISD::SELECT_CC) { 13982 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13983 N0.getValueType(), 13984 SCC.getOperand(0), SCC.getOperand(1), 13985 SCC.getOperand(4)); 13986 AddToWorklist(SETCC.getNode()); 13987 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13988 SCC.getOperand(2), SCC.getOperand(3)); 13989 } 13990 13991 return SCC; 13992 } 13993 return SDValue(); 13994 } 13995 13996 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13997 /// being selected between, see if we can simplify the select. Callers of this 13998 /// should assume that TheSelect is deleted if this returns true. As such, they 13999 /// should return the appropriate thing (e.g. the node) back to the top-level of 14000 /// the DAG combiner loop to avoid it being looked at. 14001 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 14002 SDValue RHS) { 14003 14004 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14005 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 14006 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 14007 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 14008 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 14009 SDValue Sqrt = RHS; 14010 ISD::CondCode CC; 14011 SDValue CmpLHS; 14012 const ConstantFPSDNode *Zero = nullptr; 14013 14014 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 14015 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 14016 CmpLHS = TheSelect->getOperand(0); 14017 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 14018 } else { 14019 // SELECT or VSELECT 14020 SDValue Cmp = TheSelect->getOperand(0); 14021 if (Cmp.getOpcode() == ISD::SETCC) { 14022 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 14023 CmpLHS = Cmp.getOperand(0); 14024 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 14025 } 14026 } 14027 if (Zero && Zero->isZero() && 14028 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 14029 CC == ISD::SETULT || CC == ISD::SETLT)) { 14030 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14031 CombineTo(TheSelect, Sqrt); 14032 return true; 14033 } 14034 } 14035 } 14036 // Cannot simplify select with vector condition 14037 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 14038 14039 // If this is a select from two identical things, try to pull the operation 14040 // through the select. 14041 if (LHS.getOpcode() != RHS.getOpcode() || 14042 !LHS.hasOneUse() || !RHS.hasOneUse()) 14043 return false; 14044 14045 // If this is a load and the token chain is identical, replace the select 14046 // of two loads with a load through a select of the address to load from. 14047 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 14048 // constants have been dropped into the constant pool. 14049 if (LHS.getOpcode() == ISD::LOAD) { 14050 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 14051 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 14052 14053 // Token chains must be identical. 14054 if (LHS.getOperand(0) != RHS.getOperand(0) || 14055 // Do not let this transformation reduce the number of volatile loads. 14056 LLD->isVolatile() || RLD->isVolatile() || 14057 // FIXME: If either is a pre/post inc/dec load, 14058 // we'd need to split out the address adjustment. 14059 LLD->isIndexed() || RLD->isIndexed() || 14060 // If this is an EXTLOAD, the VT's must match. 14061 LLD->getMemoryVT() != RLD->getMemoryVT() || 14062 // If this is an EXTLOAD, the kind of extension must match. 14063 (LLD->getExtensionType() != RLD->getExtensionType() && 14064 // The only exception is if one of the extensions is anyext. 14065 LLD->getExtensionType() != ISD::EXTLOAD && 14066 RLD->getExtensionType() != ISD::EXTLOAD) || 14067 // FIXME: this discards src value information. This is 14068 // over-conservative. It would be beneficial to be able to remember 14069 // both potential memory locations. Since we are discarding 14070 // src value info, don't do the transformation if the memory 14071 // locations are not in the default address space. 14072 LLD->getPointerInfo().getAddrSpace() != 0 || 14073 RLD->getPointerInfo().getAddrSpace() != 0 || 14074 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 14075 LLD->getBasePtr().getValueType())) 14076 return false; 14077 14078 // Check that the select condition doesn't reach either load. If so, 14079 // folding this will induce a cycle into the DAG. If not, this is safe to 14080 // xform, so create a select of the addresses. 14081 SDValue Addr; 14082 if (TheSelect->getOpcode() == ISD::SELECT) { 14083 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 14084 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 14085 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 14086 return false; 14087 // The loads must not depend on one another. 14088 if (LLD->isPredecessorOf(RLD) || 14089 RLD->isPredecessorOf(LLD)) 14090 return false; 14091 Addr = DAG.getSelect(SDLoc(TheSelect), 14092 LLD->getBasePtr().getValueType(), 14093 TheSelect->getOperand(0), LLD->getBasePtr(), 14094 RLD->getBasePtr()); 14095 } else { // Otherwise SELECT_CC 14096 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14097 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14098 14099 if ((LLD->hasAnyUseOfValue(1) && 14100 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14101 (RLD->hasAnyUseOfValue(1) && 14102 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14103 return false; 14104 14105 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14106 LLD->getBasePtr().getValueType(), 14107 TheSelect->getOperand(0), 14108 TheSelect->getOperand(1), 14109 LLD->getBasePtr(), RLD->getBasePtr(), 14110 TheSelect->getOperand(4)); 14111 } 14112 14113 SDValue Load; 14114 // It is safe to replace the two loads if they have different alignments, 14115 // but the new load must be the minimum (most restrictive) alignment of the 14116 // inputs. 14117 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 14118 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14119 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14120 Load = DAG.getLoad(TheSelect->getValueType(0), 14121 SDLoc(TheSelect), 14122 // FIXME: Discards pointer and AA info. 14123 LLD->getChain(), Addr, MachinePointerInfo(), 14124 LLD->isVolatile(), LLD->isNonTemporal(), 14125 isInvariant, Alignment); 14126 } else { 14127 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 14128 RLD->getExtensionType() : LLD->getExtensionType(), 14129 SDLoc(TheSelect), 14130 TheSelect->getValueType(0), 14131 // FIXME: Discards pointer and AA info. 14132 LLD->getChain(), Addr, MachinePointerInfo(), 14133 LLD->getMemoryVT(), LLD->isVolatile(), 14134 LLD->isNonTemporal(), isInvariant, Alignment); 14135 } 14136 14137 // Users of the select now use the result of the load. 14138 CombineTo(TheSelect, Load); 14139 14140 // Users of the old loads now use the new load's chain. We know the 14141 // old-load value is dead now. 14142 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14143 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14144 return true; 14145 } 14146 14147 return false; 14148 } 14149 14150 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14151 /// where 'cond' is the comparison specified by CC. 14152 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 14153 SDValue N2, SDValue N3, 14154 ISD::CondCode CC, bool NotExtCompare) { 14155 // (x ? y : y) -> y. 14156 if (N2 == N3) return N2; 14157 14158 EVT VT = N2.getValueType(); 14159 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14160 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14161 14162 // Determine if the condition we're dealing with is constant 14163 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14164 N0, N1, CC, DL, false); 14165 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14166 14167 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14168 // fold select_cc true, x, y -> x 14169 // fold select_cc false, x, y -> y 14170 return !SCCC->isNullValue() ? N2 : N3; 14171 } 14172 14173 // Check to see if we can simplify the select into an fabs node 14174 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14175 // Allow either -0.0 or 0.0 14176 if (CFP->isZero()) { 14177 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14178 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14179 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14180 N2 == N3.getOperand(0)) 14181 return DAG.getNode(ISD::FABS, DL, VT, N0); 14182 14183 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14184 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14185 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14186 N2.getOperand(0) == N3) 14187 return DAG.getNode(ISD::FABS, DL, VT, N3); 14188 } 14189 } 14190 14191 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14192 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14193 // in it. This is a win when the constant is not otherwise available because 14194 // it replaces two constant pool loads with one. We only do this if the FP 14195 // type is known to be legal, because if it isn't, then we are before legalize 14196 // types an we want the other legalization to happen first (e.g. to avoid 14197 // messing with soft float) and if the ConstantFP is not legal, because if 14198 // it is legal, we may not need to store the FP constant in a constant pool. 14199 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14200 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14201 if (TLI.isTypeLegal(N2.getValueType()) && 14202 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14203 TargetLowering::Legal && 14204 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14205 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14206 // If both constants have multiple uses, then we won't need to do an 14207 // extra load, they are likely around in registers for other users. 14208 (TV->hasOneUse() || FV->hasOneUse())) { 14209 Constant *Elts[] = { 14210 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14211 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14212 }; 14213 Type *FPTy = Elts[0]->getType(); 14214 const DataLayout &TD = DAG.getDataLayout(); 14215 14216 // Create a ConstantArray of the two constants. 14217 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14218 SDValue CPIdx = 14219 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14220 TD.getPrefTypeAlignment(FPTy)); 14221 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14222 14223 // Get the offsets to the 0 and 1 element of the array so that we can 14224 // select between them. 14225 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14226 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14227 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14228 14229 SDValue Cond = DAG.getSetCC(DL, 14230 getSetCCResultType(N0.getValueType()), 14231 N0, N1, CC); 14232 AddToWorklist(Cond.getNode()); 14233 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14234 Cond, One, Zero); 14235 AddToWorklist(CstOffset.getNode()); 14236 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14237 CstOffset); 14238 AddToWorklist(CPIdx.getNode()); 14239 return DAG.getLoad( 14240 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14241 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14242 false, false, false, Alignment); 14243 } 14244 } 14245 14246 // Check to see if we can perform the "gzip trick", transforming 14247 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14248 if (isNullConstant(N3) && CC == ISD::SETLT && 14249 (isNullConstant(N1) || // (a < 0) ? b : 0 14250 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14251 EVT XType = N0.getValueType(); 14252 EVT AType = N2.getValueType(); 14253 if (XType.bitsGE(AType)) { 14254 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14255 // single-bit constant. 14256 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14257 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14258 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14259 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14260 getShiftAmountTy(N0.getValueType())); 14261 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14262 XType, N0, ShCt); 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 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14274 XType, N0, 14275 DAG.getConstant(XType.getSizeInBits() - 1, 14276 SDLoc(N0), 14277 getShiftAmountTy(N0.getValueType()))); 14278 AddToWorklist(Shift.getNode()); 14279 14280 if (XType.bitsGT(AType)) { 14281 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14282 AddToWorklist(Shift.getNode()); 14283 } 14284 14285 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14286 } 14287 } 14288 14289 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14290 // where y is has a single bit set. 14291 // A plaintext description would be, we can turn the SELECT_CC into an AND 14292 // when the condition can be materialized as an all-ones register. Any 14293 // single bit-test can be materialized as an all-ones register with 14294 // shift-left and shift-right-arith. 14295 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14296 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14297 SDValue AndLHS = N0->getOperand(0); 14298 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14299 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14300 // Shift the tested bit over the sign bit. 14301 APInt AndMask = ConstAndRHS->getAPIntValue(); 14302 SDValue ShlAmt = 14303 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14304 getShiftAmountTy(AndLHS.getValueType())); 14305 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14306 14307 // Now arithmetic right shift it all the way over, so the result is either 14308 // all-ones, or zero. 14309 SDValue ShrAmt = 14310 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14311 getShiftAmountTy(Shl.getValueType())); 14312 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14313 14314 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14315 } 14316 } 14317 14318 // fold select C, 16, 0 -> shl C, 4 14319 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14320 TLI.getBooleanContents(N0.getValueType()) == 14321 TargetLowering::ZeroOrOneBooleanContent) { 14322 14323 // If the caller doesn't want us to simplify this into a zext of a compare, 14324 // don't do it. 14325 if (NotExtCompare && N2C->isOne()) 14326 return SDValue(); 14327 14328 // Get a SetCC of the condition 14329 // NOTE: Don't create a SETCC if it's not legal on this target. 14330 if (!LegalOperations || 14331 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14332 SDValue Temp, SCC; 14333 // cast from setcc result type to select result type 14334 if (LegalTypes) { 14335 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14336 N0, N1, CC); 14337 if (N2.getValueType().bitsLT(SCC.getValueType())) 14338 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14339 N2.getValueType()); 14340 else 14341 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14342 N2.getValueType(), SCC); 14343 } else { 14344 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14345 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14346 N2.getValueType(), SCC); 14347 } 14348 14349 AddToWorklist(SCC.getNode()); 14350 AddToWorklist(Temp.getNode()); 14351 14352 if (N2C->isOne()) 14353 return Temp; 14354 14355 // shl setcc result by log2 n2c 14356 return DAG.getNode( 14357 ISD::SHL, DL, N2.getValueType(), Temp, 14358 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14359 getShiftAmountTy(Temp.getValueType()))); 14360 } 14361 } 14362 14363 // Check to see if this is an integer abs. 14364 // select_cc setg[te] X, 0, X, -X -> 14365 // select_cc setgt X, -1, X, -X -> 14366 // select_cc setl[te] X, 0, -X, X -> 14367 // select_cc setlt X, 1, -X, X -> 14368 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14369 if (N1C) { 14370 ConstantSDNode *SubC = nullptr; 14371 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14372 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14373 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14374 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14375 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14376 (N1C->isOne() && CC == ISD::SETLT)) && 14377 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14378 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14379 14380 EVT XType = N0.getValueType(); 14381 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14382 SDLoc DL(N0); 14383 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14384 N0, 14385 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14386 getShiftAmountTy(N0.getValueType()))); 14387 SDValue Add = DAG.getNode(ISD::ADD, DL, 14388 XType, N0, Shift); 14389 AddToWorklist(Shift.getNode()); 14390 AddToWorklist(Add.getNode()); 14391 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14392 } 14393 } 14394 14395 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 14396 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 14397 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 14398 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 14399 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 14400 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 14401 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 14402 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 14403 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 14404 SDValue ValueOnZero = N2; 14405 SDValue Count = N3; 14406 // If the condition is NE instead of E, swap the operands. 14407 if (CC == ISD::SETNE) 14408 std::swap(ValueOnZero, Count); 14409 // Check if the value on zero is a constant equal to the bits in the type. 14410 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 14411 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 14412 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 14413 // legal, combine to just cttz. 14414 if ((Count.getOpcode() == ISD::CTTZ || 14415 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 14416 N0 == Count.getOperand(0) && 14417 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 14418 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 14419 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 14420 // legal, combine to just ctlz. 14421 if ((Count.getOpcode() == ISD::CTLZ || 14422 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 14423 N0 == Count.getOperand(0) && 14424 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 14425 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 14426 } 14427 } 14428 } 14429 14430 return SDValue(); 14431 } 14432 14433 /// This is a stub for TargetLowering::SimplifySetCC. 14434 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 14435 SDValue N1, ISD::CondCode Cond, 14436 SDLoc DL, bool foldBooleans) { 14437 TargetLowering::DAGCombinerInfo 14438 DagCombineInfo(DAG, Level, false, this); 14439 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14440 } 14441 14442 /// Given an ISD::SDIV node expressing a divide by constant, return 14443 /// a DAG expression to select that will generate the same value by multiplying 14444 /// by a magic number. 14445 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14446 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14447 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14448 if (!C) 14449 return SDValue(); 14450 14451 // Avoid division by zero. 14452 if (C->isNullValue()) 14453 return SDValue(); 14454 14455 std::vector<SDNode*> Built; 14456 SDValue S = 14457 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14458 14459 for (SDNode *N : Built) 14460 AddToWorklist(N); 14461 return S; 14462 } 14463 14464 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14465 /// DAG expression that will generate the same value by right shifting. 14466 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14467 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14468 if (!C) 14469 return SDValue(); 14470 14471 // Avoid division by zero. 14472 if (C->isNullValue()) 14473 return SDValue(); 14474 14475 std::vector<SDNode *> Built; 14476 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14477 14478 for (SDNode *N : Built) 14479 AddToWorklist(N); 14480 return S; 14481 } 14482 14483 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14484 /// expression that will generate the same value by multiplying by a magic 14485 /// number. 14486 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14487 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14488 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14489 if (!C) 14490 return SDValue(); 14491 14492 // Avoid division by zero. 14493 if (C->isNullValue()) 14494 return SDValue(); 14495 14496 std::vector<SDNode*> Built; 14497 SDValue S = 14498 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14499 14500 for (SDNode *N : Built) 14501 AddToWorklist(N); 14502 return S; 14503 } 14504 14505 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14506 if (Level >= AfterLegalizeDAG) 14507 return SDValue(); 14508 14509 // Expose the DAG combiner to the target combiner implementations. 14510 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14511 14512 unsigned Iterations = 0; 14513 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14514 if (Iterations) { 14515 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14516 // For the reciprocal, we need to find the zero of the function: 14517 // F(X) = A X - 1 [which has a zero at X = 1/A] 14518 // => 14519 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14520 // does not require additional intermediate precision] 14521 EVT VT = Op.getValueType(); 14522 SDLoc DL(Op); 14523 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14524 14525 AddToWorklist(Est.getNode()); 14526 14527 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14528 for (unsigned i = 0; i < Iterations; ++i) { 14529 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14530 AddToWorklist(NewEst.getNode()); 14531 14532 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14533 AddToWorklist(NewEst.getNode()); 14534 14535 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14536 AddToWorklist(NewEst.getNode()); 14537 14538 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14539 AddToWorklist(Est.getNode()); 14540 } 14541 } 14542 return Est; 14543 } 14544 14545 return SDValue(); 14546 } 14547 14548 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14549 /// For the reciprocal sqrt, we need to find the zero of the function: 14550 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14551 /// => 14552 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14553 /// As a result, we precompute A/2 prior to the iteration loop. 14554 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14555 unsigned Iterations, 14556 SDNodeFlags *Flags) { 14557 EVT VT = Arg.getValueType(); 14558 SDLoc DL(Arg); 14559 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14560 14561 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14562 // this entire sequence requires only one FP constant. 14563 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14564 AddToWorklist(HalfArg.getNode()); 14565 14566 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14567 AddToWorklist(HalfArg.getNode()); 14568 14569 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14570 for (unsigned i = 0; i < Iterations; ++i) { 14571 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14572 AddToWorklist(NewEst.getNode()); 14573 14574 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14575 AddToWorklist(NewEst.getNode()); 14576 14577 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14578 AddToWorklist(NewEst.getNode()); 14579 14580 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14581 AddToWorklist(Est.getNode()); 14582 } 14583 return Est; 14584 } 14585 14586 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14587 /// For the reciprocal sqrt, we need to find the zero of the function: 14588 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14589 /// => 14590 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14591 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14592 unsigned Iterations, 14593 SDNodeFlags *Flags) { 14594 EVT VT = Arg.getValueType(); 14595 SDLoc DL(Arg); 14596 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14597 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14598 14599 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14600 for (unsigned i = 0; i < Iterations; ++i) { 14601 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14602 AddToWorklist(HalfEst.getNode()); 14603 14604 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14605 AddToWorklist(Est.getNode()); 14606 14607 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14608 AddToWorklist(Est.getNode()); 14609 14610 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14611 AddToWorklist(Est.getNode()); 14612 14613 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14614 AddToWorklist(Est.getNode()); 14615 } 14616 return Est; 14617 } 14618 14619 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14620 if (Level >= AfterLegalizeDAG) 14621 return SDValue(); 14622 14623 // Expose the DAG combiner to the target combiner implementations. 14624 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14625 unsigned Iterations = 0; 14626 bool UseOneConstNR = false; 14627 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14628 AddToWorklist(Est.getNode()); 14629 if (Iterations) { 14630 Est = UseOneConstNR ? 14631 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14632 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14633 } 14634 return Est; 14635 } 14636 14637 return SDValue(); 14638 } 14639 14640 /// Return true if base is a frame index, which is known not to alias with 14641 /// anything but itself. Provides base object and offset as results. 14642 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14643 const GlobalValue *&GV, const void *&CV) { 14644 // Assume it is a primitive operation. 14645 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14646 14647 // If it's an adding a simple constant then integrate the offset. 14648 if (Base.getOpcode() == ISD::ADD) { 14649 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14650 Base = Base.getOperand(0); 14651 Offset += C->getZExtValue(); 14652 } 14653 } 14654 14655 // Return the underlying GlobalValue, and update the Offset. Return false 14656 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14657 // by multiple nodes with different offsets. 14658 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14659 GV = G->getGlobal(); 14660 Offset += G->getOffset(); 14661 return false; 14662 } 14663 14664 // Return the underlying Constant value, and update the Offset. Return false 14665 // for ConstantSDNodes since the same constant pool entry may be represented 14666 // by multiple nodes with different offsets. 14667 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14668 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14669 : (const void *)C->getConstVal(); 14670 Offset += C->getOffset(); 14671 return false; 14672 } 14673 // If it's any of the following then it can't alias with anything but itself. 14674 return isa<FrameIndexSDNode>(Base); 14675 } 14676 14677 /// Return true if there is any possibility that the two addresses overlap. 14678 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14679 // If they are the same then they must be aliases. 14680 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14681 14682 // If they are both volatile then they cannot be reordered. 14683 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14684 14685 // If one operation reads from invariant memory, and the other may store, they 14686 // cannot alias. These should really be checking the equivalent of mayWrite, 14687 // but it only matters for memory nodes other than load /store. 14688 if (Op0->isInvariant() && Op1->writeMem()) 14689 return false; 14690 14691 if (Op1->isInvariant() && Op0->writeMem()) 14692 return false; 14693 14694 // Gather base node and offset information. 14695 SDValue Base1, Base2; 14696 int64_t Offset1, Offset2; 14697 const GlobalValue *GV1, *GV2; 14698 const void *CV1, *CV2; 14699 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14700 Base1, Offset1, GV1, CV1); 14701 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14702 Base2, Offset2, GV2, CV2); 14703 14704 // If they have a same base address then check to see if they overlap. 14705 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14706 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14707 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14708 14709 // It is possible for different frame indices to alias each other, mostly 14710 // when tail call optimization reuses return address slots for arguments. 14711 // To catch this case, look up the actual index of frame indices to compute 14712 // the real alias relationship. 14713 if (isFrameIndex1 && isFrameIndex2) { 14714 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14715 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14716 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14717 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14718 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14719 } 14720 14721 // Otherwise, if we know what the bases are, and they aren't identical, then 14722 // we know they cannot alias. 14723 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14724 return false; 14725 14726 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14727 // compared to the size and offset of the access, we may be able to prove they 14728 // do not alias. This check is conservative for now to catch cases created by 14729 // splitting vector types. 14730 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14731 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14732 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14733 Op1->getMemoryVT().getSizeInBits() >> 3) && 14734 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14735 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14736 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14737 14738 // There is no overlap between these relatively aligned accesses of similar 14739 // size, return no alias. 14740 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14741 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14742 return false; 14743 } 14744 14745 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14746 ? CombinerGlobalAA 14747 : DAG.getSubtarget().useAA(); 14748 #ifndef NDEBUG 14749 if (CombinerAAOnlyFunc.getNumOccurrences() && 14750 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14751 UseAA = false; 14752 #endif 14753 if (UseAA && 14754 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14755 // Use alias analysis information. 14756 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14757 Op1->getSrcValueOffset()); 14758 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14759 Op0->getSrcValueOffset() - MinOffset; 14760 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14761 Op1->getSrcValueOffset() - MinOffset; 14762 AliasResult AAResult = 14763 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14764 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14765 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14766 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14767 if (AAResult == NoAlias) 14768 return false; 14769 } 14770 14771 // Otherwise we have to assume they alias. 14772 return true; 14773 } 14774 14775 /// Walk up chain skipping non-aliasing memory nodes, 14776 /// looking for aliasing nodes and adding them to the Aliases vector. 14777 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14778 SmallVectorImpl<SDValue> &Aliases) { 14779 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14780 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14781 14782 // Get alias information for node. 14783 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14784 14785 // Starting off. 14786 Chains.push_back(OriginalChain); 14787 unsigned Depth = 0; 14788 14789 // Look at each chain and determine if it is an alias. If so, add it to the 14790 // aliases list. If not, then continue up the chain looking for the next 14791 // candidate. 14792 while (!Chains.empty()) { 14793 SDValue Chain = Chains.pop_back_val(); 14794 14795 // For TokenFactor nodes, look at each operand and only continue up the 14796 // chain until we reach the depth limit. 14797 // 14798 // FIXME: The depth check could be made to return the last non-aliasing 14799 // chain we found before we hit a tokenfactor rather than the original 14800 // chain. 14801 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14802 Aliases.clear(); 14803 Aliases.push_back(OriginalChain); 14804 return; 14805 } 14806 14807 // Don't bother if we've been before. 14808 if (!Visited.insert(Chain.getNode()).second) 14809 continue; 14810 14811 switch (Chain.getOpcode()) { 14812 case ISD::EntryToken: 14813 // Entry token is ideal chain operand, but handled in FindBetterChain. 14814 break; 14815 14816 case ISD::LOAD: 14817 case ISD::STORE: { 14818 // Get alias information for Chain. 14819 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14820 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14821 14822 // If chain is alias then stop here. 14823 if (!(IsLoad && IsOpLoad) && 14824 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14825 Aliases.push_back(Chain); 14826 } else { 14827 // Look further up the chain. 14828 Chains.push_back(Chain.getOperand(0)); 14829 ++Depth; 14830 } 14831 break; 14832 } 14833 14834 case ISD::TokenFactor: 14835 // We have to check each of the operands of the token factor for "small" 14836 // token factors, so we queue them up. Adding the operands to the queue 14837 // (stack) in reverse order maintains the original order and increases the 14838 // likelihood that getNode will find a matching token factor (CSE.) 14839 if (Chain.getNumOperands() > 16) { 14840 Aliases.push_back(Chain); 14841 break; 14842 } 14843 for (unsigned n = Chain.getNumOperands(); n;) 14844 Chains.push_back(Chain.getOperand(--n)); 14845 ++Depth; 14846 break; 14847 14848 default: 14849 // For all other instructions we will just have to take what we can get. 14850 Aliases.push_back(Chain); 14851 break; 14852 } 14853 } 14854 } 14855 14856 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14857 /// (aliasing node.) 14858 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14859 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14860 14861 // Accumulate all the aliases to this node. 14862 GatherAllAliases(N, OldChain, Aliases); 14863 14864 // If no operands then chain to entry token. 14865 if (Aliases.size() == 0) 14866 return DAG.getEntryNode(); 14867 14868 // If a single operand then chain to it. We don't need to revisit it. 14869 if (Aliases.size() == 1) 14870 return Aliases[0]; 14871 14872 // Construct a custom tailored token factor. 14873 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14874 } 14875 14876 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14877 // This holds the base pointer, index, and the offset in bytes from the base 14878 // pointer. 14879 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14880 14881 // We must have a base and an offset. 14882 if (!BasePtr.Base.getNode()) 14883 return false; 14884 14885 // Do not handle stores to undef base pointers. 14886 if (BasePtr.Base.isUndef()) 14887 return false; 14888 14889 SmallVector<StoreSDNode *, 8> ChainedStores; 14890 ChainedStores.push_back(St); 14891 14892 // Walk up the chain and look for nodes with offsets from the same 14893 // base pointer. Stop when reaching an instruction with a different kind 14894 // or instruction which has a different base pointer. 14895 StoreSDNode *Index = St; 14896 while (Index) { 14897 // If the chain has more than one use, then we can't reorder the mem ops. 14898 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14899 break; 14900 14901 if (Index->isVolatile() || Index->isIndexed()) 14902 break; 14903 14904 // Find the base pointer and offset for this memory node. 14905 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 14906 14907 // Check that the base pointer is the same as the original one. 14908 if (!Ptr.equalBaseIndex(BasePtr)) 14909 break; 14910 14911 // Find the next memory operand in the chain. If the next operand in the 14912 // chain is a store then move up and continue the scan with the next 14913 // memory operand. If the next operand is a load save it and use alias 14914 // information to check if it interferes with anything. 14915 SDNode *NextInChain = Index->getChain().getNode(); 14916 while (true) { 14917 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14918 // We found a store node. Use it for the next iteration. 14919 if (STn->isVolatile() || STn->isIndexed()) { 14920 Index = nullptr; 14921 break; 14922 } 14923 ChainedStores.push_back(STn); 14924 Index = STn; 14925 break; 14926 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14927 NextInChain = Ldn->getChain().getNode(); 14928 continue; 14929 } else { 14930 Index = nullptr; 14931 break; 14932 } 14933 } 14934 } 14935 14936 bool MadeChange = false; 14937 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14938 14939 for (StoreSDNode *ChainedStore : ChainedStores) { 14940 SDValue Chain = ChainedStore->getChain(); 14941 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14942 14943 if (Chain != BetterChain) { 14944 MadeChange = true; 14945 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14946 } 14947 } 14948 14949 // Do all replacements after finding the replacements to make to avoid making 14950 // the chains more complicated by introducing new TokenFactors. 14951 for (auto Replacement : BetterChains) 14952 replaceStoreChain(Replacement.first, Replacement.second); 14953 14954 return MadeChange; 14955 } 14956 14957 /// This is the entry point for the file. 14958 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14959 CodeGenOpt::Level OptLevel) { 14960 /// This is the main entry point to this class. 14961 DAGCombiner(*this, AA, OptLevel).Run(Level); 14962 } 14963