1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "dagcombine" 44 45 STATISTIC(NodesCombined , "Number of dag nodes combined"); 46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 50 STATISTIC(SlicedLoads, "Number of load sliced"); 51 52 namespace { 53 static cl::opt<bool> 54 CombinerAA("combiner-alias-analysis", cl::Hidden, 55 cl::desc("Enable DAG combiner alias-analysis heuristics")); 56 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 64> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis &AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 // Skip handle nodes as they can't usefully be combined and confuse the 135 // zero-use deletion strategy. 136 if (N->getOpcode() == ISD::HANDLENODE) 137 return; 138 139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 140 Worklist.push_back(N); 141 } 142 143 /// Remove all instances of N from the worklist. 144 void removeFromWorklist(SDNode *N) { 145 CombinedNodes.erase(N); 146 147 auto It = WorklistMap.find(N); 148 if (It == WorklistMap.end()) 149 return; // Not in the worklist. 150 151 // Null out the entry rather than erasing it to avoid a linear operation. 152 Worklist[It->second] = nullptr; 153 WorklistMap.erase(It); 154 } 155 156 void deleteAndRecombine(SDNode *N); 157 bool recursivelyDeleteUnusedNodes(SDNode *N); 158 159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 160 bool AddTo = true); 161 162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 163 return CombineTo(N, &Res, 1, AddTo); 164 } 165 166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 167 bool AddTo = true) { 168 SDValue To[] = { Res0, Res1 }; 169 return CombineTo(N, To, 2, AddTo); 170 } 171 172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 173 174 private: 175 176 /// Check the specified integer node value to see if it can be simplified or 177 /// if things it uses can be simplified by bit propagation. 178 /// If so, return true. 179 bool SimplifyDemandedBits(SDValue Op) { 180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 181 APInt Demanded = APInt::getAllOnesValue(BitWidth); 182 return SimplifyDemandedBits(Op, Demanded); 183 } 184 185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 186 187 bool CombineToPreIndexedLoadStore(SDNode *N); 188 bool CombineToPostIndexedLoadStore(SDNode *N); 189 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 190 bool SliceUpLoad(SDNode *N); 191 192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 193 /// load. 194 /// 195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 197 /// \param EltNo index of the vector element to load. 198 /// \param OriginalLoad load that EVE came from to be replaced. 199 /// \returns EVE on success SDValue() on failure. 200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 206 SDValue PromoteIntBinOp(SDValue Op); 207 SDValue PromoteIntShiftOp(SDValue Op); 208 SDValue PromoteExtend(SDValue Op); 209 bool PromoteLoad(SDValue Op); 210 211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 212 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 213 ISD::NodeType ExtType); 214 215 /// Call the node-specific routine that knows how to fold each 216 /// particular type of node. If that doesn't do anything, try the 217 /// target-specific DAG combines. 218 SDValue combine(SDNode *N); 219 220 // Visitation implementation - Implement dag node combining for different 221 // node types. The semantics are as follows: 222 // Return Value: 223 // SDValue.getNode() == 0 - No change was made 224 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 225 // otherwise - N should be replaced by the returned Operand. 226 // 227 SDValue visitTokenFactor(SDNode *N); 228 SDValue visitMERGE_VALUES(SDNode *N); 229 SDValue visitADD(SDNode *N); 230 SDValue visitSUB(SDNode *N); 231 SDValue visitADDC(SDNode *N); 232 SDValue visitSUBC(SDNode *N); 233 SDValue visitADDE(SDNode *N); 234 SDValue visitSUBE(SDNode *N); 235 SDValue visitMUL(SDNode *N); 236 SDValue visitSDIV(SDNode *N); 237 SDValue visitUDIV(SDNode *N); 238 SDValue visitSREM(SDNode *N); 239 SDValue visitUREM(SDNode *N); 240 SDValue visitMULHU(SDNode *N); 241 SDValue visitMULHS(SDNode *N); 242 SDValue visitSMUL_LOHI(SDNode *N); 243 SDValue visitUMUL_LOHI(SDNode *N); 244 SDValue visitSMULO(SDNode *N); 245 SDValue visitUMULO(SDNode *N); 246 SDValue visitSDIVREM(SDNode *N); 247 SDValue visitUDIVREM(SDNode *N); 248 SDValue visitAND(SDNode *N); 249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 250 SDValue visitOR(SDNode *N); 251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 252 SDValue visitXOR(SDNode *N); 253 SDValue SimplifyVBinOp(SDNode *N); 254 SDValue visitSHL(SDNode *N); 255 SDValue visitSRA(SDNode *N); 256 SDValue visitSRL(SDNode *N); 257 SDValue visitRotate(SDNode *N); 258 SDValue visitBSWAP(SDNode *N); 259 SDValue visitCTLZ(SDNode *N); 260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 261 SDValue visitCTTZ(SDNode *N); 262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 263 SDValue visitCTPOP(SDNode *N); 264 SDValue visitSELECT(SDNode *N); 265 SDValue visitVSELECT(SDNode *N); 266 SDValue visitSELECT_CC(SDNode *N); 267 SDValue visitSETCC(SDNode *N); 268 SDValue visitSIGN_EXTEND(SDNode *N); 269 SDValue visitZERO_EXTEND(SDNode *N); 270 SDValue visitANY_EXTEND(SDNode *N); 271 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 272 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 273 SDValue visitTRUNCATE(SDNode *N); 274 SDValue visitBITCAST(SDNode *N); 275 SDValue visitBUILD_PAIR(SDNode *N); 276 SDValue visitFADD(SDNode *N); 277 SDValue visitFSUB(SDNode *N); 278 SDValue visitFMUL(SDNode *N); 279 SDValue visitFMA(SDNode *N); 280 SDValue visitFDIV(SDNode *N); 281 SDValue visitFREM(SDNode *N); 282 SDValue visitFSQRT(SDNode *N); 283 SDValue visitFCOPYSIGN(SDNode *N); 284 SDValue visitSINT_TO_FP(SDNode *N); 285 SDValue visitUINT_TO_FP(SDNode *N); 286 SDValue visitFP_TO_SINT(SDNode *N); 287 SDValue visitFP_TO_UINT(SDNode *N); 288 SDValue visitFP_ROUND(SDNode *N); 289 SDValue visitFP_ROUND_INREG(SDNode *N); 290 SDValue visitFP_EXTEND(SDNode *N); 291 SDValue visitFNEG(SDNode *N); 292 SDValue visitFABS(SDNode *N); 293 SDValue visitFCEIL(SDNode *N); 294 SDValue visitFTRUNC(SDNode *N); 295 SDValue visitFFLOOR(SDNode *N); 296 SDValue visitFMINNUM(SDNode *N); 297 SDValue visitFMAXNUM(SDNode *N); 298 SDValue visitBRCOND(SDNode *N); 299 SDValue visitBR_CC(SDNode *N); 300 SDValue visitLOAD(SDNode *N); 301 SDValue visitSTORE(SDNode *N); 302 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 303 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 304 SDValue visitBUILD_VECTOR(SDNode *N); 305 SDValue visitCONCAT_VECTORS(SDNode *N); 306 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 307 SDValue visitVECTOR_SHUFFLE(SDNode *N); 308 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 309 SDValue visitINSERT_SUBVECTOR(SDNode *N); 310 SDValue visitMLOAD(SDNode *N); 311 SDValue visitMSTORE(SDNode *N); 312 SDValue visitMGATHER(SDNode *N); 313 SDValue visitMSCATTER(SDNode *N); 314 SDValue visitFP_TO_FP16(SDNode *N); 315 316 SDValue visitFADDForFMACombine(SDNode *N); 317 SDValue visitFSUBForFMACombine(SDNode *N); 318 319 SDValue XformToShuffleWithZero(SDNode *N); 320 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 321 322 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 323 324 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 325 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 326 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 327 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 328 SDValue N3, ISD::CondCode CC, 329 bool NotExtCompare = false); 330 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 331 SDLoc DL, bool foldBooleans = true); 332 333 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 334 SDValue &CC) const; 335 bool isOneUseSetCC(SDValue N) const; 336 337 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 338 unsigned HiOp); 339 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 340 SDValue CombineExtLoad(SDNode *N); 341 SDValue combineRepeatedFPDivisors(SDNode *N); 342 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 343 SDValue BuildSDIV(SDNode *N); 344 SDValue BuildSDIVPow2(SDNode *N); 345 SDValue BuildUDIV(SDNode *N); 346 SDValue BuildReciprocalEstimate(SDValue Op); 347 SDValue BuildRsqrtEstimate(SDValue Op); 348 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations); 349 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations); 350 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 351 bool DemandHighBits = true); 352 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 353 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 354 SDValue InnerPos, SDValue InnerNeg, 355 unsigned PosOpcode, unsigned NegOpcode, 356 SDLoc DL); 357 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 358 SDValue ReduceLoadWidth(SDNode *N); 359 SDValue ReduceLoadOpStoreWidth(SDNode *N); 360 SDValue TransformFPLoadStorePair(SDNode *N); 361 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 362 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 363 364 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 365 366 /// Walk up chain skipping non-aliasing memory nodes, 367 /// looking for aliasing nodes and adding them to the Aliases vector. 368 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 369 SmallVectorImpl<SDValue> &Aliases); 370 371 /// Return true if there is any possibility that the two addresses overlap. 372 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 373 374 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 375 /// chain (aliasing node.) 376 SDValue FindBetterChain(SDNode *N, SDValue Chain); 377 378 /// Holds a pointer to an LSBaseSDNode as well as information on where it 379 /// is located in a sequence of memory operations connected by a chain. 380 struct MemOpLink { 381 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 382 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 383 // Ptr to the mem node. 384 LSBaseSDNode *MemNode; 385 // Offset from the base ptr. 386 int64_t OffsetFromBase; 387 // What is the sequence number of this mem node. 388 // Lowest mem operand in the DAG starts at zero. 389 unsigned SequenceNum; 390 }; 391 392 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 393 /// constant build_vector of the stored constant values in Stores. 394 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 395 SDLoc SL, 396 ArrayRef<MemOpLink> Stores, 397 EVT Ty) const; 398 399 /// This is a helper function for MergeConsecutiveStores. When the source 400 /// elements of the consecutive stores are all constants or all extracted 401 /// vector elements, try to merge them into one larger store. 402 /// \return True if a merged store was created. 403 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 404 EVT MemVT, unsigned NumElem, 405 bool IsConstantSrc, bool UseVector); 406 407 /// This is a helper function for MergeConsecutiveStores. 408 /// Stores that may be merged are placed in StoreNodes. 409 /// Loads that may alias with those stores are placed in AliasLoadNodes. 410 void getStoreMergeAndAliasCandidates( 411 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 412 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 413 414 /// Merge consecutive store operations into a wide store. 415 /// This optimization uses wide integers or vectors when possible. 416 /// \return True if some memory operations were changed. 417 bool MergeConsecutiveStores(StoreSDNode *N); 418 419 /// \brief Try to transform a truncation where C is a constant: 420 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 421 /// 422 /// \p N needs to be a truncation and its first operand an AND. Other 423 /// requirements are checked by the function (e.g. that trunc is 424 /// single-use) and if missed an empty SDValue is returned. 425 SDValue distributeTruncateThroughAnd(SDNode *N); 426 427 public: 428 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 429 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 430 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 431 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 432 } 433 434 /// Runs the dag combiner on all nodes in the work list 435 void Run(CombineLevel AtLevel); 436 437 SelectionDAG &getDAG() const { return DAG; } 438 439 /// Returns a type large enough to hold any valid shift amount - before type 440 /// legalization these can be huge. 441 EVT getShiftAmountTy(EVT LHSTy) { 442 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 443 if (LHSTy.isVector()) 444 return LHSTy; 445 auto &DL = DAG.getDataLayout(); 446 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 447 : TLI.getPointerTy(DL); 448 } 449 450 /// This method returns true if we are running before type legalization or 451 /// if the specified VT is legal. 452 bool isTypeLegal(const EVT &VT) { 453 if (!LegalTypes) return true; 454 return TLI.isTypeLegal(VT); 455 } 456 457 /// Convenience wrapper around TargetLowering::getSetCCResultType 458 EVT getSetCCResultType(EVT VT) const { 459 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 460 } 461 }; 462 } 463 464 465 namespace { 466 /// This class is a DAGUpdateListener that removes any deleted 467 /// nodes from the worklist. 468 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 469 DAGCombiner &DC; 470 public: 471 explicit WorklistRemover(DAGCombiner &dc) 472 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 473 474 void NodeDeleted(SDNode *N, SDNode *E) override { 475 DC.removeFromWorklist(N); 476 } 477 }; 478 } 479 480 //===----------------------------------------------------------------------===// 481 // TargetLowering::DAGCombinerInfo implementation 482 //===----------------------------------------------------------------------===// 483 484 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 485 ((DAGCombiner*)DC)->AddToWorklist(N); 486 } 487 488 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 489 ((DAGCombiner*)DC)->removeFromWorklist(N); 490 } 491 492 SDValue TargetLowering::DAGCombinerInfo:: 493 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 494 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 495 } 496 497 SDValue TargetLowering::DAGCombinerInfo:: 498 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 499 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 500 } 501 502 503 SDValue TargetLowering::DAGCombinerInfo:: 504 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 505 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 506 } 507 508 void TargetLowering::DAGCombinerInfo:: 509 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 510 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 511 } 512 513 //===----------------------------------------------------------------------===// 514 // Helper Functions 515 //===----------------------------------------------------------------------===// 516 517 void DAGCombiner::deleteAndRecombine(SDNode *N) { 518 removeFromWorklist(N); 519 520 // If the operands of this node are only used by the node, they will now be 521 // dead. Make sure to re-visit them and recursively delete dead nodes. 522 for (const SDValue &Op : N->ops()) 523 // For an operand generating multiple values, one of the values may 524 // become dead allowing further simplification (e.g. split index 525 // arithmetic from an indexed load). 526 if (Op->hasOneUse() || Op->getNumValues() > 1) 527 AddToWorklist(Op.getNode()); 528 529 DAG.DeleteNode(N); 530 } 531 532 /// Return 1 if we can compute the negated form of the specified expression for 533 /// the same cost as the expression itself, or 2 if we can compute the negated 534 /// form more cheaply than the expression itself. 535 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 536 const TargetLowering &TLI, 537 const TargetOptions *Options, 538 unsigned Depth = 0) { 539 // fneg is removable even if it has multiple uses. 540 if (Op.getOpcode() == ISD::FNEG) return 2; 541 542 // Don't allow anything with multiple uses. 543 if (!Op.hasOneUse()) return 0; 544 545 // Don't recurse exponentially. 546 if (Depth > 6) return 0; 547 548 switch (Op.getOpcode()) { 549 default: return false; 550 case ISD::ConstantFP: 551 // Don't invert constant FP values after legalize. The negated constant 552 // isn't necessarily legal. 553 return LegalOperations ? 0 : 1; 554 case ISD::FADD: 555 // FIXME: determine better conditions for this xform. 556 if (!Options->UnsafeFPMath) return 0; 557 558 // After operation legalization, it might not be legal to create new FSUBs. 559 if (LegalOperations && 560 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 561 return 0; 562 563 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 564 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 565 Options, Depth + 1)) 566 return V; 567 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 568 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 569 Depth + 1); 570 case ISD::FSUB: 571 // We can't turn -(A-B) into B-A when we honor signed zeros. 572 if (!Options->UnsafeFPMath) return 0; 573 574 // fold (fneg (fsub A, B)) -> (fsub B, A) 575 return 1; 576 577 case ISD::FMUL: 578 case ISD::FDIV: 579 if (Options->HonorSignDependentRoundingFPMath()) return 0; 580 581 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 582 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 583 Options, Depth + 1)) 584 return V; 585 586 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 587 Depth + 1); 588 589 case ISD::FP_EXTEND: 590 case ISD::FP_ROUND: 591 case ISD::FSIN: 592 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 593 Depth + 1); 594 } 595 } 596 597 /// If isNegatibleForFree returns true, return the newly negated expression. 598 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 599 bool LegalOperations, unsigned Depth = 0) { 600 const TargetOptions &Options = DAG.getTarget().Options; 601 // fneg is removable even if it has multiple uses. 602 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 603 604 // Don't allow anything with multiple uses. 605 assert(Op.hasOneUse() && "Unknown reuse!"); 606 607 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 608 switch (Op.getOpcode()) { 609 default: llvm_unreachable("Unknown code"); 610 case ISD::ConstantFP: { 611 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 612 V.changeSign(); 613 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 614 } 615 case ISD::FADD: 616 // FIXME: determine better conditions for this xform. 617 assert(Options.UnsafeFPMath); 618 619 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 620 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 621 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 622 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 623 GetNegatedExpression(Op.getOperand(0), DAG, 624 LegalOperations, Depth+1), 625 Op.getOperand(1)); 626 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 627 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 628 GetNegatedExpression(Op.getOperand(1), DAG, 629 LegalOperations, Depth+1), 630 Op.getOperand(0)); 631 case ISD::FSUB: 632 // We can't turn -(A-B) into B-A when we honor signed zeros. 633 assert(Options.UnsafeFPMath); 634 635 // fold (fneg (fsub 0, B)) -> B 636 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 637 if (N0CFP->isZero()) 638 return Op.getOperand(1); 639 640 // fold (fneg (fsub A, B)) -> (fsub B, A) 641 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 642 Op.getOperand(1), Op.getOperand(0)); 643 644 case ISD::FMUL: 645 case ISD::FDIV: 646 assert(!Options.HonorSignDependentRoundingFPMath()); 647 648 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 649 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 650 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 651 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 652 GetNegatedExpression(Op.getOperand(0), DAG, 653 LegalOperations, Depth+1), 654 Op.getOperand(1)); 655 656 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 657 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 658 Op.getOperand(0), 659 GetNegatedExpression(Op.getOperand(1), DAG, 660 LegalOperations, Depth+1)); 661 662 case ISD::FP_EXTEND: 663 case ISD::FSIN: 664 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 665 GetNegatedExpression(Op.getOperand(0), DAG, 666 LegalOperations, Depth+1)); 667 case ISD::FP_ROUND: 668 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 669 GetNegatedExpression(Op.getOperand(0), DAG, 670 LegalOperations, Depth+1), 671 Op.getOperand(1)); 672 } 673 } 674 675 // Return true if this node is a setcc, or is a select_cc 676 // that selects between the target values used for true and false, making it 677 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 678 // the appropriate nodes based on the type of node we are checking. This 679 // simplifies life a bit for the callers. 680 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 681 SDValue &CC) const { 682 if (N.getOpcode() == ISD::SETCC) { 683 LHS = N.getOperand(0); 684 RHS = N.getOperand(1); 685 CC = N.getOperand(2); 686 return true; 687 } 688 689 if (N.getOpcode() != ISD::SELECT_CC || 690 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 691 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 692 return false; 693 694 if (TLI.getBooleanContents(N.getValueType()) == 695 TargetLowering::UndefinedBooleanContent) 696 return false; 697 698 LHS = N.getOperand(0); 699 RHS = N.getOperand(1); 700 CC = N.getOperand(4); 701 return true; 702 } 703 704 /// Return true if this is a SetCC-equivalent operation with only one use. 705 /// If this is true, it allows the users to invert the operation for free when 706 /// it is profitable to do so. 707 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 708 SDValue N0, N1, N2; 709 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 710 return true; 711 return false; 712 } 713 714 /// Returns true if N is a BUILD_VECTOR node whose 715 /// elements are all the same constant or undefined. 716 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 717 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 718 if (!C) 719 return false; 720 721 APInt SplatUndef; 722 unsigned SplatBitSize; 723 bool HasAnyUndefs; 724 EVT EltVT = N->getValueType(0).getVectorElementType(); 725 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 726 HasAnyUndefs) && 727 EltVT.getSizeInBits() >= SplatBitSize); 728 } 729 730 // \brief Returns the SDNode if it is a constant integer BuildVector 731 // or constant integer. 732 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 733 if (isa<ConstantSDNode>(N)) 734 return N.getNode(); 735 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 736 return N.getNode(); 737 return nullptr; 738 } 739 740 // \brief Returns the SDNode if it is a constant float BuildVector 741 // or constant float. 742 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 743 if (isa<ConstantFPSDNode>(N)) 744 return N.getNode(); 745 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 746 return N.getNode(); 747 return nullptr; 748 } 749 750 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 751 // int. 752 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 753 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 754 return CN; 755 756 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 757 BitVector UndefElements; 758 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 759 760 // BuildVectors can truncate their operands. Ignore that case here. 761 // FIXME: We blindly ignore splats which include undef which is overly 762 // pessimistic. 763 if (CN && UndefElements.none() && 764 CN->getValueType(0) == N.getValueType().getScalarType()) 765 return CN; 766 } 767 768 return nullptr; 769 } 770 771 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 772 // float. 773 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 774 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 775 return CN; 776 777 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 778 BitVector UndefElements; 779 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 780 781 if (CN && UndefElements.none()) 782 return CN; 783 } 784 785 return nullptr; 786 } 787 788 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 789 SDValue N0, SDValue N1) { 790 EVT VT = N0.getValueType(); 791 if (N0.getOpcode() == Opc) { 792 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 793 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 794 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 795 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 796 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 797 return SDValue(); 798 } 799 if (N0.hasOneUse()) { 800 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 801 // use 802 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 803 if (!OpNode.getNode()) 804 return SDValue(); 805 AddToWorklist(OpNode.getNode()); 806 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 807 } 808 } 809 } 810 811 if (N1.getOpcode() == Opc) { 812 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 813 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 814 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 815 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 816 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 817 return SDValue(); 818 } 819 if (N1.hasOneUse()) { 820 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 821 // use 822 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 823 if (!OpNode.getNode()) 824 return SDValue(); 825 AddToWorklist(OpNode.getNode()); 826 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 827 } 828 } 829 } 830 831 return SDValue(); 832 } 833 834 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 835 bool AddTo) { 836 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 837 ++NodesCombined; 838 DEBUG(dbgs() << "\nReplacing.1 "; 839 N->dump(&DAG); 840 dbgs() << "\nWith: "; 841 To[0].getNode()->dump(&DAG); 842 dbgs() << " and " << NumTo-1 << " other values\n"); 843 for (unsigned i = 0, e = NumTo; i != e; ++i) 844 assert((!To[i].getNode() || 845 N->getValueType(i) == To[i].getValueType()) && 846 "Cannot combine value to value of different type!"); 847 848 WorklistRemover DeadNodes(*this); 849 DAG.ReplaceAllUsesWith(N, To); 850 if (AddTo) { 851 // Push the new nodes and any users onto the worklist 852 for (unsigned i = 0, e = NumTo; i != e; ++i) { 853 if (To[i].getNode()) { 854 AddToWorklist(To[i].getNode()); 855 AddUsersToWorklist(To[i].getNode()); 856 } 857 } 858 } 859 860 // Finally, if the node is now dead, remove it from the graph. The node 861 // may not be dead if the replacement process recursively simplified to 862 // something else needing this node. 863 if (N->use_empty()) 864 deleteAndRecombine(N); 865 return SDValue(N, 0); 866 } 867 868 void DAGCombiner:: 869 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 870 // Replace all uses. If any nodes become isomorphic to other nodes and 871 // are deleted, make sure to remove them from our worklist. 872 WorklistRemover DeadNodes(*this); 873 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 874 875 // Push the new node and any (possibly new) users onto the worklist. 876 AddToWorklist(TLO.New.getNode()); 877 AddUsersToWorklist(TLO.New.getNode()); 878 879 // Finally, if the node is now dead, remove it from the graph. The node 880 // may not be dead if the replacement process recursively simplified to 881 // something else needing this node. 882 if (TLO.Old.getNode()->use_empty()) 883 deleteAndRecombine(TLO.Old.getNode()); 884 } 885 886 /// Check the specified integer node value to see if it can be simplified or if 887 /// things it uses can be simplified by bit propagation. If so, return true. 888 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 889 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 890 APInt KnownZero, KnownOne; 891 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 892 return false; 893 894 // Revisit the node. 895 AddToWorklist(Op.getNode()); 896 897 // Replace the old value with the new one. 898 ++NodesCombined; 899 DEBUG(dbgs() << "\nReplacing.2 "; 900 TLO.Old.getNode()->dump(&DAG); 901 dbgs() << "\nWith: "; 902 TLO.New.getNode()->dump(&DAG); 903 dbgs() << '\n'); 904 905 CommitTargetLoweringOpt(TLO); 906 return true; 907 } 908 909 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 910 SDLoc dl(Load); 911 EVT VT = Load->getValueType(0); 912 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 913 914 DEBUG(dbgs() << "\nReplacing.9 "; 915 Load->dump(&DAG); 916 dbgs() << "\nWith: "; 917 Trunc.getNode()->dump(&DAG); 918 dbgs() << '\n'); 919 WorklistRemover DeadNodes(*this); 920 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 921 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 922 deleteAndRecombine(Load); 923 AddToWorklist(Trunc.getNode()); 924 } 925 926 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 927 Replace = false; 928 SDLoc dl(Op); 929 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 930 EVT MemVT = LD->getMemoryVT(); 931 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 932 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 933 : ISD::EXTLOAD) 934 : LD->getExtensionType(); 935 Replace = true; 936 return DAG.getExtLoad(ExtType, dl, PVT, 937 LD->getChain(), LD->getBasePtr(), 938 MemVT, LD->getMemOperand()); 939 } 940 941 unsigned Opc = Op.getOpcode(); 942 switch (Opc) { 943 default: break; 944 case ISD::AssertSext: 945 return DAG.getNode(ISD::AssertSext, dl, PVT, 946 SExtPromoteOperand(Op.getOperand(0), PVT), 947 Op.getOperand(1)); 948 case ISD::AssertZext: 949 return DAG.getNode(ISD::AssertZext, dl, PVT, 950 ZExtPromoteOperand(Op.getOperand(0), PVT), 951 Op.getOperand(1)); 952 case ISD::Constant: { 953 unsigned ExtOpc = 954 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 955 return DAG.getNode(ExtOpc, dl, PVT, Op); 956 } 957 } 958 959 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 960 return SDValue(); 961 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 962 } 963 964 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 965 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 966 return SDValue(); 967 EVT OldVT = Op.getValueType(); 968 SDLoc dl(Op); 969 bool Replace = false; 970 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 971 if (!NewOp.getNode()) 972 return SDValue(); 973 AddToWorklist(NewOp.getNode()); 974 975 if (Replace) 976 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 977 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 978 DAG.getValueType(OldVT)); 979 } 980 981 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 982 EVT OldVT = Op.getValueType(); 983 SDLoc dl(Op); 984 bool Replace = false; 985 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 986 if (!NewOp.getNode()) 987 return SDValue(); 988 AddToWorklist(NewOp.getNode()); 989 990 if (Replace) 991 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 992 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 993 } 994 995 /// Promote the specified integer binary operation if the target indicates it is 996 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 997 /// i32 since i16 instructions are longer. 998 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 999 if (!LegalOperations) 1000 return SDValue(); 1001 1002 EVT VT = Op.getValueType(); 1003 if (VT.isVector() || !VT.isInteger()) 1004 return SDValue(); 1005 1006 // If operation type is 'undesirable', e.g. i16 on x86, consider 1007 // promoting it. 1008 unsigned Opc = Op.getOpcode(); 1009 if (TLI.isTypeDesirableForOp(Opc, VT)) 1010 return SDValue(); 1011 1012 EVT PVT = VT; 1013 // Consult target whether it is a good idea to promote this operation and 1014 // what's the right type to promote it to. 1015 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1016 assert(PVT != VT && "Don't know what type to promote to!"); 1017 1018 bool Replace0 = false; 1019 SDValue N0 = Op.getOperand(0); 1020 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1021 if (!NN0.getNode()) 1022 return SDValue(); 1023 1024 bool Replace1 = false; 1025 SDValue N1 = Op.getOperand(1); 1026 SDValue NN1; 1027 if (N0 == N1) 1028 NN1 = NN0; 1029 else { 1030 NN1 = PromoteOperand(N1, PVT, Replace1); 1031 if (!NN1.getNode()) 1032 return SDValue(); 1033 } 1034 1035 AddToWorklist(NN0.getNode()); 1036 if (NN1.getNode()) 1037 AddToWorklist(NN1.getNode()); 1038 1039 if (Replace0) 1040 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1041 if (Replace1) 1042 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1043 1044 DEBUG(dbgs() << "\nPromoting "; 1045 Op.getNode()->dump(&DAG)); 1046 SDLoc dl(Op); 1047 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1048 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1049 } 1050 return SDValue(); 1051 } 1052 1053 /// Promote the specified integer shift operation if the target indicates it is 1054 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1055 /// i32 since i16 instructions are longer. 1056 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1057 if (!LegalOperations) 1058 return SDValue(); 1059 1060 EVT VT = Op.getValueType(); 1061 if (VT.isVector() || !VT.isInteger()) 1062 return SDValue(); 1063 1064 // If operation type is 'undesirable', e.g. i16 on x86, consider 1065 // promoting it. 1066 unsigned Opc = Op.getOpcode(); 1067 if (TLI.isTypeDesirableForOp(Opc, VT)) 1068 return SDValue(); 1069 1070 EVT PVT = VT; 1071 // Consult target whether it is a good idea to promote this operation and 1072 // what's the right type to promote it to. 1073 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1074 assert(PVT != VT && "Don't know what type to promote to!"); 1075 1076 bool Replace = false; 1077 SDValue N0 = Op.getOperand(0); 1078 if (Opc == ISD::SRA) 1079 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1080 else if (Opc == ISD::SRL) 1081 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1082 else 1083 N0 = PromoteOperand(N0, PVT, Replace); 1084 if (!N0.getNode()) 1085 return SDValue(); 1086 1087 AddToWorklist(N0.getNode()); 1088 if (Replace) 1089 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1090 1091 DEBUG(dbgs() << "\nPromoting "; 1092 Op.getNode()->dump(&DAG)); 1093 SDLoc dl(Op); 1094 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1095 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1096 } 1097 return SDValue(); 1098 } 1099 1100 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1101 if (!LegalOperations) 1102 return SDValue(); 1103 1104 EVT VT = Op.getValueType(); 1105 if (VT.isVector() || !VT.isInteger()) 1106 return SDValue(); 1107 1108 // If operation type is 'undesirable', e.g. i16 on x86, consider 1109 // promoting it. 1110 unsigned Opc = Op.getOpcode(); 1111 if (TLI.isTypeDesirableForOp(Opc, VT)) 1112 return SDValue(); 1113 1114 EVT PVT = VT; 1115 // Consult target whether it is a good idea to promote this operation and 1116 // what's the right type to promote it to. 1117 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1118 assert(PVT != VT && "Don't know what type to promote to!"); 1119 // fold (aext (aext x)) -> (aext x) 1120 // fold (aext (zext x)) -> (zext x) 1121 // fold (aext (sext x)) -> (sext x) 1122 DEBUG(dbgs() << "\nPromoting "; 1123 Op.getNode()->dump(&DAG)); 1124 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1125 } 1126 return SDValue(); 1127 } 1128 1129 bool DAGCombiner::PromoteLoad(SDValue Op) { 1130 if (!LegalOperations) 1131 return false; 1132 1133 EVT VT = Op.getValueType(); 1134 if (VT.isVector() || !VT.isInteger()) 1135 return false; 1136 1137 // If operation type is 'undesirable', e.g. i16 on x86, consider 1138 // promoting it. 1139 unsigned Opc = Op.getOpcode(); 1140 if (TLI.isTypeDesirableForOp(Opc, VT)) 1141 return false; 1142 1143 EVT PVT = VT; 1144 // Consult target whether it is a good idea to promote this operation and 1145 // what's the right type to promote it to. 1146 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1147 assert(PVT != VT && "Don't know what type to promote to!"); 1148 1149 SDLoc dl(Op); 1150 SDNode *N = Op.getNode(); 1151 LoadSDNode *LD = cast<LoadSDNode>(N); 1152 EVT MemVT = LD->getMemoryVT(); 1153 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1154 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1155 : ISD::EXTLOAD) 1156 : LD->getExtensionType(); 1157 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1158 LD->getChain(), LD->getBasePtr(), 1159 MemVT, LD->getMemOperand()); 1160 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1161 1162 DEBUG(dbgs() << "\nPromoting "; 1163 N->dump(&DAG); 1164 dbgs() << "\nTo: "; 1165 Result.getNode()->dump(&DAG); 1166 dbgs() << '\n'); 1167 WorklistRemover DeadNodes(*this); 1168 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1169 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1170 deleteAndRecombine(N); 1171 AddToWorklist(Result.getNode()); 1172 return true; 1173 } 1174 return false; 1175 } 1176 1177 /// \brief Recursively delete a node which has no uses and any operands for 1178 /// which it is the only use. 1179 /// 1180 /// Note that this both deletes the nodes and removes them from the worklist. 1181 /// It also adds any nodes who have had a user deleted to the worklist as they 1182 /// may now have only one use and subject to other combines. 1183 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1184 if (!N->use_empty()) 1185 return false; 1186 1187 SmallSetVector<SDNode *, 16> Nodes; 1188 Nodes.insert(N); 1189 do { 1190 N = Nodes.pop_back_val(); 1191 if (!N) 1192 continue; 1193 1194 if (N->use_empty()) { 1195 for (const SDValue &ChildN : N->op_values()) 1196 Nodes.insert(ChildN.getNode()); 1197 1198 removeFromWorklist(N); 1199 DAG.DeleteNode(N); 1200 } else { 1201 AddToWorklist(N); 1202 } 1203 } while (!Nodes.empty()); 1204 return true; 1205 } 1206 1207 //===----------------------------------------------------------------------===// 1208 // Main DAG Combiner implementation 1209 //===----------------------------------------------------------------------===// 1210 1211 void DAGCombiner::Run(CombineLevel AtLevel) { 1212 // set the instance variables, so that the various visit routines may use it. 1213 Level = AtLevel; 1214 LegalOperations = Level >= AfterLegalizeVectorOps; 1215 LegalTypes = Level >= AfterLegalizeTypes; 1216 1217 // Add all the dag nodes to the worklist. 1218 for (SDNode &Node : DAG.allnodes()) 1219 AddToWorklist(&Node); 1220 1221 // Create a dummy node (which is not added to allnodes), that adds a reference 1222 // to the root node, preventing it from being deleted, and tracking any 1223 // changes of the root. 1224 HandleSDNode Dummy(DAG.getRoot()); 1225 1226 // while the worklist isn't empty, find a node and 1227 // try and combine it. 1228 while (!WorklistMap.empty()) { 1229 SDNode *N; 1230 // The Worklist holds the SDNodes in order, but it may contain null entries. 1231 do { 1232 N = Worklist.pop_back_val(); 1233 } while (!N); 1234 1235 bool GoodWorklistEntry = WorklistMap.erase(N); 1236 (void)GoodWorklistEntry; 1237 assert(GoodWorklistEntry && 1238 "Found a worklist entry without a corresponding map entry!"); 1239 1240 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1241 // N is deleted from the DAG, since they too may now be dead or may have a 1242 // reduced number of uses, allowing other xforms. 1243 if (recursivelyDeleteUnusedNodes(N)) 1244 continue; 1245 1246 WorklistRemover DeadNodes(*this); 1247 1248 // If this combine is running after legalizing the DAG, re-legalize any 1249 // nodes pulled off the worklist. 1250 if (Level == AfterLegalizeDAG) { 1251 SmallSetVector<SDNode *, 16> UpdatedNodes; 1252 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1253 1254 for (SDNode *LN : UpdatedNodes) { 1255 AddToWorklist(LN); 1256 AddUsersToWorklist(LN); 1257 } 1258 if (!NIsValid) 1259 continue; 1260 } 1261 1262 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1263 1264 // Add any operands of the new node which have not yet been combined to the 1265 // worklist as well. Because the worklist uniques things already, this 1266 // won't repeatedly process the same operand. 1267 CombinedNodes.insert(N); 1268 for (const SDValue &ChildN : N->op_values()) 1269 if (!CombinedNodes.count(ChildN.getNode())) 1270 AddToWorklist(ChildN.getNode()); 1271 1272 SDValue RV = combine(N); 1273 1274 if (!RV.getNode()) 1275 continue; 1276 1277 ++NodesCombined; 1278 1279 // If we get back the same node we passed in, rather than a new node or 1280 // zero, we know that the node must have defined multiple values and 1281 // CombineTo was used. Since CombineTo takes care of the worklist 1282 // mechanics for us, we have no work to do in this case. 1283 if (RV.getNode() == N) 1284 continue; 1285 1286 assert(N->getOpcode() != ISD::DELETED_NODE && 1287 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1288 "Node was deleted but visit returned new node!"); 1289 1290 DEBUG(dbgs() << " ... into: "; 1291 RV.getNode()->dump(&DAG)); 1292 1293 // Transfer debug value. 1294 DAG.TransferDbgValues(SDValue(N, 0), RV); 1295 if (N->getNumValues() == RV.getNode()->getNumValues()) 1296 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1297 else { 1298 assert(N->getValueType(0) == RV.getValueType() && 1299 N->getNumValues() == 1 && "Type mismatch"); 1300 SDValue OpV = RV; 1301 DAG.ReplaceAllUsesWith(N, &OpV); 1302 } 1303 1304 // Push the new node and any users onto the worklist 1305 AddToWorklist(RV.getNode()); 1306 AddUsersToWorklist(RV.getNode()); 1307 1308 // Finally, if the node is now dead, remove it from the graph. The node 1309 // may not be dead if the replacement process recursively simplified to 1310 // something else needing this node. This will also take care of adding any 1311 // operands which have lost a user to the worklist. 1312 recursivelyDeleteUnusedNodes(N); 1313 } 1314 1315 // If the root changed (e.g. it was a dead load, update the root). 1316 DAG.setRoot(Dummy.getValue()); 1317 DAG.RemoveDeadNodes(); 1318 } 1319 1320 SDValue DAGCombiner::visit(SDNode *N) { 1321 switch (N->getOpcode()) { 1322 default: break; 1323 case ISD::TokenFactor: return visitTokenFactor(N); 1324 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1325 case ISD::ADD: return visitADD(N); 1326 case ISD::SUB: return visitSUB(N); 1327 case ISD::ADDC: return visitADDC(N); 1328 case ISD::SUBC: return visitSUBC(N); 1329 case ISD::ADDE: return visitADDE(N); 1330 case ISD::SUBE: return visitSUBE(N); 1331 case ISD::MUL: return visitMUL(N); 1332 case ISD::SDIV: return visitSDIV(N); 1333 case ISD::UDIV: return visitUDIV(N); 1334 case ISD::SREM: return visitSREM(N); 1335 case ISD::UREM: return visitUREM(N); 1336 case ISD::MULHU: return visitMULHU(N); 1337 case ISD::MULHS: return visitMULHS(N); 1338 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1339 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1340 case ISD::SMULO: return visitSMULO(N); 1341 case ISD::UMULO: return visitUMULO(N); 1342 case ISD::SDIVREM: return visitSDIVREM(N); 1343 case ISD::UDIVREM: return visitUDIVREM(N); 1344 case ISD::AND: return visitAND(N); 1345 case ISD::OR: return visitOR(N); 1346 case ISD::XOR: return visitXOR(N); 1347 case ISD::SHL: return visitSHL(N); 1348 case ISD::SRA: return visitSRA(N); 1349 case ISD::SRL: return visitSRL(N); 1350 case ISD::ROTR: 1351 case ISD::ROTL: return visitRotate(N); 1352 case ISD::BSWAP: return visitBSWAP(N); 1353 case ISD::CTLZ: return visitCTLZ(N); 1354 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1355 case ISD::CTTZ: return visitCTTZ(N); 1356 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1357 case ISD::CTPOP: return visitCTPOP(N); 1358 case ISD::SELECT: return visitSELECT(N); 1359 case ISD::VSELECT: return visitVSELECT(N); 1360 case ISD::SELECT_CC: return visitSELECT_CC(N); 1361 case ISD::SETCC: return visitSETCC(N); 1362 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1363 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1364 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1365 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1366 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1367 case ISD::TRUNCATE: return visitTRUNCATE(N); 1368 case ISD::BITCAST: return visitBITCAST(N); 1369 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1370 case ISD::FADD: return visitFADD(N); 1371 case ISD::FSUB: return visitFSUB(N); 1372 case ISD::FMUL: return visitFMUL(N); 1373 case ISD::FMA: return visitFMA(N); 1374 case ISD::FDIV: return visitFDIV(N); 1375 case ISD::FREM: return visitFREM(N); 1376 case ISD::FSQRT: return visitFSQRT(N); 1377 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1378 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1379 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1380 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1381 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1382 case ISD::FP_ROUND: return visitFP_ROUND(N); 1383 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1384 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1385 case ISD::FNEG: return visitFNEG(N); 1386 case ISD::FABS: return visitFABS(N); 1387 case ISD::FFLOOR: return visitFFLOOR(N); 1388 case ISD::FMINNUM: return visitFMINNUM(N); 1389 case ISD::FMAXNUM: return visitFMAXNUM(N); 1390 case ISD::FCEIL: return visitFCEIL(N); 1391 case ISD::FTRUNC: return visitFTRUNC(N); 1392 case ISD::BRCOND: return visitBRCOND(N); 1393 case ISD::BR_CC: return visitBR_CC(N); 1394 case ISD::LOAD: return visitLOAD(N); 1395 case ISD::STORE: return visitSTORE(N); 1396 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1397 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1398 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1399 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1400 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1401 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1402 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1403 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1404 case ISD::MGATHER: return visitMGATHER(N); 1405 case ISD::MLOAD: return visitMLOAD(N); 1406 case ISD::MSCATTER: return visitMSCATTER(N); 1407 case ISD::MSTORE: return visitMSTORE(N); 1408 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1409 } 1410 return SDValue(); 1411 } 1412 1413 SDValue DAGCombiner::combine(SDNode *N) { 1414 SDValue RV = visit(N); 1415 1416 // If nothing happened, try a target-specific DAG combine. 1417 if (!RV.getNode()) { 1418 assert(N->getOpcode() != ISD::DELETED_NODE && 1419 "Node was deleted but visit returned NULL!"); 1420 1421 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1422 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1423 1424 // Expose the DAG combiner to the target combiner impls. 1425 TargetLowering::DAGCombinerInfo 1426 DagCombineInfo(DAG, Level, false, this); 1427 1428 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1429 } 1430 } 1431 1432 // If nothing happened still, try promoting the operation. 1433 if (!RV.getNode()) { 1434 switch (N->getOpcode()) { 1435 default: break; 1436 case ISD::ADD: 1437 case ISD::SUB: 1438 case ISD::MUL: 1439 case ISD::AND: 1440 case ISD::OR: 1441 case ISD::XOR: 1442 RV = PromoteIntBinOp(SDValue(N, 0)); 1443 break; 1444 case ISD::SHL: 1445 case ISD::SRA: 1446 case ISD::SRL: 1447 RV = PromoteIntShiftOp(SDValue(N, 0)); 1448 break; 1449 case ISD::SIGN_EXTEND: 1450 case ISD::ZERO_EXTEND: 1451 case ISD::ANY_EXTEND: 1452 RV = PromoteExtend(SDValue(N, 0)); 1453 break; 1454 case ISD::LOAD: 1455 if (PromoteLoad(SDValue(N, 0))) 1456 RV = SDValue(N, 0); 1457 break; 1458 } 1459 } 1460 1461 // If N is a commutative binary node, try commuting it to enable more 1462 // sdisel CSE. 1463 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1464 N->getNumValues() == 1) { 1465 SDValue N0 = N->getOperand(0); 1466 SDValue N1 = N->getOperand(1); 1467 1468 // Constant operands are canonicalized to RHS. 1469 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1470 SDValue Ops[] = {N1, N0}; 1471 SDNode *CSENode; 1472 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) { 1473 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1474 &BinNode->Flags); 1475 } else { 1476 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1477 } 1478 if (CSENode) 1479 return SDValue(CSENode, 0); 1480 } 1481 } 1482 1483 return RV; 1484 } 1485 1486 /// Given a node, return its input chain if it has one, otherwise return a null 1487 /// sd operand. 1488 static SDValue getInputChainForNode(SDNode *N) { 1489 if (unsigned NumOps = N->getNumOperands()) { 1490 if (N->getOperand(0).getValueType() == MVT::Other) 1491 return N->getOperand(0); 1492 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1493 return N->getOperand(NumOps-1); 1494 for (unsigned i = 1; i < NumOps-1; ++i) 1495 if (N->getOperand(i).getValueType() == MVT::Other) 1496 return N->getOperand(i); 1497 } 1498 return SDValue(); 1499 } 1500 1501 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1502 // If N has two operands, where one has an input chain equal to the other, 1503 // the 'other' chain is redundant. 1504 if (N->getNumOperands() == 2) { 1505 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1506 return N->getOperand(0); 1507 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1508 return N->getOperand(1); 1509 } 1510 1511 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1512 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1513 SmallPtrSet<SDNode*, 16> SeenOps; 1514 bool Changed = false; // If we should replace this token factor. 1515 1516 // Start out with this token factor. 1517 TFs.push_back(N); 1518 1519 // Iterate through token factors. The TFs grows when new token factors are 1520 // encountered. 1521 for (unsigned i = 0; i < TFs.size(); ++i) { 1522 SDNode *TF = TFs[i]; 1523 1524 // Check each of the operands. 1525 for (const SDValue &Op : TF->op_values()) { 1526 1527 switch (Op.getOpcode()) { 1528 case ISD::EntryToken: 1529 // Entry tokens don't need to be added to the list. They are 1530 // redundant. 1531 Changed = true; 1532 break; 1533 1534 case ISD::TokenFactor: 1535 if (Op.hasOneUse() && 1536 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1537 // Queue up for processing. 1538 TFs.push_back(Op.getNode()); 1539 // Clean up in case the token factor is removed. 1540 AddToWorklist(Op.getNode()); 1541 Changed = true; 1542 break; 1543 } 1544 // Fall thru 1545 1546 default: 1547 // Only add if it isn't already in the list. 1548 if (SeenOps.insert(Op.getNode()).second) 1549 Ops.push_back(Op); 1550 else 1551 Changed = true; 1552 break; 1553 } 1554 } 1555 } 1556 1557 SDValue Result; 1558 1559 // If we've changed things around then replace token factor. 1560 if (Changed) { 1561 if (Ops.empty()) { 1562 // The entry token is the only possible outcome. 1563 Result = DAG.getEntryNode(); 1564 } else { 1565 // New and improved token factor. 1566 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1567 } 1568 1569 // Add users to worklist if AA is enabled, since it may introduce 1570 // a lot of new chained token factors while removing memory deps. 1571 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1572 : DAG.getSubtarget().useAA(); 1573 return CombineTo(N, Result, UseAA /*add to worklist*/); 1574 } 1575 1576 return Result; 1577 } 1578 1579 /// MERGE_VALUES can always be eliminated. 1580 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1581 WorklistRemover DeadNodes(*this); 1582 // Replacing results may cause a different MERGE_VALUES to suddenly 1583 // be CSE'd with N, and carry its uses with it. Iterate until no 1584 // uses remain, to ensure that the node can be safely deleted. 1585 // First add the users of this node to the work list so that they 1586 // can be tried again once they have new operands. 1587 AddUsersToWorklist(N); 1588 do { 1589 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1590 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1591 } while (!N->use_empty()); 1592 deleteAndRecombine(N); 1593 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1594 } 1595 1596 static bool isNullConstant(SDValue V) { 1597 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1598 return Const != nullptr && Const->isNullValue(); 1599 } 1600 1601 static bool isNullFPConstant(SDValue V) { 1602 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 1603 return Const != nullptr && Const->isZero() && !Const->isNegative(); 1604 } 1605 1606 static bool isAllOnesConstant(SDValue V) { 1607 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1608 return Const != nullptr && Const->isAllOnesValue(); 1609 } 1610 1611 static bool isOneConstant(SDValue V) { 1612 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1613 return Const != nullptr && Const->isOne(); 1614 } 1615 1616 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a 1617 /// ContantSDNode pointer else nullptr. 1618 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1619 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1620 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1621 } 1622 1623 SDValue DAGCombiner::visitADD(SDNode *N) { 1624 SDValue N0 = N->getOperand(0); 1625 SDValue N1 = N->getOperand(1); 1626 EVT VT = N0.getValueType(); 1627 1628 // fold vector ops 1629 if (VT.isVector()) { 1630 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1631 return FoldedVOp; 1632 1633 // fold (add x, 0) -> x, vector edition 1634 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1635 return N0; 1636 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1637 return N1; 1638 } 1639 1640 // fold (add x, undef) -> undef 1641 if (N0.getOpcode() == ISD::UNDEF) 1642 return N0; 1643 if (N1.getOpcode() == ISD::UNDEF) 1644 return N1; 1645 // fold (add c1, c2) -> c1+c2 1646 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1647 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1648 if (N0C && N1C) 1649 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C); 1650 // canonicalize constant to RHS 1651 if (isConstantIntBuildVectorOrConstantInt(N0) && 1652 !isConstantIntBuildVectorOrConstantInt(N1)) 1653 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1654 // fold (add x, 0) -> x 1655 if (isNullConstant(N1)) 1656 return N0; 1657 // fold (add Sym, c) -> Sym+c 1658 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1659 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1660 GA->getOpcode() == ISD::GlobalAddress) 1661 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1662 GA->getOffset() + 1663 (uint64_t)N1C->getSExtValue()); 1664 // fold ((c1-A)+c2) -> (c1+c2)-A 1665 if (N1C && N0.getOpcode() == ISD::SUB) 1666 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1667 SDLoc DL(N); 1668 return DAG.getNode(ISD::SUB, DL, VT, 1669 DAG.getConstant(N1C->getAPIntValue()+ 1670 N0C->getAPIntValue(), DL, VT), 1671 N0.getOperand(1)); 1672 } 1673 // reassociate add 1674 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1675 return RADD; 1676 // fold ((0-A) + B) -> B-A 1677 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1678 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1679 // fold (A + (0-B)) -> A-B 1680 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1681 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1682 // fold (A+(B-A)) -> B 1683 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1684 return N1.getOperand(0); 1685 // fold ((B-A)+A) -> B 1686 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1687 return N0.getOperand(0); 1688 // fold (A+(B-(A+C))) to (B-C) 1689 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1690 N0 == N1.getOperand(1).getOperand(0)) 1691 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1692 N1.getOperand(1).getOperand(1)); 1693 // fold (A+(B-(C+A))) to (B-C) 1694 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1695 N0 == N1.getOperand(1).getOperand(1)) 1696 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1697 N1.getOperand(1).getOperand(0)); 1698 // fold (A+((B-A)+or-C)) to (B+or-C) 1699 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1700 N1.getOperand(0).getOpcode() == ISD::SUB && 1701 N0 == N1.getOperand(0).getOperand(1)) 1702 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1703 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1704 1705 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1706 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1707 SDValue N00 = N0.getOperand(0); 1708 SDValue N01 = N0.getOperand(1); 1709 SDValue N10 = N1.getOperand(0); 1710 SDValue N11 = N1.getOperand(1); 1711 1712 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1714 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1715 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1716 } 1717 1718 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1719 return SDValue(N, 0); 1720 1721 // fold (a+b) -> (a|b) iff a and b share no bits. 1722 if (VT.isInteger() && !VT.isVector()) { 1723 APInt LHSZero, LHSOne; 1724 APInt RHSZero, RHSOne; 1725 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1726 1727 if (LHSZero.getBoolValue()) { 1728 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1729 1730 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1731 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1732 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1733 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1734 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1735 } 1736 } 1737 } 1738 1739 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1740 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1741 isNullConstant(N1.getOperand(0).getOperand(0))) 1742 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1743 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1744 N1.getOperand(0).getOperand(1), 1745 N1.getOperand(1))); 1746 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1747 isNullConstant(N0.getOperand(0).getOperand(0))) 1748 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1749 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1750 N0.getOperand(0).getOperand(1), 1751 N0.getOperand(1))); 1752 1753 if (N1.getOpcode() == ISD::AND) { 1754 SDValue AndOp0 = N1.getOperand(0); 1755 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1756 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1757 1758 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1759 // and similar xforms where the inner op is either ~0 or 0. 1760 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1761 SDLoc DL(N); 1762 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1763 } 1764 } 1765 1766 // add (sext i1), X -> sub X, (zext i1) 1767 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1768 N0.getOperand(0).getValueType() == MVT::i1 && 1769 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1770 SDLoc DL(N); 1771 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1772 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1773 } 1774 1775 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1776 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1777 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1778 if (TN->getVT() == MVT::i1) { 1779 SDLoc DL(N); 1780 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1781 DAG.getConstant(1, DL, VT)); 1782 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1783 } 1784 } 1785 1786 return SDValue(); 1787 } 1788 1789 SDValue DAGCombiner::visitADDC(SDNode *N) { 1790 SDValue N0 = N->getOperand(0); 1791 SDValue N1 = N->getOperand(1); 1792 EVT VT = N0.getValueType(); 1793 1794 // If the flag result is dead, turn this into an ADD. 1795 if (!N->hasAnyUseOfValue(1)) 1796 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1797 DAG.getNode(ISD::CARRY_FALSE, 1798 SDLoc(N), MVT::Glue)); 1799 1800 // canonicalize constant to RHS. 1801 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1802 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1803 if (N0C && !N1C) 1804 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1805 1806 // fold (addc x, 0) -> x + no carry out 1807 if (isNullConstant(N1)) 1808 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1809 SDLoc(N), MVT::Glue)); 1810 1811 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1812 APInt LHSZero, LHSOne; 1813 APInt RHSZero, RHSOne; 1814 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1815 1816 if (LHSZero.getBoolValue()) { 1817 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1818 1819 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1820 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1821 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1822 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1823 DAG.getNode(ISD::CARRY_FALSE, 1824 SDLoc(N), MVT::Glue)); 1825 } 1826 1827 return SDValue(); 1828 } 1829 1830 SDValue DAGCombiner::visitADDE(SDNode *N) { 1831 SDValue N0 = N->getOperand(0); 1832 SDValue N1 = N->getOperand(1); 1833 SDValue CarryIn = N->getOperand(2); 1834 1835 // canonicalize constant to RHS 1836 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1837 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1838 if (N0C && !N1C) 1839 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1840 N1, N0, CarryIn); 1841 1842 // fold (adde x, y, false) -> (addc x, y) 1843 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1844 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1845 1846 return SDValue(); 1847 } 1848 1849 // Since it may not be valid to emit a fold to zero for vector initializers 1850 // check if we can before folding. 1851 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1852 SelectionDAG &DAG, 1853 bool LegalOperations, bool LegalTypes) { 1854 if (!VT.isVector()) 1855 return DAG.getConstant(0, DL, VT); 1856 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1857 return DAG.getConstant(0, DL, VT); 1858 return SDValue(); 1859 } 1860 1861 SDValue DAGCombiner::visitSUB(SDNode *N) { 1862 SDValue N0 = N->getOperand(0); 1863 SDValue N1 = N->getOperand(1); 1864 EVT VT = N0.getValueType(); 1865 1866 // fold vector ops 1867 if (VT.isVector()) { 1868 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1869 return FoldedVOp; 1870 1871 // fold (sub x, 0) -> x, vector edition 1872 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1873 return N0; 1874 } 1875 1876 // fold (sub x, x) -> 0 1877 // FIXME: Refactor this and xor and other similar operations together. 1878 if (N0 == N1) 1879 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1880 // fold (sub c1, c2) -> c1-c2 1881 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1882 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1883 if (N0C && N1C) 1884 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C); 1885 // fold (sub x, c) -> (add x, -c) 1886 if (N1C) { 1887 SDLoc DL(N); 1888 return DAG.getNode(ISD::ADD, DL, VT, N0, 1889 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1890 } 1891 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1892 if (isAllOnesConstant(N0)) 1893 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1894 // fold A-(A-B) -> B 1895 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1896 return N1.getOperand(1); 1897 // fold (A+B)-A -> B 1898 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1899 return N0.getOperand(1); 1900 // fold (A+B)-B -> A 1901 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1902 return N0.getOperand(0); 1903 // fold C2-(A+C1) -> (C2-C1)-A 1904 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1905 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1906 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1907 SDLoc DL(N); 1908 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1909 DL, VT); 1910 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1911 N1.getOperand(0)); 1912 } 1913 // fold ((A+(B+or-C))-B) -> A+or-C 1914 if (N0.getOpcode() == ISD::ADD && 1915 (N0.getOperand(1).getOpcode() == ISD::SUB || 1916 N0.getOperand(1).getOpcode() == ISD::ADD) && 1917 N0.getOperand(1).getOperand(0) == N1) 1918 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1919 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1920 // fold ((A+(C+B))-B) -> A+C 1921 if (N0.getOpcode() == ISD::ADD && 1922 N0.getOperand(1).getOpcode() == ISD::ADD && 1923 N0.getOperand(1).getOperand(1) == N1) 1924 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1925 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1926 // fold ((A-(B-C))-C) -> A-B 1927 if (N0.getOpcode() == ISD::SUB && 1928 N0.getOperand(1).getOpcode() == ISD::SUB && 1929 N0.getOperand(1).getOperand(1) == N1) 1930 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1931 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1932 1933 // If either operand of a sub is undef, the result is undef 1934 if (N0.getOpcode() == ISD::UNDEF) 1935 return N0; 1936 if (N1.getOpcode() == ISD::UNDEF) 1937 return N1; 1938 1939 // If the relocation model supports it, consider symbol offsets. 1940 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1941 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1942 // fold (sub Sym, c) -> Sym-c 1943 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1944 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1945 GA->getOffset() - 1946 (uint64_t)N1C->getSExtValue()); 1947 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1948 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1949 if (GA->getGlobal() == GB->getGlobal()) 1950 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1951 SDLoc(N), VT); 1952 } 1953 1954 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1955 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1956 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1957 if (TN->getVT() == MVT::i1) { 1958 SDLoc DL(N); 1959 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1960 DAG.getConstant(1, DL, VT)); 1961 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1962 } 1963 } 1964 1965 return SDValue(); 1966 } 1967 1968 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1969 SDValue N0 = N->getOperand(0); 1970 SDValue N1 = N->getOperand(1); 1971 EVT VT = N0.getValueType(); 1972 1973 // If the flag result is dead, turn this into an SUB. 1974 if (!N->hasAnyUseOfValue(1)) 1975 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1976 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1977 MVT::Glue)); 1978 1979 // fold (subc x, x) -> 0 + no borrow 1980 if (N0 == N1) { 1981 SDLoc DL(N); 1982 return CombineTo(N, DAG.getConstant(0, DL, VT), 1983 DAG.getNode(ISD::CARRY_FALSE, DL, 1984 MVT::Glue)); 1985 } 1986 1987 // fold (subc x, 0) -> x + no borrow 1988 if (isNullConstant(N1)) 1989 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1990 MVT::Glue)); 1991 1992 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1993 if (isAllOnesConstant(N0)) 1994 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1995 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1996 MVT::Glue)); 1997 1998 return SDValue(); 1999 } 2000 2001 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2002 SDValue N0 = N->getOperand(0); 2003 SDValue N1 = N->getOperand(1); 2004 SDValue CarryIn = N->getOperand(2); 2005 2006 // fold (sube x, y, false) -> (subc x, y) 2007 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2008 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2009 2010 return SDValue(); 2011 } 2012 2013 SDValue DAGCombiner::visitMUL(SDNode *N) { 2014 SDValue N0 = N->getOperand(0); 2015 SDValue N1 = N->getOperand(1); 2016 EVT VT = N0.getValueType(); 2017 2018 // fold (mul x, undef) -> 0 2019 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2020 return DAG.getConstant(0, SDLoc(N), VT); 2021 2022 bool N0IsConst = false; 2023 bool N1IsConst = false; 2024 bool N1IsOpaqueConst = false; 2025 bool N0IsOpaqueConst = false; 2026 APInt ConstValue0, ConstValue1; 2027 // fold vector ops 2028 if (VT.isVector()) { 2029 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2030 return FoldedVOp; 2031 2032 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2033 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2034 } else { 2035 N0IsConst = isa<ConstantSDNode>(N0); 2036 if (N0IsConst) { 2037 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2038 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2039 } 2040 N1IsConst = isa<ConstantSDNode>(N1); 2041 if (N1IsConst) { 2042 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2043 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2044 } 2045 } 2046 2047 // fold (mul c1, c2) -> c1*c2 2048 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2049 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2050 N0.getNode(), N1.getNode()); 2051 2052 // canonicalize constant to RHS (vector doesn't have to splat) 2053 if (isConstantIntBuildVectorOrConstantInt(N0) && 2054 !isConstantIntBuildVectorOrConstantInt(N1)) 2055 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2056 // fold (mul x, 0) -> 0 2057 if (N1IsConst && ConstValue1 == 0) 2058 return N1; 2059 // We require a splat of the entire scalar bit width for non-contiguous 2060 // bit patterns. 2061 bool IsFullSplat = 2062 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2063 // fold (mul x, 1) -> x 2064 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2065 return N0; 2066 // fold (mul x, -1) -> 0-x 2067 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2068 SDLoc DL(N); 2069 return DAG.getNode(ISD::SUB, DL, VT, 2070 DAG.getConstant(0, DL, VT), N0); 2071 } 2072 // fold (mul x, (1 << c)) -> x << c 2073 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2074 IsFullSplat) { 2075 SDLoc DL(N); 2076 return DAG.getNode(ISD::SHL, DL, VT, N0, 2077 DAG.getConstant(ConstValue1.logBase2(), DL, 2078 getShiftAmountTy(N0.getValueType()))); 2079 } 2080 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2081 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2082 IsFullSplat) { 2083 unsigned Log2Val = (-ConstValue1).logBase2(); 2084 SDLoc DL(N); 2085 // FIXME: If the input is something that is easily negated (e.g. a 2086 // single-use add), we should put the negate there. 2087 return DAG.getNode(ISD::SUB, DL, VT, 2088 DAG.getConstant(0, DL, VT), 2089 DAG.getNode(ISD::SHL, DL, VT, N0, 2090 DAG.getConstant(Log2Val, DL, 2091 getShiftAmountTy(N0.getValueType())))); 2092 } 2093 2094 APInt Val; 2095 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2096 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2097 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2098 isa<ConstantSDNode>(N0.getOperand(1)))) { 2099 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2100 N1, N0.getOperand(1)); 2101 AddToWorklist(C3.getNode()); 2102 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2103 N0.getOperand(0), C3); 2104 } 2105 2106 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2107 // use. 2108 { 2109 SDValue Sh(nullptr,0), Y(nullptr,0); 2110 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2111 if (N0.getOpcode() == ISD::SHL && 2112 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2113 isa<ConstantSDNode>(N0.getOperand(1))) && 2114 N0.getNode()->hasOneUse()) { 2115 Sh = N0; Y = N1; 2116 } else if (N1.getOpcode() == ISD::SHL && 2117 isa<ConstantSDNode>(N1.getOperand(1)) && 2118 N1.getNode()->hasOneUse()) { 2119 Sh = N1; Y = N0; 2120 } 2121 2122 if (Sh.getNode()) { 2123 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2124 Sh.getOperand(0), Y); 2125 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2126 Mul, Sh.getOperand(1)); 2127 } 2128 } 2129 2130 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2131 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2132 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2133 isa<ConstantSDNode>(N0.getOperand(1)))) 2134 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2135 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2136 N0.getOperand(0), N1), 2137 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2138 N0.getOperand(1), N1)); 2139 2140 // reassociate mul 2141 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2142 return RMUL; 2143 2144 return SDValue(); 2145 } 2146 2147 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2148 SDValue N0 = N->getOperand(0); 2149 SDValue N1 = N->getOperand(1); 2150 EVT VT = N->getValueType(0); 2151 2152 // fold vector ops 2153 if (VT.isVector()) 2154 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2155 return FoldedVOp; 2156 2157 // fold (sdiv c1, c2) -> c1/c2 2158 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2159 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2160 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2161 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C); 2162 // fold (sdiv X, 1) -> X 2163 if (N1C && N1C->isOne()) 2164 return N0; 2165 // fold (sdiv X, -1) -> 0-X 2166 if (N1C && N1C->isAllOnesValue()) { 2167 SDLoc DL(N); 2168 return DAG.getNode(ISD::SUB, DL, VT, 2169 DAG.getConstant(0, DL, VT), N0); 2170 } 2171 // If we know the sign bits of both operands are zero, strength reduce to a 2172 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2173 if (!VT.isVector()) { 2174 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2175 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2176 N0, N1); 2177 } 2178 2179 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize(); 2180 // fold (sdiv X, pow2) -> simple ops after legalize 2181 // FIXME: We check for the exact bit here because the generic lowering gives 2182 // better results in that case. The target-specific lowering should learn how 2183 // to handle exact sdivs efficiently. 2184 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2185 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2186 (N1C->getAPIntValue().isPowerOf2() || 2187 (-N1C->getAPIntValue()).isPowerOf2())) { 2188 // If integer division is cheap, then don't perform the following fold. 2189 if (TLI.isIntDivCheap(N->getValueType(0), MinSize)) 2190 return SDValue(); 2191 2192 // Target-specific implementation of sdiv x, pow2. 2193 if (SDValue Res = BuildSDIVPow2(N)) 2194 return Res; 2195 2196 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2197 SDLoc DL(N); 2198 2199 // Splat the sign bit into the register 2200 SDValue SGN = 2201 DAG.getNode(ISD::SRA, DL, VT, N0, 2202 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2203 getShiftAmountTy(N0.getValueType()))); 2204 AddToWorklist(SGN.getNode()); 2205 2206 // Add (N0 < 0) ? abs2 - 1 : 0; 2207 SDValue SRL = 2208 DAG.getNode(ISD::SRL, DL, VT, SGN, 2209 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2210 getShiftAmountTy(SGN.getValueType()))); 2211 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2212 AddToWorklist(SRL.getNode()); 2213 AddToWorklist(ADD.getNode()); // Divide by pow2 2214 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2215 DAG.getConstant(lg2, DL, 2216 getShiftAmountTy(ADD.getValueType()))); 2217 2218 // If we're dividing by a positive value, we're done. Otherwise, we must 2219 // negate the result. 2220 if (N1C->getAPIntValue().isNonNegative()) 2221 return SRA; 2222 2223 AddToWorklist(SRA.getNode()); 2224 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2225 } 2226 2227 // If integer divide is expensive and we satisfy the requirements, emit an 2228 // alternate sequence. 2229 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), MinSize)) 2230 if (SDValue Op = BuildSDIV(N)) 2231 return Op; 2232 2233 // undef / X -> 0 2234 if (N0.getOpcode() == ISD::UNDEF) 2235 return DAG.getConstant(0, SDLoc(N), VT); 2236 // X / undef -> undef 2237 if (N1.getOpcode() == ISD::UNDEF) 2238 return N1; 2239 2240 return SDValue(); 2241 } 2242 2243 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2244 SDValue N0 = N->getOperand(0); 2245 SDValue N1 = N->getOperand(1); 2246 EVT VT = N->getValueType(0); 2247 2248 // fold vector ops 2249 if (VT.isVector()) 2250 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2251 return FoldedVOp; 2252 2253 // fold (udiv c1, c2) -> c1/c2 2254 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2255 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2256 if (N0C && N1C) 2257 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, 2258 N0C, N1C)) 2259 return Folded; 2260 // fold (udiv x, (1 << c)) -> x >>u c 2261 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) { 2262 SDLoc DL(N); 2263 return DAG.getNode(ISD::SRL, DL, VT, N0, 2264 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2265 getShiftAmountTy(N0.getValueType()))); 2266 } 2267 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2268 if (N1.getOpcode() == ISD::SHL) { 2269 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2270 if (SHC->getAPIntValue().isPowerOf2()) { 2271 EVT ADDVT = N1.getOperand(1).getValueType(); 2272 SDLoc DL(N); 2273 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2274 N1.getOperand(1), 2275 DAG.getConstant(SHC->getAPIntValue() 2276 .logBase2(), 2277 DL, ADDVT)); 2278 AddToWorklist(Add.getNode()); 2279 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2280 } 2281 } 2282 } 2283 2284 // fold (udiv x, c) -> alternate 2285 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize(); 2286 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), MinSize)) 2287 if (SDValue Op = BuildUDIV(N)) 2288 return Op; 2289 2290 // undef / X -> 0 2291 if (N0.getOpcode() == ISD::UNDEF) 2292 return DAG.getConstant(0, SDLoc(N), VT); 2293 // X / undef -> undef 2294 if (N1.getOpcode() == ISD::UNDEF) 2295 return N1; 2296 2297 return SDValue(); 2298 } 2299 2300 SDValue DAGCombiner::visitSREM(SDNode *N) { 2301 SDValue N0 = N->getOperand(0); 2302 SDValue N1 = N->getOperand(1); 2303 EVT VT = N->getValueType(0); 2304 2305 // fold (srem c1, c2) -> c1%c2 2306 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2307 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2308 if (N0C && N1C) 2309 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, 2310 N0C, N1C)) 2311 return Folded; 2312 // If we know the sign bits of both operands are zero, strength reduce to a 2313 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2314 if (!VT.isVector()) { 2315 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2316 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2317 } 2318 2319 // If X/C can be simplified by the division-by-constant logic, lower 2320 // X%C to the equivalent of X-X/C*C. 2321 if (N1C && !N1C->isNullValue()) { 2322 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2323 AddToWorklist(Div.getNode()); 2324 SDValue OptimizedDiv = combine(Div.getNode()); 2325 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2326 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2327 OptimizedDiv, N1); 2328 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2329 AddToWorklist(Mul.getNode()); 2330 return Sub; 2331 } 2332 } 2333 2334 // undef % X -> 0 2335 if (N0.getOpcode() == ISD::UNDEF) 2336 return DAG.getConstant(0, SDLoc(N), VT); 2337 // X % undef -> undef 2338 if (N1.getOpcode() == ISD::UNDEF) 2339 return N1; 2340 2341 return SDValue(); 2342 } 2343 2344 SDValue DAGCombiner::visitUREM(SDNode *N) { 2345 SDValue N0 = N->getOperand(0); 2346 SDValue N1 = N->getOperand(1); 2347 EVT VT = N->getValueType(0); 2348 2349 // fold (urem 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::UREM, SDLoc(N), VT, 2354 N0C, N1C)) 2355 return Folded; 2356 // fold (urem x, pow2) -> (and x, pow2-1) 2357 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2358 N1C->getAPIntValue().isPowerOf2()) { 2359 SDLoc DL(N); 2360 return DAG.getNode(ISD::AND, DL, VT, N0, 2361 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2362 } 2363 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2364 if (N1.getOpcode() == ISD::SHL) { 2365 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2366 if (SHC->getAPIntValue().isPowerOf2()) { 2367 SDLoc DL(N); 2368 SDValue Add = 2369 DAG.getNode(ISD::ADD, DL, VT, N1, 2370 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2371 VT)); 2372 AddToWorklist(Add.getNode()); 2373 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2374 } 2375 } 2376 } 2377 2378 // If X/C can be simplified by the division-by-constant logic, lower 2379 // X%C to the equivalent of X-X/C*C. 2380 if (N1C && !N1C->isNullValue()) { 2381 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2382 AddToWorklist(Div.getNode()); 2383 SDValue OptimizedDiv = combine(Div.getNode()); 2384 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2385 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2386 OptimizedDiv, N1); 2387 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2388 AddToWorklist(Mul.getNode()); 2389 return Sub; 2390 } 2391 } 2392 2393 // undef % X -> 0 2394 if (N0.getOpcode() == ISD::UNDEF) 2395 return DAG.getConstant(0, SDLoc(N), VT); 2396 // X % undef -> undef 2397 if (N1.getOpcode() == ISD::UNDEF) 2398 return N1; 2399 2400 return SDValue(); 2401 } 2402 2403 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2404 SDValue N0 = N->getOperand(0); 2405 SDValue N1 = N->getOperand(1); 2406 EVT VT = N->getValueType(0); 2407 SDLoc DL(N); 2408 2409 // fold (mulhs x, 0) -> 0 2410 if (isNullConstant(N1)) 2411 return N1; 2412 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2413 if (isOneConstant(N1)) { 2414 SDLoc DL(N); 2415 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2416 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2417 DL, 2418 getShiftAmountTy(N0.getValueType()))); 2419 } 2420 // fold (mulhs x, undef) -> 0 2421 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2422 return DAG.getConstant(0, SDLoc(N), VT); 2423 2424 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2425 // plus a shift. 2426 if (VT.isSimple() && !VT.isVector()) { 2427 MVT Simple = VT.getSimpleVT(); 2428 unsigned SimpleSize = Simple.getSizeInBits(); 2429 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2430 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2431 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2432 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2433 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2434 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2435 DAG.getConstant(SimpleSize, DL, 2436 getShiftAmountTy(N1.getValueType()))); 2437 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2438 } 2439 } 2440 2441 return SDValue(); 2442 } 2443 2444 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2445 SDValue N0 = N->getOperand(0); 2446 SDValue N1 = N->getOperand(1); 2447 EVT VT = N->getValueType(0); 2448 SDLoc DL(N); 2449 2450 // fold (mulhu x, 0) -> 0 2451 if (isNullConstant(N1)) 2452 return N1; 2453 // fold (mulhu x, 1) -> 0 2454 if (isOneConstant(N1)) 2455 return DAG.getConstant(0, DL, N0.getValueType()); 2456 // fold (mulhu x, undef) -> 0 2457 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2458 return DAG.getConstant(0, DL, VT); 2459 2460 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2461 // plus a shift. 2462 if (VT.isSimple() && !VT.isVector()) { 2463 MVT Simple = VT.getSimpleVT(); 2464 unsigned SimpleSize = Simple.getSizeInBits(); 2465 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2466 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2467 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2468 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2469 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2470 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2471 DAG.getConstant(SimpleSize, DL, 2472 getShiftAmountTy(N1.getValueType()))); 2473 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2474 } 2475 } 2476 2477 return SDValue(); 2478 } 2479 2480 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2481 /// give the opcodes for the two computations that are being performed. Return 2482 /// true if a simplification was made. 2483 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2484 unsigned HiOp) { 2485 // If the high half is not needed, just compute the low half. 2486 bool HiExists = N->hasAnyUseOfValue(1); 2487 if (!HiExists && 2488 (!LegalOperations || 2489 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2490 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2491 return CombineTo(N, Res, Res); 2492 } 2493 2494 // If the low half is not needed, just compute the high half. 2495 bool LoExists = N->hasAnyUseOfValue(0); 2496 if (!LoExists && 2497 (!LegalOperations || 2498 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2499 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2500 return CombineTo(N, Res, Res); 2501 } 2502 2503 // If both halves are used, return as it is. 2504 if (LoExists && HiExists) 2505 return SDValue(); 2506 2507 // If the two computed results can be simplified separately, separate them. 2508 if (LoExists) { 2509 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2510 AddToWorklist(Lo.getNode()); 2511 SDValue LoOpt = combine(Lo.getNode()); 2512 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2513 (!LegalOperations || 2514 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2515 return CombineTo(N, LoOpt, LoOpt); 2516 } 2517 2518 if (HiExists) { 2519 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2520 AddToWorklist(Hi.getNode()); 2521 SDValue HiOpt = combine(Hi.getNode()); 2522 if (HiOpt.getNode() && HiOpt != Hi && 2523 (!LegalOperations || 2524 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2525 return CombineTo(N, HiOpt, HiOpt); 2526 } 2527 2528 return SDValue(); 2529 } 2530 2531 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2532 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2533 return Res; 2534 2535 EVT VT = N->getValueType(0); 2536 SDLoc DL(N); 2537 2538 // If the type is twice as wide is legal, transform the mulhu to a wider 2539 // multiply plus a shift. 2540 if (VT.isSimple() && !VT.isVector()) { 2541 MVT Simple = VT.getSimpleVT(); 2542 unsigned SimpleSize = Simple.getSizeInBits(); 2543 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2544 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2545 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2546 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2547 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2548 // Compute the high part as N1. 2549 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2550 DAG.getConstant(SimpleSize, DL, 2551 getShiftAmountTy(Lo.getValueType()))); 2552 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2553 // Compute the low part as N0. 2554 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2555 return CombineTo(N, Lo, Hi); 2556 } 2557 } 2558 2559 return SDValue(); 2560 } 2561 2562 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2563 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2564 return Res; 2565 2566 EVT VT = N->getValueType(0); 2567 SDLoc DL(N); 2568 2569 // If the type is twice as wide is legal, transform the mulhu to a wider 2570 // multiply plus a shift. 2571 if (VT.isSimple() && !VT.isVector()) { 2572 MVT Simple = VT.getSimpleVT(); 2573 unsigned SimpleSize = Simple.getSizeInBits(); 2574 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2575 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2576 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2577 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2578 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2579 // Compute the high part as N1. 2580 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2581 DAG.getConstant(SimpleSize, DL, 2582 getShiftAmountTy(Lo.getValueType()))); 2583 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2584 // Compute the low part as N0. 2585 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2586 return CombineTo(N, Lo, Hi); 2587 } 2588 } 2589 2590 return SDValue(); 2591 } 2592 2593 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2594 // (smulo x, 2) -> (saddo x, x) 2595 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2596 if (C2->getAPIntValue() == 2) 2597 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2598 N->getOperand(0), N->getOperand(0)); 2599 2600 return SDValue(); 2601 } 2602 2603 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2604 // (umulo x, 2) -> (uaddo x, x) 2605 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2606 if (C2->getAPIntValue() == 2) 2607 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2608 N->getOperand(0), N->getOperand(0)); 2609 2610 return SDValue(); 2611 } 2612 2613 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2614 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM)) 2615 return Res; 2616 2617 return SDValue(); 2618 } 2619 2620 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2621 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM)) 2622 return Res; 2623 2624 return SDValue(); 2625 } 2626 2627 /// If this is a binary operator with two operands of the same opcode, try to 2628 /// simplify it. 2629 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2630 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2631 EVT VT = N0.getValueType(); 2632 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2633 2634 // Bail early if none of these transforms apply. 2635 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2636 2637 // For each of OP in AND/OR/XOR: 2638 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2639 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2640 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2641 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2642 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2643 // 2644 // do not sink logical op inside of a vector extend, since it may combine 2645 // into a vsetcc. 2646 EVT Op0VT = N0.getOperand(0).getValueType(); 2647 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2648 N0.getOpcode() == ISD::SIGN_EXTEND || 2649 N0.getOpcode() == ISD::BSWAP || 2650 // Avoid infinite looping with PromoteIntBinOp. 2651 (N0.getOpcode() == ISD::ANY_EXTEND && 2652 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2653 (N0.getOpcode() == ISD::TRUNCATE && 2654 (!TLI.isZExtFree(VT, Op0VT) || 2655 !TLI.isTruncateFree(Op0VT, VT)) && 2656 TLI.isTypeLegal(Op0VT))) && 2657 !VT.isVector() && 2658 Op0VT == N1.getOperand(0).getValueType() && 2659 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2660 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2661 N0.getOperand(0).getValueType(), 2662 N0.getOperand(0), N1.getOperand(0)); 2663 AddToWorklist(ORNode.getNode()); 2664 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2665 } 2666 2667 // For each of OP in SHL/SRL/SRA/AND... 2668 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2669 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2670 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2671 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2672 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2673 N0.getOperand(1) == N1.getOperand(1)) { 2674 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2675 N0.getOperand(0).getValueType(), 2676 N0.getOperand(0), N1.getOperand(0)); 2677 AddToWorklist(ORNode.getNode()); 2678 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2679 ORNode, N0.getOperand(1)); 2680 } 2681 2682 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2683 // Only perform this optimization after type legalization and before 2684 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2685 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2686 // we don't want to undo this promotion. 2687 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2688 // on scalars. 2689 if ((N0.getOpcode() == ISD::BITCAST || 2690 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2691 Level == AfterLegalizeTypes) { 2692 SDValue In0 = N0.getOperand(0); 2693 SDValue In1 = N1.getOperand(0); 2694 EVT In0Ty = In0.getValueType(); 2695 EVT In1Ty = In1.getValueType(); 2696 SDLoc DL(N); 2697 // If both incoming values are integers, and the original types are the 2698 // same. 2699 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2700 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2701 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2702 AddToWorklist(Op.getNode()); 2703 return BC; 2704 } 2705 } 2706 2707 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2708 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2709 // If both shuffles use the same mask, and both shuffle within a single 2710 // vector, then it is worthwhile to move the swizzle after the operation. 2711 // The type-legalizer generates this pattern when loading illegal 2712 // vector types from memory. In many cases this allows additional shuffle 2713 // optimizations. 2714 // There are other cases where moving the shuffle after the xor/and/or 2715 // is profitable even if shuffles don't perform a swizzle. 2716 // If both shuffles use the same mask, and both shuffles have the same first 2717 // or second operand, then it might still be profitable to move the shuffle 2718 // after the xor/and/or operation. 2719 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2720 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2721 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2722 2723 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2724 "Inputs to shuffles are not the same type"); 2725 2726 // Check that both shuffles use the same mask. The masks are known to be of 2727 // the same length because the result vector type is the same. 2728 // Check also that shuffles have only one use to avoid introducing extra 2729 // instructions. 2730 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2731 SVN0->getMask().equals(SVN1->getMask())) { 2732 SDValue ShOp = N0->getOperand(1); 2733 2734 // Don't try to fold this node if it requires introducing a 2735 // build vector of all zeros that might be illegal at this stage. 2736 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2737 if (!LegalTypes) 2738 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2739 else 2740 ShOp = SDValue(); 2741 } 2742 2743 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2744 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2745 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2746 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2747 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2748 N0->getOperand(0), N1->getOperand(0)); 2749 AddToWorklist(NewNode.getNode()); 2750 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2751 &SVN0->getMask()[0]); 2752 } 2753 2754 // Don't try to fold this node if it requires introducing a 2755 // build vector of all zeros that might be illegal at this stage. 2756 ShOp = N0->getOperand(0); 2757 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2758 if (!LegalTypes) 2759 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2760 else 2761 ShOp = SDValue(); 2762 } 2763 2764 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2765 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2766 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2767 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2768 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2769 N0->getOperand(1), N1->getOperand(1)); 2770 AddToWorklist(NewNode.getNode()); 2771 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2772 &SVN0->getMask()[0]); 2773 } 2774 } 2775 } 2776 2777 return SDValue(); 2778 } 2779 2780 /// This contains all DAGCombine rules which reduce two values combined by 2781 /// an And operation to a single value. This makes them reusable in the context 2782 /// of visitSELECT(). Rules involving constants are not included as 2783 /// visitSELECT() already handles those cases. 2784 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2785 SDNode *LocReference) { 2786 EVT VT = N1.getValueType(); 2787 2788 // fold (and x, undef) -> 0 2789 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2790 return DAG.getConstant(0, SDLoc(LocReference), VT); 2791 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2792 SDValue LL, LR, RL, RR, CC0, CC1; 2793 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2794 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2795 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2796 2797 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2798 LL.getValueType().isInteger()) { 2799 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2800 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2801 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2802 LR.getValueType(), LL, RL); 2803 AddToWorklist(ORNode.getNode()); 2804 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2805 } 2806 if (isAllOnesConstant(LR)) { 2807 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2808 if (Op1 == ISD::SETEQ) { 2809 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2810 LR.getValueType(), LL, RL); 2811 AddToWorklist(ANDNode.getNode()); 2812 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2813 } 2814 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2815 if (Op1 == ISD::SETGT) { 2816 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2817 LR.getValueType(), LL, RL); 2818 AddToWorklist(ORNode.getNode()); 2819 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2820 } 2821 } 2822 } 2823 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2824 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2825 Op0 == Op1 && LL.getValueType().isInteger() && 2826 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2827 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2828 SDLoc DL(N0); 2829 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2830 LL, DAG.getConstant(1, DL, 2831 LL.getValueType())); 2832 AddToWorklist(ADDNode.getNode()); 2833 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2834 DAG.getConstant(2, DL, LL.getValueType()), 2835 ISD::SETUGE); 2836 } 2837 // canonicalize equivalent to ll == rl 2838 if (LL == RR && LR == RL) { 2839 Op1 = ISD::getSetCCSwappedOperands(Op1); 2840 std::swap(RL, RR); 2841 } 2842 if (LL == RL && LR == RR) { 2843 bool isInteger = LL.getValueType().isInteger(); 2844 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2845 if (Result != ISD::SETCC_INVALID && 2846 (!LegalOperations || 2847 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2848 TLI.isOperationLegal(ISD::SETCC, 2849 getSetCCResultType(N0.getSimpleValueType()))))) 2850 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2851 LL, LR, Result); 2852 } 2853 } 2854 2855 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2856 VT.getSizeInBits() <= 64) { 2857 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2858 APInt ADDC = ADDI->getAPIntValue(); 2859 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2860 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2861 // immediate for an add, but it is legal if its top c2 bits are set, 2862 // transform the ADD so the immediate doesn't need to be materialized 2863 // in a register. 2864 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2865 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2866 SRLI->getZExtValue()); 2867 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2868 ADDC |= Mask; 2869 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2870 SDLoc DL(N0); 2871 SDValue NewAdd = 2872 DAG.getNode(ISD::ADD, DL, VT, 2873 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2874 CombineTo(N0.getNode(), NewAdd); 2875 // Return N so it doesn't get rechecked! 2876 return SDValue(LocReference, 0); 2877 } 2878 } 2879 } 2880 } 2881 } 2882 } 2883 2884 return SDValue(); 2885 } 2886 2887 SDValue DAGCombiner::visitAND(SDNode *N) { 2888 SDValue N0 = N->getOperand(0); 2889 SDValue N1 = N->getOperand(1); 2890 EVT VT = N1.getValueType(); 2891 2892 // fold vector ops 2893 if (VT.isVector()) { 2894 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2895 return FoldedVOp; 2896 2897 // fold (and x, 0) -> 0, vector edition 2898 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2899 // do not return N0, because undef node may exist in N0 2900 return DAG.getConstant( 2901 APInt::getNullValue( 2902 N0.getValueType().getScalarType().getSizeInBits()), 2903 SDLoc(N), N0.getValueType()); 2904 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2905 // do not return N1, because undef node may exist in N1 2906 return DAG.getConstant( 2907 APInt::getNullValue( 2908 N1.getValueType().getScalarType().getSizeInBits()), 2909 SDLoc(N), N1.getValueType()); 2910 2911 // fold (and x, -1) -> x, vector edition 2912 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2913 return N1; 2914 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2915 return N0; 2916 } 2917 2918 // fold (and c1, c2) -> c1&c2 2919 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2920 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2921 if (N0C && N1C && !N1C->isOpaque()) 2922 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 2923 // canonicalize constant to RHS 2924 if (isConstantIntBuildVectorOrConstantInt(N0) && 2925 !isConstantIntBuildVectorOrConstantInt(N1)) 2926 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2927 // fold (and x, -1) -> x 2928 if (isAllOnesConstant(N1)) 2929 return N0; 2930 // if (and x, c) is known to be zero, return 0 2931 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2932 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2933 APInt::getAllOnesValue(BitWidth))) 2934 return DAG.getConstant(0, SDLoc(N), VT); 2935 // reassociate and 2936 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 2937 return RAND; 2938 // fold (and (or x, C), D) -> D if (C & D) == D 2939 if (N1C && N0.getOpcode() == ISD::OR) 2940 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2941 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2942 return N1; 2943 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2944 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2945 SDValue N0Op0 = N0.getOperand(0); 2946 APInt Mask = ~N1C->getAPIntValue(); 2947 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2948 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2949 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2950 N0.getValueType(), N0Op0); 2951 2952 // Replace uses of the AND with uses of the Zero extend node. 2953 CombineTo(N, Zext); 2954 2955 // We actually want to replace all uses of the any_extend with the 2956 // zero_extend, to avoid duplicating things. This will later cause this 2957 // AND to be folded. 2958 CombineTo(N0.getNode(), Zext); 2959 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2960 } 2961 } 2962 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2963 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2964 // already be zero by virtue of the width of the base type of the load. 2965 // 2966 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2967 // more cases. 2968 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2969 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2970 N0.getOpcode() == ISD::LOAD) { 2971 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2972 N0 : N0.getOperand(0) ); 2973 2974 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2975 // This can be a pure constant or a vector splat, in which case we treat the 2976 // vector as a scalar and use the splat value. 2977 APInt Constant = APInt::getNullValue(1); 2978 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2979 Constant = C->getAPIntValue(); 2980 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2981 APInt SplatValue, SplatUndef; 2982 unsigned SplatBitSize; 2983 bool HasAnyUndefs; 2984 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2985 SplatBitSize, HasAnyUndefs); 2986 if (IsSplat) { 2987 // Undef bits can contribute to a possible optimisation if set, so 2988 // set them. 2989 SplatValue |= SplatUndef; 2990 2991 // The splat value may be something like "0x00FFFFFF", which means 0 for 2992 // the first vector value and FF for the rest, repeating. We need a mask 2993 // that will apply equally to all members of the vector, so AND all the 2994 // lanes of the constant together. 2995 EVT VT = Vector->getValueType(0); 2996 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2997 2998 // If the splat value has been compressed to a bitlength lower 2999 // than the size of the vector lane, we need to re-expand it to 3000 // the lane size. 3001 if (BitWidth > SplatBitSize) 3002 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3003 SplatBitSize < BitWidth; 3004 SplatBitSize = SplatBitSize * 2) 3005 SplatValue |= SplatValue.shl(SplatBitSize); 3006 3007 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3008 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3009 if (SplatBitSize % BitWidth == 0) { 3010 Constant = APInt::getAllOnesValue(BitWidth); 3011 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3012 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3013 } 3014 } 3015 } 3016 3017 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3018 // actually legal and isn't going to get expanded, else this is a false 3019 // optimisation. 3020 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3021 Load->getValueType(0), 3022 Load->getMemoryVT()); 3023 3024 // Resize the constant to the same size as the original memory access before 3025 // extension. If it is still the AllOnesValue then this AND is completely 3026 // unneeded. 3027 Constant = 3028 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3029 3030 bool B; 3031 switch (Load->getExtensionType()) { 3032 default: B = false; break; 3033 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3034 case ISD::ZEXTLOAD: 3035 case ISD::NON_EXTLOAD: B = true; break; 3036 } 3037 3038 if (B && Constant.isAllOnesValue()) { 3039 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3040 // preserve semantics once we get rid of the AND. 3041 SDValue NewLoad(Load, 0); 3042 if (Load->getExtensionType() == ISD::EXTLOAD) { 3043 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3044 Load->getValueType(0), SDLoc(Load), 3045 Load->getChain(), Load->getBasePtr(), 3046 Load->getOffset(), Load->getMemoryVT(), 3047 Load->getMemOperand()); 3048 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3049 if (Load->getNumValues() == 3) { 3050 // PRE/POST_INC loads have 3 values. 3051 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3052 NewLoad.getValue(2) }; 3053 CombineTo(Load, To, 3, true); 3054 } else { 3055 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3056 } 3057 } 3058 3059 // Fold the AND away, taking care not to fold to the old load node if we 3060 // replaced it. 3061 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3062 3063 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3064 } 3065 } 3066 3067 // fold (and (load x), 255) -> (zextload x, i8) 3068 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3069 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3070 if (N1C && (N0.getOpcode() == ISD::LOAD || 3071 (N0.getOpcode() == ISD::ANY_EXTEND && 3072 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3073 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3074 LoadSDNode *LN0 = HasAnyExt 3075 ? cast<LoadSDNode>(N0.getOperand(0)) 3076 : cast<LoadSDNode>(N0); 3077 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3078 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3079 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 3080 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 3081 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3082 EVT LoadedVT = LN0->getMemoryVT(); 3083 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3084 3085 if (ExtVT == LoadedVT && 3086 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3087 ExtVT))) { 3088 3089 SDValue NewLoad = 3090 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3091 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3092 LN0->getMemOperand()); 3093 AddToWorklist(N); 3094 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3095 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3096 } 3097 3098 // Do not change the width of a volatile load. 3099 // Do not generate loads of non-round integer types since these can 3100 // be expensive (and would be wrong if the type is not byte sized). 3101 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3102 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3103 ExtVT))) { 3104 EVT PtrType = LN0->getOperand(1).getValueType(); 3105 3106 unsigned Alignment = LN0->getAlignment(); 3107 SDValue NewPtr = LN0->getBasePtr(); 3108 3109 // For big endian targets, we need to add an offset to the pointer 3110 // to load the correct bytes. For little endian systems, we merely 3111 // need to read fewer bytes from the same pointer. 3112 if (DAG.getDataLayout().isBigEndian()) { 3113 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3114 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3115 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3116 SDLoc DL(LN0); 3117 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3118 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3119 Alignment = MinAlign(Alignment, PtrOff); 3120 } 3121 3122 AddToWorklist(NewPtr.getNode()); 3123 3124 SDValue Load = 3125 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3126 LN0->getChain(), NewPtr, 3127 LN0->getPointerInfo(), 3128 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3129 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3130 AddToWorklist(N); 3131 CombineTo(LN0, Load, Load.getValue(1)); 3132 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3133 } 3134 } 3135 } 3136 } 3137 3138 if (SDValue Combined = visitANDLike(N0, N1, N)) 3139 return Combined; 3140 3141 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3142 if (N0.getOpcode() == N1.getOpcode()) 3143 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3144 return Tmp; 3145 3146 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3147 // fold (and (sra)) -> (and (srl)) when possible. 3148 if (!VT.isVector() && 3149 SimplifyDemandedBits(SDValue(N, 0))) 3150 return SDValue(N, 0); 3151 3152 // fold (zext_inreg (extload x)) -> (zextload x) 3153 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3154 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3155 EVT MemVT = LN0->getMemoryVT(); 3156 // If we zero all the possible extended bits, then we can turn this into 3157 // a zextload if we are running before legalize or the operation is legal. 3158 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3159 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3160 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3161 ((!LegalOperations && !LN0->isVolatile()) || 3162 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3163 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3164 LN0->getChain(), LN0->getBasePtr(), 3165 MemVT, LN0->getMemOperand()); 3166 AddToWorklist(N); 3167 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3168 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3169 } 3170 } 3171 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3172 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3173 N0.hasOneUse()) { 3174 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3175 EVT MemVT = LN0->getMemoryVT(); 3176 // If we zero all the possible extended bits, then we can turn this into 3177 // a zextload if we are running before legalize or the operation is legal. 3178 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3179 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3180 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3181 ((!LegalOperations && !LN0->isVolatile()) || 3182 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3183 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3184 LN0->getChain(), LN0->getBasePtr(), 3185 MemVT, LN0->getMemOperand()); 3186 AddToWorklist(N); 3187 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3188 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3189 } 3190 } 3191 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3192 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3193 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3194 N0.getOperand(1), false); 3195 if (BSwap.getNode()) 3196 return BSwap; 3197 } 3198 3199 return SDValue(); 3200 } 3201 3202 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3203 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3204 bool DemandHighBits) { 3205 if (!LegalOperations) 3206 return SDValue(); 3207 3208 EVT VT = N->getValueType(0); 3209 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3210 return SDValue(); 3211 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3212 return SDValue(); 3213 3214 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3215 bool LookPassAnd0 = false; 3216 bool LookPassAnd1 = false; 3217 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3218 std::swap(N0, N1); 3219 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3220 std::swap(N0, N1); 3221 if (N0.getOpcode() == ISD::AND) { 3222 if (!N0.getNode()->hasOneUse()) 3223 return SDValue(); 3224 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3225 if (!N01C || N01C->getZExtValue() != 0xFF00) 3226 return SDValue(); 3227 N0 = N0.getOperand(0); 3228 LookPassAnd0 = true; 3229 } 3230 3231 if (N1.getOpcode() == ISD::AND) { 3232 if (!N1.getNode()->hasOneUse()) 3233 return SDValue(); 3234 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3235 if (!N11C || N11C->getZExtValue() != 0xFF) 3236 return SDValue(); 3237 N1 = N1.getOperand(0); 3238 LookPassAnd1 = true; 3239 } 3240 3241 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3242 std::swap(N0, N1); 3243 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3244 return SDValue(); 3245 if (!N0.getNode()->hasOneUse() || 3246 !N1.getNode()->hasOneUse()) 3247 return SDValue(); 3248 3249 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3250 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3251 if (!N01C || !N11C) 3252 return SDValue(); 3253 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3254 return SDValue(); 3255 3256 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3257 SDValue N00 = N0->getOperand(0); 3258 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3259 if (!N00.getNode()->hasOneUse()) 3260 return SDValue(); 3261 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3262 if (!N001C || N001C->getZExtValue() != 0xFF) 3263 return SDValue(); 3264 N00 = N00.getOperand(0); 3265 LookPassAnd0 = true; 3266 } 3267 3268 SDValue N10 = N1->getOperand(0); 3269 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3270 if (!N10.getNode()->hasOneUse()) 3271 return SDValue(); 3272 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3273 if (!N101C || N101C->getZExtValue() != 0xFF00) 3274 return SDValue(); 3275 N10 = N10.getOperand(0); 3276 LookPassAnd1 = true; 3277 } 3278 3279 if (N00 != N10) 3280 return SDValue(); 3281 3282 // Make sure everything beyond the low halfword gets set to zero since the SRL 3283 // 16 will clear the top bits. 3284 unsigned OpSizeInBits = VT.getSizeInBits(); 3285 if (DemandHighBits && OpSizeInBits > 16) { 3286 // If the left-shift isn't masked out then the only way this is a bswap is 3287 // if all bits beyond the low 8 are 0. In that case the entire pattern 3288 // reduces to a left shift anyway: leave it for other parts of the combiner. 3289 if (!LookPassAnd0) 3290 return SDValue(); 3291 3292 // However, if the right shift isn't masked out then it might be because 3293 // it's not needed. See if we can spot that too. 3294 if (!LookPassAnd1 && 3295 !DAG.MaskedValueIsZero( 3296 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3297 return SDValue(); 3298 } 3299 3300 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3301 if (OpSizeInBits > 16) { 3302 SDLoc DL(N); 3303 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3304 DAG.getConstant(OpSizeInBits - 16, DL, 3305 getShiftAmountTy(VT))); 3306 } 3307 return Res; 3308 } 3309 3310 /// Return true if the specified node is an element that makes up a 32-bit 3311 /// packed halfword byteswap. 3312 /// ((x & 0x000000ff) << 8) | 3313 /// ((x & 0x0000ff00) >> 8) | 3314 /// ((x & 0x00ff0000) << 8) | 3315 /// ((x & 0xff000000) >> 8) 3316 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3317 if (!N.getNode()->hasOneUse()) 3318 return false; 3319 3320 unsigned Opc = N.getOpcode(); 3321 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3322 return false; 3323 3324 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3325 if (!N1C) 3326 return false; 3327 3328 unsigned Num; 3329 switch (N1C->getZExtValue()) { 3330 default: 3331 return false; 3332 case 0xFF: Num = 0; break; 3333 case 0xFF00: Num = 1; break; 3334 case 0xFF0000: Num = 2; break; 3335 case 0xFF000000: Num = 3; break; 3336 } 3337 3338 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3339 SDValue N0 = N.getOperand(0); 3340 if (Opc == ISD::AND) { 3341 if (Num == 0 || Num == 2) { 3342 // (x >> 8) & 0xff 3343 // (x >> 8) & 0xff0000 3344 if (N0.getOpcode() != ISD::SRL) 3345 return false; 3346 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3347 if (!C || C->getZExtValue() != 8) 3348 return false; 3349 } else { 3350 // (x << 8) & 0xff00 3351 // (x << 8) & 0xff000000 3352 if (N0.getOpcode() != ISD::SHL) 3353 return false; 3354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3355 if (!C || C->getZExtValue() != 8) 3356 return false; 3357 } 3358 } else if (Opc == ISD::SHL) { 3359 // (x & 0xff) << 8 3360 // (x & 0xff0000) << 8 3361 if (Num != 0 && Num != 2) 3362 return false; 3363 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3364 if (!C || C->getZExtValue() != 8) 3365 return false; 3366 } else { // Opc == ISD::SRL 3367 // (x & 0xff00) >> 8 3368 // (x & 0xff000000) >> 8 3369 if (Num != 1 && Num != 3) 3370 return false; 3371 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3372 if (!C || C->getZExtValue() != 8) 3373 return false; 3374 } 3375 3376 if (Parts[Num]) 3377 return false; 3378 3379 Parts[Num] = N0.getOperand(0).getNode(); 3380 return true; 3381 } 3382 3383 /// Match a 32-bit packed halfword bswap. That is 3384 /// ((x & 0x000000ff) << 8) | 3385 /// ((x & 0x0000ff00) >> 8) | 3386 /// ((x & 0x00ff0000) << 8) | 3387 /// ((x & 0xff000000) >> 8) 3388 /// => (rotl (bswap x), 16) 3389 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3390 if (!LegalOperations) 3391 return SDValue(); 3392 3393 EVT VT = N->getValueType(0); 3394 if (VT != MVT::i32) 3395 return SDValue(); 3396 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3397 return SDValue(); 3398 3399 // Look for either 3400 // (or (or (and), (and)), (or (and), (and))) 3401 // (or (or (or (and), (and)), (and)), (and)) 3402 if (N0.getOpcode() != ISD::OR) 3403 return SDValue(); 3404 SDValue N00 = N0.getOperand(0); 3405 SDValue N01 = N0.getOperand(1); 3406 SDNode *Parts[4] = {}; 3407 3408 if (N1.getOpcode() == ISD::OR && 3409 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3410 // (or (or (and), (and)), (or (and), (and))) 3411 SDValue N000 = N00.getOperand(0); 3412 if (!isBSwapHWordElement(N000, Parts)) 3413 return SDValue(); 3414 3415 SDValue N001 = N00.getOperand(1); 3416 if (!isBSwapHWordElement(N001, Parts)) 3417 return SDValue(); 3418 SDValue N010 = N01.getOperand(0); 3419 if (!isBSwapHWordElement(N010, Parts)) 3420 return SDValue(); 3421 SDValue N011 = N01.getOperand(1); 3422 if (!isBSwapHWordElement(N011, Parts)) 3423 return SDValue(); 3424 } else { 3425 // (or (or (or (and), (and)), (and)), (and)) 3426 if (!isBSwapHWordElement(N1, Parts)) 3427 return SDValue(); 3428 if (!isBSwapHWordElement(N01, Parts)) 3429 return SDValue(); 3430 if (N00.getOpcode() != ISD::OR) 3431 return SDValue(); 3432 SDValue N000 = N00.getOperand(0); 3433 if (!isBSwapHWordElement(N000, Parts)) 3434 return SDValue(); 3435 SDValue N001 = N00.getOperand(1); 3436 if (!isBSwapHWordElement(N001, Parts)) 3437 return SDValue(); 3438 } 3439 3440 // Make sure the parts are all coming from the same node. 3441 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3442 return SDValue(); 3443 3444 SDLoc DL(N); 3445 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3446 SDValue(Parts[0], 0)); 3447 3448 // Result of the bswap should be rotated by 16. If it's not legal, then 3449 // do (x << 16) | (x >> 16). 3450 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3451 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3452 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3453 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3454 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3455 return DAG.getNode(ISD::OR, DL, VT, 3456 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3457 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3458 } 3459 3460 /// This contains all DAGCombine rules which reduce two values combined by 3461 /// an Or operation to a single value \see visitANDLike(). 3462 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3463 EVT VT = N1.getValueType(); 3464 // fold (or x, undef) -> -1 3465 if (!LegalOperations && 3466 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3467 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3468 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3469 SDLoc(LocReference), VT); 3470 } 3471 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3472 SDValue LL, LR, RL, RR, CC0, CC1; 3473 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3474 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3475 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3476 3477 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3478 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3479 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3480 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3481 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3482 LR.getValueType(), LL, RL); 3483 AddToWorklist(ORNode.getNode()); 3484 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3485 } 3486 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3487 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3488 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3489 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3490 LR.getValueType(), LL, RL); 3491 AddToWorklist(ANDNode.getNode()); 3492 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3493 } 3494 } 3495 // canonicalize equivalent to ll == rl 3496 if (LL == RR && LR == RL) { 3497 Op1 = ISD::getSetCCSwappedOperands(Op1); 3498 std::swap(RL, RR); 3499 } 3500 if (LL == RL && LR == RR) { 3501 bool isInteger = LL.getValueType().isInteger(); 3502 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3503 if (Result != ISD::SETCC_INVALID && 3504 (!LegalOperations || 3505 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3506 TLI.isOperationLegal(ISD::SETCC, 3507 getSetCCResultType(N0.getValueType()))))) 3508 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3509 LL, LR, Result); 3510 } 3511 } 3512 3513 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3514 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3515 // Don't increase # computations. 3516 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3517 // We can only do this xform if we know that bits from X that are set in C2 3518 // but not in C1 are already zero. Likewise for Y. 3519 if (const ConstantSDNode *N0O1C = 3520 getAsNonOpaqueConstant(N0.getOperand(1))) { 3521 if (const ConstantSDNode *N1O1C = 3522 getAsNonOpaqueConstant(N1.getOperand(1))) { 3523 // We can only do this xform if we know that bits from X that are set in 3524 // C2 but not in C1 are already zero. Likewise for Y. 3525 const APInt &LHSMask = N0O1C->getAPIntValue(); 3526 const APInt &RHSMask = N1O1C->getAPIntValue(); 3527 3528 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3529 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3530 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3531 N0.getOperand(0), N1.getOperand(0)); 3532 SDLoc DL(LocReference); 3533 return DAG.getNode(ISD::AND, DL, VT, X, 3534 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3535 } 3536 } 3537 } 3538 } 3539 3540 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3541 if (N0.getOpcode() == ISD::AND && 3542 N1.getOpcode() == ISD::AND && 3543 N0.getOperand(0) == N1.getOperand(0) && 3544 // Don't increase # computations. 3545 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3546 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3547 N0.getOperand(1), N1.getOperand(1)); 3548 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3549 } 3550 3551 return SDValue(); 3552 } 3553 3554 SDValue DAGCombiner::visitOR(SDNode *N) { 3555 SDValue N0 = N->getOperand(0); 3556 SDValue N1 = N->getOperand(1); 3557 EVT VT = N1.getValueType(); 3558 3559 // fold vector ops 3560 if (VT.isVector()) { 3561 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3562 return FoldedVOp; 3563 3564 // fold (or x, 0) -> x, vector edition 3565 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3566 return N1; 3567 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3568 return N0; 3569 3570 // fold (or x, -1) -> -1, vector edition 3571 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3572 // do not return N0, because undef node may exist in N0 3573 return DAG.getConstant( 3574 APInt::getAllOnesValue( 3575 N0.getValueType().getScalarType().getSizeInBits()), 3576 SDLoc(N), N0.getValueType()); 3577 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3578 // do not return N1, because undef node may exist in N1 3579 return DAG.getConstant( 3580 APInt::getAllOnesValue( 3581 N1.getValueType().getScalarType().getSizeInBits()), 3582 SDLoc(N), N1.getValueType()); 3583 3584 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3585 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3586 // Do this only if the resulting shuffle is legal. 3587 if (isa<ShuffleVectorSDNode>(N0) && 3588 isa<ShuffleVectorSDNode>(N1) && 3589 // Avoid folding a node with illegal type. 3590 TLI.isTypeLegal(VT) && 3591 N0->getOperand(1) == N1->getOperand(1) && 3592 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3593 bool CanFold = true; 3594 unsigned NumElts = VT.getVectorNumElements(); 3595 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3596 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3597 // We construct two shuffle masks: 3598 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3599 // and N1 as the second operand. 3600 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3601 // and N0 as the second operand. 3602 // We do this because OR is commutable and therefore there might be 3603 // two ways to fold this node into a shuffle. 3604 SmallVector<int,4> Mask1; 3605 SmallVector<int,4> Mask2; 3606 3607 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3608 int M0 = SV0->getMaskElt(i); 3609 int M1 = SV1->getMaskElt(i); 3610 3611 // Both shuffle indexes are undef. Propagate Undef. 3612 if (M0 < 0 && M1 < 0) { 3613 Mask1.push_back(M0); 3614 Mask2.push_back(M0); 3615 continue; 3616 } 3617 3618 if (M0 < 0 || M1 < 0 || 3619 (M0 < (int)NumElts && M1 < (int)NumElts) || 3620 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3621 CanFold = false; 3622 break; 3623 } 3624 3625 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3626 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3627 } 3628 3629 if (CanFold) { 3630 // Fold this sequence only if the resulting shuffle is 'legal'. 3631 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3632 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3633 N1->getOperand(0), &Mask1[0]); 3634 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3635 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3636 N0->getOperand(0), &Mask2[0]); 3637 } 3638 } 3639 } 3640 3641 // fold (or c1, c2) -> c1|c2 3642 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3643 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3644 if (N0C && N1C && !N1C->isOpaque()) 3645 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3646 // canonicalize constant to RHS 3647 if (isConstantIntBuildVectorOrConstantInt(N0) && 3648 !isConstantIntBuildVectorOrConstantInt(N1)) 3649 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3650 // fold (or x, 0) -> x 3651 if (isNullConstant(N1)) 3652 return N0; 3653 // fold (or x, -1) -> -1 3654 if (isAllOnesConstant(N1)) 3655 return N1; 3656 // fold (or x, c) -> c iff (x & ~c) == 0 3657 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3658 return N1; 3659 3660 if (SDValue Combined = visitORLike(N0, N1, N)) 3661 return Combined; 3662 3663 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3664 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3665 return BSwap; 3666 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3667 return BSwap; 3668 3669 // reassociate or 3670 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3671 return ROR; 3672 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3673 // iff (c1 & c2) == 0. 3674 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3675 isa<ConstantSDNode>(N0.getOperand(1))) { 3676 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3677 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3678 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3679 N1C, C1)) 3680 return DAG.getNode( 3681 ISD::AND, SDLoc(N), VT, 3682 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3683 return SDValue(); 3684 } 3685 } 3686 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3687 if (N0.getOpcode() == N1.getOpcode()) 3688 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3689 return Tmp; 3690 3691 // See if this is some rotate idiom. 3692 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3693 return SDValue(Rot, 0); 3694 3695 // Simplify the operands using demanded-bits information. 3696 if (!VT.isVector() && 3697 SimplifyDemandedBits(SDValue(N, 0))) 3698 return SDValue(N, 0); 3699 3700 return SDValue(); 3701 } 3702 3703 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3704 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3705 if (Op.getOpcode() == ISD::AND) { 3706 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3707 Mask = Op.getOperand(1); 3708 Op = Op.getOperand(0); 3709 } else { 3710 return false; 3711 } 3712 } 3713 3714 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3715 Shift = Op; 3716 return true; 3717 } 3718 3719 return false; 3720 } 3721 3722 // Return true if we can prove that, whenever Neg and Pos are both in the 3723 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3724 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3725 // 3726 // (or (shift1 X, Neg), (shift2 X, Pos)) 3727 // 3728 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3729 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3730 // to consider shift amounts with defined behavior. 3731 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3732 // If OpSize is a power of 2 then: 3733 // 3734 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3735 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3736 // 3737 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3738 // for the stronger condition: 3739 // 3740 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3741 // 3742 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3743 // we can just replace Neg with Neg' for the rest of the function. 3744 // 3745 // In other cases we check for the even stronger condition: 3746 // 3747 // Neg == OpSize - Pos [B] 3748 // 3749 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3750 // behavior if Pos == 0 (and consequently Neg == OpSize). 3751 // 3752 // We could actually use [A] whenever OpSize is a power of 2, but the 3753 // only extra cases that it would match are those uninteresting ones 3754 // where Neg and Pos are never in range at the same time. E.g. for 3755 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3756 // as well as (sub 32, Pos), but: 3757 // 3758 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3759 // 3760 // always invokes undefined behavior for 32-bit X. 3761 // 3762 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3763 unsigned MaskLoBits = 0; 3764 if (Neg.getOpcode() == ISD::AND && 3765 isPowerOf2_64(OpSize) && 3766 Neg.getOperand(1).getOpcode() == ISD::Constant && 3767 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3768 Neg = Neg.getOperand(0); 3769 MaskLoBits = Log2_64(OpSize); 3770 } 3771 3772 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3773 if (Neg.getOpcode() != ISD::SUB) 3774 return 0; 3775 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3776 if (!NegC) 3777 return 0; 3778 SDValue NegOp1 = Neg.getOperand(1); 3779 3780 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3781 // Pos'. The truncation is redundant for the purpose of the equality. 3782 if (MaskLoBits && 3783 Pos.getOpcode() == ISD::AND && 3784 Pos.getOperand(1).getOpcode() == ISD::Constant && 3785 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3786 Pos = Pos.getOperand(0); 3787 3788 // The condition we need is now: 3789 // 3790 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3791 // 3792 // If NegOp1 == Pos then we need: 3793 // 3794 // OpSize & Mask == NegC & Mask 3795 // 3796 // (because "x & Mask" is a truncation and distributes through subtraction). 3797 APInt Width; 3798 if (Pos == NegOp1) 3799 Width = NegC->getAPIntValue(); 3800 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3801 // Then the condition we want to prove becomes: 3802 // 3803 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3804 // 3805 // which, again because "x & Mask" is a truncation, becomes: 3806 // 3807 // NegC & Mask == (OpSize - PosC) & Mask 3808 // OpSize & Mask == (NegC + PosC) & Mask 3809 else if (Pos.getOpcode() == ISD::ADD && 3810 Pos.getOperand(0) == NegOp1 && 3811 Pos.getOperand(1).getOpcode() == ISD::Constant) 3812 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3813 NegC->getAPIntValue()); 3814 else 3815 return false; 3816 3817 // Now we just need to check that OpSize & Mask == Width & Mask. 3818 if (MaskLoBits) 3819 // Opsize & Mask is 0 since Mask is Opsize - 1. 3820 return Width.getLoBits(MaskLoBits) == 0; 3821 return Width == OpSize; 3822 } 3823 3824 // A subroutine of MatchRotate used once we have found an OR of two opposite 3825 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3826 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3827 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3828 // Neg with outer conversions stripped away. 3829 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3830 SDValue Neg, SDValue InnerPos, 3831 SDValue InnerNeg, unsigned PosOpcode, 3832 unsigned NegOpcode, SDLoc DL) { 3833 // fold (or (shl x, (*ext y)), 3834 // (srl x, (*ext (sub 32, y)))) -> 3835 // (rotl x, y) or (rotr x, (sub 32, y)) 3836 // 3837 // fold (or (shl x, (*ext (sub 32, y))), 3838 // (srl x, (*ext y))) -> 3839 // (rotr x, y) or (rotl x, (sub 32, y)) 3840 EVT VT = Shifted.getValueType(); 3841 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3842 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3843 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3844 HasPos ? Pos : Neg).getNode(); 3845 } 3846 3847 return nullptr; 3848 } 3849 3850 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3851 // idioms for rotate, and if the target supports rotation instructions, generate 3852 // a rot[lr]. 3853 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3854 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3855 EVT VT = LHS.getValueType(); 3856 if (!TLI.isTypeLegal(VT)) return nullptr; 3857 3858 // The target must have at least one rotate flavor. 3859 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3860 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3861 if (!HasROTL && !HasROTR) return nullptr; 3862 3863 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3864 SDValue LHSShift; // The shift. 3865 SDValue LHSMask; // AND value if any. 3866 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3867 return nullptr; // Not part of a rotate. 3868 3869 SDValue RHSShift; // The shift. 3870 SDValue RHSMask; // AND value if any. 3871 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3872 return nullptr; // Not part of a rotate. 3873 3874 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3875 return nullptr; // Not shifting the same value. 3876 3877 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3878 return nullptr; // Shifts must disagree. 3879 3880 // Canonicalize shl to left side in a shl/srl pair. 3881 if (RHSShift.getOpcode() == ISD::SHL) { 3882 std::swap(LHS, RHS); 3883 std::swap(LHSShift, RHSShift); 3884 std::swap(LHSMask , RHSMask ); 3885 } 3886 3887 unsigned OpSizeInBits = VT.getSizeInBits(); 3888 SDValue LHSShiftArg = LHSShift.getOperand(0); 3889 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3890 SDValue RHSShiftArg = RHSShift.getOperand(0); 3891 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3892 3893 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3894 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3895 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3896 RHSShiftAmt.getOpcode() == ISD::Constant) { 3897 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3898 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3899 if ((LShVal + RShVal) != OpSizeInBits) 3900 return nullptr; 3901 3902 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3903 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3904 3905 // If there is an AND of either shifted operand, apply it to the result. 3906 if (LHSMask.getNode() || RHSMask.getNode()) { 3907 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3908 3909 if (LHSMask.getNode()) { 3910 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3911 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3912 } 3913 if (RHSMask.getNode()) { 3914 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3915 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3916 } 3917 3918 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT)); 3919 } 3920 3921 return Rot.getNode(); 3922 } 3923 3924 // If there is a mask here, and we have a variable shift, we can't be sure 3925 // that we're masking out the right stuff. 3926 if (LHSMask.getNode() || RHSMask.getNode()) 3927 return nullptr; 3928 3929 // If the shift amount is sign/zext/any-extended just peel it off. 3930 SDValue LExtOp0 = LHSShiftAmt; 3931 SDValue RExtOp0 = RHSShiftAmt; 3932 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3933 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3934 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3935 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3936 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3937 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3938 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3939 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3940 LExtOp0 = LHSShiftAmt.getOperand(0); 3941 RExtOp0 = RHSShiftAmt.getOperand(0); 3942 } 3943 3944 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3945 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3946 if (TryL) 3947 return TryL; 3948 3949 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3950 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3951 if (TryR) 3952 return TryR; 3953 3954 return nullptr; 3955 } 3956 3957 SDValue DAGCombiner::visitXOR(SDNode *N) { 3958 SDValue N0 = N->getOperand(0); 3959 SDValue N1 = N->getOperand(1); 3960 EVT VT = N0.getValueType(); 3961 3962 // fold vector ops 3963 if (VT.isVector()) { 3964 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3965 return FoldedVOp; 3966 3967 // fold (xor x, 0) -> x, vector edition 3968 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3969 return N1; 3970 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3971 return N0; 3972 } 3973 3974 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3975 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3976 return DAG.getConstant(0, SDLoc(N), VT); 3977 // fold (xor x, undef) -> undef 3978 if (N0.getOpcode() == ISD::UNDEF) 3979 return N0; 3980 if (N1.getOpcode() == ISD::UNDEF) 3981 return N1; 3982 // fold (xor c1, c2) -> c1^c2 3983 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3984 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3985 if (N0C && N1C) 3986 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 3987 // canonicalize constant to RHS 3988 if (isConstantIntBuildVectorOrConstantInt(N0) && 3989 !isConstantIntBuildVectorOrConstantInt(N1)) 3990 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3991 // fold (xor x, 0) -> x 3992 if (isNullConstant(N1)) 3993 return N0; 3994 // reassociate xor 3995 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 3996 return RXOR; 3997 3998 // fold !(x cc y) -> (x !cc y) 3999 SDValue LHS, RHS, CC; 4000 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4001 bool isInt = LHS.getValueType().isInteger(); 4002 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4003 isInt); 4004 4005 if (!LegalOperations || 4006 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4007 switch (N0.getOpcode()) { 4008 default: 4009 llvm_unreachable("Unhandled SetCC Equivalent!"); 4010 case ISD::SETCC: 4011 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4012 case ISD::SELECT_CC: 4013 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4014 N0.getOperand(3), NotCC); 4015 } 4016 } 4017 } 4018 4019 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4020 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4021 N0.getNode()->hasOneUse() && 4022 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4023 SDValue V = N0.getOperand(0); 4024 SDLoc DL(N0); 4025 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4026 DAG.getConstant(1, DL, V.getValueType())); 4027 AddToWorklist(V.getNode()); 4028 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4029 } 4030 4031 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4032 if (isOneConstant(N1) && VT == MVT::i1 && 4033 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4034 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4035 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4036 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4037 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4038 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4039 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4040 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4041 } 4042 } 4043 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4044 if (isAllOnesConstant(N1) && 4045 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4046 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4047 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4048 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4049 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4050 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4051 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4052 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4053 } 4054 } 4055 // fold (xor (and x, y), y) -> (and (not x), y) 4056 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4057 N0->getOperand(1) == N1) { 4058 SDValue X = N0->getOperand(0); 4059 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4060 AddToWorklist(NotX.getNode()); 4061 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4062 } 4063 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4064 if (N1C && N0.getOpcode() == ISD::XOR) { 4065 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4066 SDLoc DL(N); 4067 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4068 DAG.getConstant(N1C->getAPIntValue() ^ 4069 N00C->getAPIntValue(), DL, VT)); 4070 } 4071 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4072 SDLoc DL(N); 4073 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4074 DAG.getConstant(N1C->getAPIntValue() ^ 4075 N01C->getAPIntValue(), DL, VT)); 4076 } 4077 } 4078 // fold (xor x, x) -> 0 4079 if (N0 == N1) 4080 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4081 4082 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4083 // Here is a concrete example of this equivalence: 4084 // i16 x == 14 4085 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4086 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4087 // 4088 // => 4089 // 4090 // i16 ~1 == 0b1111111111111110 4091 // i16 rol(~1, 14) == 0b1011111111111111 4092 // 4093 // Some additional tips to help conceptualize this transform: 4094 // - Try to see the operation as placing a single zero in a value of all ones. 4095 // - There exists no value for x which would allow the result to contain zero. 4096 // - Values of x larger than the bitwidth are undefined and do not require a 4097 // consistent result. 4098 // - Pushing the zero left requires shifting one bits in from the right. 4099 // A rotate left of ~1 is a nice way of achieving the desired result. 4100 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4101 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4102 SDLoc DL(N); 4103 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4104 N0.getOperand(1)); 4105 } 4106 4107 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4108 if (N0.getOpcode() == N1.getOpcode()) 4109 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4110 return Tmp; 4111 4112 // Simplify the expression using non-local knowledge. 4113 if (!VT.isVector() && 4114 SimplifyDemandedBits(SDValue(N, 0))) 4115 return SDValue(N, 0); 4116 4117 return SDValue(); 4118 } 4119 4120 /// Handle transforms common to the three shifts, when the shift amount is a 4121 /// constant. 4122 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4123 SDNode *LHS = N->getOperand(0).getNode(); 4124 if (!LHS->hasOneUse()) return SDValue(); 4125 4126 // We want to pull some binops through shifts, so that we have (and (shift)) 4127 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4128 // thing happens with address calculations, so it's important to canonicalize 4129 // it. 4130 bool HighBitSet = false; // Can we transform this if the high bit is set? 4131 4132 switch (LHS->getOpcode()) { 4133 default: return SDValue(); 4134 case ISD::OR: 4135 case ISD::XOR: 4136 HighBitSet = false; // We can only transform sra if the high bit is clear. 4137 break; 4138 case ISD::AND: 4139 HighBitSet = true; // We can only transform sra if the high bit is set. 4140 break; 4141 case ISD::ADD: 4142 if (N->getOpcode() != ISD::SHL) 4143 return SDValue(); // only shl(add) not sr[al](add). 4144 HighBitSet = false; // We can only transform sra if the high bit is clear. 4145 break; 4146 } 4147 4148 // We require the RHS of the binop to be a constant and not opaque as well. 4149 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4150 if (!BinOpCst) return SDValue(); 4151 4152 // FIXME: disable this unless the input to the binop is a shift by a constant. 4153 // If it is not a shift, it pessimizes some common cases like: 4154 // 4155 // void foo(int *X, int i) { X[i & 1235] = 1; } 4156 // int bar(int *X, int i) { return X[i & 255]; } 4157 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4158 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4159 BinOpLHSVal->getOpcode() != ISD::SRA && 4160 BinOpLHSVal->getOpcode() != ISD::SRL) || 4161 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4162 return SDValue(); 4163 4164 EVT VT = N->getValueType(0); 4165 4166 // If this is a signed shift right, and the high bit is modified by the 4167 // logical operation, do not perform the transformation. The highBitSet 4168 // boolean indicates the value of the high bit of the constant which would 4169 // cause it to be modified for this operation. 4170 if (N->getOpcode() == ISD::SRA) { 4171 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4172 if (BinOpRHSSignSet != HighBitSet) 4173 return SDValue(); 4174 } 4175 4176 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4177 return SDValue(); 4178 4179 // Fold the constants, shifting the binop RHS by the shift amount. 4180 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4181 N->getValueType(0), 4182 LHS->getOperand(1), N->getOperand(1)); 4183 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4184 4185 // Create the new shift. 4186 SDValue NewShift = DAG.getNode(N->getOpcode(), 4187 SDLoc(LHS->getOperand(0)), 4188 VT, LHS->getOperand(0), N->getOperand(1)); 4189 4190 // Create the new binop. 4191 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4192 } 4193 4194 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4195 assert(N->getOpcode() == ISD::TRUNCATE); 4196 assert(N->getOperand(0).getOpcode() == ISD::AND); 4197 4198 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4199 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4200 SDValue N01 = N->getOperand(0).getOperand(1); 4201 4202 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4203 if (!N01C->isOpaque()) { 4204 EVT TruncVT = N->getValueType(0); 4205 SDValue N00 = N->getOperand(0).getOperand(0); 4206 APInt TruncC = N01C->getAPIntValue(); 4207 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4208 SDLoc DL(N); 4209 4210 return DAG.getNode(ISD::AND, DL, TruncVT, 4211 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4212 DAG.getConstant(TruncC, DL, TruncVT)); 4213 } 4214 } 4215 } 4216 4217 return SDValue(); 4218 } 4219 4220 SDValue DAGCombiner::visitRotate(SDNode *N) { 4221 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4222 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4223 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4224 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4225 if (NewOp1.getNode()) 4226 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4227 N->getOperand(0), NewOp1); 4228 } 4229 return SDValue(); 4230 } 4231 4232 SDValue DAGCombiner::visitSHL(SDNode *N) { 4233 SDValue N0 = N->getOperand(0); 4234 SDValue N1 = N->getOperand(1); 4235 EVT VT = N0.getValueType(); 4236 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4237 4238 // fold vector ops 4239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4240 if (VT.isVector()) { 4241 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4242 return FoldedVOp; 4243 4244 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4245 // If setcc produces all-one true value then: 4246 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4247 if (N1CV && N1CV->isConstant()) { 4248 if (N0.getOpcode() == ISD::AND) { 4249 SDValue N00 = N0->getOperand(0); 4250 SDValue N01 = N0->getOperand(1); 4251 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4252 4253 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4254 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4255 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4256 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4257 N01CV, N1CV)) 4258 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4259 } 4260 } else { 4261 N1C = isConstOrConstSplat(N1); 4262 } 4263 } 4264 } 4265 4266 // fold (shl c1, c2) -> c1<<c2 4267 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4268 if (N0C && N1C && !N1C->isOpaque()) 4269 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4270 // fold (shl 0, x) -> 0 4271 if (isNullConstant(N0)) 4272 return N0; 4273 // fold (shl x, c >= size(x)) -> undef 4274 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4275 return DAG.getUNDEF(VT); 4276 // fold (shl x, 0) -> x 4277 if (N1C && N1C->isNullValue()) 4278 return N0; 4279 // fold (shl undef, x) -> 0 4280 if (N0.getOpcode() == ISD::UNDEF) 4281 return DAG.getConstant(0, SDLoc(N), VT); 4282 // if (shl x, c) is known to be zero, return 0 4283 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4284 APInt::getAllOnesValue(OpSizeInBits))) 4285 return DAG.getConstant(0, SDLoc(N), VT); 4286 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4287 if (N1.getOpcode() == ISD::TRUNCATE && 4288 N1.getOperand(0).getOpcode() == ISD::AND) { 4289 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4290 if (NewOp1.getNode()) 4291 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4292 } 4293 4294 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4295 return SDValue(N, 0); 4296 4297 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4298 if (N1C && N0.getOpcode() == ISD::SHL) { 4299 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4300 uint64_t c1 = N0C1->getZExtValue(); 4301 uint64_t c2 = N1C->getZExtValue(); 4302 SDLoc DL(N); 4303 if (c1 + c2 >= OpSizeInBits) 4304 return DAG.getConstant(0, DL, VT); 4305 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4306 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4307 } 4308 } 4309 4310 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4311 // For this to be valid, the second form must not preserve any of the bits 4312 // that are shifted out by the inner shift in the first form. This means 4313 // the outer shift size must be >= the number of bits added by the ext. 4314 // As a corollary, we don't care what kind of ext it is. 4315 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4316 N0.getOpcode() == ISD::ANY_EXTEND || 4317 N0.getOpcode() == ISD::SIGN_EXTEND) && 4318 N0.getOperand(0).getOpcode() == ISD::SHL) { 4319 SDValue N0Op0 = N0.getOperand(0); 4320 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4321 uint64_t c1 = N0Op0C1->getZExtValue(); 4322 uint64_t c2 = N1C->getZExtValue(); 4323 EVT InnerShiftVT = N0Op0.getValueType(); 4324 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4325 if (c2 >= OpSizeInBits - InnerShiftSize) { 4326 SDLoc DL(N0); 4327 if (c1 + c2 >= OpSizeInBits) 4328 return DAG.getConstant(0, DL, VT); 4329 return DAG.getNode(ISD::SHL, DL, VT, 4330 DAG.getNode(N0.getOpcode(), DL, VT, 4331 N0Op0->getOperand(0)), 4332 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4333 } 4334 } 4335 } 4336 4337 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4338 // Only fold this if the inner zext has no other uses to avoid increasing 4339 // the total number of instructions. 4340 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4341 N0.getOperand(0).getOpcode() == ISD::SRL) { 4342 SDValue N0Op0 = N0.getOperand(0); 4343 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4344 uint64_t c1 = N0Op0C1->getZExtValue(); 4345 if (c1 < VT.getScalarSizeInBits()) { 4346 uint64_t c2 = N1C->getZExtValue(); 4347 if (c1 == c2) { 4348 SDValue NewOp0 = N0.getOperand(0); 4349 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4350 SDLoc DL(N); 4351 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4352 NewOp0, 4353 DAG.getConstant(c2, DL, CountVT)); 4354 AddToWorklist(NewSHL.getNode()); 4355 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4356 } 4357 } 4358 } 4359 } 4360 4361 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4362 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4363 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4364 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4365 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4366 uint64_t C1 = N0C1->getZExtValue(); 4367 uint64_t C2 = N1C->getZExtValue(); 4368 SDLoc DL(N); 4369 if (C1 <= C2) 4370 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4371 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4372 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4373 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4374 } 4375 } 4376 4377 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4378 // (and (srl x, (sub c1, c2), MASK) 4379 // Only fold this if the inner shift has no other uses -- if it does, folding 4380 // this will increase the total number of instructions. 4381 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4382 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4383 uint64_t c1 = N0C1->getZExtValue(); 4384 if (c1 < OpSizeInBits) { 4385 uint64_t c2 = N1C->getZExtValue(); 4386 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4387 SDValue Shift; 4388 if (c2 > c1) { 4389 Mask = Mask.shl(c2 - c1); 4390 SDLoc DL(N); 4391 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4392 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4393 } else { 4394 Mask = Mask.lshr(c1 - c2); 4395 SDLoc DL(N); 4396 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4397 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4398 } 4399 SDLoc DL(N0); 4400 return DAG.getNode(ISD::AND, DL, VT, Shift, 4401 DAG.getConstant(Mask, DL, VT)); 4402 } 4403 } 4404 } 4405 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4406 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4407 unsigned BitSize = VT.getScalarSizeInBits(); 4408 SDLoc DL(N); 4409 SDValue HiBitsMask = 4410 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4411 BitSize - N1C->getZExtValue()), 4412 DL, VT); 4413 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4414 HiBitsMask); 4415 } 4416 4417 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4418 // Variant of version done on multiply, except mul by a power of 2 is turned 4419 // into a shift. 4420 APInt Val; 4421 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4422 (isa<ConstantSDNode>(N0.getOperand(1)) || 4423 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4424 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4425 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4426 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4427 } 4428 4429 if (N1C && !N1C->isOpaque()) 4430 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4431 return NewSHL; 4432 4433 return SDValue(); 4434 } 4435 4436 SDValue DAGCombiner::visitSRA(SDNode *N) { 4437 SDValue N0 = N->getOperand(0); 4438 SDValue N1 = N->getOperand(1); 4439 EVT VT = N0.getValueType(); 4440 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4441 4442 // fold vector ops 4443 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4444 if (VT.isVector()) { 4445 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4446 return FoldedVOp; 4447 4448 N1C = isConstOrConstSplat(N1); 4449 } 4450 4451 // fold (sra c1, c2) -> (sra c1, c2) 4452 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4453 if (N0C && N1C && !N1C->isOpaque()) 4454 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4455 // fold (sra 0, x) -> 0 4456 if (isNullConstant(N0)) 4457 return N0; 4458 // fold (sra -1, x) -> -1 4459 if (isAllOnesConstant(N0)) 4460 return N0; 4461 // fold (sra x, (setge c, size(x))) -> undef 4462 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4463 return DAG.getUNDEF(VT); 4464 // fold (sra x, 0) -> x 4465 if (N1C && N1C->isNullValue()) 4466 return N0; 4467 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4468 // sext_inreg. 4469 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4470 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4471 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4472 if (VT.isVector()) 4473 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4474 ExtVT, VT.getVectorNumElements()); 4475 if ((!LegalOperations || 4476 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4477 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4478 N0.getOperand(0), DAG.getValueType(ExtVT)); 4479 } 4480 4481 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4482 if (N1C && N0.getOpcode() == ISD::SRA) { 4483 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4484 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4485 if (Sum >= OpSizeInBits) 4486 Sum = OpSizeInBits - 1; 4487 SDLoc DL(N); 4488 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4489 DAG.getConstant(Sum, DL, N1.getValueType())); 4490 } 4491 } 4492 4493 // fold (sra (shl X, m), (sub result_size, n)) 4494 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4495 // result_size - n != m. 4496 // If truncate is free for the target sext(shl) is likely to result in better 4497 // code. 4498 if (N0.getOpcode() == ISD::SHL && N1C) { 4499 // Get the two constanst of the shifts, CN0 = m, CN = n. 4500 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4501 if (N01C) { 4502 LLVMContext &Ctx = *DAG.getContext(); 4503 // Determine what the truncate's result bitsize and type would be. 4504 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4505 4506 if (VT.isVector()) 4507 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4508 4509 // Determine the residual right-shift amount. 4510 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4511 4512 // If the shift is not a no-op (in which case this should be just a sign 4513 // extend already), the truncated to type is legal, sign_extend is legal 4514 // on that type, and the truncate to that type is both legal and free, 4515 // perform the transform. 4516 if ((ShiftAmt > 0) && 4517 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4518 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4519 TLI.isTruncateFree(VT, TruncVT)) { 4520 4521 SDLoc DL(N); 4522 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4523 getShiftAmountTy(N0.getOperand(0).getValueType())); 4524 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4525 N0.getOperand(0), Amt); 4526 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4527 Shift); 4528 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4529 N->getValueType(0), Trunc); 4530 } 4531 } 4532 } 4533 4534 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4535 if (N1.getOpcode() == ISD::TRUNCATE && 4536 N1.getOperand(0).getOpcode() == ISD::AND) { 4537 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4538 if (NewOp1.getNode()) 4539 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4540 } 4541 4542 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4543 // if c1 is equal to the number of bits the trunc removes 4544 if (N0.getOpcode() == ISD::TRUNCATE && 4545 (N0.getOperand(0).getOpcode() == ISD::SRL || 4546 N0.getOperand(0).getOpcode() == ISD::SRA) && 4547 N0.getOperand(0).hasOneUse() && 4548 N0.getOperand(0).getOperand(1).hasOneUse() && 4549 N1C) { 4550 SDValue N0Op0 = N0.getOperand(0); 4551 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4552 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4553 EVT LargeVT = N0Op0.getValueType(); 4554 4555 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4556 SDLoc DL(N); 4557 SDValue Amt = 4558 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4559 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4560 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4561 N0Op0.getOperand(0), Amt); 4562 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4563 } 4564 } 4565 } 4566 4567 // Simplify, based on bits shifted out of the LHS. 4568 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4569 return SDValue(N, 0); 4570 4571 4572 // If the sign bit is known to be zero, switch this to a SRL. 4573 if (DAG.SignBitIsZero(N0)) 4574 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4575 4576 if (N1C && !N1C->isOpaque()) 4577 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4578 return NewSRA; 4579 4580 return SDValue(); 4581 } 4582 4583 SDValue DAGCombiner::visitSRL(SDNode *N) { 4584 SDValue N0 = N->getOperand(0); 4585 SDValue N1 = N->getOperand(1); 4586 EVT VT = N0.getValueType(); 4587 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4588 4589 // fold vector ops 4590 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4591 if (VT.isVector()) { 4592 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4593 return FoldedVOp; 4594 4595 N1C = isConstOrConstSplat(N1); 4596 } 4597 4598 // fold (srl c1, c2) -> c1 >>u c2 4599 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4600 if (N0C && N1C && !N1C->isOpaque()) 4601 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4602 // fold (srl 0, x) -> 0 4603 if (isNullConstant(N0)) 4604 return N0; 4605 // fold (srl x, c >= size(x)) -> undef 4606 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4607 return DAG.getUNDEF(VT); 4608 // fold (srl x, 0) -> x 4609 if (N1C && N1C->isNullValue()) 4610 return N0; 4611 // if (srl x, c) is known to be zero, return 0 4612 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4613 APInt::getAllOnesValue(OpSizeInBits))) 4614 return DAG.getConstant(0, SDLoc(N), VT); 4615 4616 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4617 if (N1C && N0.getOpcode() == ISD::SRL) { 4618 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4619 uint64_t c1 = N01C->getZExtValue(); 4620 uint64_t c2 = N1C->getZExtValue(); 4621 SDLoc DL(N); 4622 if (c1 + c2 >= OpSizeInBits) 4623 return DAG.getConstant(0, DL, VT); 4624 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4625 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4626 } 4627 } 4628 4629 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4630 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4631 N0.getOperand(0).getOpcode() == ISD::SRL && 4632 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4633 uint64_t c1 = 4634 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4635 uint64_t c2 = N1C->getZExtValue(); 4636 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4637 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4638 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4639 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4640 if (c1 + OpSizeInBits == InnerShiftSize) { 4641 SDLoc DL(N0); 4642 if (c1 + c2 >= InnerShiftSize) 4643 return DAG.getConstant(0, DL, VT); 4644 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4645 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4646 N0.getOperand(0)->getOperand(0), 4647 DAG.getConstant(c1 + c2, DL, 4648 ShiftCountVT))); 4649 } 4650 } 4651 4652 // fold (srl (shl x, c), c) -> (and x, cst2) 4653 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4654 unsigned BitSize = N0.getScalarValueSizeInBits(); 4655 if (BitSize <= 64) { 4656 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4657 SDLoc DL(N); 4658 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4659 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4660 } 4661 } 4662 4663 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4664 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4665 // Shifting in all undef bits? 4666 EVT SmallVT = N0.getOperand(0).getValueType(); 4667 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4668 if (N1C->getZExtValue() >= BitSize) 4669 return DAG.getUNDEF(VT); 4670 4671 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4672 uint64_t ShiftAmt = N1C->getZExtValue(); 4673 SDLoc DL0(N0); 4674 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4675 N0.getOperand(0), 4676 DAG.getConstant(ShiftAmt, DL0, 4677 getShiftAmountTy(SmallVT))); 4678 AddToWorklist(SmallShift.getNode()); 4679 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4680 SDLoc DL(N); 4681 return DAG.getNode(ISD::AND, DL, VT, 4682 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4683 DAG.getConstant(Mask, DL, VT)); 4684 } 4685 } 4686 4687 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4688 // bit, which is unmodified by sra. 4689 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4690 if (N0.getOpcode() == ISD::SRA) 4691 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4692 } 4693 4694 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4695 if (N1C && N0.getOpcode() == ISD::CTLZ && 4696 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4697 APInt KnownZero, KnownOne; 4698 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4699 4700 // If any of the input bits are KnownOne, then the input couldn't be all 4701 // zeros, thus the result of the srl will always be zero. 4702 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4703 4704 // If all of the bits input the to ctlz node are known to be zero, then 4705 // the result of the ctlz is "32" and the result of the shift is one. 4706 APInt UnknownBits = ~KnownZero; 4707 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4708 4709 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4710 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4711 // Okay, we know that only that the single bit specified by UnknownBits 4712 // could be set on input to the CTLZ node. If this bit is set, the SRL 4713 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4714 // to an SRL/XOR pair, which is likely to simplify more. 4715 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4716 SDValue Op = N0.getOperand(0); 4717 4718 if (ShAmt) { 4719 SDLoc DL(N0); 4720 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4721 DAG.getConstant(ShAmt, DL, 4722 getShiftAmountTy(Op.getValueType()))); 4723 AddToWorklist(Op.getNode()); 4724 } 4725 4726 SDLoc DL(N); 4727 return DAG.getNode(ISD::XOR, DL, VT, 4728 Op, DAG.getConstant(1, DL, VT)); 4729 } 4730 } 4731 4732 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4733 if (N1.getOpcode() == ISD::TRUNCATE && 4734 N1.getOperand(0).getOpcode() == ISD::AND) { 4735 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4736 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4737 } 4738 4739 // fold operands of srl based on knowledge that the low bits are not 4740 // demanded. 4741 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4742 return SDValue(N, 0); 4743 4744 if (N1C && !N1C->isOpaque()) 4745 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4746 return NewSRL; 4747 4748 // Attempt to convert a srl of a load into a narrower zero-extending load. 4749 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4750 return NarrowLoad; 4751 4752 // Here is a common situation. We want to optimize: 4753 // 4754 // %a = ... 4755 // %b = and i32 %a, 2 4756 // %c = srl i32 %b, 1 4757 // brcond i32 %c ... 4758 // 4759 // into 4760 // 4761 // %a = ... 4762 // %b = and %a, 2 4763 // %c = setcc eq %b, 0 4764 // brcond %c ... 4765 // 4766 // However when after the source operand of SRL is optimized into AND, the SRL 4767 // itself may not be optimized further. Look for it and add the BRCOND into 4768 // the worklist. 4769 if (N->hasOneUse()) { 4770 SDNode *Use = *N->use_begin(); 4771 if (Use->getOpcode() == ISD::BRCOND) 4772 AddToWorklist(Use); 4773 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4774 // Also look pass the truncate. 4775 Use = *Use->use_begin(); 4776 if (Use->getOpcode() == ISD::BRCOND) 4777 AddToWorklist(Use); 4778 } 4779 } 4780 4781 return SDValue(); 4782 } 4783 4784 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4785 SDValue N0 = N->getOperand(0); 4786 EVT VT = N->getValueType(0); 4787 4788 // fold (bswap c1) -> c2 4789 if (isConstantIntBuildVectorOrConstantInt(N0)) 4790 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4791 // fold (bswap (bswap x)) -> x 4792 if (N0.getOpcode() == ISD::BSWAP) 4793 return N0->getOperand(0); 4794 return SDValue(); 4795 } 4796 4797 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4798 SDValue N0 = N->getOperand(0); 4799 EVT VT = N->getValueType(0); 4800 4801 // fold (ctlz c1) -> c2 4802 if (isConstantIntBuildVectorOrConstantInt(N0)) 4803 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4804 return SDValue(); 4805 } 4806 4807 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4808 SDValue N0 = N->getOperand(0); 4809 EVT VT = N->getValueType(0); 4810 4811 // fold (ctlz_zero_undef c1) -> c2 4812 if (isConstantIntBuildVectorOrConstantInt(N0)) 4813 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4814 return SDValue(); 4815 } 4816 4817 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4818 SDValue N0 = N->getOperand(0); 4819 EVT VT = N->getValueType(0); 4820 4821 // fold (cttz c1) -> c2 4822 if (isConstantIntBuildVectorOrConstantInt(N0)) 4823 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4824 return SDValue(); 4825 } 4826 4827 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4828 SDValue N0 = N->getOperand(0); 4829 EVT VT = N->getValueType(0); 4830 4831 // fold (cttz_zero_undef c1) -> c2 4832 if (isConstantIntBuildVectorOrConstantInt(N0)) 4833 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4834 return SDValue(); 4835 } 4836 4837 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4838 SDValue N0 = N->getOperand(0); 4839 EVT VT = N->getValueType(0); 4840 4841 // fold (ctpop c1) -> c2 4842 if (isConstantIntBuildVectorOrConstantInt(N0)) 4843 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4844 return SDValue(); 4845 } 4846 4847 4848 /// \brief Generate Min/Max node 4849 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4850 SDValue True, SDValue False, 4851 ISD::CondCode CC, const TargetLowering &TLI, 4852 SelectionDAG &DAG) { 4853 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4854 return SDValue(); 4855 4856 switch (CC) { 4857 case ISD::SETOLT: 4858 case ISD::SETOLE: 4859 case ISD::SETLT: 4860 case ISD::SETLE: 4861 case ISD::SETULT: 4862 case ISD::SETULE: { 4863 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4864 if (TLI.isOperationLegal(Opcode, VT)) 4865 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4866 return SDValue(); 4867 } 4868 case ISD::SETOGT: 4869 case ISD::SETOGE: 4870 case ISD::SETGT: 4871 case ISD::SETGE: 4872 case ISD::SETUGT: 4873 case ISD::SETUGE: { 4874 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4875 if (TLI.isOperationLegal(Opcode, VT)) 4876 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4877 return SDValue(); 4878 } 4879 default: 4880 return SDValue(); 4881 } 4882 } 4883 4884 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4885 SDValue N0 = N->getOperand(0); 4886 SDValue N1 = N->getOperand(1); 4887 SDValue N2 = N->getOperand(2); 4888 EVT VT = N->getValueType(0); 4889 EVT VT0 = N0.getValueType(); 4890 4891 // fold (select C, X, X) -> X 4892 if (N1 == N2) 4893 return N1; 4894 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 4895 // fold (select true, X, Y) -> X 4896 // fold (select false, X, Y) -> Y 4897 return !N0C->isNullValue() ? N1 : N2; 4898 } 4899 // fold (select C, 1, X) -> (or C, X) 4900 if (VT == MVT::i1 && isOneConstant(N1)) 4901 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4902 // fold (select C, 0, 1) -> (xor C, 1) 4903 // We can't do this reliably if integer based booleans have different contents 4904 // to floating point based booleans. This is because we can't tell whether we 4905 // have an integer-based boolean or a floating-point-based boolean unless we 4906 // can find the SETCC that produced it and inspect its operands. This is 4907 // fairly easy if C is the SETCC node, but it can potentially be 4908 // undiscoverable (or not reasonably discoverable). For example, it could be 4909 // in another basic block or it could require searching a complicated 4910 // expression. 4911 if (VT.isInteger() && 4912 (VT0 == MVT::i1 || (VT0.isInteger() && 4913 TLI.getBooleanContents(false, false) == 4914 TLI.getBooleanContents(false, true) && 4915 TLI.getBooleanContents(false, false) == 4916 TargetLowering::ZeroOrOneBooleanContent)) && 4917 isNullConstant(N1) && isOneConstant(N2)) { 4918 SDValue XORNode; 4919 if (VT == VT0) { 4920 SDLoc DL(N); 4921 return DAG.getNode(ISD::XOR, DL, VT0, 4922 N0, DAG.getConstant(1, DL, VT0)); 4923 } 4924 SDLoc DL0(N0); 4925 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 4926 N0, DAG.getConstant(1, DL0, VT0)); 4927 AddToWorklist(XORNode.getNode()); 4928 if (VT.bitsGT(VT0)) 4929 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4930 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4931 } 4932 // fold (select C, 0, X) -> (and (not C), X) 4933 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 4934 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4935 AddToWorklist(NOTNode.getNode()); 4936 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4937 } 4938 // fold (select C, X, 1) -> (or (not C), X) 4939 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 4940 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4941 AddToWorklist(NOTNode.getNode()); 4942 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4943 } 4944 // fold (select C, X, 0) -> (and C, X) 4945 if (VT == MVT::i1 && isNullConstant(N2)) 4946 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4947 // fold (select X, X, Y) -> (or X, Y) 4948 // fold (select X, 1, Y) -> (or X, Y) 4949 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 4950 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4951 // fold (select X, Y, X) -> (and X, Y) 4952 // fold (select X, Y, 0) -> (and X, Y) 4953 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 4954 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4955 4956 // If we can fold this based on the true/false value, do so. 4957 if (SimplifySelectOps(N, N1, N2)) 4958 return SDValue(N, 0); // Don't revisit N. 4959 4960 if (VT0 == MVT::i1) { 4961 // The code in this block deals with the following 2 equivalences: 4962 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 4963 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 4964 // The target can specify its prefered form with the 4965 // shouldNormalizeToSelectSequence() callback. However we always transform 4966 // to the right anyway if we find the inner select exists in the DAG anyway 4967 // and we always transform to the left side if we know that we can further 4968 // optimize the combination of the conditions. 4969 bool normalizeToSequence 4970 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 4971 // select (and Cond0, Cond1), X, Y 4972 // -> select Cond0, (select Cond1, X, Y), Y 4973 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 4974 SDValue Cond0 = N0->getOperand(0); 4975 SDValue Cond1 = N0->getOperand(1); 4976 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4977 N1.getValueType(), Cond1, N1, N2); 4978 if (normalizeToSequence || !InnerSelect.use_empty()) 4979 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 4980 InnerSelect, N2); 4981 } 4982 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 4983 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 4984 SDValue Cond0 = N0->getOperand(0); 4985 SDValue Cond1 = N0->getOperand(1); 4986 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4987 N1.getValueType(), Cond1, N1, N2); 4988 if (normalizeToSequence || !InnerSelect.use_empty()) 4989 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 4990 InnerSelect); 4991 } 4992 4993 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 4994 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 4995 SDValue N1_0 = N1->getOperand(0); 4996 SDValue N1_1 = N1->getOperand(1); 4997 SDValue N1_2 = N1->getOperand(2); 4998 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 4999 // Create the actual and node if we can generate good code for it. 5000 if (!normalizeToSequence) { 5001 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5002 N0, N1_0); 5003 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5004 N1_1, N2); 5005 } 5006 // Otherwise see if we can optimize the "and" to a better pattern. 5007 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5008 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5009 N1_1, N2); 5010 } 5011 } 5012 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5013 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5014 SDValue N2_0 = N2->getOperand(0); 5015 SDValue N2_1 = N2->getOperand(1); 5016 SDValue N2_2 = N2->getOperand(2); 5017 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5018 // Create the actual or node if we can generate good code for it. 5019 if (!normalizeToSequence) { 5020 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5021 N0, N2_0); 5022 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5023 N1, N2_2); 5024 } 5025 // Otherwise see if we can optimize to a better pattern. 5026 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5027 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5028 N1, N2_2); 5029 } 5030 } 5031 } 5032 5033 // fold selects based on a setcc into other things, such as min/max/abs 5034 if (N0.getOpcode() == ISD::SETCC) { 5035 // select x, y (fcmp lt x, y) -> fminnum x, y 5036 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5037 // 5038 // This is OK if we don't care about what happens if either operand is a 5039 // NaN. 5040 // 5041 5042 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5043 // no signed zeros as well as no nans. 5044 const TargetOptions &Options = DAG.getTarget().Options; 5045 if (Options.UnsafeFPMath && 5046 VT.isFloatingPoint() && N0.hasOneUse() && 5047 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5048 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5049 5050 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5051 N0.getOperand(1), N1, N2, CC, 5052 TLI, DAG)) 5053 return FMinMax; 5054 } 5055 5056 if ((!LegalOperations && 5057 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5058 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5059 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5060 N0.getOperand(0), N0.getOperand(1), 5061 N1, N2, N0.getOperand(2)); 5062 return SimplifySelect(SDLoc(N), N0, N1, N2); 5063 } 5064 5065 return SDValue(); 5066 } 5067 5068 static 5069 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5070 SDLoc DL(N); 5071 EVT LoVT, HiVT; 5072 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5073 5074 // Split the inputs. 5075 SDValue Lo, Hi, LL, LH, RL, RH; 5076 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5077 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5078 5079 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5080 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5081 5082 return std::make_pair(Lo, Hi); 5083 } 5084 5085 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5086 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5087 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5088 SDLoc dl(N); 5089 SDValue Cond = N->getOperand(0); 5090 SDValue LHS = N->getOperand(1); 5091 SDValue RHS = N->getOperand(2); 5092 EVT VT = N->getValueType(0); 5093 int NumElems = VT.getVectorNumElements(); 5094 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5095 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5096 Cond.getOpcode() == ISD::BUILD_VECTOR); 5097 5098 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5099 // binary ones here. 5100 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5101 return SDValue(); 5102 5103 // We're sure we have an even number of elements due to the 5104 // concat_vectors we have as arguments to vselect. 5105 // Skip BV elements until we find one that's not an UNDEF 5106 // After we find an UNDEF element, keep looping until we get to half the 5107 // length of the BV and see if all the non-undef nodes are the same. 5108 ConstantSDNode *BottomHalf = nullptr; 5109 for (int i = 0; i < NumElems / 2; ++i) { 5110 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5111 continue; 5112 5113 if (BottomHalf == nullptr) 5114 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5115 else if (Cond->getOperand(i).getNode() != BottomHalf) 5116 return SDValue(); 5117 } 5118 5119 // Do the same for the second half of the BuildVector 5120 ConstantSDNode *TopHalf = nullptr; 5121 for (int i = NumElems / 2; i < NumElems; ++i) { 5122 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5123 continue; 5124 5125 if (TopHalf == nullptr) 5126 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5127 else if (Cond->getOperand(i).getNode() != TopHalf) 5128 return SDValue(); 5129 } 5130 5131 assert(TopHalf && BottomHalf && 5132 "One half of the selector was all UNDEFs and the other was all the " 5133 "same value. This should have been addressed before this function."); 5134 return DAG.getNode( 5135 ISD::CONCAT_VECTORS, dl, VT, 5136 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5137 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5138 } 5139 5140 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5141 5142 if (Level >= AfterLegalizeTypes) 5143 return SDValue(); 5144 5145 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5146 SDValue Mask = MSC->getMask(); 5147 SDValue Data = MSC->getValue(); 5148 SDLoc DL(N); 5149 5150 // If the MSCATTER data type requires splitting and the mask is provided by a 5151 // SETCC, then split both nodes and its operands before legalization. This 5152 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5153 // and enables future optimizations (e.g. min/max pattern matching on X86). 5154 if (Mask.getOpcode() != ISD::SETCC) 5155 return SDValue(); 5156 5157 // Check if any splitting is required. 5158 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5159 TargetLowering::TypeSplitVector) 5160 return SDValue(); 5161 SDValue MaskLo, MaskHi, Lo, Hi; 5162 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5163 5164 EVT LoVT, HiVT; 5165 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5166 5167 SDValue Chain = MSC->getChain(); 5168 5169 EVT MemoryVT = MSC->getMemoryVT(); 5170 unsigned Alignment = MSC->getOriginalAlignment(); 5171 5172 EVT LoMemVT, HiMemVT; 5173 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5174 5175 SDValue DataLo, DataHi; 5176 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5177 5178 SDValue BasePtr = MSC->getBasePtr(); 5179 SDValue IndexLo, IndexHi; 5180 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5181 5182 MachineMemOperand *MMO = DAG.getMachineFunction(). 5183 getMachineMemOperand(MSC->getPointerInfo(), 5184 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5185 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5186 5187 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5188 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5189 DL, OpsLo, MMO); 5190 5191 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5192 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5193 DL, OpsHi, MMO); 5194 5195 AddToWorklist(Lo.getNode()); 5196 AddToWorklist(Hi.getNode()); 5197 5198 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5199 } 5200 5201 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5202 5203 if (Level >= AfterLegalizeTypes) 5204 return SDValue(); 5205 5206 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5207 SDValue Mask = MST->getMask(); 5208 SDValue Data = MST->getValue(); 5209 SDLoc DL(N); 5210 5211 // If the MSTORE data type requires splitting and the mask is provided by a 5212 // SETCC, then split both nodes and its operands before legalization. This 5213 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5214 // and enables future optimizations (e.g. min/max pattern matching on X86). 5215 if (Mask.getOpcode() == ISD::SETCC) { 5216 5217 // Check if any splitting is required. 5218 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5219 TargetLowering::TypeSplitVector) 5220 return SDValue(); 5221 5222 SDValue MaskLo, MaskHi, Lo, Hi; 5223 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5224 5225 EVT LoVT, HiVT; 5226 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5227 5228 SDValue Chain = MST->getChain(); 5229 SDValue Ptr = MST->getBasePtr(); 5230 5231 EVT MemoryVT = MST->getMemoryVT(); 5232 unsigned Alignment = MST->getOriginalAlignment(); 5233 5234 // if Alignment is equal to the vector size, 5235 // take the half of it for the second part 5236 unsigned SecondHalfAlignment = 5237 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5238 Alignment/2 : Alignment; 5239 5240 EVT LoMemVT, HiMemVT; 5241 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5242 5243 SDValue DataLo, DataHi; 5244 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5245 5246 MachineMemOperand *MMO = DAG.getMachineFunction(). 5247 getMachineMemOperand(MST->getPointerInfo(), 5248 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5249 Alignment, MST->getAAInfo(), MST->getRanges()); 5250 5251 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5252 MST->isTruncatingStore()); 5253 5254 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5255 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5256 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5257 5258 MMO = DAG.getMachineFunction(). 5259 getMachineMemOperand(MST->getPointerInfo(), 5260 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5261 SecondHalfAlignment, MST->getAAInfo(), 5262 MST->getRanges()); 5263 5264 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5265 MST->isTruncatingStore()); 5266 5267 AddToWorklist(Lo.getNode()); 5268 AddToWorklist(Hi.getNode()); 5269 5270 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5271 } 5272 return SDValue(); 5273 } 5274 5275 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5276 5277 if (Level >= AfterLegalizeTypes) 5278 return SDValue(); 5279 5280 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5281 SDValue Mask = MGT->getMask(); 5282 SDLoc DL(N); 5283 5284 // If the MGATHER result requires splitting and the mask is provided by a 5285 // SETCC, then split both nodes and its operands before legalization. This 5286 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5287 // and enables future optimizations (e.g. min/max pattern matching on X86). 5288 5289 if (Mask.getOpcode() != ISD::SETCC) 5290 return SDValue(); 5291 5292 EVT VT = N->getValueType(0); 5293 5294 // Check if any splitting is required. 5295 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5296 TargetLowering::TypeSplitVector) 5297 return SDValue(); 5298 5299 SDValue MaskLo, MaskHi, Lo, Hi; 5300 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5301 5302 SDValue Src0 = MGT->getValue(); 5303 SDValue Src0Lo, Src0Hi; 5304 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5305 5306 EVT LoVT, HiVT; 5307 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5308 5309 SDValue Chain = MGT->getChain(); 5310 EVT MemoryVT = MGT->getMemoryVT(); 5311 unsigned Alignment = MGT->getOriginalAlignment(); 5312 5313 EVT LoMemVT, HiMemVT; 5314 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5315 5316 SDValue BasePtr = MGT->getBasePtr(); 5317 SDValue Index = MGT->getIndex(); 5318 SDValue IndexLo, IndexHi; 5319 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5320 5321 MachineMemOperand *MMO = DAG.getMachineFunction(). 5322 getMachineMemOperand(MGT->getPointerInfo(), 5323 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5324 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5325 5326 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5327 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5328 MMO); 5329 5330 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5331 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5332 MMO); 5333 5334 AddToWorklist(Lo.getNode()); 5335 AddToWorklist(Hi.getNode()); 5336 5337 // Build a factor node to remember that this load is independent of the 5338 // other one. 5339 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5340 Hi.getValue(1)); 5341 5342 // Legalized the chain result - switch anything that used the old chain to 5343 // use the new one. 5344 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5345 5346 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5347 5348 SDValue RetOps[] = { GatherRes, Chain }; 5349 return DAG.getMergeValues(RetOps, DL); 5350 } 5351 5352 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5353 5354 if (Level >= AfterLegalizeTypes) 5355 return SDValue(); 5356 5357 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5358 SDValue Mask = MLD->getMask(); 5359 SDLoc DL(N); 5360 5361 // If the MLOAD result requires splitting and the mask is provided by a 5362 // SETCC, then split both nodes and its operands before legalization. This 5363 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5364 // and enables future optimizations (e.g. min/max pattern matching on X86). 5365 5366 if (Mask.getOpcode() == ISD::SETCC) { 5367 EVT VT = N->getValueType(0); 5368 5369 // Check if any splitting is required. 5370 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5371 TargetLowering::TypeSplitVector) 5372 return SDValue(); 5373 5374 SDValue MaskLo, MaskHi, Lo, Hi; 5375 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5376 5377 SDValue Src0 = MLD->getSrc0(); 5378 SDValue Src0Lo, Src0Hi; 5379 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5380 5381 EVT LoVT, HiVT; 5382 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5383 5384 SDValue Chain = MLD->getChain(); 5385 SDValue Ptr = MLD->getBasePtr(); 5386 EVT MemoryVT = MLD->getMemoryVT(); 5387 unsigned Alignment = MLD->getOriginalAlignment(); 5388 5389 // if Alignment is equal to the vector size, 5390 // take the half of it for the second part 5391 unsigned SecondHalfAlignment = 5392 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5393 Alignment/2 : Alignment; 5394 5395 EVT LoMemVT, HiMemVT; 5396 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5397 5398 MachineMemOperand *MMO = DAG.getMachineFunction(). 5399 getMachineMemOperand(MLD->getPointerInfo(), 5400 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5401 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5402 5403 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5404 ISD::NON_EXTLOAD); 5405 5406 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5407 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5408 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5409 5410 MMO = DAG.getMachineFunction(). 5411 getMachineMemOperand(MLD->getPointerInfo(), 5412 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5413 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5414 5415 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5416 ISD::NON_EXTLOAD); 5417 5418 AddToWorklist(Lo.getNode()); 5419 AddToWorklist(Hi.getNode()); 5420 5421 // Build a factor node to remember that this load is independent of the 5422 // other one. 5423 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5424 Hi.getValue(1)); 5425 5426 // Legalized the chain result - switch anything that used the old chain to 5427 // use the new one. 5428 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5429 5430 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5431 5432 SDValue RetOps[] = { LoadRes, Chain }; 5433 return DAG.getMergeValues(RetOps, DL); 5434 } 5435 return SDValue(); 5436 } 5437 5438 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5439 SDValue N0 = N->getOperand(0); 5440 SDValue N1 = N->getOperand(1); 5441 SDValue N2 = N->getOperand(2); 5442 SDLoc DL(N); 5443 5444 // Canonicalize integer abs. 5445 // vselect (setg[te] X, 0), X, -X -> 5446 // vselect (setgt X, -1), X, -X -> 5447 // vselect (setl[te] X, 0), -X, X -> 5448 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5449 if (N0.getOpcode() == ISD::SETCC) { 5450 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5451 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5452 bool isAbs = false; 5453 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5454 5455 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5456 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5457 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5458 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5459 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5460 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5461 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5462 5463 if (isAbs) { 5464 EVT VT = LHS.getValueType(); 5465 SDValue Shift = DAG.getNode( 5466 ISD::SRA, DL, VT, LHS, 5467 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5468 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5469 AddToWorklist(Shift.getNode()); 5470 AddToWorklist(Add.getNode()); 5471 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5472 } 5473 } 5474 5475 if (SimplifySelectOps(N, N1, N2)) 5476 return SDValue(N, 0); // Don't revisit N. 5477 5478 // If the VSELECT result requires splitting and the mask is provided by a 5479 // SETCC, then split both nodes and its operands before legalization. This 5480 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5481 // and enables future optimizations (e.g. min/max pattern matching on X86). 5482 if (N0.getOpcode() == ISD::SETCC) { 5483 EVT VT = N->getValueType(0); 5484 5485 // Check if any splitting is required. 5486 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5487 TargetLowering::TypeSplitVector) 5488 return SDValue(); 5489 5490 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5491 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5492 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5493 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5494 5495 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5496 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5497 5498 // Add the new VSELECT nodes to the work list in case they need to be split 5499 // again. 5500 AddToWorklist(Lo.getNode()); 5501 AddToWorklist(Hi.getNode()); 5502 5503 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5504 } 5505 5506 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5507 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5508 return N1; 5509 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5510 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5511 return N2; 5512 5513 // The ConvertSelectToConcatVector function is assuming both the above 5514 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5515 // and addressed. 5516 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5517 N2.getOpcode() == ISD::CONCAT_VECTORS && 5518 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5519 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5520 return CV; 5521 } 5522 5523 return SDValue(); 5524 } 5525 5526 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5527 SDValue N0 = N->getOperand(0); 5528 SDValue N1 = N->getOperand(1); 5529 SDValue N2 = N->getOperand(2); 5530 SDValue N3 = N->getOperand(3); 5531 SDValue N4 = N->getOperand(4); 5532 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5533 5534 // fold select_cc lhs, rhs, x, x, cc -> x 5535 if (N2 == N3) 5536 return N2; 5537 5538 // Determine if the condition we're dealing with is constant 5539 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5540 N0, N1, CC, SDLoc(N), false); 5541 if (SCC.getNode()) { 5542 AddToWorklist(SCC.getNode()); 5543 5544 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5545 if (!SCCC->isNullValue()) 5546 return N2; // cond always true -> true val 5547 else 5548 return N3; // cond always false -> false val 5549 } else if (SCC->getOpcode() == ISD::UNDEF) { 5550 // When the condition is UNDEF, just return the first operand. This is 5551 // coherent the DAG creation, no setcc node is created in this case 5552 return N2; 5553 } else if (SCC.getOpcode() == ISD::SETCC) { 5554 // Fold to a simpler select_cc 5555 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5556 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5557 SCC.getOperand(2)); 5558 } 5559 } 5560 5561 // If we can fold this based on the true/false value, do so. 5562 if (SimplifySelectOps(N, N2, N3)) 5563 return SDValue(N, 0); // Don't revisit N. 5564 5565 // fold select_cc into other things, such as min/max/abs 5566 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5567 } 5568 5569 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5570 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5571 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5572 SDLoc(N)); 5573 } 5574 5575 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5576 /// a build_vector of constants. 5577 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5578 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5579 /// Vector extends are not folded if operations are legal; this is to 5580 /// avoid introducing illegal build_vector dag nodes. 5581 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5582 SelectionDAG &DAG, bool LegalTypes, 5583 bool LegalOperations) { 5584 unsigned Opcode = N->getOpcode(); 5585 SDValue N0 = N->getOperand(0); 5586 EVT VT = N->getValueType(0); 5587 5588 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5589 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5590 && "Expected EXTEND dag node in input!"); 5591 5592 // fold (sext c1) -> c1 5593 // fold (zext c1) -> c1 5594 // fold (aext c1) -> c1 5595 if (isa<ConstantSDNode>(N0)) 5596 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5597 5598 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5599 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5600 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5601 EVT SVT = VT.getScalarType(); 5602 if (!(VT.isVector() && 5603 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5604 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5605 return nullptr; 5606 5607 // We can fold this node into a build_vector. 5608 unsigned VTBits = SVT.getSizeInBits(); 5609 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5610 SmallVector<SDValue, 8> Elts; 5611 unsigned NumElts = VT.getVectorNumElements(); 5612 SDLoc DL(N); 5613 5614 for (unsigned i=0; i != NumElts; ++i) { 5615 SDValue Op = N0->getOperand(i); 5616 if (Op->getOpcode() == ISD::UNDEF) { 5617 Elts.push_back(DAG.getUNDEF(SVT)); 5618 continue; 5619 } 5620 5621 SDLoc DL(Op); 5622 // Get the constant value and if needed trunc it to the size of the type. 5623 // Nodes like build_vector might have constants wider than the scalar type. 5624 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5625 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5626 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5627 else 5628 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5629 } 5630 5631 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5632 } 5633 5634 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5635 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5636 // transformation. Returns true if extension are possible and the above 5637 // mentioned transformation is profitable. 5638 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5639 unsigned ExtOpc, 5640 SmallVectorImpl<SDNode *> &ExtendNodes, 5641 const TargetLowering &TLI) { 5642 bool HasCopyToRegUses = false; 5643 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5644 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5645 UE = N0.getNode()->use_end(); 5646 UI != UE; ++UI) { 5647 SDNode *User = *UI; 5648 if (User == N) 5649 continue; 5650 if (UI.getUse().getResNo() != N0.getResNo()) 5651 continue; 5652 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5653 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5654 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5655 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5656 // Sign bits will be lost after a zext. 5657 return false; 5658 bool Add = false; 5659 for (unsigned i = 0; i != 2; ++i) { 5660 SDValue UseOp = User->getOperand(i); 5661 if (UseOp == N0) 5662 continue; 5663 if (!isa<ConstantSDNode>(UseOp)) 5664 return false; 5665 Add = true; 5666 } 5667 if (Add) 5668 ExtendNodes.push_back(User); 5669 continue; 5670 } 5671 // If truncates aren't free and there are users we can't 5672 // extend, it isn't worthwhile. 5673 if (!isTruncFree) 5674 return false; 5675 // Remember if this value is live-out. 5676 if (User->getOpcode() == ISD::CopyToReg) 5677 HasCopyToRegUses = true; 5678 } 5679 5680 if (HasCopyToRegUses) { 5681 bool BothLiveOut = false; 5682 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5683 UI != UE; ++UI) { 5684 SDUse &Use = UI.getUse(); 5685 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5686 BothLiveOut = true; 5687 break; 5688 } 5689 } 5690 if (BothLiveOut) 5691 // Both unextended and extended values are live out. There had better be 5692 // a good reason for the transformation. 5693 return ExtendNodes.size(); 5694 } 5695 return true; 5696 } 5697 5698 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5699 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5700 ISD::NodeType ExtType) { 5701 // Extend SetCC uses if necessary. 5702 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5703 SDNode *SetCC = SetCCs[i]; 5704 SmallVector<SDValue, 4> Ops; 5705 5706 for (unsigned j = 0; j != 2; ++j) { 5707 SDValue SOp = SetCC->getOperand(j); 5708 if (SOp == Trunc) 5709 Ops.push_back(ExtLoad); 5710 else 5711 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5712 } 5713 5714 Ops.push_back(SetCC->getOperand(2)); 5715 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5716 } 5717 } 5718 5719 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5720 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5721 SDValue N0 = N->getOperand(0); 5722 EVT DstVT = N->getValueType(0); 5723 EVT SrcVT = N0.getValueType(); 5724 5725 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5726 N->getOpcode() == ISD::ZERO_EXTEND) && 5727 "Unexpected node type (not an extend)!"); 5728 5729 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5730 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5731 // (v8i32 (sext (v8i16 (load x)))) 5732 // into: 5733 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5734 // (v4i32 (sextload (x + 16))))) 5735 // Where uses of the original load, i.e.: 5736 // (v8i16 (load x)) 5737 // are replaced with: 5738 // (v8i16 (truncate 5739 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5740 // (v4i32 (sextload (x + 16))))))) 5741 // 5742 // This combine is only applicable to illegal, but splittable, vectors. 5743 // All legal types, and illegal non-vector types, are handled elsewhere. 5744 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5745 // 5746 if (N0->getOpcode() != ISD::LOAD) 5747 return SDValue(); 5748 5749 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5750 5751 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5752 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5753 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5754 return SDValue(); 5755 5756 SmallVector<SDNode *, 4> SetCCs; 5757 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5758 return SDValue(); 5759 5760 ISD::LoadExtType ExtType = 5761 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5762 5763 // Try to split the vector types to get down to legal types. 5764 EVT SplitSrcVT = SrcVT; 5765 EVT SplitDstVT = DstVT; 5766 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5767 SplitSrcVT.getVectorNumElements() > 1) { 5768 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5769 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5770 } 5771 5772 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5773 return SDValue(); 5774 5775 SDLoc DL(N); 5776 const unsigned NumSplits = 5777 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5778 const unsigned Stride = SplitSrcVT.getStoreSize(); 5779 SmallVector<SDValue, 4> Loads; 5780 SmallVector<SDValue, 4> Chains; 5781 5782 SDValue BasePtr = LN0->getBasePtr(); 5783 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5784 const unsigned Offset = Idx * Stride; 5785 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5786 5787 SDValue SplitLoad = DAG.getExtLoad( 5788 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5789 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5790 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5791 Align, LN0->getAAInfo()); 5792 5793 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5794 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5795 5796 Loads.push_back(SplitLoad.getValue(0)); 5797 Chains.push_back(SplitLoad.getValue(1)); 5798 } 5799 5800 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5801 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5802 5803 CombineTo(N, NewValue); 5804 5805 // Replace uses of the original load (before extension) 5806 // with a truncate of the concatenated sextloaded vectors. 5807 SDValue Trunc = 5808 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5809 CombineTo(N0.getNode(), Trunc, NewChain); 5810 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5811 (ISD::NodeType)N->getOpcode()); 5812 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5813 } 5814 5815 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5816 SDValue N0 = N->getOperand(0); 5817 EVT VT = N->getValueType(0); 5818 5819 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5820 LegalOperations)) 5821 return SDValue(Res, 0); 5822 5823 // fold (sext (sext x)) -> (sext x) 5824 // fold (sext (aext x)) -> (sext x) 5825 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5826 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5827 N0.getOperand(0)); 5828 5829 if (N0.getOpcode() == ISD::TRUNCATE) { 5830 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5831 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5832 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5833 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5834 if (NarrowLoad.getNode() != N0.getNode()) { 5835 CombineTo(N0.getNode(), NarrowLoad); 5836 // CombineTo deleted the truncate, if needed, but not what's under it. 5837 AddToWorklist(oye); 5838 } 5839 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5840 } 5841 5842 // See if the value being truncated is already sign extended. If so, just 5843 // eliminate the trunc/sext pair. 5844 SDValue Op = N0.getOperand(0); 5845 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5846 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5847 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5848 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5849 5850 if (OpBits == DestBits) { 5851 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5852 // bits, it is already ready. 5853 if (NumSignBits > DestBits-MidBits) 5854 return Op; 5855 } else if (OpBits < DestBits) { 5856 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5857 // bits, just sext from i32. 5858 if (NumSignBits > OpBits-MidBits) 5859 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5860 } else { 5861 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5862 // bits, just truncate to i32. 5863 if (NumSignBits > OpBits-MidBits) 5864 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5865 } 5866 5867 // fold (sext (truncate x)) -> (sextinreg x). 5868 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5869 N0.getValueType())) { 5870 if (OpBits < DestBits) 5871 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5872 else if (OpBits > DestBits) 5873 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5874 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5875 DAG.getValueType(N0.getValueType())); 5876 } 5877 } 5878 5879 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5880 // Only generate vector extloads when 1) they're legal, and 2) they are 5881 // deemed desirable by the target. 5882 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5883 ((!LegalOperations && !VT.isVector() && 5884 !cast<LoadSDNode>(N0)->isVolatile()) || 5885 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5886 bool DoXform = true; 5887 SmallVector<SDNode*, 4> SetCCs; 5888 if (!N0.hasOneUse()) 5889 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5890 if (VT.isVector()) 5891 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5892 if (DoXform) { 5893 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5894 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5895 LN0->getChain(), 5896 LN0->getBasePtr(), N0.getValueType(), 5897 LN0->getMemOperand()); 5898 CombineTo(N, ExtLoad); 5899 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5900 N0.getValueType(), ExtLoad); 5901 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5902 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5903 ISD::SIGN_EXTEND); 5904 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5905 } 5906 } 5907 5908 // fold (sext (load x)) to multiple smaller sextloads. 5909 // Only on illegal but splittable vectors. 5910 if (SDValue ExtLoad = CombineExtLoad(N)) 5911 return ExtLoad; 5912 5913 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5914 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5915 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5916 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5917 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5918 EVT MemVT = LN0->getMemoryVT(); 5919 if ((!LegalOperations && !LN0->isVolatile()) || 5920 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5921 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5922 LN0->getChain(), 5923 LN0->getBasePtr(), MemVT, 5924 LN0->getMemOperand()); 5925 CombineTo(N, ExtLoad); 5926 CombineTo(N0.getNode(), 5927 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5928 N0.getValueType(), ExtLoad), 5929 ExtLoad.getValue(1)); 5930 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5931 } 5932 } 5933 5934 // fold (sext (and/or/xor (load x), cst)) -> 5935 // (and/or/xor (sextload x), (sext cst)) 5936 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5937 N0.getOpcode() == ISD::XOR) && 5938 isa<LoadSDNode>(N0.getOperand(0)) && 5939 N0.getOperand(1).getOpcode() == ISD::Constant && 5940 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5941 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5942 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5943 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5944 bool DoXform = true; 5945 SmallVector<SDNode*, 4> SetCCs; 5946 if (!N0.hasOneUse()) 5947 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5948 SetCCs, TLI); 5949 if (DoXform) { 5950 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5951 LN0->getChain(), LN0->getBasePtr(), 5952 LN0->getMemoryVT(), 5953 LN0->getMemOperand()); 5954 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5955 Mask = Mask.sext(VT.getSizeInBits()); 5956 SDLoc DL(N); 5957 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 5958 ExtLoad, DAG.getConstant(Mask, DL, VT)); 5959 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5960 SDLoc(N0.getOperand(0)), 5961 N0.getOperand(0).getValueType(), ExtLoad); 5962 CombineTo(N, And); 5963 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5964 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 5965 ISD::SIGN_EXTEND); 5966 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5967 } 5968 } 5969 } 5970 5971 if (N0.getOpcode() == ISD::SETCC) { 5972 EVT N0VT = N0.getOperand(0).getValueType(); 5973 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5974 // Only do this before legalize for now. 5975 if (VT.isVector() && !LegalOperations && 5976 TLI.getBooleanContents(N0VT) == 5977 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5978 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5979 // of the same size as the compared operands. Only optimize sext(setcc()) 5980 // if this is the case. 5981 EVT SVT = getSetCCResultType(N0VT); 5982 5983 // We know that the # elements of the results is the same as the 5984 // # elements of the compare (and the # elements of the compare result 5985 // for that matter). Check to see that they are the same size. If so, 5986 // we know that the element size of the sext'd result matches the 5987 // element size of the compare operands. 5988 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5989 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5990 N0.getOperand(1), 5991 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5992 5993 // If the desired elements are smaller or larger than the source 5994 // elements we can use a matching integer vector type and then 5995 // truncate/sign extend 5996 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5997 if (SVT == MatchingVectorType) { 5998 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5999 N0.getOperand(0), N0.getOperand(1), 6000 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6001 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6002 } 6003 } 6004 6005 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6006 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6007 SDLoc DL(N); 6008 SDValue NegOne = 6009 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6010 SDValue SCC = 6011 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6012 NegOne, DAG.getConstant(0, DL, VT), 6013 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6014 if (SCC.getNode()) return SCC; 6015 6016 if (!VT.isVector()) { 6017 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6018 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 6019 SDLoc DL(N); 6020 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6021 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6022 N0.getOperand(0), N0.getOperand(1), CC); 6023 return DAG.getSelect(DL, VT, SetCC, 6024 NegOne, DAG.getConstant(0, DL, VT)); 6025 } 6026 } 6027 } 6028 6029 // fold (sext x) -> (zext x) if the sign bit is known zero. 6030 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6031 DAG.SignBitIsZero(N0)) 6032 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6033 6034 return SDValue(); 6035 } 6036 6037 // isTruncateOf - If N is a truncate of some other value, return true, record 6038 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6039 // This function computes KnownZero to avoid a duplicated call to 6040 // computeKnownBits in the caller. 6041 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6042 APInt &KnownZero) { 6043 APInt KnownOne; 6044 if (N->getOpcode() == ISD::TRUNCATE) { 6045 Op = N->getOperand(0); 6046 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6047 return true; 6048 } 6049 6050 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6051 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6052 return false; 6053 6054 SDValue Op0 = N->getOperand(0); 6055 SDValue Op1 = N->getOperand(1); 6056 assert(Op0.getValueType() == Op1.getValueType()); 6057 6058 if (isNullConstant(Op0)) 6059 Op = Op1; 6060 else if (isNullConstant(Op1)) 6061 Op = Op0; 6062 else 6063 return false; 6064 6065 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6066 6067 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6068 return false; 6069 6070 return true; 6071 } 6072 6073 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6074 SDValue N0 = N->getOperand(0); 6075 EVT VT = N->getValueType(0); 6076 6077 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6078 LegalOperations)) 6079 return SDValue(Res, 0); 6080 6081 // fold (zext (zext x)) -> (zext x) 6082 // fold (zext (aext x)) -> (zext x) 6083 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6084 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6085 N0.getOperand(0)); 6086 6087 // fold (zext (truncate x)) -> (zext x) or 6088 // (zext (truncate x)) -> (truncate x) 6089 // This is valid when the truncated bits of x are already zero. 6090 // FIXME: We should extend this to work for vectors too. 6091 SDValue Op; 6092 APInt KnownZero; 6093 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6094 APInt TruncatedBits = 6095 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6096 APInt(Op.getValueSizeInBits(), 0) : 6097 APInt::getBitsSet(Op.getValueSizeInBits(), 6098 N0.getValueSizeInBits(), 6099 std::min(Op.getValueSizeInBits(), 6100 VT.getSizeInBits())); 6101 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6102 if (VT.bitsGT(Op.getValueType())) 6103 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6104 if (VT.bitsLT(Op.getValueType())) 6105 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6106 6107 return Op; 6108 } 6109 } 6110 6111 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6112 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6113 if (N0.getOpcode() == ISD::TRUNCATE) { 6114 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6115 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6116 if (NarrowLoad.getNode() != N0.getNode()) { 6117 CombineTo(N0.getNode(), NarrowLoad); 6118 // CombineTo deleted the truncate, if needed, but not what's under it. 6119 AddToWorklist(oye); 6120 } 6121 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6122 } 6123 } 6124 6125 // fold (zext (truncate x)) -> (and x, mask) 6126 if (N0.getOpcode() == ISD::TRUNCATE) { 6127 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6128 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6129 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6130 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6131 if (NarrowLoad.getNode() != N0.getNode()) { 6132 CombineTo(N0.getNode(), NarrowLoad); 6133 // CombineTo deleted the truncate, if needed, but not what's under it. 6134 AddToWorklist(oye); 6135 } 6136 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6137 } 6138 6139 EVT SrcVT = N0.getOperand(0).getValueType(); 6140 EVT MinVT = N0.getValueType(); 6141 6142 // Try to mask before the extension to avoid having to generate a larger mask, 6143 // possibly over several sub-vectors. 6144 if (SrcVT.bitsLT(VT)) { 6145 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6146 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6147 SDValue Op = N0.getOperand(0); 6148 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6149 AddToWorklist(Op.getNode()); 6150 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6151 } 6152 } 6153 6154 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6155 SDValue Op = N0.getOperand(0); 6156 if (SrcVT.bitsLT(VT)) { 6157 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6158 AddToWorklist(Op.getNode()); 6159 } else if (SrcVT.bitsGT(VT)) { 6160 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6161 AddToWorklist(Op.getNode()); 6162 } 6163 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6164 } 6165 } 6166 6167 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6168 // if either of the casts is not free. 6169 if (N0.getOpcode() == ISD::AND && 6170 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6171 N0.getOperand(1).getOpcode() == ISD::Constant && 6172 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6173 N0.getValueType()) || 6174 !TLI.isZExtFree(N0.getValueType(), VT))) { 6175 SDValue X = N0.getOperand(0).getOperand(0); 6176 if (X.getValueType().bitsLT(VT)) { 6177 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6178 } else if (X.getValueType().bitsGT(VT)) { 6179 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6180 } 6181 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6182 Mask = Mask.zext(VT.getSizeInBits()); 6183 SDLoc DL(N); 6184 return DAG.getNode(ISD::AND, DL, VT, 6185 X, DAG.getConstant(Mask, DL, VT)); 6186 } 6187 6188 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6189 // Only generate vector extloads when 1) they're legal, and 2) they are 6190 // deemed desirable by the target. 6191 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6192 ((!LegalOperations && !VT.isVector() && 6193 !cast<LoadSDNode>(N0)->isVolatile()) || 6194 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6195 bool DoXform = true; 6196 SmallVector<SDNode*, 4> SetCCs; 6197 if (!N0.hasOneUse()) 6198 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6199 if (VT.isVector()) 6200 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6201 if (DoXform) { 6202 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6203 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6204 LN0->getChain(), 6205 LN0->getBasePtr(), N0.getValueType(), 6206 LN0->getMemOperand()); 6207 CombineTo(N, ExtLoad); 6208 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6209 N0.getValueType(), ExtLoad); 6210 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6211 6212 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6213 ISD::ZERO_EXTEND); 6214 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6215 } 6216 } 6217 6218 // fold (zext (load x)) to multiple smaller zextloads. 6219 // Only on illegal but splittable vectors. 6220 if (SDValue ExtLoad = CombineExtLoad(N)) 6221 return ExtLoad; 6222 6223 // fold (zext (and/or/xor (load x), cst)) -> 6224 // (and/or/xor (zextload x), (zext cst)) 6225 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6226 N0.getOpcode() == ISD::XOR) && 6227 isa<LoadSDNode>(N0.getOperand(0)) && 6228 N0.getOperand(1).getOpcode() == ISD::Constant && 6229 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6230 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6231 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6232 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6233 bool DoXform = true; 6234 SmallVector<SDNode*, 4> SetCCs; 6235 if (!N0.hasOneUse()) 6236 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 6237 SetCCs, TLI); 6238 if (DoXform) { 6239 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6240 LN0->getChain(), LN0->getBasePtr(), 6241 LN0->getMemoryVT(), 6242 LN0->getMemOperand()); 6243 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6244 Mask = Mask.zext(VT.getSizeInBits()); 6245 SDLoc DL(N); 6246 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6247 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6248 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6249 SDLoc(N0.getOperand(0)), 6250 N0.getOperand(0).getValueType(), ExtLoad); 6251 CombineTo(N, And); 6252 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6253 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6254 ISD::ZERO_EXTEND); 6255 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6256 } 6257 } 6258 } 6259 6260 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6261 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6262 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6263 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6264 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6265 EVT MemVT = LN0->getMemoryVT(); 6266 if ((!LegalOperations && !LN0->isVolatile()) || 6267 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6268 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6269 LN0->getChain(), 6270 LN0->getBasePtr(), MemVT, 6271 LN0->getMemOperand()); 6272 CombineTo(N, ExtLoad); 6273 CombineTo(N0.getNode(), 6274 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6275 ExtLoad), 6276 ExtLoad.getValue(1)); 6277 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6278 } 6279 } 6280 6281 if (N0.getOpcode() == ISD::SETCC) { 6282 if (!LegalOperations && VT.isVector() && 6283 N0.getValueType().getVectorElementType() == MVT::i1) { 6284 EVT N0VT = N0.getOperand(0).getValueType(); 6285 if (getSetCCResultType(N0VT) == N0.getValueType()) 6286 return SDValue(); 6287 6288 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6289 // Only do this before legalize for now. 6290 EVT EltVT = VT.getVectorElementType(); 6291 SDLoc DL(N); 6292 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6293 DAG.getConstant(1, DL, EltVT)); 6294 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6295 // We know that the # elements of the results is the same as the 6296 // # elements of the compare (and the # elements of the compare result 6297 // for that matter). Check to see that they are the same size. If so, 6298 // we know that the element size of the sext'd result matches the 6299 // element size of the compare operands. 6300 return DAG.getNode(ISD::AND, DL, VT, 6301 DAG.getSetCC(DL, VT, N0.getOperand(0), 6302 N0.getOperand(1), 6303 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6304 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6305 OneOps)); 6306 6307 // If the desired elements are smaller or larger than the source 6308 // elements we can use a matching integer vector type and then 6309 // truncate/sign extend 6310 EVT MatchingElementType = 6311 EVT::getIntegerVT(*DAG.getContext(), 6312 N0VT.getScalarType().getSizeInBits()); 6313 EVT MatchingVectorType = 6314 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6315 N0VT.getVectorNumElements()); 6316 SDValue VsetCC = 6317 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6318 N0.getOperand(1), 6319 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6320 return DAG.getNode(ISD::AND, DL, VT, 6321 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6322 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6323 } 6324 6325 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6326 SDLoc DL(N); 6327 SDValue SCC = 6328 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6329 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6330 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6331 if (SCC.getNode()) return SCC; 6332 } 6333 6334 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6335 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6336 isa<ConstantSDNode>(N0.getOperand(1)) && 6337 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6338 N0.hasOneUse()) { 6339 SDValue ShAmt = N0.getOperand(1); 6340 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6341 if (N0.getOpcode() == ISD::SHL) { 6342 SDValue InnerZExt = N0.getOperand(0); 6343 // If the original shl may be shifting out bits, do not perform this 6344 // transformation. 6345 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6346 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6347 if (ShAmtVal > KnownZeroBits) 6348 return SDValue(); 6349 } 6350 6351 SDLoc DL(N); 6352 6353 // Ensure that the shift amount is wide enough for the shifted value. 6354 if (VT.getSizeInBits() >= 256) 6355 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6356 6357 return DAG.getNode(N0.getOpcode(), DL, VT, 6358 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6359 ShAmt); 6360 } 6361 6362 return SDValue(); 6363 } 6364 6365 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6366 SDValue N0 = N->getOperand(0); 6367 EVT VT = N->getValueType(0); 6368 6369 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6370 LegalOperations)) 6371 return SDValue(Res, 0); 6372 6373 // fold (aext (aext x)) -> (aext x) 6374 // fold (aext (zext x)) -> (zext x) 6375 // fold (aext (sext x)) -> (sext x) 6376 if (N0.getOpcode() == ISD::ANY_EXTEND || 6377 N0.getOpcode() == ISD::ZERO_EXTEND || 6378 N0.getOpcode() == ISD::SIGN_EXTEND) 6379 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6380 6381 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6382 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6383 if (N0.getOpcode() == ISD::TRUNCATE) { 6384 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6385 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6386 if (NarrowLoad.getNode() != N0.getNode()) { 6387 CombineTo(N0.getNode(), NarrowLoad); 6388 // CombineTo deleted the truncate, if needed, but not what's under it. 6389 AddToWorklist(oye); 6390 } 6391 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6392 } 6393 } 6394 6395 // fold (aext (truncate x)) 6396 if (N0.getOpcode() == ISD::TRUNCATE) { 6397 SDValue TruncOp = N0.getOperand(0); 6398 if (TruncOp.getValueType() == VT) 6399 return TruncOp; // x iff x size == zext size. 6400 if (TruncOp.getValueType().bitsGT(VT)) 6401 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6402 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6403 } 6404 6405 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6406 // if the trunc is not free. 6407 if (N0.getOpcode() == ISD::AND && 6408 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6409 N0.getOperand(1).getOpcode() == ISD::Constant && 6410 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6411 N0.getValueType())) { 6412 SDValue X = N0.getOperand(0).getOperand(0); 6413 if (X.getValueType().bitsLT(VT)) { 6414 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6415 } else if (X.getValueType().bitsGT(VT)) { 6416 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6417 } 6418 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6419 Mask = Mask.zext(VT.getSizeInBits()); 6420 SDLoc DL(N); 6421 return DAG.getNode(ISD::AND, DL, VT, 6422 X, DAG.getConstant(Mask, DL, VT)); 6423 } 6424 6425 // fold (aext (load x)) -> (aext (truncate (extload x))) 6426 // None of the supported targets knows how to perform load and any_ext 6427 // on vectors in one instruction. We only perform this transformation on 6428 // scalars. 6429 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6430 ISD::isUNINDEXEDLoad(N0.getNode()) && 6431 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6432 bool DoXform = true; 6433 SmallVector<SDNode*, 4> SetCCs; 6434 if (!N0.hasOneUse()) 6435 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6436 if (DoXform) { 6437 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6438 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6439 LN0->getChain(), 6440 LN0->getBasePtr(), N0.getValueType(), 6441 LN0->getMemOperand()); 6442 CombineTo(N, ExtLoad); 6443 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6444 N0.getValueType(), ExtLoad); 6445 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6446 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6447 ISD::ANY_EXTEND); 6448 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6449 } 6450 } 6451 6452 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6453 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6454 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6455 if (N0.getOpcode() == ISD::LOAD && 6456 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6457 N0.hasOneUse()) { 6458 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6459 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6460 EVT MemVT = LN0->getMemoryVT(); 6461 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6462 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6463 VT, LN0->getChain(), LN0->getBasePtr(), 6464 MemVT, LN0->getMemOperand()); 6465 CombineTo(N, ExtLoad); 6466 CombineTo(N0.getNode(), 6467 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6468 N0.getValueType(), ExtLoad), 6469 ExtLoad.getValue(1)); 6470 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6471 } 6472 } 6473 6474 if (N0.getOpcode() == ISD::SETCC) { 6475 // For vectors: 6476 // aext(setcc) -> vsetcc 6477 // aext(setcc) -> truncate(vsetcc) 6478 // aext(setcc) -> aext(vsetcc) 6479 // Only do this before legalize for now. 6480 if (VT.isVector() && !LegalOperations) { 6481 EVT N0VT = N0.getOperand(0).getValueType(); 6482 // We know that the # elements of the results is the same as the 6483 // # elements of the compare (and the # elements of the compare result 6484 // for that matter). Check to see that they are the same size. If so, 6485 // we know that the element size of the sext'd result matches the 6486 // element size of the compare operands. 6487 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6488 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6489 N0.getOperand(1), 6490 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6491 // If the desired elements are smaller or larger than the source 6492 // elements we can use a matching integer vector type and then 6493 // truncate/any extend 6494 else { 6495 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6496 SDValue VsetCC = 6497 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6498 N0.getOperand(1), 6499 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6500 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6501 } 6502 } 6503 6504 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6505 SDLoc DL(N); 6506 SDValue SCC = 6507 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6508 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6509 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6510 if (SCC.getNode()) 6511 return SCC; 6512 } 6513 6514 return SDValue(); 6515 } 6516 6517 /// See if the specified operand can be simplified with the knowledge that only 6518 /// the bits specified by Mask are used. If so, return the simpler operand, 6519 /// otherwise return a null SDValue. 6520 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6521 switch (V.getOpcode()) { 6522 default: break; 6523 case ISD::Constant: { 6524 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6525 assert(CV && "Const value should be ConstSDNode."); 6526 const APInt &CVal = CV->getAPIntValue(); 6527 APInt NewVal = CVal & Mask; 6528 if (NewVal != CVal) 6529 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6530 break; 6531 } 6532 case ISD::OR: 6533 case ISD::XOR: 6534 // If the LHS or RHS don't contribute bits to the or, drop them. 6535 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6536 return V.getOperand(1); 6537 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6538 return V.getOperand(0); 6539 break; 6540 case ISD::SRL: 6541 // Only look at single-use SRLs. 6542 if (!V.getNode()->hasOneUse()) 6543 break; 6544 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6545 // See if we can recursively simplify the LHS. 6546 unsigned Amt = RHSC->getZExtValue(); 6547 6548 // Watch out for shift count overflow though. 6549 if (Amt >= Mask.getBitWidth()) break; 6550 APInt NewMask = Mask << Amt; 6551 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6552 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6553 SimplifyLHS, V.getOperand(1)); 6554 } 6555 } 6556 return SDValue(); 6557 } 6558 6559 /// If the result of a wider load is shifted to right of N bits and then 6560 /// truncated to a narrower type and where N is a multiple of number of bits of 6561 /// the narrower type, transform it to a narrower load from address + N / num of 6562 /// bits of new type. If the result is to be extended, also fold the extension 6563 /// to form a extending load. 6564 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6565 unsigned Opc = N->getOpcode(); 6566 6567 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6568 SDValue N0 = N->getOperand(0); 6569 EVT VT = N->getValueType(0); 6570 EVT ExtVT = VT; 6571 6572 // This transformation isn't valid for vector loads. 6573 if (VT.isVector()) 6574 return SDValue(); 6575 6576 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6577 // extended to VT. 6578 if (Opc == ISD::SIGN_EXTEND_INREG) { 6579 ExtType = ISD::SEXTLOAD; 6580 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6581 } else if (Opc == ISD::SRL) { 6582 // Another special-case: SRL is basically zero-extending a narrower value. 6583 ExtType = ISD::ZEXTLOAD; 6584 N0 = SDValue(N, 0); 6585 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6586 if (!N01) return SDValue(); 6587 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6588 VT.getSizeInBits() - N01->getZExtValue()); 6589 } 6590 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6591 return SDValue(); 6592 6593 unsigned EVTBits = ExtVT.getSizeInBits(); 6594 6595 // Do not generate loads of non-round integer types since these can 6596 // be expensive (and would be wrong if the type is not byte sized). 6597 if (!ExtVT.isRound()) 6598 return SDValue(); 6599 6600 unsigned ShAmt = 0; 6601 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6602 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6603 ShAmt = N01->getZExtValue(); 6604 // Is the shift amount a multiple of size of VT? 6605 if ((ShAmt & (EVTBits-1)) == 0) { 6606 N0 = N0.getOperand(0); 6607 // Is the load width a multiple of size of VT? 6608 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6609 return SDValue(); 6610 } 6611 6612 // At this point, we must have a load or else we can't do the transform. 6613 if (!isa<LoadSDNode>(N0)) return SDValue(); 6614 6615 // Because a SRL must be assumed to *need* to zero-extend the high bits 6616 // (as opposed to anyext the high bits), we can't combine the zextload 6617 // lowering of SRL and an sextload. 6618 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6619 return SDValue(); 6620 6621 // If the shift amount is larger than the input type then we're not 6622 // accessing any of the loaded bytes. If the load was a zextload/extload 6623 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6624 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6625 return SDValue(); 6626 } 6627 } 6628 6629 // If the load is shifted left (and the result isn't shifted back right), 6630 // we can fold the truncate through the shift. 6631 unsigned ShLeftAmt = 0; 6632 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6633 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6634 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6635 ShLeftAmt = N01->getZExtValue(); 6636 N0 = N0.getOperand(0); 6637 } 6638 } 6639 6640 // If we haven't found a load, we can't narrow it. Don't transform one with 6641 // multiple uses, this would require adding a new load. 6642 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6643 return SDValue(); 6644 6645 // Don't change the width of a volatile load. 6646 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6647 if (LN0->isVolatile()) 6648 return SDValue(); 6649 6650 // Verify that we are actually reducing a load width here. 6651 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6652 return SDValue(); 6653 6654 // For the transform to be legal, the load must produce only two values 6655 // (the value loaded and the chain). Don't transform a pre-increment 6656 // load, for example, which produces an extra value. Otherwise the 6657 // transformation is not equivalent, and the downstream logic to replace 6658 // uses gets things wrong. 6659 if (LN0->getNumValues() > 2) 6660 return SDValue(); 6661 6662 // If the load that we're shrinking is an extload and we're not just 6663 // discarding the extension we can't simply shrink the load. Bail. 6664 // TODO: It would be possible to merge the extensions in some cases. 6665 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6666 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6667 return SDValue(); 6668 6669 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6670 return SDValue(); 6671 6672 EVT PtrType = N0.getOperand(1).getValueType(); 6673 6674 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6675 // It's not possible to generate a constant of extended or untyped type. 6676 return SDValue(); 6677 6678 // For big endian targets, we need to adjust the offset to the pointer to 6679 // load the correct bytes. 6680 if (DAG.getDataLayout().isBigEndian()) { 6681 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6682 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6683 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6684 } 6685 6686 uint64_t PtrOff = ShAmt / 8; 6687 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6688 SDLoc DL(LN0); 6689 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6690 PtrType, LN0->getBasePtr(), 6691 DAG.getConstant(PtrOff, DL, PtrType)); 6692 AddToWorklist(NewPtr.getNode()); 6693 6694 SDValue Load; 6695 if (ExtType == ISD::NON_EXTLOAD) 6696 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6697 LN0->getPointerInfo().getWithOffset(PtrOff), 6698 LN0->isVolatile(), LN0->isNonTemporal(), 6699 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6700 else 6701 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6702 LN0->getPointerInfo().getWithOffset(PtrOff), 6703 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6704 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6705 6706 // Replace the old load's chain with the new load's chain. 6707 WorklistRemover DeadNodes(*this); 6708 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6709 6710 // Shift the result left, if we've swallowed a left shift. 6711 SDValue Result = Load; 6712 if (ShLeftAmt != 0) { 6713 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6714 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6715 ShImmTy = VT; 6716 // If the shift amount is as large as the result size (but, presumably, 6717 // no larger than the source) then the useful bits of the result are 6718 // zero; we can't simply return the shortened shift, because the result 6719 // of that operation is undefined. 6720 SDLoc DL(N0); 6721 if (ShLeftAmt >= VT.getSizeInBits()) 6722 Result = DAG.getConstant(0, DL, VT); 6723 else 6724 Result = DAG.getNode(ISD::SHL, DL, VT, 6725 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6726 } 6727 6728 // Return the new loaded value. 6729 return Result; 6730 } 6731 6732 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6733 SDValue N0 = N->getOperand(0); 6734 SDValue N1 = N->getOperand(1); 6735 EVT VT = N->getValueType(0); 6736 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6737 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6738 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6739 6740 // fold (sext_in_reg c1) -> c1 6741 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6742 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6743 6744 // If the input is already sign extended, just drop the extension. 6745 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6746 return N0; 6747 6748 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6749 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6750 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6751 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6752 N0.getOperand(0), N1); 6753 6754 // fold (sext_in_reg (sext x)) -> (sext x) 6755 // fold (sext_in_reg (aext x)) -> (sext x) 6756 // if x is small enough. 6757 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6758 SDValue N00 = N0.getOperand(0); 6759 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6760 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6761 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6762 } 6763 6764 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6765 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6766 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6767 6768 // fold operands of sext_in_reg based on knowledge that the top bits are not 6769 // demanded. 6770 if (SimplifyDemandedBits(SDValue(N, 0))) 6771 return SDValue(N, 0); 6772 6773 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6774 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6775 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6776 return NarrowLoad; 6777 6778 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6779 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6780 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6781 if (N0.getOpcode() == ISD::SRL) { 6782 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6783 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6784 // We can turn this into an SRA iff the input to the SRL is already sign 6785 // extended enough. 6786 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6787 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6788 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6789 N0.getOperand(0), N0.getOperand(1)); 6790 } 6791 } 6792 6793 // fold (sext_inreg (extload x)) -> (sextload x) 6794 if (ISD::isEXTLoad(N0.getNode()) && 6795 ISD::isUNINDEXEDLoad(N0.getNode()) && 6796 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6797 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6798 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6799 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6800 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6801 LN0->getChain(), 6802 LN0->getBasePtr(), EVT, 6803 LN0->getMemOperand()); 6804 CombineTo(N, ExtLoad); 6805 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6806 AddToWorklist(ExtLoad.getNode()); 6807 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6808 } 6809 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6810 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6811 N0.hasOneUse() && 6812 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6813 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6814 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6815 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6816 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6817 LN0->getChain(), 6818 LN0->getBasePtr(), EVT, 6819 LN0->getMemOperand()); 6820 CombineTo(N, ExtLoad); 6821 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6822 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6823 } 6824 6825 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6826 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6827 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6828 N0.getOperand(1), false); 6829 if (BSwap.getNode()) 6830 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6831 BSwap, N1); 6832 } 6833 6834 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6835 // into a build_vector. 6836 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6837 SmallVector<SDValue, 8> Elts; 6838 unsigned NumElts = N0->getNumOperands(); 6839 unsigned ShAmt = VTBits - EVTBits; 6840 6841 for (unsigned i = 0; i != NumElts; ++i) { 6842 SDValue Op = N0->getOperand(i); 6843 if (Op->getOpcode() == ISD::UNDEF) { 6844 Elts.push_back(Op); 6845 continue; 6846 } 6847 6848 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6849 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6850 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6851 SDLoc(Op), Op.getValueType())); 6852 } 6853 6854 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6855 } 6856 6857 return SDValue(); 6858 } 6859 6860 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 6861 SDValue N0 = N->getOperand(0); 6862 EVT VT = N->getValueType(0); 6863 6864 if (N0.getOpcode() == ISD::UNDEF) 6865 return DAG.getUNDEF(VT); 6866 6867 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6868 LegalOperations)) 6869 return SDValue(Res, 0); 6870 6871 return SDValue(); 6872 } 6873 6874 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6875 SDValue N0 = N->getOperand(0); 6876 EVT VT = N->getValueType(0); 6877 bool isLE = DAG.getDataLayout().isLittleEndian(); 6878 6879 // noop truncate 6880 if (N0.getValueType() == N->getValueType(0)) 6881 return N0; 6882 // fold (truncate c1) -> c1 6883 if (isConstantIntBuildVectorOrConstantInt(N0)) 6884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6885 // fold (truncate (truncate x)) -> (truncate x) 6886 if (N0.getOpcode() == ISD::TRUNCATE) 6887 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6888 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6889 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6890 N0.getOpcode() == ISD::SIGN_EXTEND || 6891 N0.getOpcode() == ISD::ANY_EXTEND) { 6892 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6893 // if the source is smaller than the dest, we still need an extend 6894 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6895 N0.getOperand(0)); 6896 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6897 // if the source is larger than the dest, than we just need the truncate 6898 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6899 // if the source and dest are the same type, we can drop both the extend 6900 // and the truncate. 6901 return N0.getOperand(0); 6902 } 6903 6904 // Fold extract-and-trunc into a narrow extract. For example: 6905 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6906 // i32 y = TRUNCATE(i64 x) 6907 // -- becomes -- 6908 // v16i8 b = BITCAST (v2i64 val) 6909 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6910 // 6911 // Note: We only run this optimization after type legalization (which often 6912 // creates this pattern) and before operation legalization after which 6913 // we need to be more careful about the vector instructions that we generate. 6914 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6915 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6916 6917 EVT VecTy = N0.getOperand(0).getValueType(); 6918 EVT ExTy = N0.getValueType(); 6919 EVT TrTy = N->getValueType(0); 6920 6921 unsigned NumElem = VecTy.getVectorNumElements(); 6922 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6923 6924 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6925 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6926 6927 SDValue EltNo = N0->getOperand(1); 6928 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6929 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6930 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 6931 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6932 6933 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6934 NVT, N0.getOperand(0)); 6935 6936 SDLoc DL(N); 6937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6938 DL, TrTy, V, 6939 DAG.getConstant(Index, DL, IndexTy)); 6940 } 6941 } 6942 6943 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6944 if (N0.getOpcode() == ISD::SELECT) { 6945 EVT SrcVT = N0.getValueType(); 6946 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6947 TLI.isTruncateFree(SrcVT, VT)) { 6948 SDLoc SL(N0); 6949 SDValue Cond = N0.getOperand(0); 6950 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6951 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6952 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6953 } 6954 } 6955 6956 // Fold a series of buildvector, bitcast, and truncate if possible. 6957 // For example fold 6958 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6959 // (2xi32 (buildvector x, y)). 6960 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6961 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6962 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6963 N0.getOperand(0).hasOneUse()) { 6964 6965 SDValue BuildVect = N0.getOperand(0); 6966 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6967 EVT TruncVecEltTy = VT.getVectorElementType(); 6968 6969 // Check that the element types match. 6970 if (BuildVectEltTy == TruncVecEltTy) { 6971 // Now we only need to compute the offset of the truncated elements. 6972 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6973 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6974 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6975 6976 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6977 "Invalid number of elements"); 6978 6979 SmallVector<SDValue, 8> Opnds; 6980 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6981 Opnds.push_back(BuildVect.getOperand(i)); 6982 6983 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6984 } 6985 } 6986 6987 // See if we can simplify the input to this truncate through knowledge that 6988 // only the low bits are being used. 6989 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6990 // Currently we only perform this optimization on scalars because vectors 6991 // may have different active low bits. 6992 if (!VT.isVector()) { 6993 SDValue Shorter = 6994 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6995 VT.getSizeInBits())); 6996 if (Shorter.getNode()) 6997 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6998 } 6999 // fold (truncate (load x)) -> (smaller load x) 7000 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7001 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7002 if (SDValue Reduced = ReduceLoadWidth(N)) 7003 return Reduced; 7004 7005 // Handle the case where the load remains an extending load even 7006 // after truncation. 7007 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7008 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7009 if (!LN0->isVolatile() && 7010 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7011 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7012 VT, LN0->getChain(), LN0->getBasePtr(), 7013 LN0->getMemoryVT(), 7014 LN0->getMemOperand()); 7015 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7016 return NewLoad; 7017 } 7018 } 7019 } 7020 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7021 // where ... are all 'undef'. 7022 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7023 SmallVector<EVT, 8> VTs; 7024 SDValue V; 7025 unsigned Idx = 0; 7026 unsigned NumDefs = 0; 7027 7028 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7029 SDValue X = N0.getOperand(i); 7030 if (X.getOpcode() != ISD::UNDEF) { 7031 V = X; 7032 Idx = i; 7033 NumDefs++; 7034 } 7035 // Stop if more than one members are non-undef. 7036 if (NumDefs > 1) 7037 break; 7038 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7039 VT.getVectorElementType(), 7040 X.getValueType().getVectorNumElements())); 7041 } 7042 7043 if (NumDefs == 0) 7044 return DAG.getUNDEF(VT); 7045 7046 if (NumDefs == 1) { 7047 assert(V.getNode() && "The single defined operand is empty!"); 7048 SmallVector<SDValue, 8> Opnds; 7049 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7050 if (i != Idx) { 7051 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7052 continue; 7053 } 7054 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7055 AddToWorklist(NV.getNode()); 7056 Opnds.push_back(NV); 7057 } 7058 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7059 } 7060 } 7061 7062 // Simplify the operands using demanded-bits information. 7063 if (!VT.isVector() && 7064 SimplifyDemandedBits(SDValue(N, 0))) 7065 return SDValue(N, 0); 7066 7067 return SDValue(); 7068 } 7069 7070 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7071 SDValue Elt = N->getOperand(i); 7072 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7073 return Elt.getNode(); 7074 return Elt.getOperand(Elt.getResNo()).getNode(); 7075 } 7076 7077 /// build_pair (load, load) -> load 7078 /// if load locations are consecutive. 7079 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7080 assert(N->getOpcode() == ISD::BUILD_PAIR); 7081 7082 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7083 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7084 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7085 LD1->getAddressSpace() != LD2->getAddressSpace()) 7086 return SDValue(); 7087 EVT LD1VT = LD1->getValueType(0); 7088 7089 if (ISD::isNON_EXTLoad(LD2) && 7090 LD2->hasOneUse() && 7091 // If both are volatile this would reduce the number of volatile loads. 7092 // If one is volatile it might be ok, but play conservative and bail out. 7093 !LD1->isVolatile() && 7094 !LD2->isVolatile() && 7095 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7096 unsigned Align = LD1->getAlignment(); 7097 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7098 VT.getTypeForEVT(*DAG.getContext())); 7099 7100 if (NewAlign <= Align && 7101 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7102 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7103 LD1->getBasePtr(), LD1->getPointerInfo(), 7104 false, false, false, Align); 7105 } 7106 7107 return SDValue(); 7108 } 7109 7110 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7111 SDValue N0 = N->getOperand(0); 7112 EVT VT = N->getValueType(0); 7113 7114 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7115 // Only do this before legalize, since afterward the target may be depending 7116 // on the bitconvert. 7117 // First check to see if this is all constant. 7118 if (!LegalTypes && 7119 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7120 VT.isVector()) { 7121 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7122 7123 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7124 assert(!DestEltVT.isVector() && 7125 "Element type of vector ValueType must not be vector!"); 7126 if (isSimple) 7127 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7128 } 7129 7130 // If the input is a constant, let getNode fold it. 7131 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7132 // If we can't allow illegal operations, we need to check that this is just 7133 // a fp -> int or int -> conversion and that the resulting operation will 7134 // be legal. 7135 if (!LegalOperations || 7136 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7137 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7138 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7139 TLI.isOperationLegal(ISD::Constant, VT))) 7140 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7141 } 7142 7143 // (conv (conv x, t1), t2) -> (conv x, t2) 7144 if (N0.getOpcode() == ISD::BITCAST) 7145 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7146 N0.getOperand(0)); 7147 7148 // fold (conv (load x)) -> (load (conv*)x) 7149 // If the resultant load doesn't need a higher alignment than the original! 7150 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7151 // Do not change the width of a volatile load. 7152 !cast<LoadSDNode>(N0)->isVolatile() && 7153 // Do not remove the cast if the types differ in endian layout. 7154 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7155 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7156 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7157 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7158 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7159 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7160 VT.getTypeForEVT(*DAG.getContext())); 7161 unsigned OrigAlign = LN0->getAlignment(); 7162 7163 if (Align <= OrigAlign) { 7164 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7165 LN0->getBasePtr(), LN0->getPointerInfo(), 7166 LN0->isVolatile(), LN0->isNonTemporal(), 7167 LN0->isInvariant(), OrigAlign, 7168 LN0->getAAInfo()); 7169 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7170 return Load; 7171 } 7172 } 7173 7174 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7175 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7176 // This often reduces constant pool loads. 7177 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7178 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7179 N0.getNode()->hasOneUse() && VT.isInteger() && 7180 !VT.isVector() && !N0.getValueType().isVector()) { 7181 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7182 N0.getOperand(0)); 7183 AddToWorklist(NewConv.getNode()); 7184 7185 SDLoc DL(N); 7186 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7187 if (N0.getOpcode() == ISD::FNEG) 7188 return DAG.getNode(ISD::XOR, DL, VT, 7189 NewConv, DAG.getConstant(SignBit, DL, VT)); 7190 assert(N0.getOpcode() == ISD::FABS); 7191 return DAG.getNode(ISD::AND, DL, VT, 7192 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7193 } 7194 7195 // fold (bitconvert (fcopysign cst, x)) -> 7196 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7197 // Note that we don't handle (copysign x, cst) because this can always be 7198 // folded to an fneg or fabs. 7199 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7200 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7201 VT.isInteger() && !VT.isVector()) { 7202 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7203 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7204 if (isTypeLegal(IntXVT)) { 7205 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7206 IntXVT, N0.getOperand(1)); 7207 AddToWorklist(X.getNode()); 7208 7209 // If X has a different width than the result/lhs, sext it or truncate it. 7210 unsigned VTWidth = VT.getSizeInBits(); 7211 if (OrigXWidth < VTWidth) { 7212 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7213 AddToWorklist(X.getNode()); 7214 } else if (OrigXWidth > VTWidth) { 7215 // To get the sign bit in the right place, we have to shift it right 7216 // before truncating. 7217 SDLoc DL(X); 7218 X = DAG.getNode(ISD::SRL, DL, 7219 X.getValueType(), X, 7220 DAG.getConstant(OrigXWidth-VTWidth, DL, 7221 X.getValueType())); 7222 AddToWorklist(X.getNode()); 7223 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7224 AddToWorklist(X.getNode()); 7225 } 7226 7227 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7228 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7229 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7230 AddToWorklist(X.getNode()); 7231 7232 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7233 VT, N0.getOperand(0)); 7234 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7235 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7236 AddToWorklist(Cst.getNode()); 7237 7238 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7239 } 7240 } 7241 7242 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7243 if (N0.getOpcode() == ISD::BUILD_PAIR) 7244 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7245 return CombineLD; 7246 7247 // Remove double bitcasts from shuffles - this is often a legacy of 7248 // XformToShuffleWithZero being used to combine bitmaskings (of 7249 // float vectors bitcast to integer vectors) into shuffles. 7250 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7251 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7252 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7253 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7254 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7255 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7256 7257 // If operands are a bitcast, peek through if it casts the original VT. 7258 // If operands are a constant, just bitcast back to original VT. 7259 auto PeekThroughBitcast = [&](SDValue Op) { 7260 if (Op.getOpcode() == ISD::BITCAST && 7261 Op.getOperand(0).getValueType() == VT) 7262 return SDValue(Op.getOperand(0)); 7263 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7264 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7265 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7266 return SDValue(); 7267 }; 7268 7269 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7270 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7271 if (!(SV0 && SV1)) 7272 return SDValue(); 7273 7274 int MaskScale = 7275 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7276 SmallVector<int, 8> NewMask; 7277 for (int M : SVN->getMask()) 7278 for (int i = 0; i != MaskScale; ++i) 7279 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7280 7281 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7282 if (!LegalMask) { 7283 std::swap(SV0, SV1); 7284 ShuffleVectorSDNode::commuteMask(NewMask); 7285 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7286 } 7287 7288 if (LegalMask) 7289 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7290 } 7291 7292 return SDValue(); 7293 } 7294 7295 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7296 EVT VT = N->getValueType(0); 7297 return CombineConsecutiveLoads(N, VT); 7298 } 7299 7300 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7301 /// operands. DstEltVT indicates the destination element value type. 7302 SDValue DAGCombiner:: 7303 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7304 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7305 7306 // If this is already the right type, we're done. 7307 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7308 7309 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7310 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7311 7312 // If this is a conversion of N elements of one type to N elements of another 7313 // type, convert each element. This handles FP<->INT cases. 7314 if (SrcBitSize == DstBitSize) { 7315 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7316 BV->getValueType(0).getVectorNumElements()); 7317 7318 // Due to the FP element handling below calling this routine recursively, 7319 // we can end up with a scalar-to-vector node here. 7320 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7321 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7322 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7323 DstEltVT, BV->getOperand(0))); 7324 7325 SmallVector<SDValue, 8> Ops; 7326 for (SDValue Op : BV->op_values()) { 7327 // If the vector element type is not legal, the BUILD_VECTOR operands 7328 // are promoted and implicitly truncated. Make that explicit here. 7329 if (Op.getValueType() != SrcEltVT) 7330 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7331 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7332 DstEltVT, Op)); 7333 AddToWorklist(Ops.back().getNode()); 7334 } 7335 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7336 } 7337 7338 // Otherwise, we're growing or shrinking the elements. To avoid having to 7339 // handle annoying details of growing/shrinking FP values, we convert them to 7340 // int first. 7341 if (SrcEltVT.isFloatingPoint()) { 7342 // Convert the input float vector to a int vector where the elements are the 7343 // same sizes. 7344 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7345 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7346 SrcEltVT = IntVT; 7347 } 7348 7349 // Now we know the input is an integer vector. If the output is a FP type, 7350 // convert to integer first, then to FP of the right size. 7351 if (DstEltVT.isFloatingPoint()) { 7352 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7353 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7354 7355 // Next, convert to FP elements of the same size. 7356 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7357 } 7358 7359 SDLoc DL(BV); 7360 7361 // Okay, we know the src/dst types are both integers of differing types. 7362 // Handling growing first. 7363 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7364 if (SrcBitSize < DstBitSize) { 7365 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7366 7367 SmallVector<SDValue, 8> Ops; 7368 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7369 i += NumInputsPerOutput) { 7370 bool isLE = DAG.getDataLayout().isLittleEndian(); 7371 APInt NewBits = APInt(DstBitSize, 0); 7372 bool EltIsUndef = true; 7373 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7374 // Shift the previously computed bits over. 7375 NewBits <<= SrcBitSize; 7376 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7377 if (Op.getOpcode() == ISD::UNDEF) continue; 7378 EltIsUndef = false; 7379 7380 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7381 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7382 } 7383 7384 if (EltIsUndef) 7385 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7386 else 7387 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7388 } 7389 7390 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7391 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7392 } 7393 7394 // Finally, this must be the case where we are shrinking elements: each input 7395 // turns into multiple outputs. 7396 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7397 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7398 NumOutputsPerInput*BV->getNumOperands()); 7399 SmallVector<SDValue, 8> Ops; 7400 7401 for (const SDValue &Op : BV->op_values()) { 7402 if (Op.getOpcode() == ISD::UNDEF) { 7403 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7404 continue; 7405 } 7406 7407 APInt OpVal = cast<ConstantSDNode>(Op)-> 7408 getAPIntValue().zextOrTrunc(SrcBitSize); 7409 7410 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7411 APInt ThisVal = OpVal.trunc(DstBitSize); 7412 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7413 OpVal = OpVal.lshr(DstBitSize); 7414 } 7415 7416 // For big endian targets, swap the order of the pieces of each element. 7417 if (DAG.getDataLayout().isBigEndian()) 7418 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7419 } 7420 7421 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7422 } 7423 7424 /// Try to perform FMA combining on a given FADD node. 7425 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7426 SDValue N0 = N->getOperand(0); 7427 SDValue N1 = N->getOperand(1); 7428 EVT VT = N->getValueType(0); 7429 SDLoc SL(N); 7430 7431 const TargetOptions &Options = DAG.getTarget().Options; 7432 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7433 Options.UnsafeFPMath); 7434 7435 // Floating-point multiply-add with intermediate rounding. 7436 bool HasFMAD = (LegalOperations && 7437 TLI.isOperationLegal(ISD::FMAD, VT)); 7438 7439 // Floating-point multiply-add without intermediate rounding. 7440 bool HasFMA = ((!LegalOperations || 7441 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7442 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7443 UnsafeFPMath); 7444 7445 // No valid opcode, do not combine. 7446 if (!HasFMAD && !HasFMA) 7447 return SDValue(); 7448 7449 // Always prefer FMAD to FMA for precision. 7450 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7451 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7452 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7453 7454 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7455 // prefer to fold the multiply with fewer uses. 7456 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7457 N1.getOpcode() == ISD::FMUL) { 7458 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7459 std::swap(N0, N1); 7460 } 7461 7462 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7463 if (N0.getOpcode() == ISD::FMUL && 7464 (Aggressive || N0->hasOneUse())) { 7465 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7466 N0.getOperand(0), N0.getOperand(1), N1); 7467 } 7468 7469 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7470 // Note: Commutes FADD operands. 7471 if (N1.getOpcode() == ISD::FMUL && 7472 (Aggressive || N1->hasOneUse())) { 7473 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7474 N1.getOperand(0), N1.getOperand(1), N0); 7475 } 7476 7477 // Look through FP_EXTEND nodes to do more combining. 7478 if (UnsafeFPMath && LookThroughFPExt) { 7479 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7480 if (N0.getOpcode() == ISD::FP_EXTEND) { 7481 SDValue N00 = N0.getOperand(0); 7482 if (N00.getOpcode() == ISD::FMUL) 7483 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7484 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7485 N00.getOperand(0)), 7486 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7487 N00.getOperand(1)), N1); 7488 } 7489 7490 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7491 // Note: Commutes FADD operands. 7492 if (N1.getOpcode() == ISD::FP_EXTEND) { 7493 SDValue N10 = N1.getOperand(0); 7494 if (N10.getOpcode() == ISD::FMUL) 7495 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7496 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7497 N10.getOperand(0)), 7498 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7499 N10.getOperand(1)), N0); 7500 } 7501 } 7502 7503 // More folding opportunities when target permits. 7504 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7505 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7506 if (N0.getOpcode() == PreferredFusedOpcode && 7507 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7508 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7509 N0.getOperand(0), N0.getOperand(1), 7510 DAG.getNode(PreferredFusedOpcode, SL, VT, 7511 N0.getOperand(2).getOperand(0), 7512 N0.getOperand(2).getOperand(1), 7513 N1)); 7514 } 7515 7516 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7517 if (N1->getOpcode() == PreferredFusedOpcode && 7518 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7519 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7520 N1.getOperand(0), N1.getOperand(1), 7521 DAG.getNode(PreferredFusedOpcode, SL, VT, 7522 N1.getOperand(2).getOperand(0), 7523 N1.getOperand(2).getOperand(1), 7524 N0)); 7525 } 7526 7527 if (UnsafeFPMath && LookThroughFPExt) { 7528 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7529 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7530 auto FoldFAddFMAFPExtFMul = [&] ( 7531 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7532 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7533 DAG.getNode(PreferredFusedOpcode, SL, VT, 7534 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7535 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7536 Z)); 7537 }; 7538 if (N0.getOpcode() == PreferredFusedOpcode) { 7539 SDValue N02 = N0.getOperand(2); 7540 if (N02.getOpcode() == ISD::FP_EXTEND) { 7541 SDValue N020 = N02.getOperand(0); 7542 if (N020.getOpcode() == ISD::FMUL) 7543 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7544 N020.getOperand(0), N020.getOperand(1), 7545 N1); 7546 } 7547 } 7548 7549 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7550 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7551 // FIXME: This turns two single-precision and one double-precision 7552 // operation into two double-precision operations, which might not be 7553 // interesting for all targets, especially GPUs. 7554 auto FoldFAddFPExtFMAFMul = [&] ( 7555 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7556 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7557 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7558 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7559 DAG.getNode(PreferredFusedOpcode, SL, VT, 7560 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7561 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7562 Z)); 7563 }; 7564 if (N0.getOpcode() == ISD::FP_EXTEND) { 7565 SDValue N00 = N0.getOperand(0); 7566 if (N00.getOpcode() == PreferredFusedOpcode) { 7567 SDValue N002 = N00.getOperand(2); 7568 if (N002.getOpcode() == ISD::FMUL) 7569 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7570 N002.getOperand(0), N002.getOperand(1), 7571 N1); 7572 } 7573 } 7574 7575 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7576 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7577 if (N1.getOpcode() == PreferredFusedOpcode) { 7578 SDValue N12 = N1.getOperand(2); 7579 if (N12.getOpcode() == ISD::FP_EXTEND) { 7580 SDValue N120 = N12.getOperand(0); 7581 if (N120.getOpcode() == ISD::FMUL) 7582 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7583 N120.getOperand(0), N120.getOperand(1), 7584 N0); 7585 } 7586 } 7587 7588 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7589 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7590 // FIXME: This turns two single-precision and one double-precision 7591 // operation into two double-precision operations, which might not be 7592 // interesting for all targets, especially GPUs. 7593 if (N1.getOpcode() == ISD::FP_EXTEND) { 7594 SDValue N10 = N1.getOperand(0); 7595 if (N10.getOpcode() == PreferredFusedOpcode) { 7596 SDValue N102 = N10.getOperand(2); 7597 if (N102.getOpcode() == ISD::FMUL) 7598 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7599 N102.getOperand(0), N102.getOperand(1), 7600 N0); 7601 } 7602 } 7603 } 7604 } 7605 7606 return SDValue(); 7607 } 7608 7609 /// Try to perform FMA combining on a given FSUB node. 7610 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7611 SDValue N0 = N->getOperand(0); 7612 SDValue N1 = N->getOperand(1); 7613 EVT VT = N->getValueType(0); 7614 SDLoc SL(N); 7615 7616 const TargetOptions &Options = DAG.getTarget().Options; 7617 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7618 Options.UnsafeFPMath); 7619 7620 // Floating-point multiply-add with intermediate rounding. 7621 bool HasFMAD = (LegalOperations && 7622 TLI.isOperationLegal(ISD::FMAD, VT)); 7623 7624 // Floating-point multiply-add without intermediate rounding. 7625 bool HasFMA = ((!LegalOperations || 7626 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7627 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7628 UnsafeFPMath); 7629 7630 // No valid opcode, do not combine. 7631 if (!HasFMAD && !HasFMA) 7632 return SDValue(); 7633 7634 // Always prefer FMAD to FMA for precision. 7635 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7636 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7637 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7638 7639 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7640 if (N0.getOpcode() == ISD::FMUL && 7641 (Aggressive || N0->hasOneUse())) { 7642 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7643 N0.getOperand(0), N0.getOperand(1), 7644 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7645 } 7646 7647 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7648 // Note: Commutes FSUB operands. 7649 if (N1.getOpcode() == ISD::FMUL && 7650 (Aggressive || N1->hasOneUse())) 7651 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7652 DAG.getNode(ISD::FNEG, SL, VT, 7653 N1.getOperand(0)), 7654 N1.getOperand(1), N0); 7655 7656 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7657 if (N0.getOpcode() == ISD::FNEG && 7658 N0.getOperand(0).getOpcode() == ISD::FMUL && 7659 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7660 SDValue N00 = N0.getOperand(0).getOperand(0); 7661 SDValue N01 = N0.getOperand(0).getOperand(1); 7662 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7663 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7664 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7665 } 7666 7667 // Look through FP_EXTEND nodes to do more combining. 7668 if (UnsafeFPMath && LookThroughFPExt) { 7669 // fold (fsub (fpext (fmul x, y)), z) 7670 // -> (fma (fpext x), (fpext y), (fneg z)) 7671 if (N0.getOpcode() == ISD::FP_EXTEND) { 7672 SDValue N00 = N0.getOperand(0); 7673 if (N00.getOpcode() == ISD::FMUL) 7674 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7675 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7676 N00.getOperand(0)), 7677 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7678 N00.getOperand(1)), 7679 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7680 } 7681 7682 // fold (fsub x, (fpext (fmul y, z))) 7683 // -> (fma (fneg (fpext y)), (fpext z), x) 7684 // Note: Commutes FSUB operands. 7685 if (N1.getOpcode() == ISD::FP_EXTEND) { 7686 SDValue N10 = N1.getOperand(0); 7687 if (N10.getOpcode() == ISD::FMUL) 7688 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7689 DAG.getNode(ISD::FNEG, SL, VT, 7690 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7691 N10.getOperand(0))), 7692 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7693 N10.getOperand(1)), 7694 N0); 7695 } 7696 7697 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7698 // -> (fneg (fma (fpext x), (fpext y), z)) 7699 // Note: This could be removed with appropriate canonicalization of the 7700 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7701 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7702 // from implementing the canonicalization in visitFSUB. 7703 if (N0.getOpcode() == ISD::FP_EXTEND) { 7704 SDValue N00 = N0.getOperand(0); 7705 if (N00.getOpcode() == ISD::FNEG) { 7706 SDValue N000 = N00.getOperand(0); 7707 if (N000.getOpcode() == ISD::FMUL) { 7708 return DAG.getNode(ISD::FNEG, SL, VT, 7709 DAG.getNode(PreferredFusedOpcode, SL, VT, 7710 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7711 N000.getOperand(0)), 7712 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7713 N000.getOperand(1)), 7714 N1)); 7715 } 7716 } 7717 } 7718 7719 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7720 // -> (fneg (fma (fpext x)), (fpext y), z) 7721 // Note: This could be removed with appropriate canonicalization of the 7722 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7723 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7724 // from implementing the canonicalization in visitFSUB. 7725 if (N0.getOpcode() == ISD::FNEG) { 7726 SDValue N00 = N0.getOperand(0); 7727 if (N00.getOpcode() == ISD::FP_EXTEND) { 7728 SDValue N000 = N00.getOperand(0); 7729 if (N000.getOpcode() == ISD::FMUL) { 7730 return DAG.getNode(ISD::FNEG, SL, VT, 7731 DAG.getNode(PreferredFusedOpcode, SL, VT, 7732 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7733 N000.getOperand(0)), 7734 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7735 N000.getOperand(1)), 7736 N1)); 7737 } 7738 } 7739 } 7740 7741 } 7742 7743 // More folding opportunities when target permits. 7744 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7745 // fold (fsub (fma x, y, (fmul u, v)), z) 7746 // -> (fma x, y (fma u, v, (fneg z))) 7747 if (N0.getOpcode() == PreferredFusedOpcode && 7748 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7749 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7750 N0.getOperand(0), N0.getOperand(1), 7751 DAG.getNode(PreferredFusedOpcode, SL, VT, 7752 N0.getOperand(2).getOperand(0), 7753 N0.getOperand(2).getOperand(1), 7754 DAG.getNode(ISD::FNEG, SL, VT, 7755 N1))); 7756 } 7757 7758 // fold (fsub x, (fma y, z, (fmul u, v))) 7759 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7760 if (N1.getOpcode() == PreferredFusedOpcode && 7761 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7762 SDValue N20 = N1.getOperand(2).getOperand(0); 7763 SDValue N21 = N1.getOperand(2).getOperand(1); 7764 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7765 DAG.getNode(ISD::FNEG, SL, VT, 7766 N1.getOperand(0)), 7767 N1.getOperand(1), 7768 DAG.getNode(PreferredFusedOpcode, SL, VT, 7769 DAG.getNode(ISD::FNEG, SL, VT, N20), 7770 7771 N21, N0)); 7772 } 7773 7774 if (UnsafeFPMath && LookThroughFPExt) { 7775 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7776 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7777 if (N0.getOpcode() == PreferredFusedOpcode) { 7778 SDValue N02 = N0.getOperand(2); 7779 if (N02.getOpcode() == ISD::FP_EXTEND) { 7780 SDValue N020 = N02.getOperand(0); 7781 if (N020.getOpcode() == ISD::FMUL) 7782 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7783 N0.getOperand(0), N0.getOperand(1), 7784 DAG.getNode(PreferredFusedOpcode, SL, VT, 7785 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7786 N020.getOperand(0)), 7787 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7788 N020.getOperand(1)), 7789 DAG.getNode(ISD::FNEG, SL, VT, 7790 N1))); 7791 } 7792 } 7793 7794 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7795 // -> (fma (fpext x), (fpext y), 7796 // (fma (fpext u), (fpext v), (fneg z))) 7797 // FIXME: This turns two single-precision and one double-precision 7798 // operation into two double-precision operations, which might not be 7799 // interesting for all targets, especially GPUs. 7800 if (N0.getOpcode() == ISD::FP_EXTEND) { 7801 SDValue N00 = N0.getOperand(0); 7802 if (N00.getOpcode() == PreferredFusedOpcode) { 7803 SDValue N002 = N00.getOperand(2); 7804 if (N002.getOpcode() == ISD::FMUL) 7805 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7806 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7807 N00.getOperand(0)), 7808 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7809 N00.getOperand(1)), 7810 DAG.getNode(PreferredFusedOpcode, SL, VT, 7811 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7812 N002.getOperand(0)), 7813 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7814 N002.getOperand(1)), 7815 DAG.getNode(ISD::FNEG, SL, VT, 7816 N1))); 7817 } 7818 } 7819 7820 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7821 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7822 if (N1.getOpcode() == PreferredFusedOpcode && 7823 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7824 SDValue N120 = N1.getOperand(2).getOperand(0); 7825 if (N120.getOpcode() == ISD::FMUL) { 7826 SDValue N1200 = N120.getOperand(0); 7827 SDValue N1201 = N120.getOperand(1); 7828 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7829 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7830 N1.getOperand(1), 7831 DAG.getNode(PreferredFusedOpcode, SL, VT, 7832 DAG.getNode(ISD::FNEG, SL, VT, 7833 DAG.getNode(ISD::FP_EXTEND, SL, 7834 VT, N1200)), 7835 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7836 N1201), 7837 N0)); 7838 } 7839 } 7840 7841 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7842 // -> (fma (fneg (fpext y)), (fpext z), 7843 // (fma (fneg (fpext u)), (fpext v), x)) 7844 // FIXME: This turns two single-precision and one double-precision 7845 // operation into two double-precision operations, which might not be 7846 // interesting for all targets, especially GPUs. 7847 if (N1.getOpcode() == ISD::FP_EXTEND && 7848 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 7849 SDValue N100 = N1.getOperand(0).getOperand(0); 7850 SDValue N101 = N1.getOperand(0).getOperand(1); 7851 SDValue N102 = N1.getOperand(0).getOperand(2); 7852 if (N102.getOpcode() == ISD::FMUL) { 7853 SDValue N1020 = N102.getOperand(0); 7854 SDValue N1021 = N102.getOperand(1); 7855 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7856 DAG.getNode(ISD::FNEG, SL, VT, 7857 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7858 N100)), 7859 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 7860 DAG.getNode(PreferredFusedOpcode, SL, VT, 7861 DAG.getNode(ISD::FNEG, SL, VT, 7862 DAG.getNode(ISD::FP_EXTEND, SL, 7863 VT, N1020)), 7864 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7865 N1021), 7866 N0)); 7867 } 7868 } 7869 } 7870 } 7871 7872 return SDValue(); 7873 } 7874 7875 SDValue DAGCombiner::visitFADD(SDNode *N) { 7876 SDValue N0 = N->getOperand(0); 7877 SDValue N1 = N->getOperand(1); 7878 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7879 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7880 EVT VT = N->getValueType(0); 7881 SDLoc DL(N); 7882 const TargetOptions &Options = DAG.getTarget().Options; 7883 7884 // fold vector ops 7885 if (VT.isVector()) 7886 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7887 return FoldedVOp; 7888 7889 // fold (fadd c1, c2) -> c1 + c2 7890 if (N0CFP && N1CFP) 7891 return DAG.getNode(ISD::FADD, DL, VT, N0, N1); 7892 7893 // canonicalize constant to RHS 7894 if (N0CFP && !N1CFP) 7895 return DAG.getNode(ISD::FADD, DL, VT, N1, N0); 7896 7897 // fold (fadd A, (fneg B)) -> (fsub A, B) 7898 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7899 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 7900 return DAG.getNode(ISD::FSUB, DL, VT, N0, 7901 GetNegatedExpression(N1, DAG, LegalOperations)); 7902 7903 // fold (fadd (fneg A), B) -> (fsub B, A) 7904 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7905 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 7906 return DAG.getNode(ISD::FSUB, DL, VT, N1, 7907 GetNegatedExpression(N0, DAG, LegalOperations)); 7908 7909 // If 'unsafe math' is enabled, fold lots of things. 7910 if (Options.UnsafeFPMath) { 7911 // No FP constant should be created after legalization as Instruction 7912 // Selection pass has a hard time dealing with FP constants. 7913 bool AllowNewConst = (Level < AfterLegalizeDAG); 7914 7915 // fold (fadd A, 0) -> A 7916 if (N1CFP && N1CFP->isZero()) 7917 return N0; 7918 7919 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 7920 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 7921 isa<ConstantFPSDNode>(N0.getOperand(1))) 7922 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 7923 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1)); 7924 7925 // If allowed, fold (fadd (fneg x), x) -> 0.0 7926 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 7927 return DAG.getConstantFP(0.0, DL, VT); 7928 7929 // If allowed, fold (fadd x, (fneg x)) -> 0.0 7930 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 7931 return DAG.getConstantFP(0.0, DL, VT); 7932 7933 // We can fold chains of FADD's of the same value into multiplications. 7934 // This transform is not safe in general because we are reducing the number 7935 // of rounding steps. 7936 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 7937 if (N0.getOpcode() == ISD::FMUL) { 7938 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7939 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7940 7941 // (fadd (fmul x, c), x) -> (fmul x, c+1) 7942 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 7943 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 7944 DAG.getConstantFP(1.0, DL, VT)); 7945 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP); 7946 } 7947 7948 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 7949 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 7950 N1.getOperand(0) == N1.getOperand(1) && 7951 N0.getOperand(0) == N1.getOperand(0)) { 7952 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 7953 DAG.getConstantFP(2.0, DL, VT)); 7954 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP); 7955 } 7956 } 7957 7958 if (N1.getOpcode() == ISD::FMUL) { 7959 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7960 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 7961 7962 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 7963 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 7964 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 7965 DAG.getConstantFP(1.0, DL, VT)); 7966 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP); 7967 } 7968 7969 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 7970 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 7971 N0.getOperand(0) == N0.getOperand(1) && 7972 N1.getOperand(0) == N0.getOperand(0)) { 7973 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 7974 DAG.getConstantFP(2.0, DL, VT)); 7975 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP); 7976 } 7977 } 7978 7979 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 7980 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7981 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 7982 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 7983 (N0.getOperand(0) == N1)) { 7984 return DAG.getNode(ISD::FMUL, DL, VT, 7985 N1, DAG.getConstantFP(3.0, DL, VT)); 7986 } 7987 } 7988 7989 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 7990 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7991 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 7992 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 7993 N1.getOperand(0) == N0) { 7994 return DAG.getNode(ISD::FMUL, DL, VT, 7995 N0, DAG.getConstantFP(3.0, DL, VT)); 7996 } 7997 } 7998 7999 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8000 if (AllowNewConst && 8001 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8002 N0.getOperand(0) == N0.getOperand(1) && 8003 N1.getOperand(0) == N1.getOperand(1) && 8004 N0.getOperand(0) == N1.getOperand(0)) { 8005 return DAG.getNode(ISD::FMUL, DL, VT, 8006 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT)); 8007 } 8008 } 8009 } // enable-unsafe-fp-math 8010 8011 // FADD -> FMA combines: 8012 if (SDValue Fused = visitFADDForFMACombine(N)) { 8013 AddToWorklist(Fused.getNode()); 8014 return Fused; 8015 } 8016 8017 return SDValue(); 8018 } 8019 8020 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8021 SDValue N0 = N->getOperand(0); 8022 SDValue N1 = N->getOperand(1); 8023 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8024 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8025 EVT VT = N->getValueType(0); 8026 SDLoc dl(N); 8027 const TargetOptions &Options = DAG.getTarget().Options; 8028 8029 // fold vector ops 8030 if (VT.isVector()) 8031 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8032 return FoldedVOp; 8033 8034 // fold (fsub c1, c2) -> c1-c2 8035 if (N0CFP && N1CFP) 8036 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1); 8037 8038 // fold (fsub A, (fneg B)) -> (fadd A, B) 8039 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8040 return DAG.getNode(ISD::FADD, dl, VT, N0, 8041 GetNegatedExpression(N1, DAG, LegalOperations)); 8042 8043 // If 'unsafe math' is enabled, fold lots of things. 8044 if (Options.UnsafeFPMath) { 8045 // (fsub A, 0) -> A 8046 if (N1CFP && N1CFP->isZero()) 8047 return N0; 8048 8049 // (fsub 0, B) -> -B 8050 if (N0CFP && N0CFP->isZero()) { 8051 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8052 return GetNegatedExpression(N1, DAG, LegalOperations); 8053 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8054 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8055 } 8056 8057 // (fsub x, x) -> 0.0 8058 if (N0 == N1) 8059 return DAG.getConstantFP(0.0f, dl, VT); 8060 8061 // (fsub x, (fadd x, y)) -> (fneg y) 8062 // (fsub x, (fadd y, x)) -> (fneg y) 8063 if (N1.getOpcode() == ISD::FADD) { 8064 SDValue N10 = N1->getOperand(0); 8065 SDValue N11 = N1->getOperand(1); 8066 8067 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8068 return GetNegatedExpression(N11, DAG, LegalOperations); 8069 8070 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8071 return GetNegatedExpression(N10, DAG, LegalOperations); 8072 } 8073 } 8074 8075 // FSUB -> FMA combines: 8076 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8077 AddToWorklist(Fused.getNode()); 8078 return Fused; 8079 } 8080 8081 return SDValue(); 8082 } 8083 8084 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8085 SDValue N0 = N->getOperand(0); 8086 SDValue N1 = N->getOperand(1); 8087 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8088 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8089 EVT VT = N->getValueType(0); 8090 SDLoc DL(N); 8091 const TargetOptions &Options = DAG.getTarget().Options; 8092 8093 // fold vector ops 8094 if (VT.isVector()) { 8095 // This just handles C1 * C2 for vectors. Other vector folds are below. 8096 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8097 return FoldedVOp; 8098 } 8099 8100 // fold (fmul c1, c2) -> c1*c2 8101 if (N0CFP && N1CFP) 8102 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1); 8103 8104 // canonicalize constant to RHS 8105 if (isConstantFPBuildVectorOrConstantFP(N0) && 8106 !isConstantFPBuildVectorOrConstantFP(N1)) 8107 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0); 8108 8109 // fold (fmul A, 1.0) -> A 8110 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8111 return N0; 8112 8113 if (Options.UnsafeFPMath) { 8114 // fold (fmul A, 0) -> 0 8115 if (N1CFP && N1CFP->isZero()) 8116 return N1; 8117 8118 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8119 if (N0.getOpcode() == ISD::FMUL) { 8120 // Fold scalars or any vector constants (not just splats). 8121 // This fold is done in general by InstCombine, but extra fmul insts 8122 // may have been generated during lowering. 8123 SDValue N00 = N0.getOperand(0); 8124 SDValue N01 = N0.getOperand(1); 8125 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8126 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8127 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8128 8129 // Check 1: Make sure that the first operand of the inner multiply is NOT 8130 // a constant. Otherwise, we may induce infinite looping. 8131 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8132 // Check 2: Make sure that the second operand of the inner multiply and 8133 // the second operand of the outer multiply are constants. 8134 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8135 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8136 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1); 8137 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts); 8138 } 8139 } 8140 } 8141 8142 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8143 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8144 // during an early run of DAGCombiner can prevent folding with fmuls 8145 // inserted during lowering. 8146 if (N0.getOpcode() == ISD::FADD && 8147 (N0.getOperand(0) == N0.getOperand(1)) && 8148 N0.hasOneUse()) { 8149 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8150 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1); 8151 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts); 8152 } 8153 } 8154 8155 // fold (fmul X, 2.0) -> (fadd X, X) 8156 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8157 return DAG.getNode(ISD::FADD, DL, VT, N0, N0); 8158 8159 // fold (fmul X, -1.0) -> (fneg X) 8160 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8161 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8162 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8163 8164 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8165 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8166 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8167 // Both can be negated for free, check to see if at least one is cheaper 8168 // negated. 8169 if (LHSNeg == 2 || RHSNeg == 2) 8170 return DAG.getNode(ISD::FMUL, DL, VT, 8171 GetNegatedExpression(N0, DAG, LegalOperations), 8172 GetNegatedExpression(N1, DAG, LegalOperations)); 8173 } 8174 } 8175 8176 return SDValue(); 8177 } 8178 8179 SDValue DAGCombiner::visitFMA(SDNode *N) { 8180 SDValue N0 = N->getOperand(0); 8181 SDValue N1 = N->getOperand(1); 8182 SDValue N2 = N->getOperand(2); 8183 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8184 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8185 EVT VT = N->getValueType(0); 8186 SDLoc dl(N); 8187 const TargetOptions &Options = DAG.getTarget().Options; 8188 8189 // Constant fold FMA. 8190 if (isa<ConstantFPSDNode>(N0) && 8191 isa<ConstantFPSDNode>(N1) && 8192 isa<ConstantFPSDNode>(N2)) { 8193 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8194 } 8195 8196 if (Options.UnsafeFPMath) { 8197 if (N0CFP && N0CFP->isZero()) 8198 return N2; 8199 if (N1CFP && N1CFP->isZero()) 8200 return N2; 8201 } 8202 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8203 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8204 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8205 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8206 8207 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8208 if (N0CFP && !N1CFP) 8209 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8210 8211 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8212 if (Options.UnsafeFPMath && N1CFP && 8213 N2.getOpcode() == ISD::FMUL && 8214 N0 == N2.getOperand(0) && 8215 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 8216 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8217 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 8218 } 8219 8220 8221 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8222 if (Options.UnsafeFPMath && 8223 N0.getOpcode() == ISD::FMUL && N1CFP && 8224 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 8225 return DAG.getNode(ISD::FMA, dl, VT, 8226 N0.getOperand(0), 8227 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 8228 N2); 8229 } 8230 8231 // (fma x, 1, y) -> (fadd x, y) 8232 // (fma x, -1, y) -> (fadd (fneg x), y) 8233 if (N1CFP) { 8234 if (N1CFP->isExactlyValue(1.0)) 8235 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8236 8237 if (N1CFP->isExactlyValue(-1.0) && 8238 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8239 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8240 AddToWorklist(RHSNeg.getNode()); 8241 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8242 } 8243 } 8244 8245 // (fma x, c, x) -> (fmul x, (c+1)) 8246 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 8247 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8248 DAG.getNode(ISD::FADD, dl, VT, 8249 N1, DAG.getConstantFP(1.0, dl, VT))); 8250 8251 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8252 if (Options.UnsafeFPMath && N1CFP && 8253 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 8254 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8255 DAG.getNode(ISD::FADD, dl, VT, 8256 N1, DAG.getConstantFP(-1.0, dl, VT))); 8257 8258 8259 return SDValue(); 8260 } 8261 8262 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8263 // reciprocal. 8264 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8265 // Notice that this is not always beneficial. One reason is different target 8266 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8267 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8268 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8269 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8270 if (!DAG.getTarget().Options.UnsafeFPMath) 8271 return SDValue(); 8272 8273 // Skip if current node is a reciprocal. 8274 SDValue N0 = N->getOperand(0); 8275 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8276 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8277 return SDValue(); 8278 8279 // Exit early if the target does not want this transform or if there can't 8280 // possibly be enough uses of the divisor to make the transform worthwhile. 8281 SDValue N1 = N->getOperand(1); 8282 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8283 if (!MinUses || N1->use_size() < MinUses) 8284 return SDValue(); 8285 8286 // Find all FDIV users of the same divisor. 8287 // Use a set because duplicates may be present in the user list. 8288 SetVector<SDNode *> Users; 8289 for (auto *U : N1->uses()) 8290 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) 8291 Users.insert(U); 8292 8293 // Now that we have the actual number of divisor uses, make sure it meets 8294 // the minimum threshold specified by the target. 8295 if (Users.size() < MinUses) 8296 return SDValue(); 8297 8298 EVT VT = N->getValueType(0); 8299 SDLoc DL(N); 8300 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8301 // FIXME: This optimization requires some level of fast-math, so the 8302 // created reciprocal node should at least have the 'allowReciprocal' 8303 // fast-math-flag set. 8304 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1); 8305 8306 // Dividend / Divisor -> Dividend * Reciprocal 8307 for (auto *U : Users) { 8308 SDValue Dividend = U->getOperand(0); 8309 if (Dividend != FPOne) { 8310 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8311 Reciprocal); 8312 CombineTo(U, NewNode); 8313 } else if (U != Reciprocal.getNode()) { 8314 // In the absence of fast-math-flags, this user node is always the 8315 // same node as Reciprocal, but with FMF they may be different nodes. 8316 CombineTo(U, Reciprocal); 8317 } 8318 } 8319 return SDValue(N, 0); // N was replaced. 8320 } 8321 8322 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8323 SDValue N0 = N->getOperand(0); 8324 SDValue N1 = N->getOperand(1); 8325 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8326 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8327 EVT VT = N->getValueType(0); 8328 SDLoc DL(N); 8329 const TargetOptions &Options = DAG.getTarget().Options; 8330 8331 // fold vector ops 8332 if (VT.isVector()) 8333 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8334 return FoldedVOp; 8335 8336 // fold (fdiv c1, c2) -> c1/c2 8337 if (N0CFP && N1CFP) 8338 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 8339 8340 if (Options.UnsafeFPMath) { 8341 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8342 if (N1CFP) { 8343 // Compute the reciprocal 1.0 / c2. 8344 APFloat N1APF = N1CFP->getValueAPF(); 8345 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8346 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8347 // Only do the transform if the reciprocal is a legal fp immediate that 8348 // isn't too nasty (eg NaN, denormal, ...). 8349 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8350 (!LegalOperations || 8351 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8352 // backend)... we should handle this gracefully after Legalize. 8353 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8354 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8355 TLI.isFPImmLegal(Recip, VT))) 8356 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8357 DAG.getConstantFP(Recip, DL, VT)); 8358 } 8359 8360 // If this FDIV is part of a reciprocal square root, it may be folded 8361 // into a target-specific square root estimate instruction. 8362 if (N1.getOpcode() == ISD::FSQRT) { 8363 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) { 8364 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8365 } 8366 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8367 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8368 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 8369 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8370 AddToWorklist(RV.getNode()); 8371 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8372 } 8373 } else if (N1.getOpcode() == ISD::FP_ROUND && 8374 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8375 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 8376 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8377 AddToWorklist(RV.getNode()); 8378 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8379 } 8380 } else if (N1.getOpcode() == ISD::FMUL) { 8381 // Look through an FMUL. Even though this won't remove the FDIV directly, 8382 // it's still worthwhile to get rid of the FSQRT if possible. 8383 SDValue SqrtOp; 8384 SDValue OtherOp; 8385 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8386 SqrtOp = N1.getOperand(0); 8387 OtherOp = N1.getOperand(1); 8388 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8389 SqrtOp = N1.getOperand(1); 8390 OtherOp = N1.getOperand(0); 8391 } 8392 if (SqrtOp.getNode()) { 8393 // We found a FSQRT, so try to make this fold: 8394 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8395 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) { 8396 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp); 8397 AddToWorklist(RV.getNode()); 8398 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8399 } 8400 } 8401 } 8402 8403 // Fold into a reciprocal estimate and multiply instead of a real divide. 8404 if (SDValue RV = BuildReciprocalEstimate(N1)) { 8405 AddToWorklist(RV.getNode()); 8406 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8407 } 8408 } 8409 8410 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8411 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8412 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8413 // Both can be negated for free, check to see if at least one is cheaper 8414 // negated. 8415 if (LHSNeg == 2 || RHSNeg == 2) 8416 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8417 GetNegatedExpression(N0, DAG, LegalOperations), 8418 GetNegatedExpression(N1, DAG, LegalOperations)); 8419 } 8420 } 8421 8422 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8423 return CombineRepeatedDivisors; 8424 8425 return SDValue(); 8426 } 8427 8428 SDValue DAGCombiner::visitFREM(SDNode *N) { 8429 SDValue N0 = N->getOperand(0); 8430 SDValue N1 = N->getOperand(1); 8431 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8432 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8433 EVT VT = N->getValueType(0); 8434 8435 // fold (frem c1, c2) -> fmod(c1,c2) 8436 if (N0CFP && N1CFP) 8437 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 8438 8439 return SDValue(); 8440 } 8441 8442 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8443 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8444 return SDValue(); 8445 8446 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8447 SDValue RV = BuildRsqrtEstimate(N->getOperand(0)); 8448 if (!RV) 8449 return SDValue(); 8450 8451 EVT VT = RV.getValueType(); 8452 SDLoc DL(N); 8453 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV); 8454 AddToWorklist(RV.getNode()); 8455 8456 // Unfortunately, RV is now NaN if the input was exactly 0. 8457 // Select out this case and force the answer to 0. 8458 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8459 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8460 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8461 AddToWorklist(ZeroCmp.getNode()); 8462 AddToWorklist(RV.getNode()); 8463 8464 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8465 ZeroCmp, Zero, RV); 8466 } 8467 8468 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8469 SDValue N0 = N->getOperand(0); 8470 SDValue N1 = N->getOperand(1); 8471 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8472 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8473 EVT VT = N->getValueType(0); 8474 8475 if (N0CFP && N1CFP) // Constant fold 8476 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8477 8478 if (N1CFP) { 8479 const APFloat& V = N1CFP->getValueAPF(); 8480 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8481 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8482 if (!V.isNegative()) { 8483 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8484 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8485 } else { 8486 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8487 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8488 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8489 } 8490 } 8491 8492 // copysign(fabs(x), y) -> copysign(x, y) 8493 // copysign(fneg(x), y) -> copysign(x, y) 8494 // copysign(copysign(x,z), y) -> copysign(x, y) 8495 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8496 N0.getOpcode() == ISD::FCOPYSIGN) 8497 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8498 N0.getOperand(0), N1); 8499 8500 // copysign(x, abs(y)) -> abs(x) 8501 if (N1.getOpcode() == ISD::FABS) 8502 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8503 8504 // copysign(x, copysign(y,z)) -> copysign(x, z) 8505 if (N1.getOpcode() == ISD::FCOPYSIGN) 8506 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8507 N0, N1.getOperand(1)); 8508 8509 // copysign(x, fp_extend(y)) -> copysign(x, y) 8510 // copysign(x, fp_round(y)) -> copysign(x, y) 8511 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8512 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8513 N0, N1.getOperand(0)); 8514 8515 return SDValue(); 8516 } 8517 8518 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8519 SDValue N0 = N->getOperand(0); 8520 EVT VT = N->getValueType(0); 8521 EVT OpVT = N0.getValueType(); 8522 8523 // fold (sint_to_fp c1) -> c1fp 8524 if (isConstantIntBuildVectorOrConstantInt(N0) && 8525 // ...but only if the target supports immediate floating-point values 8526 (!LegalOperations || 8527 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8528 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8529 8530 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8531 // but UINT_TO_FP is legal on this target, try to convert. 8532 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8533 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8534 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8535 if (DAG.SignBitIsZero(N0)) 8536 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8537 } 8538 8539 // The next optimizations are desirable only if SELECT_CC can be lowered. 8540 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8541 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8542 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8543 !VT.isVector() && 8544 (!LegalOperations || 8545 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8546 SDLoc DL(N); 8547 SDValue Ops[] = 8548 { N0.getOperand(0), N0.getOperand(1), 8549 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8550 N0.getOperand(2) }; 8551 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8552 } 8553 8554 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8555 // (select_cc x, y, 1.0, 0.0,, cc) 8556 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8557 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8558 (!LegalOperations || 8559 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8560 SDLoc DL(N); 8561 SDValue Ops[] = 8562 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8563 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8564 N0.getOperand(0).getOperand(2) }; 8565 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8566 } 8567 } 8568 8569 return SDValue(); 8570 } 8571 8572 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8573 SDValue N0 = N->getOperand(0); 8574 EVT VT = N->getValueType(0); 8575 EVT OpVT = N0.getValueType(); 8576 8577 // fold (uint_to_fp c1) -> c1fp 8578 if (isConstantIntBuildVectorOrConstantInt(N0) && 8579 // ...but only if the target supports immediate floating-point values 8580 (!LegalOperations || 8581 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8582 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8583 8584 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8585 // but SINT_TO_FP is legal on this target, try to convert. 8586 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8587 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8588 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8589 if (DAG.SignBitIsZero(N0)) 8590 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8591 } 8592 8593 // The next optimizations are desirable only if SELECT_CC can be lowered. 8594 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8595 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8596 8597 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8598 (!LegalOperations || 8599 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8600 SDLoc DL(N); 8601 SDValue Ops[] = 8602 { N0.getOperand(0), N0.getOperand(1), 8603 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8604 N0.getOperand(2) }; 8605 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8606 } 8607 } 8608 8609 return SDValue(); 8610 } 8611 8612 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8613 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8614 SDValue N0 = N->getOperand(0); 8615 EVT VT = N->getValueType(0); 8616 8617 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8618 return SDValue(); 8619 8620 SDValue Src = N0.getOperand(0); 8621 EVT SrcVT = Src.getValueType(); 8622 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8623 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8624 8625 // We can safely assume the conversion won't overflow the output range, 8626 // because (for example) (uint8_t)18293.f is undefined behavior. 8627 8628 // Since we can assume the conversion won't overflow, our decision as to 8629 // whether the input will fit in the float should depend on the minimum 8630 // of the input range and output range. 8631 8632 // This means this is also safe for a signed input and unsigned output, since 8633 // a negative input would lead to undefined behavior. 8634 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8635 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8636 unsigned ActualSize = std::min(InputSize, OutputSize); 8637 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8638 8639 // We can only fold away the float conversion if the input range can be 8640 // represented exactly in the float range. 8641 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8642 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8643 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8644 : ISD::ZERO_EXTEND; 8645 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8646 } 8647 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8648 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8649 if (SrcVT == VT) 8650 return Src; 8651 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8652 } 8653 return SDValue(); 8654 } 8655 8656 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8657 SDValue N0 = N->getOperand(0); 8658 EVT VT = N->getValueType(0); 8659 8660 // fold (fp_to_sint c1fp) -> c1 8661 if (isConstantFPBuildVectorOrConstantFP(N0)) 8662 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8663 8664 return FoldIntToFPToInt(N, DAG); 8665 } 8666 8667 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8668 SDValue N0 = N->getOperand(0); 8669 EVT VT = N->getValueType(0); 8670 8671 // fold (fp_to_uint c1fp) -> c1 8672 if (isConstantFPBuildVectorOrConstantFP(N0)) 8673 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8674 8675 return FoldIntToFPToInt(N, DAG); 8676 } 8677 8678 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8679 SDValue N0 = N->getOperand(0); 8680 SDValue N1 = N->getOperand(1); 8681 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8682 EVT VT = N->getValueType(0); 8683 8684 // fold (fp_round c1fp) -> c1fp 8685 if (N0CFP) 8686 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8687 8688 // fold (fp_round (fp_extend x)) -> x 8689 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8690 return N0.getOperand(0); 8691 8692 // fold (fp_round (fp_round x)) -> (fp_round x) 8693 if (N0.getOpcode() == ISD::FP_ROUND) { 8694 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8695 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8696 // If the first fp_round isn't a value preserving truncation, it might 8697 // introduce a tie in the second fp_round, that wouldn't occur in the 8698 // single-step fp_round we want to fold to. 8699 // In other words, double rounding isn't the same as rounding. 8700 // Also, this is a value preserving truncation iff both fp_round's are. 8701 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 8702 SDLoc DL(N); 8703 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 8704 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 8705 } 8706 } 8707 8708 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8709 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8710 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8711 N0.getOperand(0), N1); 8712 AddToWorklist(Tmp.getNode()); 8713 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8714 Tmp, N0.getOperand(1)); 8715 } 8716 8717 return SDValue(); 8718 } 8719 8720 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8721 SDValue N0 = N->getOperand(0); 8722 EVT VT = N->getValueType(0); 8723 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8724 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8725 8726 // fold (fp_round_inreg c1fp) -> c1fp 8727 if (N0CFP && isTypeLegal(EVT)) { 8728 SDLoc DL(N); 8729 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 8730 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 8731 } 8732 8733 return SDValue(); 8734 } 8735 8736 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8737 SDValue N0 = N->getOperand(0); 8738 EVT VT = N->getValueType(0); 8739 8740 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8741 if (N->hasOneUse() && 8742 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8743 return SDValue(); 8744 8745 // fold (fp_extend c1fp) -> c1fp 8746 if (isConstantFPBuildVectorOrConstantFP(N0)) 8747 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8748 8749 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 8750 if (N0.getOpcode() == ISD::FP16_TO_FP && 8751 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 8752 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 8753 8754 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8755 // value of X. 8756 if (N0.getOpcode() == ISD::FP_ROUND 8757 && N0.getNode()->getConstantOperandVal(1) == 1) { 8758 SDValue In = N0.getOperand(0); 8759 if (In.getValueType() == VT) return In; 8760 if (VT.bitsLT(In.getValueType())) 8761 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8762 In, N0.getOperand(1)); 8763 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8764 } 8765 8766 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8767 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8768 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8769 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8770 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8771 LN0->getChain(), 8772 LN0->getBasePtr(), N0.getValueType(), 8773 LN0->getMemOperand()); 8774 CombineTo(N, ExtLoad); 8775 CombineTo(N0.getNode(), 8776 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8777 N0.getValueType(), ExtLoad, 8778 DAG.getIntPtrConstant(1, SDLoc(N0))), 8779 ExtLoad.getValue(1)); 8780 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8781 } 8782 8783 return SDValue(); 8784 } 8785 8786 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8787 SDValue N0 = N->getOperand(0); 8788 EVT VT = N->getValueType(0); 8789 8790 // fold (fceil c1) -> fceil(c1) 8791 if (isConstantFPBuildVectorOrConstantFP(N0)) 8792 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8793 8794 return SDValue(); 8795 } 8796 8797 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8798 SDValue N0 = N->getOperand(0); 8799 EVT VT = N->getValueType(0); 8800 8801 // fold (ftrunc c1) -> ftrunc(c1) 8802 if (isConstantFPBuildVectorOrConstantFP(N0)) 8803 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8804 8805 return SDValue(); 8806 } 8807 8808 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8809 SDValue N0 = N->getOperand(0); 8810 EVT VT = N->getValueType(0); 8811 8812 // fold (ffloor c1) -> ffloor(c1) 8813 if (isConstantFPBuildVectorOrConstantFP(N0)) 8814 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8815 8816 return SDValue(); 8817 } 8818 8819 // FIXME: FNEG and FABS have a lot in common; refactor. 8820 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8821 SDValue N0 = N->getOperand(0); 8822 EVT VT = N->getValueType(0); 8823 8824 // Constant fold FNEG. 8825 if (isConstantFPBuildVectorOrConstantFP(N0)) 8826 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 8827 8828 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8829 &DAG.getTarget().Options)) 8830 return GetNegatedExpression(N0, DAG, LegalOperations); 8831 8832 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8833 // constant pool values. 8834 if (!TLI.isFNegFree(VT) && 8835 N0.getOpcode() == ISD::BITCAST && 8836 N0.getNode()->hasOneUse()) { 8837 SDValue Int = N0.getOperand(0); 8838 EVT IntVT = Int.getValueType(); 8839 if (IntVT.isInteger() && !IntVT.isVector()) { 8840 APInt SignMask; 8841 if (N0.getValueType().isVector()) { 8842 // For a vector, get a mask such as 0x80... per scalar element 8843 // and splat it. 8844 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8845 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8846 } else { 8847 // For a scalar, just generate 0x80... 8848 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 8849 } 8850 SDLoc DL0(N0); 8851 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 8852 DAG.getConstant(SignMask, DL0, IntVT)); 8853 AddToWorklist(Int.getNode()); 8854 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 8855 } 8856 } 8857 8858 // (fneg (fmul c, x)) -> (fmul -c, x) 8859 if (N0.getOpcode() == ISD::FMUL && 8860 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 8861 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8862 if (CFP1) { 8863 APFloat CVal = CFP1->getValueAPF(); 8864 CVal.changeSign(); 8865 if (Level >= AfterLegalizeDAG && 8866 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 8867 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 8868 return DAG.getNode( 8869 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 8870 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 8871 } 8872 } 8873 8874 return SDValue(); 8875 } 8876 8877 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 8878 SDValue N0 = N->getOperand(0); 8879 SDValue N1 = N->getOperand(1); 8880 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8881 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8882 8883 if (N0CFP && N1CFP) { 8884 const APFloat &C0 = N0CFP->getValueAPF(); 8885 const APFloat &C1 = N1CFP->getValueAPF(); 8886 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0)); 8887 } 8888 8889 if (N0CFP) { 8890 EVT VT = N->getValueType(0); 8891 // Canonicalize to constant on RHS. 8892 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 8893 } 8894 8895 return SDValue(); 8896 } 8897 8898 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 8899 SDValue N0 = N->getOperand(0); 8900 SDValue N1 = N->getOperand(1); 8901 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8902 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8903 8904 if (N0CFP && N1CFP) { 8905 const APFloat &C0 = N0CFP->getValueAPF(); 8906 const APFloat &C1 = N1CFP->getValueAPF(); 8907 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0)); 8908 } 8909 8910 if (N0CFP) { 8911 EVT VT = N->getValueType(0); 8912 // Canonicalize to constant on RHS. 8913 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 8914 } 8915 8916 return SDValue(); 8917 } 8918 8919 SDValue DAGCombiner::visitFABS(SDNode *N) { 8920 SDValue N0 = N->getOperand(0); 8921 EVT VT = N->getValueType(0); 8922 8923 // fold (fabs c1) -> fabs(c1) 8924 if (isConstantFPBuildVectorOrConstantFP(N0)) 8925 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8926 8927 // fold (fabs (fabs x)) -> (fabs x) 8928 if (N0.getOpcode() == ISD::FABS) 8929 return N->getOperand(0); 8930 8931 // fold (fabs (fneg x)) -> (fabs x) 8932 // fold (fabs (fcopysign x, y)) -> (fabs x) 8933 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 8934 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 8935 8936 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 8937 // constant pool values. 8938 if (!TLI.isFAbsFree(VT) && 8939 N0.getOpcode() == ISD::BITCAST && 8940 N0.getNode()->hasOneUse()) { 8941 SDValue Int = N0.getOperand(0); 8942 EVT IntVT = Int.getValueType(); 8943 if (IntVT.isInteger() && !IntVT.isVector()) { 8944 APInt SignMask; 8945 if (N0.getValueType().isVector()) { 8946 // For a vector, get a mask such as 0x7f... per scalar element 8947 // and splat it. 8948 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8949 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8950 } else { 8951 // For a scalar, just generate 0x7f... 8952 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 8953 } 8954 SDLoc DL(N0); 8955 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 8956 DAG.getConstant(SignMask, DL, IntVT)); 8957 AddToWorklist(Int.getNode()); 8958 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 8959 } 8960 } 8961 8962 return SDValue(); 8963 } 8964 8965 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 8966 SDValue Chain = N->getOperand(0); 8967 SDValue N1 = N->getOperand(1); 8968 SDValue N2 = N->getOperand(2); 8969 8970 // If N is a constant we could fold this into a fallthrough or unconditional 8971 // branch. However that doesn't happen very often in normal code, because 8972 // Instcombine/SimplifyCFG should have handled the available opportunities. 8973 // If we did this folding here, it would be necessary to update the 8974 // MachineBasicBlock CFG, which is awkward. 8975 8976 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 8977 // on the target. 8978 if (N1.getOpcode() == ISD::SETCC && 8979 TLI.isOperationLegalOrCustom(ISD::BR_CC, 8980 N1.getOperand(0).getValueType())) { 8981 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8982 Chain, N1.getOperand(2), 8983 N1.getOperand(0), N1.getOperand(1), N2); 8984 } 8985 8986 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 8987 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 8988 (N1.getOperand(0).hasOneUse() && 8989 N1.getOperand(0).getOpcode() == ISD::SRL))) { 8990 SDNode *Trunc = nullptr; 8991 if (N1.getOpcode() == ISD::TRUNCATE) { 8992 // Look pass the truncate. 8993 Trunc = N1.getNode(); 8994 N1 = N1.getOperand(0); 8995 } 8996 8997 // Match this pattern so that we can generate simpler code: 8998 // 8999 // %a = ... 9000 // %b = and i32 %a, 2 9001 // %c = srl i32 %b, 1 9002 // brcond i32 %c ... 9003 // 9004 // into 9005 // 9006 // %a = ... 9007 // %b = and i32 %a, 2 9008 // %c = setcc eq %b, 0 9009 // brcond %c ... 9010 // 9011 // This applies only when the AND constant value has one bit set and the 9012 // SRL constant is equal to the log2 of the AND constant. The back-end is 9013 // smart enough to convert the result into a TEST/JMP sequence. 9014 SDValue Op0 = N1.getOperand(0); 9015 SDValue Op1 = N1.getOperand(1); 9016 9017 if (Op0.getOpcode() == ISD::AND && 9018 Op1.getOpcode() == ISD::Constant) { 9019 SDValue AndOp1 = Op0.getOperand(1); 9020 9021 if (AndOp1.getOpcode() == ISD::Constant) { 9022 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9023 9024 if (AndConst.isPowerOf2() && 9025 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9026 SDLoc DL(N); 9027 SDValue SetCC = 9028 DAG.getSetCC(DL, 9029 getSetCCResultType(Op0.getValueType()), 9030 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9031 ISD::SETNE); 9032 9033 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9034 MVT::Other, Chain, SetCC, N2); 9035 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9036 // will convert it back to (X & C1) >> C2. 9037 CombineTo(N, NewBRCond, false); 9038 // Truncate is dead. 9039 if (Trunc) 9040 deleteAndRecombine(Trunc); 9041 // Replace the uses of SRL with SETCC 9042 WorklistRemover DeadNodes(*this); 9043 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9044 deleteAndRecombine(N1.getNode()); 9045 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9046 } 9047 } 9048 } 9049 9050 if (Trunc) 9051 // Restore N1 if the above transformation doesn't match. 9052 N1 = N->getOperand(1); 9053 } 9054 9055 // Transform br(xor(x, y)) -> br(x != y) 9056 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9057 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9058 SDNode *TheXor = N1.getNode(); 9059 SDValue Op0 = TheXor->getOperand(0); 9060 SDValue Op1 = TheXor->getOperand(1); 9061 if (Op0.getOpcode() == Op1.getOpcode()) { 9062 // Avoid missing important xor optimizations. 9063 if (SDValue Tmp = visitXOR(TheXor)) { 9064 if (Tmp.getNode() != TheXor) { 9065 DEBUG(dbgs() << "\nReplacing.8 "; 9066 TheXor->dump(&DAG); 9067 dbgs() << "\nWith: "; 9068 Tmp.getNode()->dump(&DAG); 9069 dbgs() << '\n'); 9070 WorklistRemover DeadNodes(*this); 9071 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9072 deleteAndRecombine(TheXor); 9073 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9074 MVT::Other, Chain, Tmp, N2); 9075 } 9076 9077 // visitXOR has changed XOR's operands or replaced the XOR completely, 9078 // bail out. 9079 return SDValue(N, 0); 9080 } 9081 } 9082 9083 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9084 bool Equal = false; 9085 if (isOneConstant(Op0) && Op0.hasOneUse() && 9086 Op0.getOpcode() == ISD::XOR) { 9087 TheXor = Op0.getNode(); 9088 Equal = true; 9089 } 9090 9091 EVT SetCCVT = N1.getValueType(); 9092 if (LegalTypes) 9093 SetCCVT = getSetCCResultType(SetCCVT); 9094 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9095 SetCCVT, 9096 Op0, Op1, 9097 Equal ? ISD::SETEQ : ISD::SETNE); 9098 // Replace the uses of XOR with SETCC 9099 WorklistRemover DeadNodes(*this); 9100 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9101 deleteAndRecombine(N1.getNode()); 9102 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9103 MVT::Other, Chain, SetCC, N2); 9104 } 9105 } 9106 9107 return SDValue(); 9108 } 9109 9110 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9111 // 9112 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9113 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9114 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9115 9116 // If N is a constant we could fold this into a fallthrough or unconditional 9117 // branch. However that doesn't happen very often in normal code, because 9118 // Instcombine/SimplifyCFG should have handled the available opportunities. 9119 // If we did this folding here, it would be necessary to update the 9120 // MachineBasicBlock CFG, which is awkward. 9121 9122 // Use SimplifySetCC to simplify SETCC's. 9123 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9124 CondLHS, CondRHS, CC->get(), SDLoc(N), 9125 false); 9126 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9127 9128 // fold to a simpler setcc 9129 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9130 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9131 N->getOperand(0), Simp.getOperand(2), 9132 Simp.getOperand(0), Simp.getOperand(1), 9133 N->getOperand(4)); 9134 9135 return SDValue(); 9136 } 9137 9138 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9139 /// and that N may be folded in the load / store addressing mode. 9140 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9141 SelectionDAG &DAG, 9142 const TargetLowering &TLI) { 9143 EVT VT; 9144 unsigned AS; 9145 9146 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9147 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9148 return false; 9149 VT = LD->getMemoryVT(); 9150 AS = LD->getAddressSpace(); 9151 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9152 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9153 return false; 9154 VT = ST->getMemoryVT(); 9155 AS = ST->getAddressSpace(); 9156 } else 9157 return false; 9158 9159 TargetLowering::AddrMode AM; 9160 if (N->getOpcode() == ISD::ADD) { 9161 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9162 if (Offset) 9163 // [reg +/- imm] 9164 AM.BaseOffs = Offset->getSExtValue(); 9165 else 9166 // [reg +/- reg] 9167 AM.Scale = 1; 9168 } else if (N->getOpcode() == ISD::SUB) { 9169 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9170 if (Offset) 9171 // [reg +/- imm] 9172 AM.BaseOffs = -Offset->getSExtValue(); 9173 else 9174 // [reg +/- reg] 9175 AM.Scale = 1; 9176 } else 9177 return false; 9178 9179 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9180 VT.getTypeForEVT(*DAG.getContext()), AS); 9181 } 9182 9183 /// Try turning a load/store into a pre-indexed load/store when the base 9184 /// pointer is an add or subtract and it has other uses besides the load/store. 9185 /// After the transformation, the new indexed load/store has effectively folded 9186 /// the add/subtract in and all of its other uses are redirected to the 9187 /// new load/store. 9188 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9189 if (Level < AfterLegalizeDAG) 9190 return false; 9191 9192 bool isLoad = true; 9193 SDValue Ptr; 9194 EVT VT; 9195 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9196 if (LD->isIndexed()) 9197 return false; 9198 VT = LD->getMemoryVT(); 9199 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9200 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9201 return false; 9202 Ptr = LD->getBasePtr(); 9203 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9204 if (ST->isIndexed()) 9205 return false; 9206 VT = ST->getMemoryVT(); 9207 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9208 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9209 return false; 9210 Ptr = ST->getBasePtr(); 9211 isLoad = false; 9212 } else { 9213 return false; 9214 } 9215 9216 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9217 // out. There is no reason to make this a preinc/predec. 9218 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9219 Ptr.getNode()->hasOneUse()) 9220 return false; 9221 9222 // Ask the target to do addressing mode selection. 9223 SDValue BasePtr; 9224 SDValue Offset; 9225 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9226 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9227 return false; 9228 9229 // Backends without true r+i pre-indexed forms may need to pass a 9230 // constant base with a variable offset so that constant coercion 9231 // will work with the patterns in canonical form. 9232 bool Swapped = false; 9233 if (isa<ConstantSDNode>(BasePtr)) { 9234 std::swap(BasePtr, Offset); 9235 Swapped = true; 9236 } 9237 9238 // Don't create a indexed load / store with zero offset. 9239 if (isNullConstant(Offset)) 9240 return false; 9241 9242 // Try turning it into a pre-indexed load / store except when: 9243 // 1) The new base ptr is a frame index. 9244 // 2) If N is a store and the new base ptr is either the same as or is a 9245 // predecessor of the value being stored. 9246 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9247 // that would create a cycle. 9248 // 4) All uses are load / store ops that use it as old base ptr. 9249 9250 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9251 // (plus the implicit offset) to a register to preinc anyway. 9252 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9253 return false; 9254 9255 // Check #2. 9256 if (!isLoad) { 9257 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9258 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9259 return false; 9260 } 9261 9262 // If the offset is a constant, there may be other adds of constants that 9263 // can be folded with this one. We should do this to avoid having to keep 9264 // a copy of the original base pointer. 9265 SmallVector<SDNode *, 16> OtherUses; 9266 if (isa<ConstantSDNode>(Offset)) 9267 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9268 UE = BasePtr.getNode()->use_end(); 9269 UI != UE; ++UI) { 9270 SDUse &Use = UI.getUse(); 9271 // Skip the use that is Ptr and uses of other results from BasePtr's 9272 // node (important for nodes that return multiple results). 9273 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9274 continue; 9275 9276 if (Use.getUser()->isPredecessorOf(N)) 9277 continue; 9278 9279 if (Use.getUser()->getOpcode() != ISD::ADD && 9280 Use.getUser()->getOpcode() != ISD::SUB) { 9281 OtherUses.clear(); 9282 break; 9283 } 9284 9285 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9286 if (!isa<ConstantSDNode>(Op1)) { 9287 OtherUses.clear(); 9288 break; 9289 } 9290 9291 // FIXME: In some cases, we can be smarter about this. 9292 if (Op1.getValueType() != Offset.getValueType()) { 9293 OtherUses.clear(); 9294 break; 9295 } 9296 9297 OtherUses.push_back(Use.getUser()); 9298 } 9299 9300 if (Swapped) 9301 std::swap(BasePtr, Offset); 9302 9303 // Now check for #3 and #4. 9304 bool RealUse = false; 9305 9306 // Caches for hasPredecessorHelper 9307 SmallPtrSet<const SDNode *, 32> Visited; 9308 SmallVector<const SDNode *, 16> Worklist; 9309 9310 for (SDNode *Use : Ptr.getNode()->uses()) { 9311 if (Use == N) 9312 continue; 9313 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9314 return false; 9315 9316 // If Ptr may be folded in addressing mode of other use, then it's 9317 // not profitable to do this transformation. 9318 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9319 RealUse = true; 9320 } 9321 9322 if (!RealUse) 9323 return false; 9324 9325 SDValue Result; 9326 if (isLoad) 9327 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9328 BasePtr, Offset, AM); 9329 else 9330 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9331 BasePtr, Offset, AM); 9332 ++PreIndexedNodes; 9333 ++NodesCombined; 9334 DEBUG(dbgs() << "\nReplacing.4 "; 9335 N->dump(&DAG); 9336 dbgs() << "\nWith: "; 9337 Result.getNode()->dump(&DAG); 9338 dbgs() << '\n'); 9339 WorklistRemover DeadNodes(*this); 9340 if (isLoad) { 9341 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9342 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9343 } else { 9344 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9345 } 9346 9347 // Finally, since the node is now dead, remove it from the graph. 9348 deleteAndRecombine(N); 9349 9350 if (Swapped) 9351 std::swap(BasePtr, Offset); 9352 9353 // Replace other uses of BasePtr that can be updated to use Ptr 9354 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9355 unsigned OffsetIdx = 1; 9356 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9357 OffsetIdx = 0; 9358 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9359 BasePtr.getNode() && "Expected BasePtr operand"); 9360 9361 // We need to replace ptr0 in the following expression: 9362 // x0 * offset0 + y0 * ptr0 = t0 9363 // knowing that 9364 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9365 // 9366 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9367 // indexed load/store and the expresion that needs to be re-written. 9368 // 9369 // Therefore, we have: 9370 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9371 9372 ConstantSDNode *CN = 9373 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9374 int X0, X1, Y0, Y1; 9375 APInt Offset0 = CN->getAPIntValue(); 9376 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9377 9378 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9379 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9380 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9381 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9382 9383 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9384 9385 APInt CNV = Offset0; 9386 if (X0 < 0) CNV = -CNV; 9387 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9388 else CNV = CNV - Offset1; 9389 9390 SDLoc DL(OtherUses[i]); 9391 9392 // We can now generate the new expression. 9393 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9394 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9395 9396 SDValue NewUse = DAG.getNode(Opcode, 9397 DL, 9398 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9399 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9400 deleteAndRecombine(OtherUses[i]); 9401 } 9402 9403 // Replace the uses of Ptr with uses of the updated base value. 9404 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9405 deleteAndRecombine(Ptr.getNode()); 9406 9407 return true; 9408 } 9409 9410 /// Try to combine a load/store with a add/sub of the base pointer node into a 9411 /// post-indexed load/store. The transformation folded the add/subtract into the 9412 /// new indexed load/store effectively and all of its uses are redirected to the 9413 /// new load/store. 9414 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9415 if (Level < AfterLegalizeDAG) 9416 return false; 9417 9418 bool isLoad = true; 9419 SDValue Ptr; 9420 EVT VT; 9421 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9422 if (LD->isIndexed()) 9423 return false; 9424 VT = LD->getMemoryVT(); 9425 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9426 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9427 return false; 9428 Ptr = LD->getBasePtr(); 9429 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9430 if (ST->isIndexed()) 9431 return false; 9432 VT = ST->getMemoryVT(); 9433 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9434 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9435 return false; 9436 Ptr = ST->getBasePtr(); 9437 isLoad = false; 9438 } else { 9439 return false; 9440 } 9441 9442 if (Ptr.getNode()->hasOneUse()) 9443 return false; 9444 9445 for (SDNode *Op : Ptr.getNode()->uses()) { 9446 if (Op == N || 9447 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9448 continue; 9449 9450 SDValue BasePtr; 9451 SDValue Offset; 9452 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9453 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9454 // Don't create a indexed load / store with zero offset. 9455 if (isNullConstant(Offset)) 9456 continue; 9457 9458 // Try turning it into a post-indexed load / store except when 9459 // 1) All uses are load / store ops that use it as base ptr (and 9460 // it may be folded as addressing mmode). 9461 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9462 // nor a successor of N. Otherwise, if Op is folded that would 9463 // create a cycle. 9464 9465 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9466 continue; 9467 9468 // Check for #1. 9469 bool TryNext = false; 9470 for (SDNode *Use : BasePtr.getNode()->uses()) { 9471 if (Use == Ptr.getNode()) 9472 continue; 9473 9474 // If all the uses are load / store addresses, then don't do the 9475 // transformation. 9476 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9477 bool RealUse = false; 9478 for (SDNode *UseUse : Use->uses()) { 9479 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9480 RealUse = true; 9481 } 9482 9483 if (!RealUse) { 9484 TryNext = true; 9485 break; 9486 } 9487 } 9488 } 9489 9490 if (TryNext) 9491 continue; 9492 9493 // Check for #2 9494 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9495 SDValue Result = isLoad 9496 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9497 BasePtr, Offset, AM) 9498 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9499 BasePtr, Offset, AM); 9500 ++PostIndexedNodes; 9501 ++NodesCombined; 9502 DEBUG(dbgs() << "\nReplacing.5 "; 9503 N->dump(&DAG); 9504 dbgs() << "\nWith: "; 9505 Result.getNode()->dump(&DAG); 9506 dbgs() << '\n'); 9507 WorklistRemover DeadNodes(*this); 9508 if (isLoad) { 9509 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9510 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9511 } else { 9512 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9513 } 9514 9515 // Finally, since the node is now dead, remove it from the graph. 9516 deleteAndRecombine(N); 9517 9518 // Replace the uses of Use with uses of the updated base value. 9519 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9520 Result.getValue(isLoad ? 1 : 0)); 9521 deleteAndRecombine(Op); 9522 return true; 9523 } 9524 } 9525 } 9526 9527 return false; 9528 } 9529 9530 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9531 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9532 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9533 assert(AM != ISD::UNINDEXED); 9534 SDValue BP = LD->getOperand(1); 9535 SDValue Inc = LD->getOperand(2); 9536 9537 // Some backends use TargetConstants for load offsets, but don't expect 9538 // TargetConstants in general ADD nodes. We can convert these constants into 9539 // regular Constants (if the constant is not opaque). 9540 assert((Inc.getOpcode() != ISD::TargetConstant || 9541 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9542 "Cannot split out indexing using opaque target constants"); 9543 if (Inc.getOpcode() == ISD::TargetConstant) { 9544 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9545 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9546 ConstInc->getValueType(0)); 9547 } 9548 9549 unsigned Opc = 9550 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9551 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9552 } 9553 9554 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9555 LoadSDNode *LD = cast<LoadSDNode>(N); 9556 SDValue Chain = LD->getChain(); 9557 SDValue Ptr = LD->getBasePtr(); 9558 9559 // If load is not volatile and there are no uses of the loaded value (and 9560 // the updated indexed value in case of indexed loads), change uses of the 9561 // chain value into uses of the chain input (i.e. delete the dead load). 9562 if (!LD->isVolatile()) { 9563 if (N->getValueType(1) == MVT::Other) { 9564 // Unindexed loads. 9565 if (!N->hasAnyUseOfValue(0)) { 9566 // It's not safe to use the two value CombineTo variant here. e.g. 9567 // v1, chain2 = load chain1, loc 9568 // v2, chain3 = load chain2, loc 9569 // v3 = add v2, c 9570 // Now we replace use of chain2 with chain1. This makes the second load 9571 // isomorphic to the one we are deleting, and thus makes this load live. 9572 DEBUG(dbgs() << "\nReplacing.6 "; 9573 N->dump(&DAG); 9574 dbgs() << "\nWith chain: "; 9575 Chain.getNode()->dump(&DAG); 9576 dbgs() << "\n"); 9577 WorklistRemover DeadNodes(*this); 9578 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9579 9580 if (N->use_empty()) 9581 deleteAndRecombine(N); 9582 9583 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9584 } 9585 } else { 9586 // Indexed loads. 9587 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9588 9589 // If this load has an opaque TargetConstant offset, then we cannot split 9590 // the indexing into an add/sub directly (that TargetConstant may not be 9591 // valid for a different type of node, and we cannot convert an opaque 9592 // target constant into a regular constant). 9593 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9594 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9595 9596 if (!N->hasAnyUseOfValue(0) && 9597 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9598 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9599 SDValue Index; 9600 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9601 Index = SplitIndexingFromLoad(LD); 9602 // Try to fold the base pointer arithmetic into subsequent loads and 9603 // stores. 9604 AddUsersToWorklist(N); 9605 } else 9606 Index = DAG.getUNDEF(N->getValueType(1)); 9607 DEBUG(dbgs() << "\nReplacing.7 "; 9608 N->dump(&DAG); 9609 dbgs() << "\nWith: "; 9610 Undef.getNode()->dump(&DAG); 9611 dbgs() << " and 2 other values\n"); 9612 WorklistRemover DeadNodes(*this); 9613 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9614 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9615 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9616 deleteAndRecombine(N); 9617 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9618 } 9619 } 9620 } 9621 9622 // If this load is directly stored, replace the load value with the stored 9623 // value. 9624 // TODO: Handle store large -> read small portion. 9625 // TODO: Handle TRUNCSTORE/LOADEXT 9626 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9627 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9628 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9629 if (PrevST->getBasePtr() == Ptr && 9630 PrevST->getValue().getValueType() == N->getValueType(0)) 9631 return CombineTo(N, Chain.getOperand(1), Chain); 9632 } 9633 } 9634 9635 // Try to infer better alignment information than the load already has. 9636 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9637 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9638 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9639 SDValue NewLoad = 9640 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9641 LD->getValueType(0), 9642 Chain, Ptr, LD->getPointerInfo(), 9643 LD->getMemoryVT(), 9644 LD->isVolatile(), LD->isNonTemporal(), 9645 LD->isInvariant(), Align, LD->getAAInfo()); 9646 if (NewLoad.getNode() != N) 9647 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9648 } 9649 } 9650 } 9651 9652 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9653 : DAG.getSubtarget().useAA(); 9654 #ifndef NDEBUG 9655 if (CombinerAAOnlyFunc.getNumOccurrences() && 9656 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9657 UseAA = false; 9658 #endif 9659 if (UseAA && LD->isUnindexed()) { 9660 // Walk up chain skipping non-aliasing memory nodes. 9661 SDValue BetterChain = FindBetterChain(N, Chain); 9662 9663 // If there is a better chain. 9664 if (Chain != BetterChain) { 9665 SDValue ReplLoad; 9666 9667 // Replace the chain to void dependency. 9668 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9669 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9670 BetterChain, Ptr, LD->getMemOperand()); 9671 } else { 9672 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9673 LD->getValueType(0), 9674 BetterChain, Ptr, LD->getMemoryVT(), 9675 LD->getMemOperand()); 9676 } 9677 9678 // Create token factor to keep old chain connected. 9679 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9680 MVT::Other, Chain, ReplLoad.getValue(1)); 9681 9682 // Make sure the new and old chains are cleaned up. 9683 AddToWorklist(Token.getNode()); 9684 9685 // Replace uses with load result and token factor. Don't add users 9686 // to work list. 9687 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9688 } 9689 } 9690 9691 // Try transforming N to an indexed load. 9692 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9693 return SDValue(N, 0); 9694 9695 // Try to slice up N to more direct loads if the slices are mapped to 9696 // different register banks or pairing can take place. 9697 if (SliceUpLoad(N)) 9698 return SDValue(N, 0); 9699 9700 return SDValue(); 9701 } 9702 9703 namespace { 9704 /// \brief Helper structure used to slice a load in smaller loads. 9705 /// Basically a slice is obtained from the following sequence: 9706 /// Origin = load Ty1, Base 9707 /// Shift = srl Ty1 Origin, CstTy Amount 9708 /// Inst = trunc Shift to Ty2 9709 /// 9710 /// Then, it will be rewriten into: 9711 /// Slice = load SliceTy, Base + SliceOffset 9712 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9713 /// 9714 /// SliceTy is deduced from the number of bits that are actually used to 9715 /// build Inst. 9716 struct LoadedSlice { 9717 /// \brief Helper structure used to compute the cost of a slice. 9718 struct Cost { 9719 /// Are we optimizing for code size. 9720 bool ForCodeSize; 9721 /// Various cost. 9722 unsigned Loads; 9723 unsigned Truncates; 9724 unsigned CrossRegisterBanksCopies; 9725 unsigned ZExts; 9726 unsigned Shift; 9727 9728 Cost(bool ForCodeSize = false) 9729 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9730 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9731 9732 /// \brief Get the cost of one isolated slice. 9733 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9734 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9735 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9736 EVT TruncType = LS.Inst->getValueType(0); 9737 EVT LoadedType = LS.getLoadedType(); 9738 if (TruncType != LoadedType && 9739 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9740 ZExts = 1; 9741 } 9742 9743 /// \brief Account for slicing gain in the current cost. 9744 /// Slicing provide a few gains like removing a shift or a 9745 /// truncate. This method allows to grow the cost of the original 9746 /// load with the gain from this slice. 9747 void addSliceGain(const LoadedSlice &LS) { 9748 // Each slice saves a truncate. 9749 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9750 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 9751 LS.Inst->getValueType(0))) 9752 ++Truncates; 9753 // If there is a shift amount, this slice gets rid of it. 9754 if (LS.Shift) 9755 ++Shift; 9756 // If this slice can merge a cross register bank copy, account for it. 9757 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9758 ++CrossRegisterBanksCopies; 9759 } 9760 9761 Cost &operator+=(const Cost &RHS) { 9762 Loads += RHS.Loads; 9763 Truncates += RHS.Truncates; 9764 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9765 ZExts += RHS.ZExts; 9766 Shift += RHS.Shift; 9767 return *this; 9768 } 9769 9770 bool operator==(const Cost &RHS) const { 9771 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9772 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9773 ZExts == RHS.ZExts && Shift == RHS.Shift; 9774 } 9775 9776 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9777 9778 bool operator<(const Cost &RHS) const { 9779 // Assume cross register banks copies are as expensive as loads. 9780 // FIXME: Do we want some more target hooks? 9781 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9782 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9783 // Unless we are optimizing for code size, consider the 9784 // expensive operation first. 9785 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9786 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9787 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9788 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9789 } 9790 9791 bool operator>(const Cost &RHS) const { return RHS < *this; } 9792 9793 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9794 9795 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9796 }; 9797 // The last instruction that represent the slice. This should be a 9798 // truncate instruction. 9799 SDNode *Inst; 9800 // The original load instruction. 9801 LoadSDNode *Origin; 9802 // The right shift amount in bits from the original load. 9803 unsigned Shift; 9804 // The DAG from which Origin came from. 9805 // This is used to get some contextual information about legal types, etc. 9806 SelectionDAG *DAG; 9807 9808 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9809 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9810 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9811 9812 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9813 /// \return Result is \p BitWidth and has used bits set to 1 and 9814 /// not used bits set to 0. 9815 APInt getUsedBits() const { 9816 // Reproduce the trunc(lshr) sequence: 9817 // - Start from the truncated value. 9818 // - Zero extend to the desired bit width. 9819 // - Shift left. 9820 assert(Origin && "No original load to compare against."); 9821 unsigned BitWidth = Origin->getValueSizeInBits(0); 9822 assert(Inst && "This slice is not bound to an instruction"); 9823 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9824 "Extracted slice is bigger than the whole type!"); 9825 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9826 UsedBits.setAllBits(); 9827 UsedBits = UsedBits.zext(BitWidth); 9828 UsedBits <<= Shift; 9829 return UsedBits; 9830 } 9831 9832 /// \brief Get the size of the slice to be loaded in bytes. 9833 unsigned getLoadedSize() const { 9834 unsigned SliceSize = getUsedBits().countPopulation(); 9835 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 9836 return SliceSize / 8; 9837 } 9838 9839 /// \brief Get the type that will be loaded for this slice. 9840 /// Note: This may not be the final type for the slice. 9841 EVT getLoadedType() const { 9842 assert(DAG && "Missing context"); 9843 LLVMContext &Ctxt = *DAG->getContext(); 9844 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 9845 } 9846 9847 /// \brief Get the alignment of the load used for this slice. 9848 unsigned getAlignment() const { 9849 unsigned Alignment = Origin->getAlignment(); 9850 unsigned Offset = getOffsetFromBase(); 9851 if (Offset != 0) 9852 Alignment = MinAlign(Alignment, Alignment + Offset); 9853 return Alignment; 9854 } 9855 9856 /// \brief Check if this slice can be rewritten with legal operations. 9857 bool isLegal() const { 9858 // An invalid slice is not legal. 9859 if (!Origin || !Inst || !DAG) 9860 return false; 9861 9862 // Offsets are for indexed load only, we do not handle that. 9863 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 9864 return false; 9865 9866 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9867 9868 // Check that the type is legal. 9869 EVT SliceType = getLoadedType(); 9870 if (!TLI.isTypeLegal(SliceType)) 9871 return false; 9872 9873 // Check that the load is legal for this type. 9874 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 9875 return false; 9876 9877 // Check that the offset can be computed. 9878 // 1. Check its type. 9879 EVT PtrType = Origin->getBasePtr().getValueType(); 9880 if (PtrType == MVT::Untyped || PtrType.isExtended()) 9881 return false; 9882 9883 // 2. Check that it fits in the immediate. 9884 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 9885 return false; 9886 9887 // 3. Check that the computation is legal. 9888 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 9889 return false; 9890 9891 // Check that the zext is legal if it needs one. 9892 EVT TruncateType = Inst->getValueType(0); 9893 if (TruncateType != SliceType && 9894 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 9895 return false; 9896 9897 return true; 9898 } 9899 9900 /// \brief Get the offset in bytes of this slice in the original chunk of 9901 /// bits. 9902 /// \pre DAG != nullptr. 9903 uint64_t getOffsetFromBase() const { 9904 assert(DAG && "Missing context."); 9905 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 9906 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 9907 uint64_t Offset = Shift / 8; 9908 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 9909 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 9910 "The size of the original loaded type is not a multiple of a" 9911 " byte."); 9912 // If Offset is bigger than TySizeInBytes, it means we are loading all 9913 // zeros. This should have been optimized before in the process. 9914 assert(TySizeInBytes > Offset && 9915 "Invalid shift amount for given loaded size"); 9916 if (IsBigEndian) 9917 Offset = TySizeInBytes - Offset - getLoadedSize(); 9918 return Offset; 9919 } 9920 9921 /// \brief Generate the sequence of instructions to load the slice 9922 /// represented by this object and redirect the uses of this slice to 9923 /// this new sequence of instructions. 9924 /// \pre this->Inst && this->Origin are valid Instructions and this 9925 /// object passed the legal check: LoadedSlice::isLegal returned true. 9926 /// \return The last instruction of the sequence used to load the slice. 9927 SDValue loadSlice() const { 9928 assert(Inst && Origin && "Unable to replace a non-existing slice."); 9929 const SDValue &OldBaseAddr = Origin->getBasePtr(); 9930 SDValue BaseAddr = OldBaseAddr; 9931 // Get the offset in that chunk of bytes w.r.t. the endianess. 9932 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 9933 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 9934 if (Offset) { 9935 // BaseAddr = BaseAddr + Offset. 9936 EVT ArithType = BaseAddr.getValueType(); 9937 SDLoc DL(Origin); 9938 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 9939 DAG->getConstant(Offset, DL, ArithType)); 9940 } 9941 9942 // Create the type of the loaded slice according to its size. 9943 EVT SliceType = getLoadedType(); 9944 9945 // Create the load for the slice. 9946 SDValue LastInst = DAG->getLoad( 9947 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 9948 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 9949 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 9950 // If the final type is not the same as the loaded type, this means that 9951 // we have to pad with zero. Create a zero extend for that. 9952 EVT FinalType = Inst->getValueType(0); 9953 if (SliceType != FinalType) 9954 LastInst = 9955 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 9956 return LastInst; 9957 } 9958 9959 /// \brief Check if this slice can be merged with an expensive cross register 9960 /// bank copy. E.g., 9961 /// i = load i32 9962 /// f = bitcast i32 i to float 9963 bool canMergeExpensiveCrossRegisterBankCopy() const { 9964 if (!Inst || !Inst->hasOneUse()) 9965 return false; 9966 SDNode *Use = *Inst->use_begin(); 9967 if (Use->getOpcode() != ISD::BITCAST) 9968 return false; 9969 assert(DAG && "Missing context"); 9970 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9971 EVT ResVT = Use->getValueType(0); 9972 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 9973 const TargetRegisterClass *ArgRC = 9974 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 9975 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 9976 return false; 9977 9978 // At this point, we know that we perform a cross-register-bank copy. 9979 // Check if it is expensive. 9980 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 9981 // Assume bitcasts are cheap, unless both register classes do not 9982 // explicitly share a common sub class. 9983 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 9984 return false; 9985 9986 // Check if it will be merged with the load. 9987 // 1. Check the alignment constraint. 9988 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 9989 ResVT.getTypeForEVT(*DAG->getContext())); 9990 9991 if (RequiredAlignment > getAlignment()) 9992 return false; 9993 9994 // 2. Check that the load is a legal operation for that type. 9995 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 9996 return false; 9997 9998 // 3. Check that we do not have a zext in the way. 9999 if (Inst->getValueType(0) != getLoadedType()) 10000 return false; 10001 10002 return true; 10003 } 10004 }; 10005 } 10006 10007 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10008 /// \p UsedBits looks like 0..0 1..1 0..0. 10009 static bool areUsedBitsDense(const APInt &UsedBits) { 10010 // If all the bits are one, this is dense! 10011 if (UsedBits.isAllOnesValue()) 10012 return true; 10013 10014 // Get rid of the unused bits on the right. 10015 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10016 // Get rid of the unused bits on the left. 10017 if (NarrowedUsedBits.countLeadingZeros()) 10018 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10019 // Check that the chunk of bits is completely used. 10020 return NarrowedUsedBits.isAllOnesValue(); 10021 } 10022 10023 /// \brief Check whether or not \p First and \p Second are next to each other 10024 /// in memory. This means that there is no hole between the bits loaded 10025 /// by \p First and the bits loaded by \p Second. 10026 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10027 const LoadedSlice &Second) { 10028 assert(First.Origin == Second.Origin && First.Origin && 10029 "Unable to match different memory origins."); 10030 APInt UsedBits = First.getUsedBits(); 10031 assert((UsedBits & Second.getUsedBits()) == 0 && 10032 "Slices are not supposed to overlap."); 10033 UsedBits |= Second.getUsedBits(); 10034 return areUsedBitsDense(UsedBits); 10035 } 10036 10037 /// \brief Adjust the \p GlobalLSCost according to the target 10038 /// paring capabilities and the layout of the slices. 10039 /// \pre \p GlobalLSCost should account for at least as many loads as 10040 /// there is in the slices in \p LoadedSlices. 10041 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10042 LoadedSlice::Cost &GlobalLSCost) { 10043 unsigned NumberOfSlices = LoadedSlices.size(); 10044 // If there is less than 2 elements, no pairing is possible. 10045 if (NumberOfSlices < 2) 10046 return; 10047 10048 // Sort the slices so that elements that are likely to be next to each 10049 // other in memory are next to each other in the list. 10050 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10051 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10052 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10053 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10054 }); 10055 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10056 // First (resp. Second) is the first (resp. Second) potentially candidate 10057 // to be placed in a paired load. 10058 const LoadedSlice *First = nullptr; 10059 const LoadedSlice *Second = nullptr; 10060 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10061 // Set the beginning of the pair. 10062 First = Second) { 10063 10064 Second = &LoadedSlices[CurrSlice]; 10065 10066 // If First is NULL, it means we start a new pair. 10067 // Get to the next slice. 10068 if (!First) 10069 continue; 10070 10071 EVT LoadedType = First->getLoadedType(); 10072 10073 // If the types of the slices are different, we cannot pair them. 10074 if (LoadedType != Second->getLoadedType()) 10075 continue; 10076 10077 // Check if the target supplies paired loads for this type. 10078 unsigned RequiredAlignment = 0; 10079 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10080 // move to the next pair, this type is hopeless. 10081 Second = nullptr; 10082 continue; 10083 } 10084 // Check if we meet the alignment requirement. 10085 if (RequiredAlignment > First->getAlignment()) 10086 continue; 10087 10088 // Check that both loads are next to each other in memory. 10089 if (!areSlicesNextToEachOther(*First, *Second)) 10090 continue; 10091 10092 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10093 --GlobalLSCost.Loads; 10094 // Move to the next pair. 10095 Second = nullptr; 10096 } 10097 } 10098 10099 /// \brief Check the profitability of all involved LoadedSlice. 10100 /// Currently, it is considered profitable if there is exactly two 10101 /// involved slices (1) which are (2) next to each other in memory, and 10102 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10103 /// 10104 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10105 /// the elements themselves. 10106 /// 10107 /// FIXME: When the cost model will be mature enough, we can relax 10108 /// constraints (1) and (2). 10109 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10110 const APInt &UsedBits, bool ForCodeSize) { 10111 unsigned NumberOfSlices = LoadedSlices.size(); 10112 if (StressLoadSlicing) 10113 return NumberOfSlices > 1; 10114 10115 // Check (1). 10116 if (NumberOfSlices != 2) 10117 return false; 10118 10119 // Check (2). 10120 if (!areUsedBitsDense(UsedBits)) 10121 return false; 10122 10123 // Check (3). 10124 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10125 // The original code has one big load. 10126 OrigCost.Loads = 1; 10127 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10128 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10129 // Accumulate the cost of all the slices. 10130 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10131 GlobalSlicingCost += SliceCost; 10132 10133 // Account as cost in the original configuration the gain obtained 10134 // with the current slices. 10135 OrigCost.addSliceGain(LS); 10136 } 10137 10138 // If the target supports paired load, adjust the cost accordingly. 10139 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10140 return OrigCost > GlobalSlicingCost; 10141 } 10142 10143 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10144 /// operations, split it in the various pieces being extracted. 10145 /// 10146 /// This sort of thing is introduced by SROA. 10147 /// This slicing takes care not to insert overlapping loads. 10148 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10149 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10150 if (Level < AfterLegalizeDAG) 10151 return false; 10152 10153 LoadSDNode *LD = cast<LoadSDNode>(N); 10154 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10155 !LD->getValueType(0).isInteger()) 10156 return false; 10157 10158 // Keep track of already used bits to detect overlapping values. 10159 // In that case, we will just abort the transformation. 10160 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10161 10162 SmallVector<LoadedSlice, 4> LoadedSlices; 10163 10164 // Check if this load is used as several smaller chunks of bits. 10165 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10166 // of computation for each trunc. 10167 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10168 UI != UIEnd; ++UI) { 10169 // Skip the uses of the chain. 10170 if (UI.getUse().getResNo() != 0) 10171 continue; 10172 10173 SDNode *User = *UI; 10174 unsigned Shift = 0; 10175 10176 // Check if this is a trunc(lshr). 10177 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10178 isa<ConstantSDNode>(User->getOperand(1))) { 10179 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10180 User = *User->use_begin(); 10181 } 10182 10183 // At this point, User is a Truncate, iff we encountered, trunc or 10184 // trunc(lshr). 10185 if (User->getOpcode() != ISD::TRUNCATE) 10186 return false; 10187 10188 // The width of the type must be a power of 2 and greater than 8-bits. 10189 // Otherwise the load cannot be represented in LLVM IR. 10190 // Moreover, if we shifted with a non-8-bits multiple, the slice 10191 // will be across several bytes. We do not support that. 10192 unsigned Width = User->getValueSizeInBits(0); 10193 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10194 return 0; 10195 10196 // Build the slice for this chain of computations. 10197 LoadedSlice LS(User, LD, Shift, &DAG); 10198 APInt CurrentUsedBits = LS.getUsedBits(); 10199 10200 // Check if this slice overlaps with another. 10201 if ((CurrentUsedBits & UsedBits) != 0) 10202 return false; 10203 // Update the bits used globally. 10204 UsedBits |= CurrentUsedBits; 10205 10206 // Check if the new slice would be legal. 10207 if (!LS.isLegal()) 10208 return false; 10209 10210 // Record the slice. 10211 LoadedSlices.push_back(LS); 10212 } 10213 10214 // Abort slicing if it does not seem to be profitable. 10215 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10216 return false; 10217 10218 ++SlicedLoads; 10219 10220 // Rewrite each chain to use an independent load. 10221 // By construction, each chain can be represented by a unique load. 10222 10223 // Prepare the argument for the new token factor for all the slices. 10224 SmallVector<SDValue, 8> ArgChains; 10225 for (SmallVectorImpl<LoadedSlice>::const_iterator 10226 LSIt = LoadedSlices.begin(), 10227 LSItEnd = LoadedSlices.end(); 10228 LSIt != LSItEnd; ++LSIt) { 10229 SDValue SliceInst = LSIt->loadSlice(); 10230 CombineTo(LSIt->Inst, SliceInst, true); 10231 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10232 SliceInst = SliceInst.getOperand(0); 10233 assert(SliceInst->getOpcode() == ISD::LOAD && 10234 "It takes more than a zext to get to the loaded slice!!"); 10235 ArgChains.push_back(SliceInst.getValue(1)); 10236 } 10237 10238 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10239 ArgChains); 10240 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10241 return true; 10242 } 10243 10244 /// Check to see if V is (and load (ptr), imm), where the load is having 10245 /// specific bytes cleared out. If so, return the byte size being masked out 10246 /// and the shift amount. 10247 static std::pair<unsigned, unsigned> 10248 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10249 std::pair<unsigned, unsigned> Result(0, 0); 10250 10251 // Check for the structure we're looking for. 10252 if (V->getOpcode() != ISD::AND || 10253 !isa<ConstantSDNode>(V->getOperand(1)) || 10254 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10255 return Result; 10256 10257 // Check the chain and pointer. 10258 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10259 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10260 10261 // The store should be chained directly to the load or be an operand of a 10262 // tokenfactor. 10263 if (LD == Chain.getNode()) 10264 ; // ok. 10265 else if (Chain->getOpcode() != ISD::TokenFactor) 10266 return Result; // Fail. 10267 else { 10268 bool isOk = false; 10269 for (const SDValue &ChainOp : Chain->op_values()) 10270 if (ChainOp.getNode() == LD) { 10271 isOk = true; 10272 break; 10273 } 10274 if (!isOk) return Result; 10275 } 10276 10277 // This only handles simple types. 10278 if (V.getValueType() != MVT::i16 && 10279 V.getValueType() != MVT::i32 && 10280 V.getValueType() != MVT::i64) 10281 return Result; 10282 10283 // Check the constant mask. Invert it so that the bits being masked out are 10284 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10285 // follow the sign bit for uniformity. 10286 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10287 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10288 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10289 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10290 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10291 if (NotMaskLZ == 64) return Result; // All zero mask. 10292 10293 // See if we have a continuous run of bits. If so, we have 0*1+0* 10294 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10295 return Result; 10296 10297 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10298 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10299 NotMaskLZ -= 64-V.getValueSizeInBits(); 10300 10301 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10302 switch (MaskedBytes) { 10303 case 1: 10304 case 2: 10305 case 4: break; 10306 default: return Result; // All one mask, or 5-byte mask. 10307 } 10308 10309 // Verify that the first bit starts at a multiple of mask so that the access 10310 // is aligned the same as the access width. 10311 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10312 10313 Result.first = MaskedBytes; 10314 Result.second = NotMaskTZ/8; 10315 return Result; 10316 } 10317 10318 10319 /// Check to see if IVal is something that provides a value as specified by 10320 /// MaskInfo. If so, replace the specified store with a narrower store of 10321 /// truncated IVal. 10322 static SDNode * 10323 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10324 SDValue IVal, StoreSDNode *St, 10325 DAGCombiner *DC) { 10326 unsigned NumBytes = MaskInfo.first; 10327 unsigned ByteShift = MaskInfo.second; 10328 SelectionDAG &DAG = DC->getDAG(); 10329 10330 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10331 // that uses this. If not, this is not a replacement. 10332 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10333 ByteShift*8, (ByteShift+NumBytes)*8); 10334 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10335 10336 // Check that it is legal on the target to do this. It is legal if the new 10337 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10338 // legalization. 10339 MVT VT = MVT::getIntegerVT(NumBytes*8); 10340 if (!DC->isTypeLegal(VT)) 10341 return nullptr; 10342 10343 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10344 // shifted by ByteShift and truncated down to NumBytes. 10345 if (ByteShift) { 10346 SDLoc DL(IVal); 10347 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10348 DAG.getConstant(ByteShift*8, DL, 10349 DC->getShiftAmountTy(IVal.getValueType()))); 10350 } 10351 10352 // Figure out the offset for the store and the alignment of the access. 10353 unsigned StOffset; 10354 unsigned NewAlign = St->getAlignment(); 10355 10356 if (DAG.getDataLayout().isLittleEndian()) 10357 StOffset = ByteShift; 10358 else 10359 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10360 10361 SDValue Ptr = St->getBasePtr(); 10362 if (StOffset) { 10363 SDLoc DL(IVal); 10364 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10365 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10366 NewAlign = MinAlign(NewAlign, StOffset); 10367 } 10368 10369 // Truncate down to the new size. 10370 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10371 10372 ++OpsNarrowed; 10373 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10374 St->getPointerInfo().getWithOffset(StOffset), 10375 false, false, NewAlign).getNode(); 10376 } 10377 10378 10379 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10380 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10381 /// narrowing the load and store if it would end up being a win for performance 10382 /// or code size. 10383 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10384 StoreSDNode *ST = cast<StoreSDNode>(N); 10385 if (ST->isVolatile()) 10386 return SDValue(); 10387 10388 SDValue Chain = ST->getChain(); 10389 SDValue Value = ST->getValue(); 10390 SDValue Ptr = ST->getBasePtr(); 10391 EVT VT = Value.getValueType(); 10392 10393 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10394 return SDValue(); 10395 10396 unsigned Opc = Value.getOpcode(); 10397 10398 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10399 // is a byte mask indicating a consecutive number of bytes, check to see if 10400 // Y is known to provide just those bytes. If so, we try to replace the 10401 // load + replace + store sequence with a single (narrower) store, which makes 10402 // the load dead. 10403 if (Opc == ISD::OR) { 10404 std::pair<unsigned, unsigned> MaskedLoad; 10405 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10406 if (MaskedLoad.first) 10407 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10408 Value.getOperand(1), ST,this)) 10409 return SDValue(NewST, 0); 10410 10411 // Or is commutative, so try swapping X and Y. 10412 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10413 if (MaskedLoad.first) 10414 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10415 Value.getOperand(0), ST,this)) 10416 return SDValue(NewST, 0); 10417 } 10418 10419 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10420 Value.getOperand(1).getOpcode() != ISD::Constant) 10421 return SDValue(); 10422 10423 SDValue N0 = Value.getOperand(0); 10424 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10425 Chain == SDValue(N0.getNode(), 1)) { 10426 LoadSDNode *LD = cast<LoadSDNode>(N0); 10427 if (LD->getBasePtr() != Ptr || 10428 LD->getPointerInfo().getAddrSpace() != 10429 ST->getPointerInfo().getAddrSpace()) 10430 return SDValue(); 10431 10432 // Find the type to narrow it the load / op / store to. 10433 SDValue N1 = Value.getOperand(1); 10434 unsigned BitWidth = N1.getValueSizeInBits(); 10435 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10436 if (Opc == ISD::AND) 10437 Imm ^= APInt::getAllOnesValue(BitWidth); 10438 if (Imm == 0 || Imm.isAllOnesValue()) 10439 return SDValue(); 10440 unsigned ShAmt = Imm.countTrailingZeros(); 10441 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10442 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10443 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10444 // The narrowing should be profitable, the load/store operation should be 10445 // legal (or custom) and the store size should be equal to the NewVT width. 10446 while (NewBW < BitWidth && 10447 (NewVT.getStoreSizeInBits() != NewBW || 10448 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10449 !TLI.isNarrowingProfitable(VT, NewVT))) { 10450 NewBW = NextPowerOf2(NewBW); 10451 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10452 } 10453 if (NewBW >= BitWidth) 10454 return SDValue(); 10455 10456 // If the lsb changed does not start at the type bitwidth boundary, 10457 // start at the previous one. 10458 if (ShAmt % NewBW) 10459 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10460 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10461 std::min(BitWidth, ShAmt + NewBW)); 10462 if ((Imm & Mask) == Imm) { 10463 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10464 if (Opc == ISD::AND) 10465 NewImm ^= APInt::getAllOnesValue(NewBW); 10466 uint64_t PtrOff = ShAmt / 8; 10467 // For big endian targets, we need to adjust the offset to the pointer to 10468 // load the correct bytes. 10469 if (DAG.getDataLayout().isBigEndian()) 10470 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10471 10472 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10473 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10474 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10475 return SDValue(); 10476 10477 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10478 Ptr.getValueType(), Ptr, 10479 DAG.getConstant(PtrOff, SDLoc(LD), 10480 Ptr.getValueType())); 10481 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10482 LD->getChain(), NewPtr, 10483 LD->getPointerInfo().getWithOffset(PtrOff), 10484 LD->isVolatile(), LD->isNonTemporal(), 10485 LD->isInvariant(), NewAlign, 10486 LD->getAAInfo()); 10487 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10488 DAG.getConstant(NewImm, SDLoc(Value), 10489 NewVT)); 10490 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10491 NewVal, NewPtr, 10492 ST->getPointerInfo().getWithOffset(PtrOff), 10493 false, false, NewAlign); 10494 10495 AddToWorklist(NewPtr.getNode()); 10496 AddToWorklist(NewLD.getNode()); 10497 AddToWorklist(NewVal.getNode()); 10498 WorklistRemover DeadNodes(*this); 10499 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10500 ++OpsNarrowed; 10501 return NewST; 10502 } 10503 } 10504 10505 return SDValue(); 10506 } 10507 10508 /// For a given floating point load / store pair, if the load value isn't used 10509 /// by any other operations, then consider transforming the pair to integer 10510 /// load / store operations if the target deems the transformation profitable. 10511 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10512 StoreSDNode *ST = cast<StoreSDNode>(N); 10513 SDValue Chain = ST->getChain(); 10514 SDValue Value = ST->getValue(); 10515 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10516 Value.hasOneUse() && 10517 Chain == SDValue(Value.getNode(), 1)) { 10518 LoadSDNode *LD = cast<LoadSDNode>(Value); 10519 EVT VT = LD->getMemoryVT(); 10520 if (!VT.isFloatingPoint() || 10521 VT != ST->getMemoryVT() || 10522 LD->isNonTemporal() || 10523 ST->isNonTemporal() || 10524 LD->getPointerInfo().getAddrSpace() != 0 || 10525 ST->getPointerInfo().getAddrSpace() != 0) 10526 return SDValue(); 10527 10528 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10529 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10530 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10531 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10532 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10533 return SDValue(); 10534 10535 unsigned LDAlign = LD->getAlignment(); 10536 unsigned STAlign = ST->getAlignment(); 10537 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10538 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10539 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10540 return SDValue(); 10541 10542 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10543 LD->getChain(), LD->getBasePtr(), 10544 LD->getPointerInfo(), 10545 false, false, false, LDAlign); 10546 10547 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10548 NewLD, ST->getBasePtr(), 10549 ST->getPointerInfo(), 10550 false, false, STAlign); 10551 10552 AddToWorklist(NewLD.getNode()); 10553 AddToWorklist(NewST.getNode()); 10554 WorklistRemover DeadNodes(*this); 10555 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10556 ++LdStFP2Int; 10557 return NewST; 10558 } 10559 10560 return SDValue(); 10561 } 10562 10563 namespace { 10564 /// Helper struct to parse and store a memory address as base + index + offset. 10565 /// We ignore sign extensions when it is safe to do so. 10566 /// The following two expressions are not equivalent. To differentiate we need 10567 /// to store whether there was a sign extension involved in the index 10568 /// computation. 10569 /// (load (i64 add (i64 copyfromreg %c) 10570 /// (i64 signextend (add (i8 load %index) 10571 /// (i8 1)))) 10572 /// vs 10573 /// 10574 /// (load (i64 add (i64 copyfromreg %c) 10575 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10576 /// (i32 1))))) 10577 struct BaseIndexOffset { 10578 SDValue Base; 10579 SDValue Index; 10580 int64_t Offset; 10581 bool IsIndexSignExt; 10582 10583 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10584 10585 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10586 bool IsIndexSignExt) : 10587 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10588 10589 bool equalBaseIndex(const BaseIndexOffset &Other) { 10590 return Other.Base == Base && Other.Index == Index && 10591 Other.IsIndexSignExt == IsIndexSignExt; 10592 } 10593 10594 /// Parses tree in Ptr for base, index, offset addresses. 10595 static BaseIndexOffset match(SDValue Ptr) { 10596 bool IsIndexSignExt = false; 10597 10598 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10599 // instruction, then it could be just the BASE or everything else we don't 10600 // know how to handle. Just use Ptr as BASE and give up. 10601 if (Ptr->getOpcode() != ISD::ADD) 10602 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10603 10604 // We know that we have at least an ADD instruction. Try to pattern match 10605 // the simple case of BASE + OFFSET. 10606 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10607 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10608 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10609 IsIndexSignExt); 10610 } 10611 10612 // Inside a loop the current BASE pointer is calculated using an ADD and a 10613 // MUL instruction. In this case Ptr is the actual BASE pointer. 10614 // (i64 add (i64 %array_ptr) 10615 // (i64 mul (i64 %induction_var) 10616 // (i64 %element_size))) 10617 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10618 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10619 10620 // Look at Base + Index + Offset cases. 10621 SDValue Base = Ptr->getOperand(0); 10622 SDValue IndexOffset = Ptr->getOperand(1); 10623 10624 // Skip signextends. 10625 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10626 IndexOffset = IndexOffset->getOperand(0); 10627 IsIndexSignExt = true; 10628 } 10629 10630 // Either the case of Base + Index (no offset) or something else. 10631 if (IndexOffset->getOpcode() != ISD::ADD) 10632 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10633 10634 // Now we have the case of Base + Index + offset. 10635 SDValue Index = IndexOffset->getOperand(0); 10636 SDValue Offset = IndexOffset->getOperand(1); 10637 10638 if (!isa<ConstantSDNode>(Offset)) 10639 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10640 10641 // Ignore signextends. 10642 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10643 Index = Index->getOperand(0); 10644 IsIndexSignExt = true; 10645 } else IsIndexSignExt = false; 10646 10647 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10648 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10649 } 10650 }; 10651 } // namespace 10652 10653 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 10654 SDLoc SL, 10655 ArrayRef<MemOpLink> Stores, 10656 EVT Ty) const { 10657 SmallVector<SDValue, 8> BuildVector; 10658 10659 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) 10660 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue()); 10661 10662 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 10663 } 10664 10665 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10666 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10667 unsigned NumElem, bool IsConstantSrc, bool UseVector) { 10668 // Make sure we have something to merge. 10669 if (NumElem < 2) 10670 return false; 10671 10672 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10673 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10674 unsigned LatestNodeUsed = 0; 10675 10676 for (unsigned i=0; i < NumElem; ++i) { 10677 // Find a chain for the new wide-store operand. Notice that some 10678 // of the store nodes that we found may not be selected for inclusion 10679 // in the wide store. The chain we use needs to be the chain of the 10680 // latest store node which is *used* and replaced by the wide store. 10681 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10682 LatestNodeUsed = i; 10683 } 10684 10685 // The latest Node in the DAG. 10686 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10687 SDLoc DL(StoreNodes[0].MemNode); 10688 10689 SDValue StoredVal; 10690 if (UseVector) { 10691 // Find a legal type for the vector store. 10692 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10693 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 10694 if (IsConstantSrc) { 10695 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty); 10696 } else { 10697 SmallVector<SDValue, 8> Ops; 10698 for (unsigned i = 0; i < NumElem ; ++i) { 10699 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10700 SDValue Val = St->getValue(); 10701 // All of the operands of a BUILD_VECTOR must have the same type. 10702 if (Val.getValueType() != MemVT) 10703 return false; 10704 Ops.push_back(Val); 10705 } 10706 10707 // Build the extracted vector elements back into a vector. 10708 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops); 10709 } 10710 } else { 10711 // We should always use a vector store when merging extracted vector 10712 // elements, so this path implies a store of constants. 10713 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10714 10715 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 10716 APInt StoreInt(SizeInBits, 0); 10717 10718 // Construct a single integer constant which is made of the smaller 10719 // constant inputs. 10720 bool IsLE = DAG.getDataLayout().isLittleEndian(); 10721 for (unsigned i = 0; i < NumElem ; ++i) { 10722 unsigned Idx = IsLE ? (NumElem - 1 - i) : i; 10723 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10724 SDValue Val = St->getValue(); 10725 StoreInt <<= ElementSizeBytes * 8; 10726 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10727 StoreInt |= C->getAPIntValue().zext(SizeInBits); 10728 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10729 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 10730 } else { 10731 llvm_unreachable("Invalid constant element type"); 10732 } 10733 } 10734 10735 // Create the new Load and Store operations. 10736 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 10737 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 10738 } 10739 10740 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal, 10741 FirstInChain->getBasePtr(), 10742 FirstInChain->getPointerInfo(), 10743 false, false, 10744 FirstInChain->getAlignment()); 10745 10746 // Replace the last store with the new store 10747 CombineTo(LatestOp, NewStore); 10748 // Erase all other stores. 10749 for (unsigned i = 0; i < NumElem ; ++i) { 10750 if (StoreNodes[i].MemNode == LatestOp) 10751 continue; 10752 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10753 // ReplaceAllUsesWith will replace all uses that existed when it was 10754 // called, but graph optimizations may cause new ones to appear. For 10755 // example, the case in pr14333 looks like 10756 // 10757 // St's chain -> St -> another store -> X 10758 // 10759 // And the only difference from St to the other store is the chain. 10760 // When we change it's chain to be St's chain they become identical, 10761 // get CSEed and the net result is that X is now a use of St. 10762 // Since we know that St is redundant, just iterate. 10763 while (!St->use_empty()) 10764 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10765 deleteAndRecombine(St); 10766 } 10767 10768 return true; 10769 } 10770 10771 void DAGCombiner::getStoreMergeAndAliasCandidates( 10772 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 10773 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 10774 // This holds the base pointer, index, and the offset in bytes from the base 10775 // pointer. 10776 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10777 10778 // We must have a base and an offset. 10779 if (!BasePtr.Base.getNode()) 10780 return; 10781 10782 // Do not handle stores to undef base pointers. 10783 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10784 return; 10785 10786 // Walk up the chain and look for nodes with offsets from the same 10787 // base pointer. Stop when reaching an instruction with a different kind 10788 // or instruction which has a different base pointer. 10789 EVT MemVT = St->getMemoryVT(); 10790 unsigned Seq = 0; 10791 StoreSDNode *Index = St; 10792 while (Index) { 10793 // If the chain has more than one use, then we can't reorder the mem ops. 10794 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10795 break; 10796 10797 // Find the base pointer and offset for this memory node. 10798 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 10799 10800 // Check that the base pointer is the same as the original one. 10801 if (!Ptr.equalBaseIndex(BasePtr)) 10802 break; 10803 10804 // The memory operands must not be volatile. 10805 if (Index->isVolatile() || Index->isIndexed()) 10806 break; 10807 10808 // No truncation. 10809 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 10810 if (St->isTruncatingStore()) 10811 break; 10812 10813 // The stored memory type must be the same. 10814 if (Index->getMemoryVT() != MemVT) 10815 break; 10816 10817 // We found a potential memory operand to merge. 10818 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 10819 10820 // Find the next memory operand in the chain. If the next operand in the 10821 // chain is a store then move up and continue the scan with the next 10822 // memory operand. If the next operand is a load save it and use alias 10823 // information to check if it interferes with anything. 10824 SDNode *NextInChain = Index->getChain().getNode(); 10825 while (1) { 10826 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 10827 // We found a store node. Use it for the next iteration. 10828 Index = STn; 10829 break; 10830 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 10831 if (Ldn->isVolatile()) { 10832 Index = nullptr; 10833 break; 10834 } 10835 10836 // Save the load node for later. Continue the scan. 10837 AliasLoadNodes.push_back(Ldn); 10838 NextInChain = Ldn->getChain().getNode(); 10839 continue; 10840 } else { 10841 Index = nullptr; 10842 break; 10843 } 10844 } 10845 } 10846 } 10847 10848 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 10849 if (OptLevel == CodeGenOpt::None) 10850 return false; 10851 10852 EVT MemVT = St->getMemoryVT(); 10853 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10854 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 10855 Attribute::NoImplicitFloat); 10856 10857 // This function cannot currently deal with non-byte-sized memory sizes. 10858 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 10859 return false; 10860 10861 // Don't merge vectors into wider inputs. 10862 if (MemVT.isVector() || !MemVT.isSimple()) 10863 return false; 10864 10865 // Perform an early exit check. Do not bother looking at stored values that 10866 // are not constants, loads, or extracted vector elements. 10867 SDValue StoredVal = St->getValue(); 10868 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 10869 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 10870 isa<ConstantFPSDNode>(StoredVal); 10871 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 10872 10873 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 10874 return false; 10875 10876 // Only look at ends of store sequences. 10877 SDValue Chain = SDValue(St, 0); 10878 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 10879 return false; 10880 10881 // Save the LoadSDNodes that we find in the chain. 10882 // We need to make sure that these nodes do not interfere with 10883 // any of the store nodes. 10884 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 10885 10886 // Save the StoreSDNodes that we find in the chain. 10887 SmallVector<MemOpLink, 8> StoreNodes; 10888 10889 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 10890 10891 // Check if there is anything to merge. 10892 if (StoreNodes.size() < 2) 10893 return false; 10894 10895 // Sort the memory operands according to their distance from the base pointer. 10896 std::sort(StoreNodes.begin(), StoreNodes.end(), 10897 [](MemOpLink LHS, MemOpLink RHS) { 10898 return LHS.OffsetFromBase < RHS.OffsetFromBase || 10899 (LHS.OffsetFromBase == RHS.OffsetFromBase && 10900 LHS.SequenceNum > RHS.SequenceNum); 10901 }); 10902 10903 // Scan the memory operations on the chain and find the first non-consecutive 10904 // store memory address. 10905 unsigned LastConsecutiveStore = 0; 10906 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 10907 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 10908 10909 // Check that the addresses are consecutive starting from the second 10910 // element in the list of stores. 10911 if (i > 0) { 10912 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 10913 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10914 break; 10915 } 10916 10917 bool Alias = false; 10918 // Check if this store interferes with any of the loads that we found. 10919 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 10920 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 10921 Alias = true; 10922 break; 10923 } 10924 // We found a load that alias with this store. Stop the sequence. 10925 if (Alias) 10926 break; 10927 10928 // Mark this node as useful. 10929 LastConsecutiveStore = i; 10930 } 10931 10932 // The node with the lowest store address. 10933 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10934 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 10935 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 10936 LLVMContext &Context = *DAG.getContext(); 10937 const DataLayout &DL = DAG.getDataLayout(); 10938 10939 // Store the constants into memory as one consecutive store. 10940 if (IsConstantSrc) { 10941 unsigned LastLegalType = 0; 10942 unsigned LastLegalVectorType = 0; 10943 bool NonZero = false; 10944 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10945 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10946 SDValue StoredVal = St->getValue(); 10947 10948 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 10949 NonZero |= !C->isNullValue(); 10950 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 10951 NonZero |= !C->getConstantFPValue()->isNullValue(); 10952 } else { 10953 // Non-constant. 10954 break; 10955 } 10956 10957 // Find a legal type for the constant store. 10958 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 10959 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 10960 if (TLI.isTypeLegal(StoreTy) && 10961 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 10962 FirstStoreAlign)) { 10963 LastLegalType = i+1; 10964 // Or check whether a truncstore is legal. 10965 } else if (TLI.getTypeAction(Context, StoreTy) == 10966 TargetLowering::TypePromoteInteger) { 10967 EVT LegalizedStoredValueTy = 10968 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 10969 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10970 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 10971 FirstStoreAS, FirstStoreAlign)) { 10972 LastLegalType = i + 1; 10973 } 10974 } 10975 10976 // Find a legal type for the vector store. 10977 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 10978 if (TLI.isTypeLegal(Ty) && 10979 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 10980 FirstStoreAlign)) { 10981 LastLegalVectorType = i + 1; 10982 } 10983 } 10984 10985 10986 // We only use vectors if the constant is known to be zero or the target 10987 // allows it and the function is not marked with the noimplicitfloat 10988 // attribute. 10989 if (NoVectors) { 10990 LastLegalVectorType = 0; 10991 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT, 10992 LastLegalVectorType, 10993 FirstStoreAS)) { 10994 LastLegalVectorType = 0; 10995 } 10996 10997 // Check if we found a legal integer type to store. 10998 if (LastLegalType == 0 && LastLegalVectorType == 0) 10999 return false; 11000 11001 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11002 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11003 11004 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11005 true, UseVector); 11006 } 11007 11008 // When extracting multiple vector elements, try to store them 11009 // in one vector store rather than a sequence of scalar stores. 11010 if (IsExtractVecEltSrc) { 11011 unsigned NumElem = 0; 11012 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11013 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11014 SDValue StoredVal = St->getValue(); 11015 // This restriction could be loosened. 11016 // Bail out if any stored values are not elements extracted from a vector. 11017 // It should be possible to handle mixed sources, but load sources need 11018 // more careful handling (see the block of code below that handles 11019 // consecutive loads). 11020 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11021 return false; 11022 11023 // Find a legal type for the vector store. 11024 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11025 if (TLI.isTypeLegal(Ty) && 11026 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11027 FirstStoreAlign)) 11028 NumElem = i + 1; 11029 } 11030 11031 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11032 false, true); 11033 } 11034 11035 // Below we handle the case of multiple consecutive stores that 11036 // come from multiple consecutive loads. We merge them into a single 11037 // wide load and a single wide store. 11038 11039 // Look for load nodes which are used by the stored values. 11040 SmallVector<MemOpLink, 8> LoadNodes; 11041 11042 // Find acceptable loads. Loads need to have the same chain (token factor), 11043 // must not be zext, volatile, indexed, and they must be consecutive. 11044 BaseIndexOffset LdBasePtr; 11045 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11046 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11047 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11048 if (!Ld) break; 11049 11050 // Loads must only have one use. 11051 if (!Ld->hasNUsesOfValue(1, 0)) 11052 break; 11053 11054 // The memory operands must not be volatile. 11055 if (Ld->isVolatile() || Ld->isIndexed()) 11056 break; 11057 11058 // We do not accept ext loads. 11059 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11060 break; 11061 11062 // The stored memory type must be the same. 11063 if (Ld->getMemoryVT() != MemVT) 11064 break; 11065 11066 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 11067 // If this is not the first ptr that we check. 11068 if (LdBasePtr.Base.getNode()) { 11069 // The base ptr must be the same. 11070 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11071 break; 11072 } else { 11073 // Check that all other base pointers are the same as this one. 11074 LdBasePtr = LdPtr; 11075 } 11076 11077 // We found a potential memory operand to merge. 11078 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11079 } 11080 11081 if (LoadNodes.size() < 2) 11082 return false; 11083 11084 // If we have load/store pair instructions and we only have two values, 11085 // don't bother. 11086 unsigned RequiredAlignment; 11087 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11088 St->getAlignment() >= RequiredAlignment) 11089 return false; 11090 11091 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11092 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11093 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11094 11095 // Scan the memory operations on the chain and find the first non-consecutive 11096 // load memory address. These variables hold the index in the store node 11097 // array. 11098 unsigned LastConsecutiveLoad = 0; 11099 // This variable refers to the size and not index in the array. 11100 unsigned LastLegalVectorType = 0; 11101 unsigned LastLegalIntegerType = 0; 11102 StartAddress = LoadNodes[0].OffsetFromBase; 11103 SDValue FirstChain = FirstLoad->getChain(); 11104 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11105 // All loads much share the same chain. 11106 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11107 break; 11108 11109 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11110 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11111 break; 11112 LastConsecutiveLoad = i; 11113 11114 // Find a legal type for the vector store. 11115 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11116 if (TLI.isTypeLegal(StoreTy) && 11117 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11118 FirstStoreAlign) && 11119 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11120 FirstLoadAlign)) { 11121 LastLegalVectorType = i + 1; 11122 } 11123 11124 // Find a legal type for the integer store. 11125 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11126 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11127 if (TLI.isTypeLegal(StoreTy) && 11128 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11129 FirstStoreAlign) && 11130 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11131 FirstLoadAlign)) 11132 LastLegalIntegerType = i + 1; 11133 // Or check whether a truncstore and extload is legal. 11134 else if (TLI.getTypeAction(Context, StoreTy) == 11135 TargetLowering::TypePromoteInteger) { 11136 EVT LegalizedStoredValueTy = 11137 TLI.getTypeToTransformTo(Context, StoreTy); 11138 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11139 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11140 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11141 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11142 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11143 FirstStoreAS, FirstStoreAlign) && 11144 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11145 FirstLoadAS, FirstLoadAlign)) 11146 LastLegalIntegerType = i+1; 11147 } 11148 } 11149 11150 // Only use vector types if the vector type is larger than the integer type. 11151 // If they are the same, use integers. 11152 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11153 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11154 11155 // We add +1 here because the LastXXX variables refer to location while 11156 // the NumElem refers to array/index size. 11157 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11158 NumElem = std::min(LastLegalType, NumElem); 11159 11160 if (NumElem < 2) 11161 return false; 11162 11163 // The latest Node in the DAG. 11164 unsigned LatestNodeUsed = 0; 11165 for (unsigned i=1; i<NumElem; ++i) { 11166 // Find a chain for the new wide-store operand. Notice that some 11167 // of the store nodes that we found may not be selected for inclusion 11168 // in the wide store. The chain we use needs to be the chain of the 11169 // latest store node which is *used* and replaced by the wide store. 11170 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11171 LatestNodeUsed = i; 11172 } 11173 11174 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11175 11176 // Find if it is better to use vectors or integers to load and store 11177 // to memory. 11178 EVT JointMemOpVT; 11179 if (UseVectorTy) { 11180 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11181 } else { 11182 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11183 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11184 } 11185 11186 SDLoc LoadDL(LoadNodes[0].MemNode); 11187 SDLoc StoreDL(StoreNodes[0].MemNode); 11188 11189 SDValue NewLoad = DAG.getLoad( 11190 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11191 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11192 11193 SDValue NewStore = DAG.getStore( 11194 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(), 11195 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11196 11197 // Replace one of the loads with the new load. 11198 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 11199 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11200 SDValue(NewLoad.getNode(), 1)); 11201 11202 // Remove the rest of the load chains. 11203 for (unsigned i = 1; i < NumElem ; ++i) { 11204 // Replace all chain users of the old load nodes with the chain of the new 11205 // load node. 11206 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11207 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 11208 } 11209 11210 // Replace the last store with the new store. 11211 CombineTo(LatestOp, NewStore); 11212 // Erase all other stores. 11213 for (unsigned i = 0; i < NumElem ; ++i) { 11214 // Remove all Store nodes. 11215 if (StoreNodes[i].MemNode == LatestOp) 11216 continue; 11217 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11218 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11219 deleteAndRecombine(St); 11220 } 11221 11222 return true; 11223 } 11224 11225 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11226 StoreSDNode *ST = cast<StoreSDNode>(N); 11227 SDValue Chain = ST->getChain(); 11228 SDValue Value = ST->getValue(); 11229 SDValue Ptr = ST->getBasePtr(); 11230 11231 // If this is a store of a bit convert, store the input value if the 11232 // resultant store does not need a higher alignment than the original. 11233 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11234 ST->isUnindexed()) { 11235 unsigned OrigAlign = ST->getAlignment(); 11236 EVT SVT = Value.getOperand(0).getValueType(); 11237 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11238 SVT.getTypeForEVT(*DAG.getContext())); 11239 if (Align <= OrigAlign && 11240 ((!LegalOperations && !ST->isVolatile()) || 11241 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11242 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11243 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11244 ST->isNonTemporal(), OrigAlign, 11245 ST->getAAInfo()); 11246 } 11247 11248 // Turn 'store undef, Ptr' -> nothing. 11249 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11250 return Chain; 11251 11252 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11253 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 11254 // NOTE: If the original store is volatile, this transform must not increase 11255 // the number of stores. For example, on x86-32 an f64 can be stored in one 11256 // processor operation but an i64 (which is not legal) requires two. So the 11257 // transform should not be done in this case. 11258 if (Value.getOpcode() != ISD::TargetConstantFP) { 11259 SDValue Tmp; 11260 switch (CFP->getSimpleValueType(0).SimpleTy) { 11261 default: llvm_unreachable("Unknown FP type"); 11262 case MVT::f16: // We don't do this for these yet. 11263 case MVT::f80: 11264 case MVT::f128: 11265 case MVT::ppcf128: 11266 break; 11267 case MVT::f32: 11268 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11269 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11270 ; 11271 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11272 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11273 MVT::i32); 11274 return DAG.getStore(Chain, SDLoc(N), Tmp, 11275 Ptr, ST->getMemOperand()); 11276 } 11277 break; 11278 case MVT::f64: 11279 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11280 !ST->isVolatile()) || 11281 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11282 ; 11283 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11284 getZExtValue(), SDLoc(CFP), MVT::i64); 11285 return DAG.getStore(Chain, SDLoc(N), Tmp, 11286 Ptr, ST->getMemOperand()); 11287 } 11288 11289 if (!ST->isVolatile() && 11290 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11291 // Many FP stores are not made apparent until after legalize, e.g. for 11292 // argument passing. Since this is so common, custom legalize the 11293 // 64-bit integer store into two 32-bit stores. 11294 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11295 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11296 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11297 if (DAG.getDataLayout().isBigEndian()) 11298 std::swap(Lo, Hi); 11299 11300 unsigned Alignment = ST->getAlignment(); 11301 bool isVolatile = ST->isVolatile(); 11302 bool isNonTemporal = ST->isNonTemporal(); 11303 AAMDNodes AAInfo = ST->getAAInfo(); 11304 11305 SDLoc DL(N); 11306 11307 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 11308 Ptr, ST->getPointerInfo(), 11309 isVolatile, isNonTemporal, 11310 ST->getAlignment(), AAInfo); 11311 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11312 DAG.getConstant(4, DL, Ptr.getValueType())); 11313 Alignment = MinAlign(Alignment, 4U); 11314 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 11315 Ptr, ST->getPointerInfo().getWithOffset(4), 11316 isVolatile, isNonTemporal, 11317 Alignment, AAInfo); 11318 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11319 St0, St1); 11320 } 11321 11322 break; 11323 } 11324 } 11325 } 11326 11327 // Try to infer better alignment information than the store already has. 11328 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11329 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11330 if (Align > ST->getAlignment()) { 11331 SDValue NewStore = 11332 DAG.getTruncStore(Chain, SDLoc(N), Value, 11333 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11334 ST->isVolatile(), ST->isNonTemporal(), Align, 11335 ST->getAAInfo()); 11336 if (NewStore.getNode() != N) 11337 return CombineTo(ST, NewStore, true); 11338 } 11339 } 11340 } 11341 11342 // Try transforming a pair floating point load / store ops to integer 11343 // load / store ops. 11344 if (SDValue NewST = TransformFPLoadStorePair(N)) 11345 return NewST; 11346 11347 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11348 : DAG.getSubtarget().useAA(); 11349 #ifndef NDEBUG 11350 if (CombinerAAOnlyFunc.getNumOccurrences() && 11351 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11352 UseAA = false; 11353 #endif 11354 if (UseAA && ST->isUnindexed()) { 11355 // Walk up chain skipping non-aliasing memory nodes. 11356 SDValue BetterChain = FindBetterChain(N, Chain); 11357 11358 // If there is a better chain. 11359 if (Chain != BetterChain) { 11360 SDValue ReplStore; 11361 11362 // Replace the chain to avoid dependency. 11363 if (ST->isTruncatingStore()) { 11364 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 11365 ST->getMemoryVT(), ST->getMemOperand()); 11366 } else { 11367 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 11368 ST->getMemOperand()); 11369 } 11370 11371 // Create token to keep both nodes around. 11372 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11373 MVT::Other, Chain, ReplStore); 11374 11375 // Make sure the new and old chains are cleaned up. 11376 AddToWorklist(Token.getNode()); 11377 11378 // Don't add users to work list. 11379 return CombineTo(N, Token, false); 11380 } 11381 } 11382 11383 // Try transforming N to an indexed store. 11384 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11385 return SDValue(N, 0); 11386 11387 // FIXME: is there such a thing as a truncating indexed store? 11388 if (ST->isTruncatingStore() && ST->isUnindexed() && 11389 Value.getValueType().isInteger()) { 11390 // See if we can simplify the input to this truncstore with knowledge that 11391 // only the low bits are being used. For example: 11392 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11393 SDValue Shorter = 11394 GetDemandedBits(Value, 11395 APInt::getLowBitsSet( 11396 Value.getValueType().getScalarType().getSizeInBits(), 11397 ST->getMemoryVT().getScalarType().getSizeInBits())); 11398 AddToWorklist(Value.getNode()); 11399 if (Shorter.getNode()) 11400 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11401 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11402 11403 // Otherwise, see if we can simplify the operation with 11404 // SimplifyDemandedBits, which only works if the value has a single use. 11405 if (SimplifyDemandedBits(Value, 11406 APInt::getLowBitsSet( 11407 Value.getValueType().getScalarType().getSizeInBits(), 11408 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11409 return SDValue(N, 0); 11410 } 11411 11412 // If this is a load followed by a store to the same location, then the store 11413 // is dead/noop. 11414 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11415 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11416 ST->isUnindexed() && !ST->isVolatile() && 11417 // There can't be any side effects between the load and store, such as 11418 // a call or store. 11419 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11420 // The store is dead, remove it. 11421 return Chain; 11422 } 11423 } 11424 11425 // If this is a store followed by a store with the same value to the same 11426 // location, then the store is dead/noop. 11427 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11428 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11429 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11430 ST1->isUnindexed() && !ST1->isVolatile()) { 11431 // The store is dead, remove it. 11432 return Chain; 11433 } 11434 } 11435 11436 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11437 // truncating store. We can do this even if this is already a truncstore. 11438 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11439 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11440 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11441 ST->getMemoryVT())) { 11442 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11443 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11444 } 11445 11446 // Only perform this optimization before the types are legal, because we 11447 // don't want to perform this optimization on every DAGCombine invocation. 11448 if (!LegalTypes) { 11449 bool EverChanged = false; 11450 11451 do { 11452 // There can be multiple store sequences on the same chain. 11453 // Keep trying to merge store sequences until we are unable to do so 11454 // or until we merge the last store on the chain. 11455 bool Changed = MergeConsecutiveStores(ST); 11456 EverChanged |= Changed; 11457 if (!Changed) break; 11458 } while (ST->getOpcode() != ISD::DELETED_NODE); 11459 11460 if (EverChanged) 11461 return SDValue(N, 0); 11462 } 11463 11464 return ReduceLoadOpStoreWidth(N); 11465 } 11466 11467 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11468 SDValue InVec = N->getOperand(0); 11469 SDValue InVal = N->getOperand(1); 11470 SDValue EltNo = N->getOperand(2); 11471 SDLoc dl(N); 11472 11473 // If the inserted element is an UNDEF, just use the input vector. 11474 if (InVal.getOpcode() == ISD::UNDEF) 11475 return InVec; 11476 11477 EVT VT = InVec.getValueType(); 11478 11479 // If we can't generate a legal BUILD_VECTOR, exit 11480 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11481 return SDValue(); 11482 11483 // Check that we know which element is being inserted 11484 if (!isa<ConstantSDNode>(EltNo)) 11485 return SDValue(); 11486 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11487 11488 // Canonicalize insert_vector_elt dag nodes. 11489 // Example: 11490 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11491 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11492 // 11493 // Do this only if the child insert_vector node has one use; also 11494 // do this only if indices are both constants and Idx1 < Idx0. 11495 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11496 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11497 unsigned OtherElt = 11498 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11499 if (Elt < OtherElt) { 11500 // Swap nodes. 11501 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11502 InVec.getOperand(0), InVal, EltNo); 11503 AddToWorklist(NewOp.getNode()); 11504 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11505 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11506 } 11507 } 11508 11509 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11510 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11511 // vector elements. 11512 SmallVector<SDValue, 8> Ops; 11513 // Do not combine these two vectors if the output vector will not replace 11514 // the input vector. 11515 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11516 Ops.append(InVec.getNode()->op_begin(), 11517 InVec.getNode()->op_end()); 11518 } else if (InVec.getOpcode() == ISD::UNDEF) { 11519 unsigned NElts = VT.getVectorNumElements(); 11520 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11521 } else { 11522 return SDValue(); 11523 } 11524 11525 // Insert the element 11526 if (Elt < Ops.size()) { 11527 // All the operands of BUILD_VECTOR must have the same type; 11528 // we enforce that here. 11529 EVT OpVT = Ops[0].getValueType(); 11530 if (InVal.getValueType() != OpVT) 11531 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11532 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11533 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11534 Ops[Elt] = InVal; 11535 } 11536 11537 // Return the new vector 11538 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 11539 } 11540 11541 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 11542 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 11543 EVT ResultVT = EVE->getValueType(0); 11544 EVT VecEltVT = InVecVT.getVectorElementType(); 11545 unsigned Align = OriginalLoad->getAlignment(); 11546 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 11547 VecEltVT.getTypeForEVT(*DAG.getContext())); 11548 11549 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 11550 return SDValue(); 11551 11552 Align = NewAlign; 11553 11554 SDValue NewPtr = OriginalLoad->getBasePtr(); 11555 SDValue Offset; 11556 EVT PtrType = NewPtr.getValueType(); 11557 MachinePointerInfo MPI; 11558 SDLoc DL(EVE); 11559 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 11560 int Elt = ConstEltNo->getZExtValue(); 11561 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 11562 Offset = DAG.getConstant(PtrOff, DL, PtrType); 11563 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 11564 } else { 11565 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 11566 Offset = DAG.getNode( 11567 ISD::MUL, DL, PtrType, Offset, 11568 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 11569 MPI = OriginalLoad->getPointerInfo(); 11570 } 11571 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 11572 11573 // The replacement we need to do here is a little tricky: we need to 11574 // replace an extractelement of a load with a load. 11575 // Use ReplaceAllUsesOfValuesWith to do the replacement. 11576 // Note that this replacement assumes that the extractvalue is the only 11577 // use of the load; that's okay because we don't want to perform this 11578 // transformation in other cases anyway. 11579 SDValue Load; 11580 SDValue Chain; 11581 if (ResultVT.bitsGT(VecEltVT)) { 11582 // If the result type of vextract is wider than the load, then issue an 11583 // extending load instead. 11584 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 11585 VecEltVT) 11586 ? ISD::ZEXTLOAD 11587 : ISD::EXTLOAD; 11588 Load = DAG.getExtLoad( 11589 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 11590 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11591 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11592 Chain = Load.getValue(1); 11593 } else { 11594 Load = DAG.getLoad( 11595 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 11596 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11597 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11598 Chain = Load.getValue(1); 11599 if (ResultVT.bitsLT(VecEltVT)) 11600 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 11601 else 11602 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 11603 } 11604 WorklistRemover DeadNodes(*this); 11605 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 11606 SDValue To[] = { Load, Chain }; 11607 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 11608 // Since we're explicitly calling ReplaceAllUses, add the new node to the 11609 // worklist explicitly as well. 11610 AddToWorklist(Load.getNode()); 11611 AddUsersToWorklist(Load.getNode()); // Add users too 11612 // Make sure to revisit this node to clean it up; it will usually be dead. 11613 AddToWorklist(EVE); 11614 ++OpsNarrowed; 11615 return SDValue(EVE, 0); 11616 } 11617 11618 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 11619 // (vextract (scalar_to_vector val, 0) -> val 11620 SDValue InVec = N->getOperand(0); 11621 EVT VT = InVec.getValueType(); 11622 EVT NVT = N->getValueType(0); 11623 11624 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 11625 // Check if the result type doesn't match the inserted element type. A 11626 // SCALAR_TO_VECTOR may truncate the inserted element and the 11627 // EXTRACT_VECTOR_ELT may widen the extracted vector. 11628 SDValue InOp = InVec.getOperand(0); 11629 if (InOp.getValueType() != NVT) { 11630 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11631 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 11632 } 11633 return InOp; 11634 } 11635 11636 SDValue EltNo = N->getOperand(1); 11637 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 11638 11639 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 11640 // We only perform this optimization before the op legalization phase because 11641 // we may introduce new vector instructions which are not backed by TD 11642 // patterns. For example on AVX, extracting elements from a wide vector 11643 // without using extract_subvector. However, if we can find an underlying 11644 // scalar value, then we can always use that. 11645 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 11646 && ConstEltNo) { 11647 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11648 int NumElem = VT.getVectorNumElements(); 11649 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 11650 // Find the new index to extract from. 11651 int OrigElt = SVOp->getMaskElt(Elt); 11652 11653 // Extracting an undef index is undef. 11654 if (OrigElt == -1) 11655 return DAG.getUNDEF(NVT); 11656 11657 // Select the right vector half to extract from. 11658 SDValue SVInVec; 11659 if (OrigElt < NumElem) { 11660 SVInVec = InVec->getOperand(0); 11661 } else { 11662 SVInVec = InVec->getOperand(1); 11663 OrigElt -= NumElem; 11664 } 11665 11666 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 11667 SDValue InOp = SVInVec.getOperand(OrigElt); 11668 if (InOp.getValueType() != NVT) { 11669 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11670 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 11671 } 11672 11673 return InOp; 11674 } 11675 11676 // FIXME: We should handle recursing on other vector shuffles and 11677 // scalar_to_vector here as well. 11678 11679 if (!LegalOperations) { 11680 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 11681 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 11682 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 11683 } 11684 } 11685 11686 bool BCNumEltsChanged = false; 11687 EVT ExtVT = VT.getVectorElementType(); 11688 EVT LVT = ExtVT; 11689 11690 // If the result of load has to be truncated, then it's not necessarily 11691 // profitable. 11692 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 11693 return SDValue(); 11694 11695 if (InVec.getOpcode() == ISD::BITCAST) { 11696 // Don't duplicate a load with other uses. 11697 if (!InVec.hasOneUse()) 11698 return SDValue(); 11699 11700 EVT BCVT = InVec.getOperand(0).getValueType(); 11701 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 11702 return SDValue(); 11703 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 11704 BCNumEltsChanged = true; 11705 InVec = InVec.getOperand(0); 11706 ExtVT = BCVT.getVectorElementType(); 11707 } 11708 11709 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 11710 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 11711 ISD::isNormalLoad(InVec.getNode()) && 11712 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 11713 SDValue Index = N->getOperand(1); 11714 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 11715 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 11716 OrigLoad); 11717 } 11718 11719 // Perform only after legalization to ensure build_vector / vector_shuffle 11720 // optimizations have already been done. 11721 if (!LegalOperations) return SDValue(); 11722 11723 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 11724 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 11725 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 11726 11727 if (ConstEltNo) { 11728 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11729 11730 LoadSDNode *LN0 = nullptr; 11731 const ShuffleVectorSDNode *SVN = nullptr; 11732 if (ISD::isNormalLoad(InVec.getNode())) { 11733 LN0 = cast<LoadSDNode>(InVec); 11734 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 11735 InVec.getOperand(0).getValueType() == ExtVT && 11736 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 11737 // Don't duplicate a load with other uses. 11738 if (!InVec.hasOneUse()) 11739 return SDValue(); 11740 11741 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11742 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11743 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11744 // => 11745 // (load $addr+1*size) 11746 11747 // Don't duplicate a load with other uses. 11748 if (!InVec.hasOneUse()) 11749 return SDValue(); 11750 11751 // If the bit convert changed the number of elements, it is unsafe 11752 // to examine the mask. 11753 if (BCNumEltsChanged) 11754 return SDValue(); 11755 11756 // Select the input vector, guarding against out of range extract vector. 11757 unsigned NumElems = VT.getVectorNumElements(); 11758 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 11759 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 11760 11761 if (InVec.getOpcode() == ISD::BITCAST) { 11762 // Don't duplicate a load with other uses. 11763 if (!InVec.hasOneUse()) 11764 return SDValue(); 11765 11766 InVec = InVec.getOperand(0); 11767 } 11768 if (ISD::isNormalLoad(InVec.getNode())) { 11769 LN0 = cast<LoadSDNode>(InVec); 11770 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 11771 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 11772 } 11773 } 11774 11775 // Make sure we found a non-volatile load and the extractelement is 11776 // the only use. 11777 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 11778 return SDValue(); 11779 11780 // If Idx was -1 above, Elt is going to be -1, so just return undef. 11781 if (Elt == -1) 11782 return DAG.getUNDEF(LVT); 11783 11784 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 11785 } 11786 11787 return SDValue(); 11788 } 11789 11790 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 11791 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 11792 // We perform this optimization post type-legalization because 11793 // the type-legalizer often scalarizes integer-promoted vectors. 11794 // Performing this optimization before may create bit-casts which 11795 // will be type-legalized to complex code sequences. 11796 // We perform this optimization only before the operation legalizer because we 11797 // may introduce illegal operations. 11798 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 11799 return SDValue(); 11800 11801 unsigned NumInScalars = N->getNumOperands(); 11802 SDLoc dl(N); 11803 EVT VT = N->getValueType(0); 11804 11805 // Check to see if this is a BUILD_VECTOR of a bunch of values 11806 // which come from any_extend or zero_extend nodes. If so, we can create 11807 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 11808 // optimizations. We do not handle sign-extend because we can't fill the sign 11809 // using shuffles. 11810 EVT SourceType = MVT::Other; 11811 bool AllAnyExt = true; 11812 11813 for (unsigned i = 0; i != NumInScalars; ++i) { 11814 SDValue In = N->getOperand(i); 11815 // Ignore undef inputs. 11816 if (In.getOpcode() == ISD::UNDEF) continue; 11817 11818 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 11819 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 11820 11821 // Abort if the element is not an extension. 11822 if (!ZeroExt && !AnyExt) { 11823 SourceType = MVT::Other; 11824 break; 11825 } 11826 11827 // The input is a ZeroExt or AnyExt. Check the original type. 11828 EVT InTy = In.getOperand(0).getValueType(); 11829 11830 // Check that all of the widened source types are the same. 11831 if (SourceType == MVT::Other) 11832 // First time. 11833 SourceType = InTy; 11834 else if (InTy != SourceType) { 11835 // Multiple income types. Abort. 11836 SourceType = MVT::Other; 11837 break; 11838 } 11839 11840 // Check if all of the extends are ANY_EXTENDs. 11841 AllAnyExt &= AnyExt; 11842 } 11843 11844 // In order to have valid types, all of the inputs must be extended from the 11845 // same source type and all of the inputs must be any or zero extend. 11846 // Scalar sizes must be a power of two. 11847 EVT OutScalarTy = VT.getScalarType(); 11848 bool ValidTypes = SourceType != MVT::Other && 11849 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 11850 isPowerOf2_32(SourceType.getSizeInBits()); 11851 11852 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 11853 // turn into a single shuffle instruction. 11854 if (!ValidTypes) 11855 return SDValue(); 11856 11857 bool isLE = DAG.getDataLayout().isLittleEndian(); 11858 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 11859 assert(ElemRatio > 1 && "Invalid element size ratio"); 11860 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 11861 DAG.getConstant(0, SDLoc(N), SourceType); 11862 11863 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 11864 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 11865 11866 // Populate the new build_vector 11867 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11868 SDValue Cast = N->getOperand(i); 11869 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 11870 Cast.getOpcode() == ISD::ZERO_EXTEND || 11871 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 11872 SDValue In; 11873 if (Cast.getOpcode() == ISD::UNDEF) 11874 In = DAG.getUNDEF(SourceType); 11875 else 11876 In = Cast->getOperand(0); 11877 unsigned Index = isLE ? (i * ElemRatio) : 11878 (i * ElemRatio + (ElemRatio - 1)); 11879 11880 assert(Index < Ops.size() && "Invalid index"); 11881 Ops[Index] = In; 11882 } 11883 11884 // The type of the new BUILD_VECTOR node. 11885 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 11886 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 11887 "Invalid vector size"); 11888 // Check if the new vector type is legal. 11889 if (!isTypeLegal(VecVT)) return SDValue(); 11890 11891 // Make the new BUILD_VECTOR. 11892 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 11893 11894 // The new BUILD_VECTOR node has the potential to be further optimized. 11895 AddToWorklist(BV.getNode()); 11896 // Bitcast to the desired type. 11897 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11898 } 11899 11900 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 11901 EVT VT = N->getValueType(0); 11902 11903 unsigned NumInScalars = N->getNumOperands(); 11904 SDLoc dl(N); 11905 11906 EVT SrcVT = MVT::Other; 11907 unsigned Opcode = ISD::DELETED_NODE; 11908 unsigned NumDefs = 0; 11909 11910 for (unsigned i = 0; i != NumInScalars; ++i) { 11911 SDValue In = N->getOperand(i); 11912 unsigned Opc = In.getOpcode(); 11913 11914 if (Opc == ISD::UNDEF) 11915 continue; 11916 11917 // If all scalar values are floats and converted from integers. 11918 if (Opcode == ISD::DELETED_NODE && 11919 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 11920 Opcode = Opc; 11921 } 11922 11923 if (Opc != Opcode) 11924 return SDValue(); 11925 11926 EVT InVT = In.getOperand(0).getValueType(); 11927 11928 // If all scalar values are typed differently, bail out. It's chosen to 11929 // simplify BUILD_VECTOR of integer types. 11930 if (SrcVT == MVT::Other) 11931 SrcVT = InVT; 11932 if (SrcVT != InVT) 11933 return SDValue(); 11934 NumDefs++; 11935 } 11936 11937 // If the vector has just one element defined, it's not worth to fold it into 11938 // a vectorized one. 11939 if (NumDefs < 2) 11940 return SDValue(); 11941 11942 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 11943 && "Should only handle conversion from integer to float."); 11944 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 11945 11946 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 11947 11948 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 11949 return SDValue(); 11950 11951 // Just because the floating-point vector type is legal does not necessarily 11952 // mean that the corresponding integer vector type is. 11953 if (!isTypeLegal(NVT)) 11954 return SDValue(); 11955 11956 SmallVector<SDValue, 8> Opnds; 11957 for (unsigned i = 0; i != NumInScalars; ++i) { 11958 SDValue In = N->getOperand(i); 11959 11960 if (In.getOpcode() == ISD::UNDEF) 11961 Opnds.push_back(DAG.getUNDEF(SrcVT)); 11962 else 11963 Opnds.push_back(In.getOperand(0)); 11964 } 11965 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 11966 AddToWorklist(BV.getNode()); 11967 11968 return DAG.getNode(Opcode, dl, VT, BV); 11969 } 11970 11971 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 11972 unsigned NumInScalars = N->getNumOperands(); 11973 SDLoc dl(N); 11974 EVT VT = N->getValueType(0); 11975 11976 // A vector built entirely of undefs is undef. 11977 if (ISD::allOperandsUndef(N)) 11978 return DAG.getUNDEF(VT); 11979 11980 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 11981 return V; 11982 11983 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 11984 return V; 11985 11986 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 11987 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 11988 // at most two distinct vectors, turn this into a shuffle node. 11989 11990 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 11991 if (!isTypeLegal(VT)) 11992 return SDValue(); 11993 11994 // May only combine to shuffle after legalize if shuffle is legal. 11995 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 11996 return SDValue(); 11997 11998 SDValue VecIn1, VecIn2; 11999 bool UsesZeroVector = false; 12000 for (unsigned i = 0; i != NumInScalars; ++i) { 12001 SDValue Op = N->getOperand(i); 12002 // Ignore undef inputs. 12003 if (Op.getOpcode() == ISD::UNDEF) continue; 12004 12005 // See if we can combine this build_vector into a blend with a zero vector. 12006 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12007 UsesZeroVector = true; 12008 continue; 12009 } 12010 12011 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12012 // constant index, bail out. 12013 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12014 !isa<ConstantSDNode>(Op.getOperand(1))) { 12015 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12016 break; 12017 } 12018 12019 // We allow up to two distinct input vectors. 12020 SDValue ExtractedFromVec = Op.getOperand(0); 12021 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12022 continue; 12023 12024 if (!VecIn1.getNode()) { 12025 VecIn1 = ExtractedFromVec; 12026 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12027 VecIn2 = ExtractedFromVec; 12028 } else { 12029 // Too many inputs. 12030 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12031 break; 12032 } 12033 } 12034 12035 // If everything is good, we can make a shuffle operation. 12036 if (VecIn1.getNode()) { 12037 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12038 SmallVector<int, 8> Mask; 12039 for (unsigned i = 0; i != NumInScalars; ++i) { 12040 unsigned Opcode = N->getOperand(i).getOpcode(); 12041 if (Opcode == ISD::UNDEF) { 12042 Mask.push_back(-1); 12043 continue; 12044 } 12045 12046 // Operands can also be zero. 12047 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12048 assert(UsesZeroVector && 12049 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12050 "Unexpected node found!"); 12051 Mask.push_back(NumInScalars+i); 12052 continue; 12053 } 12054 12055 // If extracting from the first vector, just use the index directly. 12056 SDValue Extract = N->getOperand(i); 12057 SDValue ExtVal = Extract.getOperand(1); 12058 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12059 if (Extract.getOperand(0) == VecIn1) { 12060 Mask.push_back(ExtIndex); 12061 continue; 12062 } 12063 12064 // Otherwise, use InIdx + InputVecSize 12065 Mask.push_back(InNumElements + ExtIndex); 12066 } 12067 12068 // Avoid introducing illegal shuffles with zero. 12069 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12070 return SDValue(); 12071 12072 // We can't generate a shuffle node with mismatched input and output types. 12073 // Attempt to transform a single input vector to the correct type. 12074 if ((VT != VecIn1.getValueType())) { 12075 // If the input vector type has a different base type to the output 12076 // vector type, bail out. 12077 EVT VTElemType = VT.getVectorElementType(); 12078 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12079 (VecIn2.getNode() && 12080 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12081 return SDValue(); 12082 12083 // If the input vector is too small, widen it. 12084 // We only support widening of vectors which are half the size of the 12085 // output registers. For example XMM->YMM widening on X86 with AVX. 12086 EVT VecInT = VecIn1.getValueType(); 12087 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12088 // If we only have one small input, widen it by adding undef values. 12089 if (!VecIn2.getNode()) 12090 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12091 DAG.getUNDEF(VecIn1.getValueType())); 12092 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12093 // If we have two small inputs of the same type, try to concat them. 12094 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12095 VecIn2 = SDValue(nullptr, 0); 12096 } else 12097 return SDValue(); 12098 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12099 // If the input vector is too large, try to split it. 12100 // We don't support having two input vectors that are too large. 12101 // If the zero vector was used, we can not split the vector, 12102 // since we'd need 3 inputs. 12103 if (UsesZeroVector || VecIn2.getNode()) 12104 return SDValue(); 12105 12106 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12107 return SDValue(); 12108 12109 // Try to replace VecIn1 with two extract_subvectors 12110 // No need to update the masks, they should still be correct. 12111 VecIn2 = DAG.getNode( 12112 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12113 DAG.getConstant(VT.getVectorNumElements(), dl, 12114 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12115 VecIn1 = DAG.getNode( 12116 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12117 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12118 } else 12119 return SDValue(); 12120 } 12121 12122 if (UsesZeroVector) 12123 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12124 DAG.getConstantFP(0.0, dl, VT); 12125 else 12126 // If VecIn2 is unused then change it to undef. 12127 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12128 12129 // Check that we were able to transform all incoming values to the same 12130 // type. 12131 if (VecIn2.getValueType() != VecIn1.getValueType() || 12132 VecIn1.getValueType() != VT) 12133 return SDValue(); 12134 12135 // Return the new VECTOR_SHUFFLE node. 12136 SDValue Ops[2]; 12137 Ops[0] = VecIn1; 12138 Ops[1] = VecIn2; 12139 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12140 } 12141 12142 return SDValue(); 12143 } 12144 12145 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12146 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12147 EVT OpVT = N->getOperand(0).getValueType(); 12148 12149 // If the operands are legal vectors, leave them alone. 12150 if (TLI.isTypeLegal(OpVT)) 12151 return SDValue(); 12152 12153 SDLoc DL(N); 12154 EVT VT = N->getValueType(0); 12155 SmallVector<SDValue, 8> Ops; 12156 12157 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12158 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12159 12160 // Keep track of what we encounter. 12161 bool AnyInteger = false; 12162 bool AnyFP = false; 12163 for (const SDValue &Op : N->ops()) { 12164 if (ISD::BITCAST == Op.getOpcode() && 12165 !Op.getOperand(0).getValueType().isVector()) 12166 Ops.push_back(Op.getOperand(0)); 12167 else if (ISD::UNDEF == Op.getOpcode()) 12168 Ops.push_back(ScalarUndef); 12169 else 12170 return SDValue(); 12171 12172 // Note whether we encounter an integer or floating point scalar. 12173 // If it's neither, bail out, it could be something weird like x86mmx. 12174 EVT LastOpVT = Ops.back().getValueType(); 12175 if (LastOpVT.isFloatingPoint()) 12176 AnyFP = true; 12177 else if (LastOpVT.isInteger()) 12178 AnyInteger = true; 12179 else 12180 return SDValue(); 12181 } 12182 12183 // If any of the operands is a floating point scalar bitcast to a vector, 12184 // use floating point types throughout, and bitcast everything. 12185 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12186 if (AnyFP) { 12187 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12188 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12189 if (AnyInteger) { 12190 for (SDValue &Op : Ops) { 12191 if (Op.getValueType() == SVT) 12192 continue; 12193 if (Op.getOpcode() == ISD::UNDEF) 12194 Op = ScalarUndef; 12195 else 12196 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12197 } 12198 } 12199 } 12200 12201 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12202 VT.getSizeInBits() / SVT.getSizeInBits()); 12203 return DAG.getNode(ISD::BITCAST, DL, VT, 12204 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12205 } 12206 12207 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12208 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 12209 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 12210 // inputs come from at most two distinct vectors, turn this into a shuffle 12211 // node. 12212 12213 // If we only have one input vector, we don't need to do any concatenation. 12214 if (N->getNumOperands() == 1) 12215 return N->getOperand(0); 12216 12217 // Check if all of the operands are undefs. 12218 EVT VT = N->getValueType(0); 12219 if (ISD::allOperandsUndef(N)) 12220 return DAG.getUNDEF(VT); 12221 12222 // Optimize concat_vectors where all but the first of the vectors are undef. 12223 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12224 return Op.getOpcode() == ISD::UNDEF; 12225 })) { 12226 SDValue In = N->getOperand(0); 12227 assert(In.getValueType().isVector() && "Must concat vectors"); 12228 12229 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12230 if (In->getOpcode() == ISD::BITCAST && 12231 !In->getOperand(0)->getValueType(0).isVector()) { 12232 SDValue Scalar = In->getOperand(0); 12233 12234 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12235 // look through the trunc so we can still do the transform: 12236 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12237 if (Scalar->getOpcode() == ISD::TRUNCATE && 12238 !TLI.isTypeLegal(Scalar.getValueType()) && 12239 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12240 Scalar = Scalar->getOperand(0); 12241 12242 EVT SclTy = Scalar->getValueType(0); 12243 12244 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12245 return SDValue(); 12246 12247 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12248 VT.getSizeInBits() / SclTy.getSizeInBits()); 12249 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12250 return SDValue(); 12251 12252 SDLoc dl = SDLoc(N); 12253 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12254 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12255 } 12256 } 12257 12258 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12259 // We have already tested above for an UNDEF only concatenation. 12260 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12261 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12262 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12263 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12264 }; 12265 bool AllBuildVectorsOrUndefs = 12266 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12267 if (AllBuildVectorsOrUndefs) { 12268 SmallVector<SDValue, 8> Opnds; 12269 EVT SVT = VT.getScalarType(); 12270 12271 EVT MinVT = SVT; 12272 if (!SVT.isFloatingPoint()) { 12273 // If BUILD_VECTOR are from built from integer, they may have different 12274 // operand types. Get the smallest type and truncate all operands to it. 12275 bool FoundMinVT = false; 12276 for (const SDValue &Op : N->ops()) 12277 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12278 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12279 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12280 FoundMinVT = true; 12281 } 12282 assert(FoundMinVT && "Concat vector type mismatch"); 12283 } 12284 12285 for (const SDValue &Op : N->ops()) { 12286 EVT OpVT = Op.getValueType(); 12287 unsigned NumElts = OpVT.getVectorNumElements(); 12288 12289 if (ISD::UNDEF == Op.getOpcode()) 12290 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12291 12292 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12293 if (SVT.isFloatingPoint()) { 12294 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12295 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12296 } else { 12297 for (unsigned i = 0; i != NumElts; ++i) 12298 Opnds.push_back( 12299 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12300 } 12301 } 12302 } 12303 12304 assert(VT.getVectorNumElements() == Opnds.size() && 12305 "Concat vector type mismatch"); 12306 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12307 } 12308 12309 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12310 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12311 return V; 12312 12313 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12314 // nodes often generate nop CONCAT_VECTOR nodes. 12315 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12316 // place the incoming vectors at the exact same location. 12317 SDValue SingleSource = SDValue(); 12318 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12319 12320 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12321 SDValue Op = N->getOperand(i); 12322 12323 if (Op.getOpcode() == ISD::UNDEF) 12324 continue; 12325 12326 // Check if this is the identity extract: 12327 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12328 return SDValue(); 12329 12330 // Find the single incoming vector for the extract_subvector. 12331 if (SingleSource.getNode()) { 12332 if (Op.getOperand(0) != SingleSource) 12333 return SDValue(); 12334 } else { 12335 SingleSource = Op.getOperand(0); 12336 12337 // Check the source type is the same as the type of the result. 12338 // If not, this concat may extend the vector, so we can not 12339 // optimize it away. 12340 if (SingleSource.getValueType() != N->getValueType(0)) 12341 return SDValue(); 12342 } 12343 12344 unsigned IdentityIndex = i * PartNumElem; 12345 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12346 // The extract index must be constant. 12347 if (!CS) 12348 return SDValue(); 12349 12350 // Check that we are reading from the identity index. 12351 if (CS->getZExtValue() != IdentityIndex) 12352 return SDValue(); 12353 } 12354 12355 if (SingleSource.getNode()) 12356 return SingleSource; 12357 12358 return SDValue(); 12359 } 12360 12361 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12362 EVT NVT = N->getValueType(0); 12363 SDValue V = N->getOperand(0); 12364 12365 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12366 // Combine: 12367 // (extract_subvec (concat V1, V2, ...), i) 12368 // Into: 12369 // Vi if possible 12370 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12371 // type. 12372 if (V->getOperand(0).getValueType() != NVT) 12373 return SDValue(); 12374 unsigned Idx = N->getConstantOperandVal(1); 12375 unsigned NumElems = NVT.getVectorNumElements(); 12376 assert((Idx % NumElems) == 0 && 12377 "IDX in concat is not a multiple of the result vector length."); 12378 return V->getOperand(Idx / NumElems); 12379 } 12380 12381 // Skip bitcasting 12382 if (V->getOpcode() == ISD::BITCAST) 12383 V = V.getOperand(0); 12384 12385 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 12386 SDLoc dl(N); 12387 // Handle only simple case where vector being inserted and vector 12388 // being extracted are of same type, and are half size of larger vectors. 12389 EVT BigVT = V->getOperand(0).getValueType(); 12390 EVT SmallVT = V->getOperand(1).getValueType(); 12391 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 12392 return SDValue(); 12393 12394 // Only handle cases where both indexes are constants with the same type. 12395 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12396 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12397 12398 if (InsIdx && ExtIdx && 12399 InsIdx->getValueType(0).getSizeInBits() <= 64 && 12400 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 12401 // Combine: 12402 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 12403 // Into: 12404 // indices are equal or bit offsets are equal => V1 12405 // otherwise => (extract_subvec V1, ExtIdx) 12406 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 12407 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 12408 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 12409 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 12410 DAG.getNode(ISD::BITCAST, dl, 12411 N->getOperand(0).getValueType(), 12412 V->getOperand(0)), N->getOperand(1)); 12413 } 12414 } 12415 12416 return SDValue(); 12417 } 12418 12419 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 12420 SDValue V, SelectionDAG &DAG) { 12421 SDLoc DL(V); 12422 EVT VT = V.getValueType(); 12423 12424 switch (V.getOpcode()) { 12425 default: 12426 return V; 12427 12428 case ISD::CONCAT_VECTORS: { 12429 EVT OpVT = V->getOperand(0).getValueType(); 12430 int OpSize = OpVT.getVectorNumElements(); 12431 SmallBitVector OpUsedElements(OpSize, false); 12432 bool FoundSimplification = false; 12433 SmallVector<SDValue, 4> NewOps; 12434 NewOps.reserve(V->getNumOperands()); 12435 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12436 SDValue Op = V->getOperand(i); 12437 bool OpUsed = false; 12438 for (int j = 0; j < OpSize; ++j) 12439 if (UsedElements[i * OpSize + j]) { 12440 OpUsedElements[j] = true; 12441 OpUsed = true; 12442 } 12443 NewOps.push_back( 12444 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 12445 : DAG.getUNDEF(OpVT)); 12446 FoundSimplification |= Op == NewOps.back(); 12447 OpUsedElements.reset(); 12448 } 12449 if (FoundSimplification) 12450 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 12451 return V; 12452 } 12453 12454 case ISD::INSERT_SUBVECTOR: { 12455 SDValue BaseV = V->getOperand(0); 12456 SDValue SubV = V->getOperand(1); 12457 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12458 if (!IdxN) 12459 return V; 12460 12461 int SubSize = SubV.getValueType().getVectorNumElements(); 12462 int Idx = IdxN->getZExtValue(); 12463 bool SubVectorUsed = false; 12464 SmallBitVector SubUsedElements(SubSize, false); 12465 for (int i = 0; i < SubSize; ++i) 12466 if (UsedElements[i + Idx]) { 12467 SubVectorUsed = true; 12468 SubUsedElements[i] = true; 12469 UsedElements[i + Idx] = false; 12470 } 12471 12472 // Now recurse on both the base and sub vectors. 12473 SDValue SimplifiedSubV = 12474 SubVectorUsed 12475 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 12476 : DAG.getUNDEF(SubV.getValueType()); 12477 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 12478 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 12479 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 12480 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 12481 return V; 12482 } 12483 } 12484 } 12485 12486 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 12487 SDValue N1, SelectionDAG &DAG) { 12488 EVT VT = SVN->getValueType(0); 12489 int NumElts = VT.getVectorNumElements(); 12490 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 12491 for (int M : SVN->getMask()) 12492 if (M >= 0 && M < NumElts) 12493 N0UsedElements[M] = true; 12494 else if (M >= NumElts) 12495 N1UsedElements[M - NumElts] = true; 12496 12497 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 12498 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 12499 if (S0 == N0 && S1 == N1) 12500 return SDValue(); 12501 12502 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 12503 } 12504 12505 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 12506 // or turn a shuffle of a single concat into simpler shuffle then concat. 12507 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 12508 EVT VT = N->getValueType(0); 12509 unsigned NumElts = VT.getVectorNumElements(); 12510 12511 SDValue N0 = N->getOperand(0); 12512 SDValue N1 = N->getOperand(1); 12513 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12514 12515 SmallVector<SDValue, 4> Ops; 12516 EVT ConcatVT = N0.getOperand(0).getValueType(); 12517 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 12518 unsigned NumConcats = NumElts / NumElemsPerConcat; 12519 12520 // Special case: shuffle(concat(A,B)) can be more efficiently represented 12521 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 12522 // half vector elements. 12523 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 12524 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 12525 SVN->getMask().end(), [](int i) { return i == -1; })) { 12526 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 12527 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat)); 12528 N1 = DAG.getUNDEF(ConcatVT); 12529 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 12530 } 12531 12532 // Look at every vector that's inserted. We're looking for exact 12533 // subvector-sized copies from a concatenated vector 12534 for (unsigned I = 0; I != NumConcats; ++I) { 12535 // Make sure we're dealing with a copy. 12536 unsigned Begin = I * NumElemsPerConcat; 12537 bool AllUndef = true, NoUndef = true; 12538 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 12539 if (SVN->getMaskElt(J) >= 0) 12540 AllUndef = false; 12541 else 12542 NoUndef = false; 12543 } 12544 12545 if (NoUndef) { 12546 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 12547 return SDValue(); 12548 12549 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 12550 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 12551 return SDValue(); 12552 12553 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 12554 if (FirstElt < N0.getNumOperands()) 12555 Ops.push_back(N0.getOperand(FirstElt)); 12556 else 12557 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 12558 12559 } else if (AllUndef) { 12560 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 12561 } else { // Mixed with general masks and undefs, can't do optimization. 12562 return SDValue(); 12563 } 12564 } 12565 12566 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 12567 } 12568 12569 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 12570 EVT VT = N->getValueType(0); 12571 unsigned NumElts = VT.getVectorNumElements(); 12572 12573 SDValue N0 = N->getOperand(0); 12574 SDValue N1 = N->getOperand(1); 12575 12576 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 12577 12578 // Canonicalize shuffle undef, undef -> undef 12579 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 12580 return DAG.getUNDEF(VT); 12581 12582 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12583 12584 // Canonicalize shuffle v, v -> v, undef 12585 if (N0 == N1) { 12586 SmallVector<int, 8> NewMask; 12587 for (unsigned i = 0; i != NumElts; ++i) { 12588 int Idx = SVN->getMaskElt(i); 12589 if (Idx >= (int)NumElts) Idx -= NumElts; 12590 NewMask.push_back(Idx); 12591 } 12592 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 12593 &NewMask[0]); 12594 } 12595 12596 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 12597 if (N0.getOpcode() == ISD::UNDEF) { 12598 SmallVector<int, 8> NewMask; 12599 for (unsigned i = 0; i != NumElts; ++i) { 12600 int Idx = SVN->getMaskElt(i); 12601 if (Idx >= 0) { 12602 if (Idx >= (int)NumElts) 12603 Idx -= NumElts; 12604 else 12605 Idx = -1; // remove reference to lhs 12606 } 12607 NewMask.push_back(Idx); 12608 } 12609 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 12610 &NewMask[0]); 12611 } 12612 12613 // Remove references to rhs if it is undef 12614 if (N1.getOpcode() == ISD::UNDEF) { 12615 bool Changed = false; 12616 SmallVector<int, 8> NewMask; 12617 for (unsigned i = 0; i != NumElts; ++i) { 12618 int Idx = SVN->getMaskElt(i); 12619 if (Idx >= (int)NumElts) { 12620 Idx = -1; 12621 Changed = true; 12622 } 12623 NewMask.push_back(Idx); 12624 } 12625 if (Changed) 12626 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 12627 } 12628 12629 // If it is a splat, check if the argument vector is another splat or a 12630 // build_vector. 12631 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 12632 SDNode *V = N0.getNode(); 12633 12634 // If this is a bit convert that changes the element type of the vector but 12635 // not the number of vector elements, look through it. Be careful not to 12636 // look though conversions that change things like v4f32 to v2f64. 12637 if (V->getOpcode() == ISD::BITCAST) { 12638 SDValue ConvInput = V->getOperand(0); 12639 if (ConvInput.getValueType().isVector() && 12640 ConvInput.getValueType().getVectorNumElements() == NumElts) 12641 V = ConvInput.getNode(); 12642 } 12643 12644 if (V->getOpcode() == ISD::BUILD_VECTOR) { 12645 assert(V->getNumOperands() == NumElts && 12646 "BUILD_VECTOR has wrong number of operands"); 12647 SDValue Base; 12648 bool AllSame = true; 12649 for (unsigned i = 0; i != NumElts; ++i) { 12650 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 12651 Base = V->getOperand(i); 12652 break; 12653 } 12654 } 12655 // Splat of <u, u, u, u>, return <u, u, u, u> 12656 if (!Base.getNode()) 12657 return N0; 12658 for (unsigned i = 0; i != NumElts; ++i) { 12659 if (V->getOperand(i) != Base) { 12660 AllSame = false; 12661 break; 12662 } 12663 } 12664 // Splat of <x, x, x, x>, return <x, x, x, x> 12665 if (AllSame) 12666 return N0; 12667 12668 // Canonicalize any other splat as a build_vector. 12669 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 12670 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 12671 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 12672 V->getValueType(0), Ops); 12673 12674 // We may have jumped through bitcasts, so the type of the 12675 // BUILD_VECTOR may not match the type of the shuffle. 12676 if (V->getValueType(0) != VT) 12677 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 12678 return NewBV; 12679 } 12680 } 12681 12682 // There are various patterns used to build up a vector from smaller vectors, 12683 // subvectors, or elements. Scan chains of these and replace unused insertions 12684 // or components with undef. 12685 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 12686 return S; 12687 12688 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12689 Level < AfterLegalizeVectorOps && 12690 (N1.getOpcode() == ISD::UNDEF || 12691 (N1.getOpcode() == ISD::CONCAT_VECTORS && 12692 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 12693 SDValue V = partitionShuffleOfConcats(N, DAG); 12694 12695 if (V.getNode()) 12696 return V; 12697 } 12698 12699 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 12700 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 12701 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 12702 SmallVector<SDValue, 8> Ops; 12703 for (int M : SVN->getMask()) { 12704 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 12705 if (M >= 0) { 12706 int Idx = M % NumElts; 12707 SDValue &S = (M < (int)NumElts ? N0 : N1); 12708 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 12709 Op = S.getOperand(Idx); 12710 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 12711 if (Idx == 0) 12712 Op = S.getOperand(0); 12713 } else { 12714 // Operand can't be combined - bail out. 12715 break; 12716 } 12717 } 12718 Ops.push_back(Op); 12719 } 12720 if (Ops.size() == VT.getVectorNumElements()) { 12721 // BUILD_VECTOR requires all inputs to be of the same type, find the 12722 // maximum type and extend them all. 12723 EVT SVT = VT.getScalarType(); 12724 if (SVT.isInteger()) 12725 for (SDValue &Op : Ops) 12726 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 12727 if (SVT != VT.getScalarType()) 12728 for (SDValue &Op : Ops) 12729 Op = TLI.isZExtFree(Op.getValueType(), SVT) 12730 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 12731 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 12732 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 12733 } 12734 } 12735 12736 // If this shuffle only has a single input that is a bitcasted shuffle, 12737 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 12738 // back to their original types. 12739 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 12740 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 12741 TLI.isTypeLegal(VT)) { 12742 12743 // Peek through the bitcast only if there is one user. 12744 SDValue BC0 = N0; 12745 while (BC0.getOpcode() == ISD::BITCAST) { 12746 if (!BC0.hasOneUse()) 12747 break; 12748 BC0 = BC0.getOperand(0); 12749 } 12750 12751 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 12752 if (Scale == 1) 12753 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 12754 12755 SmallVector<int, 8> NewMask; 12756 for (int M : Mask) 12757 for (int s = 0; s != Scale; ++s) 12758 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 12759 return NewMask; 12760 }; 12761 12762 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 12763 EVT SVT = VT.getScalarType(); 12764 EVT InnerVT = BC0->getValueType(0); 12765 EVT InnerSVT = InnerVT.getScalarType(); 12766 12767 // Determine which shuffle works with the smaller scalar type. 12768 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 12769 EVT ScaleSVT = ScaleVT.getScalarType(); 12770 12771 if (TLI.isTypeLegal(ScaleVT) && 12772 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 12773 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 12774 12775 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12776 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12777 12778 // Scale the shuffle masks to the smaller scalar type. 12779 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 12780 SmallVector<int, 8> InnerMask = 12781 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 12782 SmallVector<int, 8> OuterMask = 12783 ScaleShuffleMask(SVN->getMask(), OuterScale); 12784 12785 // Merge the shuffle masks. 12786 SmallVector<int, 8> NewMask; 12787 for (int M : OuterMask) 12788 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 12789 12790 // Test for shuffle mask legality over both commutations. 12791 SDValue SV0 = BC0->getOperand(0); 12792 SDValue SV1 = BC0->getOperand(1); 12793 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12794 if (!LegalMask) { 12795 std::swap(SV0, SV1); 12796 ShuffleVectorSDNode::commuteMask(NewMask); 12797 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12798 } 12799 12800 if (LegalMask) { 12801 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 12802 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 12803 return DAG.getNode( 12804 ISD::BITCAST, SDLoc(N), VT, 12805 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 12806 } 12807 } 12808 } 12809 } 12810 12811 // Canonicalize shuffles according to rules: 12812 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 12813 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 12814 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 12815 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 12816 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 12817 TLI.isTypeLegal(VT)) { 12818 // The incoming shuffle must be of the same type as the result of the 12819 // current shuffle. 12820 assert(N1->getOperand(0).getValueType() == VT && 12821 "Shuffle types don't match"); 12822 12823 SDValue SV0 = N1->getOperand(0); 12824 SDValue SV1 = N1->getOperand(1); 12825 bool HasSameOp0 = N0 == SV0; 12826 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 12827 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 12828 // Commute the operands of this shuffle so that next rule 12829 // will trigger. 12830 return DAG.getCommutedVectorShuffle(*SVN); 12831 } 12832 12833 // Try to fold according to rules: 12834 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12835 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12836 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12837 // Don't try to fold shuffles with illegal type. 12838 // Only fold if this shuffle is the only user of the other shuffle. 12839 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 12840 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 12841 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 12842 12843 // The incoming shuffle must be of the same type as the result of the 12844 // current shuffle. 12845 assert(OtherSV->getOperand(0).getValueType() == VT && 12846 "Shuffle types don't match"); 12847 12848 SDValue SV0, SV1; 12849 SmallVector<int, 4> Mask; 12850 // Compute the combined shuffle mask for a shuffle with SV0 as the first 12851 // operand, and SV1 as the second operand. 12852 for (unsigned i = 0; i != NumElts; ++i) { 12853 int Idx = SVN->getMaskElt(i); 12854 if (Idx < 0) { 12855 // Propagate Undef. 12856 Mask.push_back(Idx); 12857 continue; 12858 } 12859 12860 SDValue CurrentVec; 12861 if (Idx < (int)NumElts) { 12862 // This shuffle index refers to the inner shuffle N0. Lookup the inner 12863 // shuffle mask to identify which vector is actually referenced. 12864 Idx = OtherSV->getMaskElt(Idx); 12865 if (Idx < 0) { 12866 // Propagate Undef. 12867 Mask.push_back(Idx); 12868 continue; 12869 } 12870 12871 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 12872 : OtherSV->getOperand(1); 12873 } else { 12874 // This shuffle index references an element within N1. 12875 CurrentVec = N1; 12876 } 12877 12878 // Simple case where 'CurrentVec' is UNDEF. 12879 if (CurrentVec.getOpcode() == ISD::UNDEF) { 12880 Mask.push_back(-1); 12881 continue; 12882 } 12883 12884 // Canonicalize the shuffle index. We don't know yet if CurrentVec 12885 // will be the first or second operand of the combined shuffle. 12886 Idx = Idx % NumElts; 12887 if (!SV0.getNode() || SV0 == CurrentVec) { 12888 // Ok. CurrentVec is the left hand side. 12889 // Update the mask accordingly. 12890 SV0 = CurrentVec; 12891 Mask.push_back(Idx); 12892 continue; 12893 } 12894 12895 // Bail out if we cannot convert the shuffle pair into a single shuffle. 12896 if (SV1.getNode() && SV1 != CurrentVec) 12897 return SDValue(); 12898 12899 // Ok. CurrentVec is the right hand side. 12900 // Update the mask accordingly. 12901 SV1 = CurrentVec; 12902 Mask.push_back(Idx + NumElts); 12903 } 12904 12905 // Check if all indices in Mask are Undef. In case, propagate Undef. 12906 bool isUndefMask = true; 12907 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 12908 isUndefMask &= Mask[i] < 0; 12909 12910 if (isUndefMask) 12911 return DAG.getUNDEF(VT); 12912 12913 if (!SV0.getNode()) 12914 SV0 = DAG.getUNDEF(VT); 12915 if (!SV1.getNode()) 12916 SV1 = DAG.getUNDEF(VT); 12917 12918 // Avoid introducing shuffles with illegal mask. 12919 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 12920 ShuffleVectorSDNode::commuteMask(Mask); 12921 12922 if (!TLI.isShuffleMaskLegal(Mask, VT)) 12923 return SDValue(); 12924 12925 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 12926 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 12927 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 12928 std::swap(SV0, SV1); 12929 } 12930 12931 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12932 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12933 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12934 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 12935 } 12936 12937 return SDValue(); 12938 } 12939 12940 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 12941 SDValue InVal = N->getOperand(0); 12942 EVT VT = N->getValueType(0); 12943 12944 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 12945 // with a VECTOR_SHUFFLE. 12946 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12947 SDValue InVec = InVal->getOperand(0); 12948 SDValue EltNo = InVal->getOperand(1); 12949 12950 // FIXME: We could support implicit truncation if the shuffle can be 12951 // scaled to a smaller vector scalar type. 12952 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 12953 if (C0 && VT == InVec.getValueType() && 12954 VT.getScalarType() == InVal.getValueType()) { 12955 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 12956 int Elt = C0->getZExtValue(); 12957 NewMask[0] = Elt; 12958 12959 if (TLI.isShuffleMaskLegal(NewMask, VT)) 12960 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 12961 NewMask); 12962 } 12963 } 12964 12965 return SDValue(); 12966 } 12967 12968 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 12969 SDValue N0 = N->getOperand(0); 12970 SDValue N2 = N->getOperand(2); 12971 12972 // If the input vector is a concatenation, and the insert replaces 12973 // one of the halves, we can optimize into a single concat_vectors. 12974 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12975 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 12976 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 12977 EVT VT = N->getValueType(0); 12978 12979 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12980 // (concat_vectors Z, Y) 12981 if (InsIdx == 0) 12982 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12983 N->getOperand(1), N0.getOperand(1)); 12984 12985 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12986 // (concat_vectors X, Z) 12987 if (InsIdx == VT.getVectorNumElements()/2) 12988 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12989 N0.getOperand(0), N->getOperand(1)); 12990 } 12991 12992 return SDValue(); 12993 } 12994 12995 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 12996 SDValue N0 = N->getOperand(0); 12997 12998 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 12999 if (N0->getOpcode() == ISD::FP16_TO_FP) 13000 return N0->getOperand(0); 13001 13002 return SDValue(); 13003 } 13004 13005 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13006 /// with the destination vector and a zero vector. 13007 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13008 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13009 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13010 EVT VT = N->getValueType(0); 13011 SDValue LHS = N->getOperand(0); 13012 SDValue RHS = N->getOperand(1); 13013 SDLoc dl(N); 13014 13015 // Make sure we're not running after operation legalization where it 13016 // may have custom lowered the vector shuffles. 13017 if (LegalOperations) 13018 return SDValue(); 13019 13020 if (N->getOpcode() != ISD::AND) 13021 return SDValue(); 13022 13023 if (RHS.getOpcode() == ISD::BITCAST) 13024 RHS = RHS.getOperand(0); 13025 13026 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13027 return SDValue(); 13028 13029 EVT RVT = RHS.getValueType(); 13030 unsigned NumElts = RHS.getNumOperands(); 13031 13032 // Attempt to create a valid clear mask, splitting the mask into 13033 // sub elements and checking to see if each is 13034 // all zeros or all ones - suitable for shuffle masking. 13035 auto BuildClearMask = [&](int Split) { 13036 int NumSubElts = NumElts * Split; 13037 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13038 13039 SmallVector<int, 8> Indices; 13040 for (int i = 0; i != NumSubElts; ++i) { 13041 int EltIdx = i / Split; 13042 int SubIdx = i % Split; 13043 SDValue Elt = RHS.getOperand(EltIdx); 13044 if (Elt.getOpcode() == ISD::UNDEF) { 13045 Indices.push_back(-1); 13046 continue; 13047 } 13048 13049 APInt Bits; 13050 if (isa<ConstantSDNode>(Elt)) 13051 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13052 else if (isa<ConstantFPSDNode>(Elt)) 13053 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13054 else 13055 return SDValue(); 13056 13057 // Extract the sub element from the constant bit mask. 13058 if (DAG.getDataLayout().isBigEndian()) { 13059 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13060 } else { 13061 Bits = Bits.lshr(SubIdx * NumSubBits); 13062 } 13063 13064 if (Split > 1) 13065 Bits = Bits.trunc(NumSubBits); 13066 13067 if (Bits.isAllOnesValue()) 13068 Indices.push_back(i); 13069 else if (Bits == 0) 13070 Indices.push_back(i + NumSubElts); 13071 else 13072 return SDValue(); 13073 } 13074 13075 // Let's see if the target supports this vector_shuffle. 13076 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13077 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13078 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13079 return SDValue(); 13080 13081 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13082 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13083 DAG.getBitcast(ClearVT, LHS), 13084 Zero, &Indices[0])); 13085 }; 13086 13087 // Determine maximum split level (byte level masking). 13088 int MaxSplit = 1; 13089 if (RVT.getScalarSizeInBits() % 8 == 0) 13090 MaxSplit = RVT.getScalarSizeInBits() / 8; 13091 13092 for (int Split = 1; Split <= MaxSplit; ++Split) 13093 if (RVT.getScalarSizeInBits() % Split == 0) 13094 if (SDValue S = BuildClearMask(Split)) 13095 return S; 13096 13097 return SDValue(); 13098 } 13099 13100 /// Visit a binary vector operation, like ADD. 13101 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13102 assert(N->getValueType(0).isVector() && 13103 "SimplifyVBinOp only works on vectors!"); 13104 13105 SDValue LHS = N->getOperand(0); 13106 SDValue RHS = N->getOperand(1); 13107 13108 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 13109 // this operation. 13110 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 13111 RHS.getOpcode() == ISD::BUILD_VECTOR) { 13112 // Check if both vectors are constants. If not bail out. 13113 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 13114 cast<BuildVectorSDNode>(RHS)->isConstant())) 13115 return SDValue(); 13116 13117 SmallVector<SDValue, 8> Ops; 13118 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 13119 SDValue LHSOp = LHS.getOperand(i); 13120 SDValue RHSOp = RHS.getOperand(i); 13121 13122 // Can't fold divide by zero. 13123 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 13124 N->getOpcode() == ISD::FDIV) { 13125 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP && 13126 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero())) 13127 break; 13128 } 13129 13130 EVT VT = LHSOp.getValueType(); 13131 EVT RVT = RHSOp.getValueType(); 13132 if (RVT != VT) { 13133 // Integer BUILD_VECTOR operands may have types larger than the element 13134 // size (e.g., when the element type is not legal). Prior to type 13135 // legalization, the types may not match between the two BUILD_VECTORS. 13136 // Truncate one of the operands to make them match. 13137 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 13138 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 13139 } else { 13140 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 13141 VT = RVT; 13142 } 13143 } 13144 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 13145 LHSOp, RHSOp); 13146 if (FoldOp.getOpcode() != ISD::UNDEF && 13147 FoldOp.getOpcode() != ISD::Constant && 13148 FoldOp.getOpcode() != ISD::ConstantFP) 13149 break; 13150 Ops.push_back(FoldOp); 13151 AddToWorklist(FoldOp.getNode()); 13152 } 13153 13154 if (Ops.size() == LHS.getNumOperands()) 13155 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 13156 } 13157 13158 // Try to convert a constant mask AND into a shuffle clear mask. 13159 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13160 return Shuffle; 13161 13162 // Type legalization might introduce new shuffles in the DAG. 13163 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13164 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13165 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13166 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13167 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 13168 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 13169 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13170 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13171 13172 if (SVN0->getMask().equals(SVN1->getMask())) { 13173 EVT VT = N->getValueType(0); 13174 SDValue UndefVector = LHS.getOperand(1); 13175 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13176 LHS.getOperand(0), RHS.getOperand(0)); 13177 AddUsersToWorklist(N); 13178 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13179 &SVN0->getMask()[0]); 13180 } 13181 } 13182 13183 return SDValue(); 13184 } 13185 13186 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13187 SDValue N1, SDValue N2){ 13188 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13189 13190 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13191 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13192 13193 // If we got a simplified select_cc node back from SimplifySelectCC, then 13194 // break it down into a new SETCC node, and a new SELECT node, and then return 13195 // the SELECT node, since we were called with a SELECT node. 13196 if (SCC.getNode()) { 13197 // Check to see if we got a select_cc back (to turn into setcc/select). 13198 // Otherwise, just return whatever node we got back, like fabs. 13199 if (SCC.getOpcode() == ISD::SELECT_CC) { 13200 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13201 N0.getValueType(), 13202 SCC.getOperand(0), SCC.getOperand(1), 13203 SCC.getOperand(4)); 13204 AddToWorklist(SETCC.getNode()); 13205 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13206 SCC.getOperand(2), SCC.getOperand(3)); 13207 } 13208 13209 return SCC; 13210 } 13211 return SDValue(); 13212 } 13213 13214 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13215 /// being selected between, see if we can simplify the select. Callers of this 13216 /// should assume that TheSelect is deleted if this returns true. As such, they 13217 /// should return the appropriate thing (e.g. the node) back to the top-level of 13218 /// the DAG combiner loop to avoid it being looked at. 13219 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13220 SDValue RHS) { 13221 13222 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13223 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13224 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13225 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13226 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13227 SDValue Sqrt = RHS; 13228 ISD::CondCode CC; 13229 SDValue CmpLHS; 13230 const ConstantFPSDNode *NegZero = nullptr; 13231 13232 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13233 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13234 CmpLHS = TheSelect->getOperand(0); 13235 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13236 } else { 13237 // SELECT or VSELECT 13238 SDValue Cmp = TheSelect->getOperand(0); 13239 if (Cmp.getOpcode() == ISD::SETCC) { 13240 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13241 CmpLHS = Cmp.getOperand(0); 13242 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13243 } 13244 } 13245 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13246 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13247 CC == ISD::SETULT || CC == ISD::SETLT)) { 13248 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13249 CombineTo(TheSelect, Sqrt); 13250 return true; 13251 } 13252 } 13253 } 13254 // Cannot simplify select with vector condition 13255 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13256 13257 // If this is a select from two identical things, try to pull the operation 13258 // through the select. 13259 if (LHS.getOpcode() != RHS.getOpcode() || 13260 !LHS.hasOneUse() || !RHS.hasOneUse()) 13261 return false; 13262 13263 // If this is a load and the token chain is identical, replace the select 13264 // of two loads with a load through a select of the address to load from. 13265 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13266 // constants have been dropped into the constant pool. 13267 if (LHS.getOpcode() == ISD::LOAD) { 13268 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13269 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13270 13271 // Token chains must be identical. 13272 if (LHS.getOperand(0) != RHS.getOperand(0) || 13273 // Do not let this transformation reduce the number of volatile loads. 13274 LLD->isVolatile() || RLD->isVolatile() || 13275 // FIXME: If either is a pre/post inc/dec load, 13276 // we'd need to split out the address adjustment. 13277 LLD->isIndexed() || RLD->isIndexed() || 13278 // If this is an EXTLOAD, the VT's must match. 13279 LLD->getMemoryVT() != RLD->getMemoryVT() || 13280 // If this is an EXTLOAD, the kind of extension must match. 13281 (LLD->getExtensionType() != RLD->getExtensionType() && 13282 // The only exception is if one of the extensions is anyext. 13283 LLD->getExtensionType() != ISD::EXTLOAD && 13284 RLD->getExtensionType() != ISD::EXTLOAD) || 13285 // FIXME: this discards src value information. This is 13286 // over-conservative. It would be beneficial to be able to remember 13287 // both potential memory locations. Since we are discarding 13288 // src value info, don't do the transformation if the memory 13289 // locations are not in the default address space. 13290 LLD->getPointerInfo().getAddrSpace() != 0 || 13291 RLD->getPointerInfo().getAddrSpace() != 0 || 13292 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13293 LLD->getBasePtr().getValueType())) 13294 return false; 13295 13296 // Check that the select condition doesn't reach either load. If so, 13297 // folding this will induce a cycle into the DAG. If not, this is safe to 13298 // xform, so create a select of the addresses. 13299 SDValue Addr; 13300 if (TheSelect->getOpcode() == ISD::SELECT) { 13301 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13302 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13303 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13304 return false; 13305 // The loads must not depend on one another. 13306 if (LLD->isPredecessorOf(RLD) || 13307 RLD->isPredecessorOf(LLD)) 13308 return false; 13309 Addr = DAG.getSelect(SDLoc(TheSelect), 13310 LLD->getBasePtr().getValueType(), 13311 TheSelect->getOperand(0), LLD->getBasePtr(), 13312 RLD->getBasePtr()); 13313 } else { // Otherwise SELECT_CC 13314 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13315 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13316 13317 if ((LLD->hasAnyUseOfValue(1) && 13318 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13319 (RLD->hasAnyUseOfValue(1) && 13320 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13321 return false; 13322 13323 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13324 LLD->getBasePtr().getValueType(), 13325 TheSelect->getOperand(0), 13326 TheSelect->getOperand(1), 13327 LLD->getBasePtr(), RLD->getBasePtr(), 13328 TheSelect->getOperand(4)); 13329 } 13330 13331 SDValue Load; 13332 // It is safe to replace the two loads if they have different alignments, 13333 // but the new load must be the minimum (most restrictive) alignment of the 13334 // inputs. 13335 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13336 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13337 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13338 Load = DAG.getLoad(TheSelect->getValueType(0), 13339 SDLoc(TheSelect), 13340 // FIXME: Discards pointer and AA info. 13341 LLD->getChain(), Addr, MachinePointerInfo(), 13342 LLD->isVolatile(), LLD->isNonTemporal(), 13343 isInvariant, Alignment); 13344 } else { 13345 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13346 RLD->getExtensionType() : LLD->getExtensionType(), 13347 SDLoc(TheSelect), 13348 TheSelect->getValueType(0), 13349 // FIXME: Discards pointer and AA info. 13350 LLD->getChain(), Addr, MachinePointerInfo(), 13351 LLD->getMemoryVT(), LLD->isVolatile(), 13352 LLD->isNonTemporal(), isInvariant, Alignment); 13353 } 13354 13355 // Users of the select now use the result of the load. 13356 CombineTo(TheSelect, Load); 13357 13358 // Users of the old loads now use the new load's chain. We know the 13359 // old-load value is dead now. 13360 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13361 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13362 return true; 13363 } 13364 13365 return false; 13366 } 13367 13368 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13369 /// where 'cond' is the comparison specified by CC. 13370 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13371 SDValue N2, SDValue N3, 13372 ISD::CondCode CC, bool NotExtCompare) { 13373 // (x ? y : y) -> y. 13374 if (N2 == N3) return N2; 13375 13376 EVT VT = N2.getValueType(); 13377 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13378 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13379 13380 // Determine if the condition we're dealing with is constant 13381 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13382 N0, N1, CC, DL, false); 13383 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13384 13385 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 13386 // fold select_cc true, x, y -> x 13387 // fold select_cc false, x, y -> y 13388 return !SCCC->isNullValue() ? N2 : N3; 13389 } 13390 13391 // Check to see if we can simplify the select into an fabs node 13392 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13393 // Allow either -0.0 or 0.0 13394 if (CFP->isZero()) { 13395 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13396 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13397 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13398 N2 == N3.getOperand(0)) 13399 return DAG.getNode(ISD::FABS, DL, VT, N0); 13400 13401 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 13402 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 13403 N0 == N3 && N2.getOpcode() == ISD::FNEG && 13404 N2.getOperand(0) == N3) 13405 return DAG.getNode(ISD::FABS, DL, VT, N3); 13406 } 13407 } 13408 13409 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 13410 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 13411 // in it. This is a win when the constant is not otherwise available because 13412 // it replaces two constant pool loads with one. We only do this if the FP 13413 // type is known to be legal, because if it isn't, then we are before legalize 13414 // types an we want the other legalization to happen first (e.g. to avoid 13415 // messing with soft float) and if the ConstantFP is not legal, because if 13416 // it is legal, we may not need to store the FP constant in a constant pool. 13417 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 13418 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 13419 if (TLI.isTypeLegal(N2.getValueType()) && 13420 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 13421 TargetLowering::Legal && 13422 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 13423 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 13424 // If both constants have multiple uses, then we won't need to do an 13425 // extra load, they are likely around in registers for other users. 13426 (TV->hasOneUse() || FV->hasOneUse())) { 13427 Constant *Elts[] = { 13428 const_cast<ConstantFP*>(FV->getConstantFPValue()), 13429 const_cast<ConstantFP*>(TV->getConstantFPValue()) 13430 }; 13431 Type *FPTy = Elts[0]->getType(); 13432 const DataLayout &TD = DAG.getDataLayout(); 13433 13434 // Create a ConstantArray of the two constants. 13435 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 13436 SDValue CPIdx = 13437 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 13438 TD.getPrefTypeAlignment(FPTy)); 13439 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 13440 13441 // Get the offsets to the 0 and 1 element of the array so that we can 13442 // select between them. 13443 SDValue Zero = DAG.getIntPtrConstant(0, DL); 13444 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 13445 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 13446 13447 SDValue Cond = DAG.getSetCC(DL, 13448 getSetCCResultType(N0.getValueType()), 13449 N0, N1, CC); 13450 AddToWorklist(Cond.getNode()); 13451 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 13452 Cond, One, Zero); 13453 AddToWorklist(CstOffset.getNode()); 13454 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 13455 CstOffset); 13456 AddToWorklist(CPIdx.getNode()); 13457 return DAG.getLoad( 13458 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 13459 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 13460 false, false, false, Alignment); 13461 } 13462 } 13463 13464 // Check to see if we can perform the "gzip trick", transforming 13465 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 13466 if (isNullConstant(N3) && CC == ISD::SETLT && 13467 (isNullConstant(N1) || // (a < 0) ? b : 0 13468 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 13469 EVT XType = N0.getValueType(); 13470 EVT AType = N2.getValueType(); 13471 if (XType.bitsGE(AType)) { 13472 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 13473 // single-bit constant. 13474 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 13475 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 13476 ShCtV = XType.getSizeInBits() - ShCtV - 1; 13477 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 13478 getShiftAmountTy(N0.getValueType())); 13479 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 13480 XType, N0, ShCt); 13481 AddToWorklist(Shift.getNode()); 13482 13483 if (XType.bitsGT(AType)) { 13484 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13485 AddToWorklist(Shift.getNode()); 13486 } 13487 13488 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13489 } 13490 13491 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 13492 XType, N0, 13493 DAG.getConstant(XType.getSizeInBits() - 1, 13494 SDLoc(N0), 13495 getShiftAmountTy(N0.getValueType()))); 13496 AddToWorklist(Shift.getNode()); 13497 13498 if (XType.bitsGT(AType)) { 13499 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13500 AddToWorklist(Shift.getNode()); 13501 } 13502 13503 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13504 } 13505 } 13506 13507 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 13508 // where y is has a single bit set. 13509 // A plaintext description would be, we can turn the SELECT_CC into an AND 13510 // when the condition can be materialized as an all-ones register. Any 13511 // single bit-test can be materialized as an all-ones register with 13512 // shift-left and shift-right-arith. 13513 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 13514 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 13515 SDValue AndLHS = N0->getOperand(0); 13516 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13517 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 13518 // Shift the tested bit over the sign bit. 13519 APInt AndMask = ConstAndRHS->getAPIntValue(); 13520 SDValue ShlAmt = 13521 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 13522 getShiftAmountTy(AndLHS.getValueType())); 13523 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 13524 13525 // Now arithmetic right shift it all the way over, so the result is either 13526 // all-ones, or zero. 13527 SDValue ShrAmt = 13528 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 13529 getShiftAmountTy(Shl.getValueType())); 13530 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 13531 13532 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 13533 } 13534 } 13535 13536 // fold select C, 16, 0 -> shl C, 4 13537 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 13538 TLI.getBooleanContents(N0.getValueType()) == 13539 TargetLowering::ZeroOrOneBooleanContent) { 13540 13541 // If the caller doesn't want us to simplify this into a zext of a compare, 13542 // don't do it. 13543 if (NotExtCompare && N2C->isOne()) 13544 return SDValue(); 13545 13546 // Get a SetCC of the condition 13547 // NOTE: Don't create a SETCC if it's not legal on this target. 13548 if (!LegalOperations || 13549 TLI.isOperationLegal(ISD::SETCC, 13550 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 13551 SDValue Temp, SCC; 13552 // cast from setcc result type to select result type 13553 if (LegalTypes) { 13554 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 13555 N0, N1, CC); 13556 if (N2.getValueType().bitsLT(SCC.getValueType())) 13557 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 13558 N2.getValueType()); 13559 else 13560 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13561 N2.getValueType(), SCC); 13562 } else { 13563 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 13564 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13565 N2.getValueType(), SCC); 13566 } 13567 13568 AddToWorklist(SCC.getNode()); 13569 AddToWorklist(Temp.getNode()); 13570 13571 if (N2C->isOne()) 13572 return Temp; 13573 13574 // shl setcc result by log2 n2c 13575 return DAG.getNode( 13576 ISD::SHL, DL, N2.getValueType(), Temp, 13577 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 13578 getShiftAmountTy(Temp.getValueType()))); 13579 } 13580 } 13581 13582 // Check to see if this is the equivalent of setcc 13583 // FIXME: Turn all of these into setcc if setcc if setcc is legal 13584 // otherwise, go ahead with the folds. 13585 if (0 && isNullConstant(N3) && isOneConstant(N2)) { 13586 EVT XType = N0.getValueType(); 13587 if (!LegalOperations || 13588 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 13589 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 13590 if (Res.getValueType() != VT) 13591 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 13592 return Res; 13593 } 13594 13595 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 13596 if (isNullConstant(N1) && CC == ISD::SETEQ && 13597 (!LegalOperations || 13598 TLI.isOperationLegal(ISD::CTLZ, XType))) { 13599 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 13600 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 13601 DAG.getConstant(Log2_32(XType.getSizeInBits()), 13602 SDLoc(Ctlz), 13603 getShiftAmountTy(Ctlz.getValueType()))); 13604 } 13605 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 13606 if (isNullConstant(N1) && CC == ISD::SETGT) { 13607 SDLoc DL(N0); 13608 SDValue NegN0 = DAG.getNode(ISD::SUB, DL, 13609 XType, DAG.getConstant(0, DL, XType), N0); 13610 SDValue NotN0 = DAG.getNOT(DL, N0, XType); 13611 return DAG.getNode(ISD::SRL, DL, XType, 13612 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 13613 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13614 getShiftAmountTy(XType))); 13615 } 13616 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 13617 if (isAllOnesConstant(N1) && CC == ISD::SETGT) { 13618 SDLoc DL(N0); 13619 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0, 13620 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13621 getShiftAmountTy(N0.getValueType()))); 13622 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL, 13623 XType)); 13624 } 13625 } 13626 13627 // Check to see if this is an integer abs. 13628 // select_cc setg[te] X, 0, X, -X -> 13629 // select_cc setgt X, -1, X, -X -> 13630 // select_cc setl[te] X, 0, -X, X -> 13631 // select_cc setlt X, 1, -X, X -> 13632 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 13633 if (N1C) { 13634 ConstantSDNode *SubC = nullptr; 13635 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 13636 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 13637 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 13638 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 13639 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 13640 (N1C->isOne() && CC == ISD::SETLT)) && 13641 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 13642 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 13643 13644 EVT XType = N0.getValueType(); 13645 if (SubC && SubC->isNullValue() && XType.isInteger()) { 13646 SDLoc DL(N0); 13647 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 13648 N0, 13649 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13650 getShiftAmountTy(N0.getValueType()))); 13651 SDValue Add = DAG.getNode(ISD::ADD, DL, 13652 XType, N0, Shift); 13653 AddToWorklist(Shift.getNode()); 13654 AddToWorklist(Add.getNode()); 13655 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 13656 } 13657 } 13658 13659 return SDValue(); 13660 } 13661 13662 /// This is a stub for TargetLowering::SimplifySetCC. 13663 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 13664 SDValue N1, ISD::CondCode Cond, 13665 SDLoc DL, bool foldBooleans) { 13666 TargetLowering::DAGCombinerInfo 13667 DagCombineInfo(DAG, Level, false, this); 13668 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 13669 } 13670 13671 /// Given an ISD::SDIV node expressing a divide by constant, return 13672 /// a DAG expression to select that will generate the same value by multiplying 13673 /// by a magic number. 13674 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13675 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 13676 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13677 if (!C) 13678 return SDValue(); 13679 13680 // Avoid division by zero. 13681 if (C->isNullValue()) 13682 return SDValue(); 13683 13684 std::vector<SDNode*> Built; 13685 SDValue S = 13686 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13687 13688 for (SDNode *N : Built) 13689 AddToWorklist(N); 13690 return S; 13691 } 13692 13693 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 13694 /// DAG expression that will generate the same value by right shifting. 13695 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 13696 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13697 if (!C) 13698 return SDValue(); 13699 13700 // Avoid division by zero. 13701 if (C->isNullValue()) 13702 return SDValue(); 13703 13704 std::vector<SDNode *> Built; 13705 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 13706 13707 for (SDNode *N : Built) 13708 AddToWorklist(N); 13709 return S; 13710 } 13711 13712 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 13713 /// expression that will generate the same value by multiplying by a magic 13714 /// number. 13715 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13716 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 13717 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13718 if (!C) 13719 return SDValue(); 13720 13721 // Avoid division by zero. 13722 if (C->isNullValue()) 13723 return SDValue(); 13724 13725 std::vector<SDNode*> Built; 13726 SDValue S = 13727 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13728 13729 for (SDNode *N : Built) 13730 AddToWorklist(N); 13731 return S; 13732 } 13733 13734 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) { 13735 if (Level >= AfterLegalizeDAG) 13736 return SDValue(); 13737 13738 // Expose the DAG combiner to the target combiner implementations. 13739 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13740 13741 unsigned Iterations = 0; 13742 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 13743 if (Iterations) { 13744 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13745 // For the reciprocal, we need to find the zero of the function: 13746 // F(X) = A X - 1 [which has a zero at X = 1/A] 13747 // => 13748 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 13749 // does not require additional intermediate precision] 13750 EVT VT = Op.getValueType(); 13751 SDLoc DL(Op); 13752 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 13753 13754 AddToWorklist(Est.getNode()); 13755 13756 // Newton iterations: Est = Est + Est (1 - Arg * Est) 13757 for (unsigned i = 0; i < Iterations; ++i) { 13758 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est); 13759 AddToWorklist(NewEst.getNode()); 13760 13761 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst); 13762 AddToWorklist(NewEst.getNode()); 13763 13764 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13765 AddToWorklist(NewEst.getNode()); 13766 13767 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst); 13768 AddToWorklist(Est.getNode()); 13769 } 13770 } 13771 return Est; 13772 } 13773 13774 return SDValue(); 13775 } 13776 13777 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13778 /// For the reciprocal sqrt, we need to find the zero of the function: 13779 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13780 /// => 13781 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 13782 /// As a result, we precompute A/2 prior to the iteration loop. 13783 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 13784 unsigned Iterations) { 13785 EVT VT = Arg.getValueType(); 13786 SDLoc DL(Arg); 13787 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 13788 13789 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 13790 // this entire sequence requires only one FP constant. 13791 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg); 13792 AddToWorklist(HalfArg.getNode()); 13793 13794 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg); 13795 AddToWorklist(HalfArg.getNode()); 13796 13797 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 13798 for (unsigned i = 0; i < Iterations; ++i) { 13799 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13800 AddToWorklist(NewEst.getNode()); 13801 13802 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst); 13803 AddToWorklist(NewEst.getNode()); 13804 13805 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst); 13806 AddToWorklist(NewEst.getNode()); 13807 13808 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13809 AddToWorklist(Est.getNode()); 13810 } 13811 return Est; 13812 } 13813 13814 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13815 /// For the reciprocal sqrt, we need to find the zero of the function: 13816 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13817 /// => 13818 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 13819 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 13820 unsigned Iterations) { 13821 EVT VT = Arg.getValueType(); 13822 SDLoc DL(Arg); 13823 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 13824 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 13825 13826 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 13827 for (unsigned i = 0; i < Iterations; ++i) { 13828 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf); 13829 AddToWorklist(HalfEst.getNode()); 13830 13831 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13832 AddToWorklist(Est.getNode()); 13833 13834 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg); 13835 AddToWorklist(Est.getNode()); 13836 13837 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree); 13838 AddToWorklist(Est.getNode()); 13839 13840 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst); 13841 AddToWorklist(Est.getNode()); 13842 } 13843 return Est; 13844 } 13845 13846 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) { 13847 if (Level >= AfterLegalizeDAG) 13848 return SDValue(); 13849 13850 // Expose the DAG combiner to the target combiner implementations. 13851 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13852 unsigned Iterations = 0; 13853 bool UseOneConstNR = false; 13854 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 13855 AddToWorklist(Est.getNode()); 13856 if (Iterations) { 13857 Est = UseOneConstNR ? 13858 BuildRsqrtNROneConst(Op, Est, Iterations) : 13859 BuildRsqrtNRTwoConst(Op, Est, Iterations); 13860 } 13861 return Est; 13862 } 13863 13864 return SDValue(); 13865 } 13866 13867 /// Return true if base is a frame index, which is known not to alias with 13868 /// anything but itself. Provides base object and offset as results. 13869 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 13870 const GlobalValue *&GV, const void *&CV) { 13871 // Assume it is a primitive operation. 13872 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 13873 13874 // If it's an adding a simple constant then integrate the offset. 13875 if (Base.getOpcode() == ISD::ADD) { 13876 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 13877 Base = Base.getOperand(0); 13878 Offset += C->getZExtValue(); 13879 } 13880 } 13881 13882 // Return the underlying GlobalValue, and update the Offset. Return false 13883 // for GlobalAddressSDNode since the same GlobalAddress may be represented 13884 // by multiple nodes with different offsets. 13885 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 13886 GV = G->getGlobal(); 13887 Offset += G->getOffset(); 13888 return false; 13889 } 13890 13891 // Return the underlying Constant value, and update the Offset. Return false 13892 // for ConstantSDNodes since the same constant pool entry may be represented 13893 // by multiple nodes with different offsets. 13894 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 13895 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 13896 : (const void *)C->getConstVal(); 13897 Offset += C->getOffset(); 13898 return false; 13899 } 13900 // If it's any of the following then it can't alias with anything but itself. 13901 return isa<FrameIndexSDNode>(Base); 13902 } 13903 13904 /// Return true if there is any possibility that the two addresses overlap. 13905 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 13906 // If they are the same then they must be aliases. 13907 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 13908 13909 // If they are both volatile then they cannot be reordered. 13910 if (Op0->isVolatile() && Op1->isVolatile()) return true; 13911 13912 // If one operation reads from invariant memory, and the other may store, they 13913 // cannot alias. These should really be checking the equivalent of mayWrite, 13914 // but it only matters for memory nodes other than load /store. 13915 if (Op0->isInvariant() && Op1->writeMem()) 13916 return false; 13917 13918 if (Op1->isInvariant() && Op0->writeMem()) 13919 return false; 13920 13921 // Gather base node and offset information. 13922 SDValue Base1, Base2; 13923 int64_t Offset1, Offset2; 13924 const GlobalValue *GV1, *GV2; 13925 const void *CV1, *CV2; 13926 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 13927 Base1, Offset1, GV1, CV1); 13928 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 13929 Base2, Offset2, GV2, CV2); 13930 13931 // If they have a same base address then check to see if they overlap. 13932 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 13933 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13934 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13935 13936 // It is possible for different frame indices to alias each other, mostly 13937 // when tail call optimization reuses return address slots for arguments. 13938 // To catch this case, look up the actual index of frame indices to compute 13939 // the real alias relationship. 13940 if (isFrameIndex1 && isFrameIndex2) { 13941 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 13942 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 13943 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 13944 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13945 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13946 } 13947 13948 // Otherwise, if we know what the bases are, and they aren't identical, then 13949 // we know they cannot alias. 13950 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 13951 return false; 13952 13953 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 13954 // compared to the size and offset of the access, we may be able to prove they 13955 // do not alias. This check is conservative for now to catch cases created by 13956 // splitting vector types. 13957 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 13958 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 13959 (Op0->getMemoryVT().getSizeInBits() >> 3 == 13960 Op1->getMemoryVT().getSizeInBits() >> 3) && 13961 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 13962 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 13963 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 13964 13965 // There is no overlap between these relatively aligned accesses of similar 13966 // size, return no alias. 13967 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 13968 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 13969 return false; 13970 } 13971 13972 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 13973 ? CombinerGlobalAA 13974 : DAG.getSubtarget().useAA(); 13975 #ifndef NDEBUG 13976 if (CombinerAAOnlyFunc.getNumOccurrences() && 13977 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 13978 UseAA = false; 13979 #endif 13980 if (UseAA && 13981 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 13982 // Use alias analysis information. 13983 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 13984 Op1->getSrcValueOffset()); 13985 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 13986 Op0->getSrcValueOffset() - MinOffset; 13987 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 13988 Op1->getSrcValueOffset() - MinOffset; 13989 AliasResult AAResult = 13990 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 13991 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 13992 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 13993 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 13994 if (AAResult == NoAlias) 13995 return false; 13996 } 13997 13998 // Otherwise we have to assume they alias. 13999 return true; 14000 } 14001 14002 /// Walk up chain skipping non-aliasing memory nodes, 14003 /// looking for aliasing nodes and adding them to the Aliases vector. 14004 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14005 SmallVectorImpl<SDValue> &Aliases) { 14006 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14007 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14008 14009 // Get alias information for node. 14010 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14011 14012 // Starting off. 14013 Chains.push_back(OriginalChain); 14014 unsigned Depth = 0; 14015 14016 // Look at each chain and determine if it is an alias. If so, add it to the 14017 // aliases list. If not, then continue up the chain looking for the next 14018 // candidate. 14019 while (!Chains.empty()) { 14020 SDValue Chain = Chains.pop_back_val(); 14021 14022 // For TokenFactor nodes, look at each operand and only continue up the 14023 // chain until we find two aliases. If we've seen two aliases, assume we'll 14024 // find more and revert to original chain since the xform is unlikely to be 14025 // profitable. 14026 // 14027 // FIXME: The depth check could be made to return the last non-aliasing 14028 // chain we found before we hit a tokenfactor rather than the original 14029 // chain. 14030 if (Depth > 6 || Aliases.size() == 2) { 14031 Aliases.clear(); 14032 Aliases.push_back(OriginalChain); 14033 return; 14034 } 14035 14036 // Don't bother if we've been before. 14037 if (!Visited.insert(Chain.getNode()).second) 14038 continue; 14039 14040 switch (Chain.getOpcode()) { 14041 case ISD::EntryToken: 14042 // Entry token is ideal chain operand, but handled in FindBetterChain. 14043 break; 14044 14045 case ISD::LOAD: 14046 case ISD::STORE: { 14047 // Get alias information for Chain. 14048 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14049 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14050 14051 // If chain is alias then stop here. 14052 if (!(IsLoad && IsOpLoad) && 14053 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14054 Aliases.push_back(Chain); 14055 } else { 14056 // Look further up the chain. 14057 Chains.push_back(Chain.getOperand(0)); 14058 ++Depth; 14059 } 14060 break; 14061 } 14062 14063 case ISD::TokenFactor: 14064 // We have to check each of the operands of the token factor for "small" 14065 // token factors, so we queue them up. Adding the operands to the queue 14066 // (stack) in reverse order maintains the original order and increases the 14067 // likelihood that getNode will find a matching token factor (CSE.) 14068 if (Chain.getNumOperands() > 16) { 14069 Aliases.push_back(Chain); 14070 break; 14071 } 14072 for (unsigned n = Chain.getNumOperands(); n;) 14073 Chains.push_back(Chain.getOperand(--n)); 14074 ++Depth; 14075 break; 14076 14077 default: 14078 // For all other instructions we will just have to take what we can get. 14079 Aliases.push_back(Chain); 14080 break; 14081 } 14082 } 14083 14084 // We need to be careful here to also search for aliases through the 14085 // value operand of a store, etc. Consider the following situation: 14086 // Token1 = ... 14087 // L1 = load Token1, %52 14088 // S1 = store Token1, L1, %51 14089 // L2 = load Token1, %52+8 14090 // S2 = store Token1, L2, %51+8 14091 // Token2 = Token(S1, S2) 14092 // L3 = load Token2, %53 14093 // S3 = store Token2, L3, %52 14094 // L4 = load Token2, %53+8 14095 // S4 = store Token2, L4, %52+8 14096 // If we search for aliases of S3 (which loads address %52), and we look 14097 // only through the chain, then we'll miss the trivial dependence on L1 14098 // (which also loads from %52). We then might change all loads and 14099 // stores to use Token1 as their chain operand, which could result in 14100 // copying %53 into %52 before copying %52 into %51 (which should 14101 // happen first). 14102 // 14103 // The problem is, however, that searching for such data dependencies 14104 // can become expensive, and the cost is not directly related to the 14105 // chain depth. Instead, we'll rule out such configurations here by 14106 // insisting that we've visited all chain users (except for users 14107 // of the original chain, which is not necessary). When doing this, 14108 // we need to look through nodes we don't care about (otherwise, things 14109 // like register copies will interfere with trivial cases). 14110 14111 SmallVector<const SDNode *, 16> Worklist; 14112 for (const SDNode *N : Visited) 14113 if (N != OriginalChain.getNode()) 14114 Worklist.push_back(N); 14115 14116 while (!Worklist.empty()) { 14117 const SDNode *M = Worklist.pop_back_val(); 14118 14119 // We have already visited M, and want to make sure we've visited any uses 14120 // of M that we care about. For uses that we've not visisted, and don't 14121 // care about, queue them to the worklist. 14122 14123 for (SDNode::use_iterator UI = M->use_begin(), 14124 UIE = M->use_end(); UI != UIE; ++UI) 14125 if (UI.getUse().getValueType() == MVT::Other && 14126 Visited.insert(*UI).second) { 14127 if (isa<MemSDNode>(*UI)) { 14128 // We've not visited this use, and we care about it (it could have an 14129 // ordering dependency with the original node). 14130 Aliases.clear(); 14131 Aliases.push_back(OriginalChain); 14132 return; 14133 } 14134 14135 // We've not visited this use, but we don't care about it. Mark it as 14136 // visited and enqueue it to the worklist. 14137 Worklist.push_back(*UI); 14138 } 14139 } 14140 } 14141 14142 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14143 /// (aliasing node.) 14144 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14145 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14146 14147 // Accumulate all the aliases to this node. 14148 GatherAllAliases(N, OldChain, Aliases); 14149 14150 // If no operands then chain to entry token. 14151 if (Aliases.size() == 0) 14152 return DAG.getEntryNode(); 14153 14154 // If a single operand then chain to it. We don't need to revisit it. 14155 if (Aliases.size() == 1) 14156 return Aliases[0]; 14157 14158 // Construct a custom tailored token factor. 14159 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14160 } 14161 14162 /// This is the entry point for the file. 14163 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14164 CodeGenOpt::Level OptLevel) { 14165 /// This is the main entry point to this class. 14166 DAGCombiner(*this, AA, OptLevel).Run(Level); 14167 } 14168