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 visitCTLZ(SDNode *N); 259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 260 SDValue visitCTTZ(SDNode *N); 261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 262 SDValue visitCTPOP(SDNode *N); 263 SDValue visitSELECT(SDNode *N); 264 SDValue visitVSELECT(SDNode *N); 265 SDValue visitSELECT_CC(SDNode *N); 266 SDValue visitSETCC(SDNode *N); 267 SDValue visitSIGN_EXTEND(SDNode *N); 268 SDValue visitZERO_EXTEND(SDNode *N); 269 SDValue visitANY_EXTEND(SDNode *N); 270 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 271 SDValue visitTRUNCATE(SDNode *N); 272 SDValue visitBITCAST(SDNode *N); 273 SDValue visitBUILD_PAIR(SDNode *N); 274 SDValue visitFADD(SDNode *N); 275 SDValue visitFSUB(SDNode *N); 276 SDValue visitFMUL(SDNode *N); 277 SDValue visitFMA(SDNode *N); 278 SDValue visitFDIV(SDNode *N); 279 SDValue visitFREM(SDNode *N); 280 SDValue visitFSQRT(SDNode *N); 281 SDValue visitFCOPYSIGN(SDNode *N); 282 SDValue visitSINT_TO_FP(SDNode *N); 283 SDValue visitUINT_TO_FP(SDNode *N); 284 SDValue visitFP_TO_SINT(SDNode *N); 285 SDValue visitFP_TO_UINT(SDNode *N); 286 SDValue visitFP_ROUND(SDNode *N); 287 SDValue visitFP_ROUND_INREG(SDNode *N); 288 SDValue visitFP_EXTEND(SDNode *N); 289 SDValue visitFNEG(SDNode *N); 290 SDValue visitFABS(SDNode *N); 291 SDValue visitFCEIL(SDNode *N); 292 SDValue visitFTRUNC(SDNode *N); 293 SDValue visitFFLOOR(SDNode *N); 294 SDValue visitFMINNUM(SDNode *N); 295 SDValue visitFMAXNUM(SDNode *N); 296 SDValue visitBRCOND(SDNode *N); 297 SDValue visitBR_CC(SDNode *N); 298 SDValue visitLOAD(SDNode *N); 299 SDValue visitSTORE(SDNode *N); 300 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 302 SDValue visitBUILD_VECTOR(SDNode *N); 303 SDValue visitCONCAT_VECTORS(SDNode *N); 304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 305 SDValue visitVECTOR_SHUFFLE(SDNode *N); 306 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 307 SDValue visitINSERT_SUBVECTOR(SDNode *N); 308 SDValue visitMLOAD(SDNode *N); 309 SDValue visitMSTORE(SDNode *N); 310 SDValue visitMGATHER(SDNode *N); 311 SDValue visitMSCATTER(SDNode *N); 312 SDValue visitFP_TO_FP16(SDNode *N); 313 314 SDValue visitFADDForFMACombine(SDNode *N); 315 SDValue visitFSUBForFMACombine(SDNode *N); 316 317 SDValue XformToShuffleWithZero(SDNode *N); 318 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 319 320 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 321 322 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 323 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 324 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 325 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 326 SDValue N3, ISD::CondCode CC, 327 bool NotExtCompare = false); 328 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 329 SDLoc DL, bool foldBooleans = true); 330 331 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 332 SDValue &CC) const; 333 bool isOneUseSetCC(SDValue N) const; 334 335 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 336 unsigned HiOp); 337 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 338 SDValue CombineExtLoad(SDNode *N); 339 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 340 SDValue BuildSDIV(SDNode *N); 341 SDValue BuildSDIVPow2(SDNode *N); 342 SDValue BuildUDIV(SDNode *N); 343 SDValue BuildReciprocalEstimate(SDValue Op); 344 SDValue BuildRsqrtEstimate(SDValue Op); 345 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations); 346 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations); 347 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 348 bool DemandHighBits = true); 349 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 350 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 351 SDValue InnerPos, SDValue InnerNeg, 352 unsigned PosOpcode, unsigned NegOpcode, 353 SDLoc DL); 354 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 355 SDValue ReduceLoadWidth(SDNode *N); 356 SDValue ReduceLoadOpStoreWidth(SDNode *N); 357 SDValue TransformFPLoadStorePair(SDNode *N); 358 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 359 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 360 361 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 362 363 /// Walk up chain skipping non-aliasing memory nodes, 364 /// looking for aliasing nodes and adding them to the Aliases vector. 365 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 366 SmallVectorImpl<SDValue> &Aliases); 367 368 /// Return true if there is any possibility that the two addresses overlap. 369 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 370 371 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 372 /// chain (aliasing node.) 373 SDValue FindBetterChain(SDNode *N, SDValue Chain); 374 375 /// Holds a pointer to an LSBaseSDNode as well as information on where it 376 /// is located in a sequence of memory operations connected by a chain. 377 struct MemOpLink { 378 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 379 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 380 // Ptr to the mem node. 381 LSBaseSDNode *MemNode; 382 // Offset from the base ptr. 383 int64_t OffsetFromBase; 384 // What is the sequence number of this mem node. 385 // Lowest mem operand in the DAG starts at zero. 386 unsigned SequenceNum; 387 }; 388 389 /// This is a helper function for MergeConsecutiveStores. When the source 390 /// elements of the consecutive stores are all constants or all extracted 391 /// vector elements, try to merge them into one larger store. 392 /// \return True if a merged store was created. 393 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 394 EVT MemVT, unsigned NumElem, 395 bool IsConstantSrc, bool UseVector); 396 397 /// Merge consecutive store operations into a wide store. 398 /// This optimization uses wide integers or vectors when possible. 399 /// \return True if some memory operations were changed. 400 bool MergeConsecutiveStores(StoreSDNode *N); 401 402 /// \brief Try to transform a truncation where C is a constant: 403 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 404 /// 405 /// \p N needs to be a truncation and its first operand an AND. Other 406 /// requirements are checked by the function (e.g. that trunc is 407 /// single-use) and if missed an empty SDValue is returned. 408 SDValue distributeTruncateThroughAnd(SDNode *N); 409 410 public: 411 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 412 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 413 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 414 auto *F = DAG.getMachineFunction().getFunction(); 415 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) || 416 F->hasFnAttribute(Attribute::MinSize); 417 } 418 419 /// Runs the dag combiner on all nodes in the work list 420 void Run(CombineLevel AtLevel); 421 422 SelectionDAG &getDAG() const { return DAG; } 423 424 /// Returns a type large enough to hold any valid shift amount - before type 425 /// legalization these can be huge. 426 EVT getShiftAmountTy(EVT LHSTy) { 427 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 428 if (LHSTy.isVector()) 429 return LHSTy; 430 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 431 : TLI.getPointerTy(); 432 } 433 434 /// This method returns true if we are running before type legalization or 435 /// if the specified VT is legal. 436 bool isTypeLegal(const EVT &VT) { 437 if (!LegalTypes) return true; 438 return TLI.isTypeLegal(VT); 439 } 440 441 /// Convenience wrapper around TargetLowering::getSetCCResultType 442 EVT getSetCCResultType(EVT VT) const { 443 return TLI.getSetCCResultType(*DAG.getContext(), VT); 444 } 445 }; 446 } 447 448 449 namespace { 450 /// This class is a DAGUpdateListener that removes any deleted 451 /// nodes from the worklist. 452 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 453 DAGCombiner &DC; 454 public: 455 explicit WorklistRemover(DAGCombiner &dc) 456 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 457 458 void NodeDeleted(SDNode *N, SDNode *E) override { 459 DC.removeFromWorklist(N); 460 } 461 }; 462 } 463 464 //===----------------------------------------------------------------------===// 465 // TargetLowering::DAGCombinerInfo implementation 466 //===----------------------------------------------------------------------===// 467 468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 469 ((DAGCombiner*)DC)->AddToWorklist(N); 470 } 471 472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 473 ((DAGCombiner*)DC)->removeFromWorklist(N); 474 } 475 476 SDValue TargetLowering::DAGCombinerInfo:: 477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 478 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 479 } 480 481 SDValue TargetLowering::DAGCombinerInfo:: 482 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 483 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 484 } 485 486 487 SDValue TargetLowering::DAGCombinerInfo:: 488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 489 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 490 } 491 492 void TargetLowering::DAGCombinerInfo:: 493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 494 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 495 } 496 497 //===----------------------------------------------------------------------===// 498 // Helper Functions 499 //===----------------------------------------------------------------------===// 500 501 void DAGCombiner::deleteAndRecombine(SDNode *N) { 502 removeFromWorklist(N); 503 504 // If the operands of this node are only used by the node, they will now be 505 // dead. Make sure to re-visit them and recursively delete dead nodes. 506 for (const SDValue &Op : N->ops()) 507 // For an operand generating multiple values, one of the values may 508 // become dead allowing further simplification (e.g. split index 509 // arithmetic from an indexed load). 510 if (Op->hasOneUse() || Op->getNumValues() > 1) 511 AddToWorklist(Op.getNode()); 512 513 DAG.DeleteNode(N); 514 } 515 516 /// Return 1 if we can compute the negated form of the specified expression for 517 /// the same cost as the expression itself, or 2 if we can compute the negated 518 /// form more cheaply than the expression itself. 519 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 520 const TargetLowering &TLI, 521 const TargetOptions *Options, 522 unsigned Depth = 0) { 523 // fneg is removable even if it has multiple uses. 524 if (Op.getOpcode() == ISD::FNEG) return 2; 525 526 // Don't allow anything with multiple uses. 527 if (!Op.hasOneUse()) return 0; 528 529 // Don't recurse exponentially. 530 if (Depth > 6) return 0; 531 532 switch (Op.getOpcode()) { 533 default: return false; 534 case ISD::ConstantFP: 535 // Don't invert constant FP values after legalize. The negated constant 536 // isn't necessarily legal. 537 return LegalOperations ? 0 : 1; 538 case ISD::FADD: 539 // FIXME: determine better conditions for this xform. 540 if (!Options->UnsafeFPMath) return 0; 541 542 // After operation legalization, it might not be legal to create new FSUBs. 543 if (LegalOperations && 544 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 545 return 0; 546 547 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 548 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 549 Options, Depth + 1)) 550 return V; 551 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 552 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 553 Depth + 1); 554 case ISD::FSUB: 555 // We can't turn -(A-B) into B-A when we honor signed zeros. 556 if (!Options->UnsafeFPMath) return 0; 557 558 // fold (fneg (fsub A, B)) -> (fsub B, A) 559 return 1; 560 561 case ISD::FMUL: 562 case ISD::FDIV: 563 if (Options->HonorSignDependentRoundingFPMath()) return 0; 564 565 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 566 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 567 Options, Depth + 1)) 568 return V; 569 570 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 571 Depth + 1); 572 573 case ISD::FP_EXTEND: 574 case ISD::FP_ROUND: 575 case ISD::FSIN: 576 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 577 Depth + 1); 578 } 579 } 580 581 /// If isNegatibleForFree returns true, return the newly negated expression. 582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 583 bool LegalOperations, unsigned Depth = 0) { 584 const TargetOptions &Options = DAG.getTarget().Options; 585 // fneg is removable even if it has multiple uses. 586 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 587 588 // Don't allow anything with multiple uses. 589 assert(Op.hasOneUse() && "Unknown reuse!"); 590 591 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 592 switch (Op.getOpcode()) { 593 default: llvm_unreachable("Unknown code"); 594 case ISD::ConstantFP: { 595 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 596 V.changeSign(); 597 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 598 } 599 case ISD::FADD: 600 // FIXME: determine better conditions for this xform. 601 assert(Options.UnsafeFPMath); 602 603 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 604 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 605 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 607 GetNegatedExpression(Op.getOperand(0), DAG, 608 LegalOperations, Depth+1), 609 Op.getOperand(1)); 610 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 611 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 612 GetNegatedExpression(Op.getOperand(1), DAG, 613 LegalOperations, Depth+1), 614 Op.getOperand(0)); 615 case ISD::FSUB: 616 // We can't turn -(A-B) into B-A when we honor signed zeros. 617 assert(Options.UnsafeFPMath); 618 619 // fold (fneg (fsub 0, B)) -> B 620 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 621 if (N0CFP->getValueAPF().isZero()) 622 return Op.getOperand(1); 623 624 // fold (fneg (fsub A, B)) -> (fsub B, A) 625 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 626 Op.getOperand(1), Op.getOperand(0)); 627 628 case ISD::FMUL: 629 case ISD::FDIV: 630 assert(!Options.HonorSignDependentRoundingFPMath()); 631 632 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 633 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 634 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 636 GetNegatedExpression(Op.getOperand(0), DAG, 637 LegalOperations, Depth+1), 638 Op.getOperand(1)); 639 640 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 641 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 642 Op.getOperand(0), 643 GetNegatedExpression(Op.getOperand(1), DAG, 644 LegalOperations, Depth+1)); 645 646 case ISD::FP_EXTEND: 647 case ISD::FSIN: 648 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 649 GetNegatedExpression(Op.getOperand(0), DAG, 650 LegalOperations, Depth+1)); 651 case ISD::FP_ROUND: 652 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 653 GetNegatedExpression(Op.getOperand(0), DAG, 654 LegalOperations, Depth+1), 655 Op.getOperand(1)); 656 } 657 } 658 659 // Return true if this node is a setcc, or is a select_cc 660 // that selects between the target values used for true and false, making it 661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 662 // the appropriate nodes based on the type of node we are checking. This 663 // simplifies life a bit for the callers. 664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 665 SDValue &CC) const { 666 if (N.getOpcode() == ISD::SETCC) { 667 LHS = N.getOperand(0); 668 RHS = N.getOperand(1); 669 CC = N.getOperand(2); 670 return true; 671 } 672 673 if (N.getOpcode() != ISD::SELECT_CC || 674 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 675 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 676 return false; 677 678 if (TLI.getBooleanContents(N.getValueType()) == 679 TargetLowering::UndefinedBooleanContent) 680 return false; 681 682 LHS = N.getOperand(0); 683 RHS = N.getOperand(1); 684 CC = N.getOperand(4); 685 return true; 686 } 687 688 /// Return true if this is a SetCC-equivalent operation with only one use. 689 /// If this is true, it allows the users to invert the operation for free when 690 /// it is profitable to do so. 691 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 692 SDValue N0, N1, N2; 693 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 694 return true; 695 return false; 696 } 697 698 /// Returns true if N is a BUILD_VECTOR node whose 699 /// elements are all the same constant or undefined. 700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 701 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 702 if (!C) 703 return false; 704 705 APInt SplatUndef; 706 unsigned SplatBitSize; 707 bool HasAnyUndefs; 708 EVT EltVT = N->getValueType(0).getVectorElementType(); 709 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 710 HasAnyUndefs) && 711 EltVT.getSizeInBits() >= SplatBitSize); 712 } 713 714 // \brief Returns the SDNode if it is a constant integer BuildVector 715 // or constant integer. 716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 717 if (isa<ConstantSDNode>(N)) 718 return N.getNode(); 719 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 720 return N.getNode(); 721 return nullptr; 722 } 723 724 // \brief Returns the SDNode if it is a constant float BuildVector 725 // or constant float. 726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 727 if (isa<ConstantFPSDNode>(N)) 728 return N.getNode(); 729 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 730 return N.getNode(); 731 return nullptr; 732 } 733 734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 735 // int. 736 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 738 return CN; 739 740 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 741 BitVector UndefElements; 742 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 743 744 // BuildVectors can truncate their operands. Ignore that case here. 745 // FIXME: We blindly ignore splats which include undef which is overly 746 // pessimistic. 747 if (CN && UndefElements.none() && 748 CN->getValueType(0) == N.getValueType().getScalarType()) 749 return CN; 750 } 751 752 return nullptr; 753 } 754 755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 756 // float. 757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 758 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 759 return CN; 760 761 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 762 BitVector UndefElements; 763 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 764 765 if (CN && UndefElements.none()) 766 return CN; 767 } 768 769 return nullptr; 770 } 771 772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 773 SDValue N0, SDValue N1) { 774 EVT VT = N0.getValueType(); 775 if (N0.getOpcode() == Opc) { 776 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 777 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 778 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 779 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 780 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 781 return SDValue(); 782 } 783 if (N0.hasOneUse()) { 784 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 785 // use 786 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 787 if (!OpNode.getNode()) 788 return SDValue(); 789 AddToWorklist(OpNode.getNode()); 790 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 791 } 792 } 793 } 794 795 if (N1.getOpcode() == Opc) { 796 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 797 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 798 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 799 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 800 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 801 return SDValue(); 802 } 803 if (N1.hasOneUse()) { 804 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 805 // use 806 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 807 if (!OpNode.getNode()) 808 return SDValue(); 809 AddToWorklist(OpNode.getNode()); 810 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 811 } 812 } 813 } 814 815 return SDValue(); 816 } 817 818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 819 bool AddTo) { 820 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 821 ++NodesCombined; 822 DEBUG(dbgs() << "\nReplacing.1 "; 823 N->dump(&DAG); 824 dbgs() << "\nWith: "; 825 To[0].getNode()->dump(&DAG); 826 dbgs() << " and " << NumTo-1 << " other values\n"); 827 for (unsigned i = 0, e = NumTo; i != e; ++i) 828 assert((!To[i].getNode() || 829 N->getValueType(i) == To[i].getValueType()) && 830 "Cannot combine value to value of different type!"); 831 832 WorklistRemover DeadNodes(*this); 833 DAG.ReplaceAllUsesWith(N, To); 834 if (AddTo) { 835 // Push the new nodes and any users onto the worklist 836 for (unsigned i = 0, e = NumTo; i != e; ++i) { 837 if (To[i].getNode()) { 838 AddToWorklist(To[i].getNode()); 839 AddUsersToWorklist(To[i].getNode()); 840 } 841 } 842 } 843 844 // Finally, if the node is now dead, remove it from the graph. The node 845 // may not be dead if the replacement process recursively simplified to 846 // something else needing this node. 847 if (N->use_empty()) 848 deleteAndRecombine(N); 849 return SDValue(N, 0); 850 } 851 852 void DAGCombiner:: 853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 854 // Replace all uses. If any nodes become isomorphic to other nodes and 855 // are deleted, make sure to remove them from our worklist. 856 WorklistRemover DeadNodes(*this); 857 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 858 859 // Push the new node and any (possibly new) users onto the worklist. 860 AddToWorklist(TLO.New.getNode()); 861 AddUsersToWorklist(TLO.New.getNode()); 862 863 // Finally, if the node is now dead, remove it from the graph. The node 864 // may not be dead if the replacement process recursively simplified to 865 // something else needing this node. 866 if (TLO.Old.getNode()->use_empty()) 867 deleteAndRecombine(TLO.Old.getNode()); 868 } 869 870 /// Check the specified integer node value to see if it can be simplified or if 871 /// things it uses can be simplified by bit propagation. If so, return true. 872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 873 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 874 APInt KnownZero, KnownOne; 875 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 876 return false; 877 878 // Revisit the node. 879 AddToWorklist(Op.getNode()); 880 881 // Replace the old value with the new one. 882 ++NodesCombined; 883 DEBUG(dbgs() << "\nReplacing.2 "; 884 TLO.Old.getNode()->dump(&DAG); 885 dbgs() << "\nWith: "; 886 TLO.New.getNode()->dump(&DAG); 887 dbgs() << '\n'); 888 889 CommitTargetLoweringOpt(TLO); 890 return true; 891 } 892 893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 894 SDLoc dl(Load); 895 EVT VT = Load->getValueType(0); 896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 897 898 DEBUG(dbgs() << "\nReplacing.9 "; 899 Load->dump(&DAG); 900 dbgs() << "\nWith: "; 901 Trunc.getNode()->dump(&DAG); 902 dbgs() << '\n'); 903 WorklistRemover DeadNodes(*this); 904 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 905 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 906 deleteAndRecombine(Load); 907 AddToWorklist(Trunc.getNode()); 908 } 909 910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 911 Replace = false; 912 SDLoc dl(Op); 913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 914 EVT MemVT = LD->getMemoryVT(); 915 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 916 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 917 : ISD::EXTLOAD) 918 : LD->getExtensionType(); 919 Replace = true; 920 return DAG.getExtLoad(ExtType, dl, PVT, 921 LD->getChain(), LD->getBasePtr(), 922 MemVT, LD->getMemOperand()); 923 } 924 925 unsigned Opc = Op.getOpcode(); 926 switch (Opc) { 927 default: break; 928 case ISD::AssertSext: 929 return DAG.getNode(ISD::AssertSext, dl, PVT, 930 SExtPromoteOperand(Op.getOperand(0), PVT), 931 Op.getOperand(1)); 932 case ISD::AssertZext: 933 return DAG.getNode(ISD::AssertZext, dl, PVT, 934 ZExtPromoteOperand(Op.getOperand(0), PVT), 935 Op.getOperand(1)); 936 case ISD::Constant: { 937 unsigned ExtOpc = 938 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 939 return DAG.getNode(ExtOpc, dl, PVT, Op); 940 } 941 } 942 943 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 944 return SDValue(); 945 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 946 } 947 948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 949 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 950 return SDValue(); 951 EVT OldVT = Op.getValueType(); 952 SDLoc dl(Op); 953 bool Replace = false; 954 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 955 if (!NewOp.getNode()) 956 return SDValue(); 957 AddToWorklist(NewOp.getNode()); 958 959 if (Replace) 960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 961 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 962 DAG.getValueType(OldVT)); 963 } 964 965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 966 EVT OldVT = Op.getValueType(); 967 SDLoc dl(Op); 968 bool Replace = false; 969 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 970 if (!NewOp.getNode()) 971 return SDValue(); 972 AddToWorklist(NewOp.getNode()); 973 974 if (Replace) 975 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 976 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 977 } 978 979 /// Promote the specified integer binary operation if the target indicates it is 980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 981 /// i32 since i16 instructions are longer. 982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 983 if (!LegalOperations) 984 return SDValue(); 985 986 EVT VT = Op.getValueType(); 987 if (VT.isVector() || !VT.isInteger()) 988 return SDValue(); 989 990 // If operation type is 'undesirable', e.g. i16 on x86, consider 991 // promoting it. 992 unsigned Opc = Op.getOpcode(); 993 if (TLI.isTypeDesirableForOp(Opc, VT)) 994 return SDValue(); 995 996 EVT PVT = VT; 997 // Consult target whether it is a good idea to promote this operation and 998 // what's the right type to promote it to. 999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1000 assert(PVT != VT && "Don't know what type to promote to!"); 1001 1002 bool Replace0 = false; 1003 SDValue N0 = Op.getOperand(0); 1004 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1005 if (!NN0.getNode()) 1006 return SDValue(); 1007 1008 bool Replace1 = false; 1009 SDValue N1 = Op.getOperand(1); 1010 SDValue NN1; 1011 if (N0 == N1) 1012 NN1 = NN0; 1013 else { 1014 NN1 = PromoteOperand(N1, PVT, Replace1); 1015 if (!NN1.getNode()) 1016 return SDValue(); 1017 } 1018 1019 AddToWorklist(NN0.getNode()); 1020 if (NN1.getNode()) 1021 AddToWorklist(NN1.getNode()); 1022 1023 if (Replace0) 1024 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1025 if (Replace1) 1026 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1027 1028 DEBUG(dbgs() << "\nPromoting "; 1029 Op.getNode()->dump(&DAG)); 1030 SDLoc dl(Op); 1031 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1032 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1033 } 1034 return SDValue(); 1035 } 1036 1037 /// Promote the specified integer shift operation if the target indicates it is 1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1039 /// i32 since i16 instructions are longer. 1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1041 if (!LegalOperations) 1042 return SDValue(); 1043 1044 EVT VT = Op.getValueType(); 1045 if (VT.isVector() || !VT.isInteger()) 1046 return SDValue(); 1047 1048 // If operation type is 'undesirable', e.g. i16 on x86, consider 1049 // promoting it. 1050 unsigned Opc = Op.getOpcode(); 1051 if (TLI.isTypeDesirableForOp(Opc, VT)) 1052 return SDValue(); 1053 1054 EVT PVT = VT; 1055 // Consult target whether it is a good idea to promote this operation and 1056 // what's the right type to promote it to. 1057 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1058 assert(PVT != VT && "Don't know what type to promote to!"); 1059 1060 bool Replace = false; 1061 SDValue N0 = Op.getOperand(0); 1062 if (Opc == ISD::SRA) 1063 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1064 else if (Opc == ISD::SRL) 1065 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1066 else 1067 N0 = PromoteOperand(N0, PVT, Replace); 1068 if (!N0.getNode()) 1069 return SDValue(); 1070 1071 AddToWorklist(N0.getNode()); 1072 if (Replace) 1073 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1074 1075 DEBUG(dbgs() << "\nPromoting "; 1076 Op.getNode()->dump(&DAG)); 1077 SDLoc dl(Op); 1078 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1079 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1080 } 1081 return SDValue(); 1082 } 1083 1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1085 if (!LegalOperations) 1086 return SDValue(); 1087 1088 EVT VT = Op.getValueType(); 1089 if (VT.isVector() || !VT.isInteger()) 1090 return SDValue(); 1091 1092 // If operation type is 'undesirable', e.g. i16 on x86, consider 1093 // promoting it. 1094 unsigned Opc = Op.getOpcode(); 1095 if (TLI.isTypeDesirableForOp(Opc, VT)) 1096 return SDValue(); 1097 1098 EVT PVT = VT; 1099 // Consult target whether it is a good idea to promote this operation and 1100 // what's the right type to promote it to. 1101 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1102 assert(PVT != VT && "Don't know what type to promote to!"); 1103 // fold (aext (aext x)) -> (aext x) 1104 // fold (aext (zext x)) -> (zext x) 1105 // fold (aext (sext x)) -> (sext x) 1106 DEBUG(dbgs() << "\nPromoting "; 1107 Op.getNode()->dump(&DAG)); 1108 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1109 } 1110 return SDValue(); 1111 } 1112 1113 bool DAGCombiner::PromoteLoad(SDValue Op) { 1114 if (!LegalOperations) 1115 return false; 1116 1117 EVT VT = Op.getValueType(); 1118 if (VT.isVector() || !VT.isInteger()) 1119 return false; 1120 1121 // If operation type is 'undesirable', e.g. i16 on x86, consider 1122 // promoting it. 1123 unsigned Opc = Op.getOpcode(); 1124 if (TLI.isTypeDesirableForOp(Opc, VT)) 1125 return false; 1126 1127 EVT PVT = VT; 1128 // Consult target whether it is a good idea to promote this operation and 1129 // what's the right type to promote it to. 1130 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1131 assert(PVT != VT && "Don't know what type to promote to!"); 1132 1133 SDLoc dl(Op); 1134 SDNode *N = Op.getNode(); 1135 LoadSDNode *LD = cast<LoadSDNode>(N); 1136 EVT MemVT = LD->getMemoryVT(); 1137 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1138 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1139 : ISD::EXTLOAD) 1140 : LD->getExtensionType(); 1141 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1142 LD->getChain(), LD->getBasePtr(), 1143 MemVT, LD->getMemOperand()); 1144 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1145 1146 DEBUG(dbgs() << "\nPromoting "; 1147 N->dump(&DAG); 1148 dbgs() << "\nTo: "; 1149 Result.getNode()->dump(&DAG); 1150 dbgs() << '\n'); 1151 WorklistRemover DeadNodes(*this); 1152 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1153 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1154 deleteAndRecombine(N); 1155 AddToWorklist(Result.getNode()); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 /// \brief Recursively delete a node which has no uses and any operands for 1162 /// which it is the only use. 1163 /// 1164 /// Note that this both deletes the nodes and removes them from the worklist. 1165 /// It also adds any nodes who have had a user deleted to the worklist as they 1166 /// may now have only one use and subject to other combines. 1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1168 if (!N->use_empty()) 1169 return false; 1170 1171 SmallSetVector<SDNode *, 16> Nodes; 1172 Nodes.insert(N); 1173 do { 1174 N = Nodes.pop_back_val(); 1175 if (!N) 1176 continue; 1177 1178 if (N->use_empty()) { 1179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1180 Nodes.insert(N->getOperand(i).getNode()); 1181 1182 removeFromWorklist(N); 1183 DAG.DeleteNode(N); 1184 } else { 1185 AddToWorklist(N); 1186 } 1187 } while (!Nodes.empty()); 1188 return true; 1189 } 1190 1191 //===----------------------------------------------------------------------===// 1192 // Main DAG Combiner implementation 1193 //===----------------------------------------------------------------------===// 1194 1195 void DAGCombiner::Run(CombineLevel AtLevel) { 1196 // set the instance variables, so that the various visit routines may use it. 1197 Level = AtLevel; 1198 LegalOperations = Level >= AfterLegalizeVectorOps; 1199 LegalTypes = Level >= AfterLegalizeTypes; 1200 1201 // Add all the dag nodes to the worklist. 1202 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1203 E = DAG.allnodes_end(); I != E; ++I) 1204 AddToWorklist(I); 1205 1206 // Create a dummy node (which is not added to allnodes), that adds a reference 1207 // to the root node, preventing it from being deleted, and tracking any 1208 // changes of the root. 1209 HandleSDNode Dummy(DAG.getRoot()); 1210 1211 // while the worklist isn't empty, find a node and 1212 // try and combine it. 1213 while (!WorklistMap.empty()) { 1214 SDNode *N; 1215 // The Worklist holds the SDNodes in order, but it may contain null entries. 1216 do { 1217 N = Worklist.pop_back_val(); 1218 } while (!N); 1219 1220 bool GoodWorklistEntry = WorklistMap.erase(N); 1221 (void)GoodWorklistEntry; 1222 assert(GoodWorklistEntry && 1223 "Found a worklist entry without a corresponding map entry!"); 1224 1225 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1226 // N is deleted from the DAG, since they too may now be dead or may have a 1227 // reduced number of uses, allowing other xforms. 1228 if (recursivelyDeleteUnusedNodes(N)) 1229 continue; 1230 1231 WorklistRemover DeadNodes(*this); 1232 1233 // If this combine is running after legalizing the DAG, re-legalize any 1234 // nodes pulled off the worklist. 1235 if (Level == AfterLegalizeDAG) { 1236 SmallSetVector<SDNode *, 16> UpdatedNodes; 1237 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1238 1239 for (SDNode *LN : UpdatedNodes) { 1240 AddToWorklist(LN); 1241 AddUsersToWorklist(LN); 1242 } 1243 if (!NIsValid) 1244 continue; 1245 } 1246 1247 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1248 1249 // Add any operands of the new node which have not yet been combined to the 1250 // worklist as well. Because the worklist uniques things already, this 1251 // won't repeatedly process the same operand. 1252 CombinedNodes.insert(N); 1253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1254 if (!CombinedNodes.count(N->getOperand(i).getNode())) 1255 AddToWorklist(N->getOperand(i).getNode()); 1256 1257 SDValue RV = combine(N); 1258 1259 if (!RV.getNode()) 1260 continue; 1261 1262 ++NodesCombined; 1263 1264 // If we get back the same node we passed in, rather than a new node or 1265 // zero, we know that the node must have defined multiple values and 1266 // CombineTo was used. Since CombineTo takes care of the worklist 1267 // mechanics for us, we have no work to do in this case. 1268 if (RV.getNode() == N) 1269 continue; 1270 1271 assert(N->getOpcode() != ISD::DELETED_NODE && 1272 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1273 "Node was deleted but visit returned new node!"); 1274 1275 DEBUG(dbgs() << " ... into: "; 1276 RV.getNode()->dump(&DAG)); 1277 1278 // Transfer debug value. 1279 DAG.TransferDbgValues(SDValue(N, 0), RV); 1280 if (N->getNumValues() == RV.getNode()->getNumValues()) 1281 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1282 else { 1283 assert(N->getValueType(0) == RV.getValueType() && 1284 N->getNumValues() == 1 && "Type mismatch"); 1285 SDValue OpV = RV; 1286 DAG.ReplaceAllUsesWith(N, &OpV); 1287 } 1288 1289 // Push the new node and any users onto the worklist 1290 AddToWorklist(RV.getNode()); 1291 AddUsersToWorklist(RV.getNode()); 1292 1293 // Finally, if the node is now dead, remove it from the graph. The node 1294 // may not be dead if the replacement process recursively simplified to 1295 // something else needing this node. This will also take care of adding any 1296 // operands which have lost a user to the worklist. 1297 recursivelyDeleteUnusedNodes(N); 1298 } 1299 1300 // If the root changed (e.g. it was a dead load, update the root). 1301 DAG.setRoot(Dummy.getValue()); 1302 DAG.RemoveDeadNodes(); 1303 } 1304 1305 SDValue DAGCombiner::visit(SDNode *N) { 1306 switch (N->getOpcode()) { 1307 default: break; 1308 case ISD::TokenFactor: return visitTokenFactor(N); 1309 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1310 case ISD::ADD: return visitADD(N); 1311 case ISD::SUB: return visitSUB(N); 1312 case ISD::ADDC: return visitADDC(N); 1313 case ISD::SUBC: return visitSUBC(N); 1314 case ISD::ADDE: return visitADDE(N); 1315 case ISD::SUBE: return visitSUBE(N); 1316 case ISD::MUL: return visitMUL(N); 1317 case ISD::SDIV: return visitSDIV(N); 1318 case ISD::UDIV: return visitUDIV(N); 1319 case ISD::SREM: return visitSREM(N); 1320 case ISD::UREM: return visitUREM(N); 1321 case ISD::MULHU: return visitMULHU(N); 1322 case ISD::MULHS: return visitMULHS(N); 1323 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1324 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1325 case ISD::SMULO: return visitSMULO(N); 1326 case ISD::UMULO: return visitUMULO(N); 1327 case ISD::SDIVREM: return visitSDIVREM(N); 1328 case ISD::UDIVREM: return visitUDIVREM(N); 1329 case ISD::AND: return visitAND(N); 1330 case ISD::OR: return visitOR(N); 1331 case ISD::XOR: return visitXOR(N); 1332 case ISD::SHL: return visitSHL(N); 1333 case ISD::SRA: return visitSRA(N); 1334 case ISD::SRL: return visitSRL(N); 1335 case ISD::ROTR: 1336 case ISD::ROTL: return visitRotate(N); 1337 case ISD::CTLZ: return visitCTLZ(N); 1338 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1339 case ISD::CTTZ: return visitCTTZ(N); 1340 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1341 case ISD::CTPOP: return visitCTPOP(N); 1342 case ISD::SELECT: return visitSELECT(N); 1343 case ISD::VSELECT: return visitVSELECT(N); 1344 case ISD::SELECT_CC: return visitSELECT_CC(N); 1345 case ISD::SETCC: return visitSETCC(N); 1346 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1347 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1348 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1349 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1350 case ISD::TRUNCATE: return visitTRUNCATE(N); 1351 case ISD::BITCAST: return visitBITCAST(N); 1352 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1353 case ISD::FADD: return visitFADD(N); 1354 case ISD::FSUB: return visitFSUB(N); 1355 case ISD::FMUL: return visitFMUL(N); 1356 case ISD::FMA: return visitFMA(N); 1357 case ISD::FDIV: return visitFDIV(N); 1358 case ISD::FREM: return visitFREM(N); 1359 case ISD::FSQRT: return visitFSQRT(N); 1360 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1361 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1362 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1363 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1364 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1365 case ISD::FP_ROUND: return visitFP_ROUND(N); 1366 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1367 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1368 case ISD::FNEG: return visitFNEG(N); 1369 case ISD::FABS: return visitFABS(N); 1370 case ISD::FFLOOR: return visitFFLOOR(N); 1371 case ISD::FMINNUM: return visitFMINNUM(N); 1372 case ISD::FMAXNUM: return visitFMAXNUM(N); 1373 case ISD::FCEIL: return visitFCEIL(N); 1374 case ISD::FTRUNC: return visitFTRUNC(N); 1375 case ISD::BRCOND: return visitBRCOND(N); 1376 case ISD::BR_CC: return visitBR_CC(N); 1377 case ISD::LOAD: return visitLOAD(N); 1378 case ISD::STORE: return visitSTORE(N); 1379 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1380 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1381 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1382 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1383 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1384 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1385 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1386 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1387 case ISD::MGATHER: return visitMGATHER(N); 1388 case ISD::MLOAD: return visitMLOAD(N); 1389 case ISD::MSCATTER: return visitMSCATTER(N); 1390 case ISD::MSTORE: return visitMSTORE(N); 1391 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1392 } 1393 return SDValue(); 1394 } 1395 1396 SDValue DAGCombiner::combine(SDNode *N) { 1397 SDValue RV = visit(N); 1398 1399 // If nothing happened, try a target-specific DAG combine. 1400 if (!RV.getNode()) { 1401 assert(N->getOpcode() != ISD::DELETED_NODE && 1402 "Node was deleted but visit returned NULL!"); 1403 1404 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1405 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1406 1407 // Expose the DAG combiner to the target combiner impls. 1408 TargetLowering::DAGCombinerInfo 1409 DagCombineInfo(DAG, Level, false, this); 1410 1411 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1412 } 1413 } 1414 1415 // If nothing happened still, try promoting the operation. 1416 if (!RV.getNode()) { 1417 switch (N->getOpcode()) { 1418 default: break; 1419 case ISD::ADD: 1420 case ISD::SUB: 1421 case ISD::MUL: 1422 case ISD::AND: 1423 case ISD::OR: 1424 case ISD::XOR: 1425 RV = PromoteIntBinOp(SDValue(N, 0)); 1426 break; 1427 case ISD::SHL: 1428 case ISD::SRA: 1429 case ISD::SRL: 1430 RV = PromoteIntShiftOp(SDValue(N, 0)); 1431 break; 1432 case ISD::SIGN_EXTEND: 1433 case ISD::ZERO_EXTEND: 1434 case ISD::ANY_EXTEND: 1435 RV = PromoteExtend(SDValue(N, 0)); 1436 break; 1437 case ISD::LOAD: 1438 if (PromoteLoad(SDValue(N, 0))) 1439 RV = SDValue(N, 0); 1440 break; 1441 } 1442 } 1443 1444 // If N is a commutative binary node, try commuting it to enable more 1445 // sdisel CSE. 1446 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1447 N->getNumValues() == 1) { 1448 SDValue N0 = N->getOperand(0); 1449 SDValue N1 = N->getOperand(1); 1450 1451 // Constant operands are canonicalized to RHS. 1452 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1453 SDValue Ops[] = {N1, N0}; 1454 SDNode *CSENode; 1455 if (const BinaryWithFlagsSDNode *BinNode = 1456 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1458 BinNode->Flags.hasNoUnsignedWrap(), 1459 BinNode->Flags.hasNoSignedWrap(), 1460 BinNode->Flags.hasExact()); 1461 } else { 1462 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1463 } 1464 if (CSENode) 1465 return SDValue(CSENode, 0); 1466 } 1467 } 1468 1469 return RV; 1470 } 1471 1472 /// Given a node, return its input chain if it has one, otherwise return a null 1473 /// sd operand. 1474 static SDValue getInputChainForNode(SDNode *N) { 1475 if (unsigned NumOps = N->getNumOperands()) { 1476 if (N->getOperand(0).getValueType() == MVT::Other) 1477 return N->getOperand(0); 1478 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1479 return N->getOperand(NumOps-1); 1480 for (unsigned i = 1; i < NumOps-1; ++i) 1481 if (N->getOperand(i).getValueType() == MVT::Other) 1482 return N->getOperand(i); 1483 } 1484 return SDValue(); 1485 } 1486 1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1488 // If N has two operands, where one has an input chain equal to the other, 1489 // the 'other' chain is redundant. 1490 if (N->getNumOperands() == 2) { 1491 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1492 return N->getOperand(0); 1493 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1494 return N->getOperand(1); 1495 } 1496 1497 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1498 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1499 SmallPtrSet<SDNode*, 16> SeenOps; 1500 bool Changed = false; // If we should replace this token factor. 1501 1502 // Start out with this token factor. 1503 TFs.push_back(N); 1504 1505 // Iterate through token factors. The TFs grows when new token factors are 1506 // encountered. 1507 for (unsigned i = 0; i < TFs.size(); ++i) { 1508 SDNode *TF = TFs[i]; 1509 1510 // Check each of the operands. 1511 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1512 SDValue Op = TF->getOperand(i); 1513 1514 switch (Op.getOpcode()) { 1515 case ISD::EntryToken: 1516 // Entry tokens don't need to be added to the list. They are 1517 // redundant. 1518 Changed = true; 1519 break; 1520 1521 case ISD::TokenFactor: 1522 if (Op.hasOneUse() && 1523 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1524 // Queue up for processing. 1525 TFs.push_back(Op.getNode()); 1526 // Clean up in case the token factor is removed. 1527 AddToWorklist(Op.getNode()); 1528 Changed = true; 1529 break; 1530 } 1531 // Fall thru 1532 1533 default: 1534 // Only add if it isn't already in the list. 1535 if (SeenOps.insert(Op.getNode()).second) 1536 Ops.push_back(Op); 1537 else 1538 Changed = true; 1539 break; 1540 } 1541 } 1542 } 1543 1544 SDValue Result; 1545 1546 // If we've changed things around then replace token factor. 1547 if (Changed) { 1548 if (Ops.empty()) { 1549 // The entry token is the only possible outcome. 1550 Result = DAG.getEntryNode(); 1551 } else { 1552 // New and improved token factor. 1553 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1554 } 1555 1556 // Add users to worklist if AA is enabled, since it may introduce 1557 // a lot of new chained token factors while removing memory deps. 1558 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1559 : DAG.getSubtarget().useAA(); 1560 return CombineTo(N, Result, UseAA /*add to worklist*/); 1561 } 1562 1563 return Result; 1564 } 1565 1566 /// MERGE_VALUES can always be eliminated. 1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1568 WorklistRemover DeadNodes(*this); 1569 // Replacing results may cause a different MERGE_VALUES to suddenly 1570 // be CSE'd with N, and carry its uses with it. Iterate until no 1571 // uses remain, to ensure that the node can be safely deleted. 1572 // First add the users of this node to the work list so that they 1573 // can be tried again once they have new operands. 1574 AddUsersToWorklist(N); 1575 do { 1576 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1577 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1578 } while (!N->use_empty()); 1579 deleteAndRecombine(N); 1580 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1581 } 1582 1583 SDValue DAGCombiner::visitADD(SDNode *N) { 1584 SDValue N0 = N->getOperand(0); 1585 SDValue N1 = N->getOperand(1); 1586 EVT VT = N0.getValueType(); 1587 1588 // fold vector ops 1589 if (VT.isVector()) { 1590 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1591 return FoldedVOp; 1592 1593 // fold (add x, 0) -> x, vector edition 1594 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1595 return N0; 1596 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1597 return N1; 1598 } 1599 1600 // fold (add x, undef) -> undef 1601 if (N0.getOpcode() == ISD::UNDEF) 1602 return N0; 1603 if (N1.getOpcode() == ISD::UNDEF) 1604 return N1; 1605 // fold (add c1, c2) -> c1+c2 1606 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1607 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1608 if (N0C && N1C) 1609 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C); 1610 // canonicalize constant to RHS 1611 if (isConstantIntBuildVectorOrConstantInt(N0) && 1612 !isConstantIntBuildVectorOrConstantInt(N1)) 1613 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1614 // fold (add x, 0) -> x 1615 if (N1C && N1C->isNullValue()) 1616 return N0; 1617 // fold (add Sym, c) -> Sym+c 1618 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1619 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1620 GA->getOpcode() == ISD::GlobalAddress) 1621 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1622 GA->getOffset() + 1623 (uint64_t)N1C->getSExtValue()); 1624 // fold ((c1-A)+c2) -> (c1+c2)-A 1625 if (N1C && N0.getOpcode() == ISD::SUB) 1626 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 1627 SDLoc DL(N); 1628 return DAG.getNode(ISD::SUB, DL, VT, 1629 DAG.getConstant(N1C->getAPIntValue()+ 1630 N0C->getAPIntValue(), DL, VT), 1631 N0.getOperand(1)); 1632 } 1633 // reassociate add 1634 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1635 return RADD; 1636 // fold ((0-A) + B) -> B-A 1637 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1638 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1639 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1640 // fold (A + (0-B)) -> A-B 1641 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1642 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1643 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1644 // fold (A+(B-A)) -> B 1645 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1646 return N1.getOperand(0); 1647 // fold ((B-A)+A) -> B 1648 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1649 return N0.getOperand(0); 1650 // fold (A+(B-(A+C))) to (B-C) 1651 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1652 N0 == N1.getOperand(1).getOperand(0)) 1653 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1654 N1.getOperand(1).getOperand(1)); 1655 // fold (A+(B-(C+A))) to (B-C) 1656 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1657 N0 == N1.getOperand(1).getOperand(1)) 1658 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1659 N1.getOperand(1).getOperand(0)); 1660 // fold (A+((B-A)+or-C)) to (B+or-C) 1661 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1662 N1.getOperand(0).getOpcode() == ISD::SUB && 1663 N0 == N1.getOperand(0).getOperand(1)) 1664 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1665 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1666 1667 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1668 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1669 SDValue N00 = N0.getOperand(0); 1670 SDValue N01 = N0.getOperand(1); 1671 SDValue N10 = N1.getOperand(0); 1672 SDValue N11 = N1.getOperand(1); 1673 1674 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1675 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1676 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1677 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1678 } 1679 1680 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1681 return SDValue(N, 0); 1682 1683 // fold (a+b) -> (a|b) iff a and b share no bits. 1684 if (VT.isInteger() && !VT.isVector()) { 1685 APInt LHSZero, LHSOne; 1686 APInt RHSZero, RHSOne; 1687 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1688 1689 if (LHSZero.getBoolValue()) { 1690 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1691 1692 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1693 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1694 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1695 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1696 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1697 } 1698 } 1699 } 1700 1701 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1702 if (N1.getOpcode() == ISD::SHL && 1703 N1.getOperand(0).getOpcode() == ISD::SUB) 1704 if (ConstantSDNode *C = 1705 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1706 if (C->getAPIntValue() == 0) 1707 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1708 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1709 N1.getOperand(0).getOperand(1), 1710 N1.getOperand(1))); 1711 if (N0.getOpcode() == ISD::SHL && 1712 N0.getOperand(0).getOpcode() == ISD::SUB) 1713 if (ConstantSDNode *C = 1714 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1715 if (C->getAPIntValue() == 0) 1716 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1717 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1718 N0.getOperand(0).getOperand(1), 1719 N0.getOperand(1))); 1720 1721 if (N1.getOpcode() == ISD::AND) { 1722 SDValue AndOp0 = N1.getOperand(0); 1723 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1724 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1725 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1726 1727 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1728 // and similar xforms where the inner op is either ~0 or 0. 1729 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1730 SDLoc DL(N); 1731 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1732 } 1733 } 1734 1735 // add (sext i1), X -> sub X, (zext i1) 1736 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1737 N0.getOperand(0).getValueType() == MVT::i1 && 1738 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1739 SDLoc DL(N); 1740 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1741 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1742 } 1743 1744 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1745 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1746 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1747 if (TN->getVT() == MVT::i1) { 1748 SDLoc DL(N); 1749 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1750 DAG.getConstant(1, DL, VT)); 1751 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1752 } 1753 } 1754 1755 return SDValue(); 1756 } 1757 1758 SDValue DAGCombiner::visitADDC(SDNode *N) { 1759 SDValue N0 = N->getOperand(0); 1760 SDValue N1 = N->getOperand(1); 1761 EVT VT = N0.getValueType(); 1762 1763 // If the flag result is dead, turn this into an ADD. 1764 if (!N->hasAnyUseOfValue(1)) 1765 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1766 DAG.getNode(ISD::CARRY_FALSE, 1767 SDLoc(N), MVT::Glue)); 1768 1769 // canonicalize constant to RHS. 1770 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1771 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1772 if (N0C && !N1C) 1773 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1774 1775 // fold (addc x, 0) -> x + no carry out 1776 if (N1C && N1C->isNullValue()) 1777 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1778 SDLoc(N), MVT::Glue)); 1779 1780 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1781 APInt LHSZero, LHSOne; 1782 APInt RHSZero, RHSOne; 1783 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1784 1785 if (LHSZero.getBoolValue()) { 1786 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1787 1788 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1789 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1790 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1791 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1792 DAG.getNode(ISD::CARRY_FALSE, 1793 SDLoc(N), MVT::Glue)); 1794 } 1795 1796 return SDValue(); 1797 } 1798 1799 SDValue DAGCombiner::visitADDE(SDNode *N) { 1800 SDValue N0 = N->getOperand(0); 1801 SDValue N1 = N->getOperand(1); 1802 SDValue CarryIn = N->getOperand(2); 1803 1804 // canonicalize constant to RHS 1805 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1806 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1807 if (N0C && !N1C) 1808 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1809 N1, N0, CarryIn); 1810 1811 // fold (adde x, y, false) -> (addc x, y) 1812 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1813 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1814 1815 return SDValue(); 1816 } 1817 1818 // Since it may not be valid to emit a fold to zero for vector initializers 1819 // check if we can before folding. 1820 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1821 SelectionDAG &DAG, 1822 bool LegalOperations, bool LegalTypes) { 1823 if (!VT.isVector()) 1824 return DAG.getConstant(0, DL, VT); 1825 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1826 return DAG.getConstant(0, DL, VT); 1827 return SDValue(); 1828 } 1829 1830 SDValue DAGCombiner::visitSUB(SDNode *N) { 1831 SDValue N0 = N->getOperand(0); 1832 SDValue N1 = N->getOperand(1); 1833 EVT VT = N0.getValueType(); 1834 1835 // fold vector ops 1836 if (VT.isVector()) { 1837 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1838 return FoldedVOp; 1839 1840 // fold (sub x, 0) -> x, vector edition 1841 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1842 return N0; 1843 } 1844 1845 // fold (sub x, x) -> 0 1846 // FIXME: Refactor this and xor and other similar operations together. 1847 if (N0 == N1) 1848 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1849 // fold (sub c1, c2) -> c1-c2 1850 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1851 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1852 if (N0C && N1C) 1853 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C); 1854 // fold (sub x, c) -> (add x, -c) 1855 if (N1C) { 1856 SDLoc DL(N); 1857 return DAG.getNode(ISD::ADD, DL, VT, N0, 1858 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1859 } 1860 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1861 if (N0C && N0C->isAllOnesValue()) 1862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1863 // fold A-(A-B) -> B 1864 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1865 return N1.getOperand(1); 1866 // fold (A+B)-A -> B 1867 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1868 return N0.getOperand(1); 1869 // fold (A+B)-B -> A 1870 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1871 return N0.getOperand(0); 1872 // fold C2-(A+C1) -> (C2-C1)-A 1873 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1874 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1875 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1876 SDLoc DL(N); 1877 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1878 DL, VT); 1879 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1880 N1.getOperand(0)); 1881 } 1882 // fold ((A+(B+or-C))-B) -> A+or-C 1883 if (N0.getOpcode() == ISD::ADD && 1884 (N0.getOperand(1).getOpcode() == ISD::SUB || 1885 N0.getOperand(1).getOpcode() == ISD::ADD) && 1886 N0.getOperand(1).getOperand(0) == N1) 1887 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1888 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1889 // fold ((A+(C+B))-B) -> A+C 1890 if (N0.getOpcode() == ISD::ADD && 1891 N0.getOperand(1).getOpcode() == ISD::ADD && 1892 N0.getOperand(1).getOperand(1) == N1) 1893 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1894 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1895 // fold ((A-(B-C))-C) -> A-B 1896 if (N0.getOpcode() == ISD::SUB && 1897 N0.getOperand(1).getOpcode() == ISD::SUB && 1898 N0.getOperand(1).getOperand(1) == N1) 1899 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1900 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1901 1902 // If either operand of a sub is undef, the result is undef 1903 if (N0.getOpcode() == ISD::UNDEF) 1904 return N0; 1905 if (N1.getOpcode() == ISD::UNDEF) 1906 return N1; 1907 1908 // If the relocation model supports it, consider symbol offsets. 1909 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1910 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1911 // fold (sub Sym, c) -> Sym-c 1912 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1913 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1914 GA->getOffset() - 1915 (uint64_t)N1C->getSExtValue()); 1916 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1917 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1918 if (GA->getGlobal() == GB->getGlobal()) 1919 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1920 SDLoc(N), VT); 1921 } 1922 1923 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1924 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1925 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1926 if (TN->getVT() == MVT::i1) { 1927 SDLoc DL(N); 1928 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1929 DAG.getConstant(1, DL, VT)); 1930 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1931 } 1932 } 1933 1934 return SDValue(); 1935 } 1936 1937 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1938 SDValue N0 = N->getOperand(0); 1939 SDValue N1 = N->getOperand(1); 1940 EVT VT = N0.getValueType(); 1941 1942 // If the flag result is dead, turn this into an SUB. 1943 if (!N->hasAnyUseOfValue(1)) 1944 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1945 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1946 MVT::Glue)); 1947 1948 // fold (subc x, x) -> 0 + no borrow 1949 if (N0 == N1) { 1950 SDLoc DL(N); 1951 return CombineTo(N, DAG.getConstant(0, DL, VT), 1952 DAG.getNode(ISD::CARRY_FALSE, DL, 1953 MVT::Glue)); 1954 } 1955 1956 // fold (subc x, 0) -> x + no borrow 1957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1959 if (N1C && N1C->isNullValue()) 1960 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1961 MVT::Glue)); 1962 1963 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1964 if (N0C && N0C->isAllOnesValue()) 1965 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1966 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1967 MVT::Glue)); 1968 1969 return SDValue(); 1970 } 1971 1972 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1973 SDValue N0 = N->getOperand(0); 1974 SDValue N1 = N->getOperand(1); 1975 SDValue CarryIn = N->getOperand(2); 1976 1977 // fold (sube x, y, false) -> (subc x, y) 1978 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1979 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1980 1981 return SDValue(); 1982 } 1983 1984 SDValue DAGCombiner::visitMUL(SDNode *N) { 1985 SDValue N0 = N->getOperand(0); 1986 SDValue N1 = N->getOperand(1); 1987 EVT VT = N0.getValueType(); 1988 1989 // fold (mul x, undef) -> 0 1990 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1991 return DAG.getConstant(0, SDLoc(N), VT); 1992 1993 bool N0IsConst = false; 1994 bool N1IsConst = false; 1995 APInt ConstValue0, ConstValue1; 1996 // fold vector ops 1997 if (VT.isVector()) { 1998 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1999 return FoldedVOp; 2000 2001 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2002 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2003 } else { 2004 N0IsConst = isa<ConstantSDNode>(N0); 2005 if (N0IsConst) 2006 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2007 N1IsConst = isa<ConstantSDNode>(N1); 2008 if (N1IsConst) 2009 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2010 } 2011 2012 // fold (mul c1, c2) -> c1*c2 2013 if (N0IsConst && N1IsConst) 2014 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2015 N0.getNode(), N1.getNode()); 2016 2017 // canonicalize constant to RHS (vector doesn't have to splat) 2018 if (isConstantIntBuildVectorOrConstantInt(N0) && 2019 !isConstantIntBuildVectorOrConstantInt(N1)) 2020 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2021 // fold (mul x, 0) -> 0 2022 if (N1IsConst && ConstValue1 == 0) 2023 return N1; 2024 // We require a splat of the entire scalar bit width for non-contiguous 2025 // bit patterns. 2026 bool IsFullSplat = 2027 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2028 // fold (mul x, 1) -> x 2029 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2030 return N0; 2031 // fold (mul x, -1) -> 0-x 2032 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2033 SDLoc DL(N); 2034 return DAG.getNode(ISD::SUB, DL, VT, 2035 DAG.getConstant(0, DL, VT), N0); 2036 } 2037 // fold (mul x, (1 << c)) -> x << c 2038 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) { 2039 SDLoc DL(N); 2040 return DAG.getNode(ISD::SHL, DL, VT, N0, 2041 DAG.getConstant(ConstValue1.logBase2(), DL, 2042 getShiftAmountTy(N0.getValueType()))); 2043 } 2044 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2045 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 2046 unsigned Log2Val = (-ConstValue1).logBase2(); 2047 SDLoc DL(N); 2048 // FIXME: If the input is something that is easily negated (e.g. a 2049 // single-use add), we should put the negate there. 2050 return DAG.getNode(ISD::SUB, DL, VT, 2051 DAG.getConstant(0, DL, VT), 2052 DAG.getNode(ISD::SHL, DL, VT, N0, 2053 DAG.getConstant(Log2Val, DL, 2054 getShiftAmountTy(N0.getValueType())))); 2055 } 2056 2057 APInt Val; 2058 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2059 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2060 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2061 isa<ConstantSDNode>(N0.getOperand(1)))) { 2062 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2063 N1, N0.getOperand(1)); 2064 AddToWorklist(C3.getNode()); 2065 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2066 N0.getOperand(0), C3); 2067 } 2068 2069 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2070 // use. 2071 { 2072 SDValue Sh(nullptr,0), Y(nullptr,0); 2073 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2074 if (N0.getOpcode() == ISD::SHL && 2075 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2076 isa<ConstantSDNode>(N0.getOperand(1))) && 2077 N0.getNode()->hasOneUse()) { 2078 Sh = N0; Y = N1; 2079 } else if (N1.getOpcode() == ISD::SHL && 2080 isa<ConstantSDNode>(N1.getOperand(1)) && 2081 N1.getNode()->hasOneUse()) { 2082 Sh = N1; Y = N0; 2083 } 2084 2085 if (Sh.getNode()) { 2086 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2087 Sh.getOperand(0), Y); 2088 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2089 Mul, Sh.getOperand(1)); 2090 } 2091 } 2092 2093 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2094 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2095 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2096 isa<ConstantSDNode>(N0.getOperand(1)))) 2097 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2098 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2099 N0.getOperand(0), N1), 2100 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2101 N0.getOperand(1), N1)); 2102 2103 // reassociate mul 2104 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2105 return RMUL; 2106 2107 return SDValue(); 2108 } 2109 2110 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2111 SDValue N0 = N->getOperand(0); 2112 SDValue N1 = N->getOperand(1); 2113 EVT VT = N->getValueType(0); 2114 2115 // fold vector ops 2116 if (VT.isVector()) 2117 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2118 return FoldedVOp; 2119 2120 // fold (sdiv c1, c2) -> c1/c2 2121 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2122 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2123 if (N0C && N1C && !N1C->isNullValue()) 2124 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C); 2125 // fold (sdiv X, 1) -> X 2126 if (N1C && N1C->getAPIntValue() == 1LL) 2127 return N0; 2128 // fold (sdiv X, -1) -> 0-X 2129 if (N1C && N1C->isAllOnesValue()) { 2130 SDLoc DL(N); 2131 return DAG.getNode(ISD::SUB, DL, VT, 2132 DAG.getConstant(0, DL, VT), N0); 2133 } 2134 // If we know the sign bits of both operands are zero, strength reduce to a 2135 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2136 if (!VT.isVector()) { 2137 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2138 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2139 N0, N1); 2140 } 2141 2142 // fold (sdiv X, pow2) -> simple ops after legalize 2143 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2144 (-N1C->getAPIntValue()).isPowerOf2())) { 2145 // If dividing by powers of two is cheap, then don't perform the following 2146 // fold. 2147 if (TLI.isPow2SDivCheap()) 2148 return SDValue(); 2149 2150 // Target-specific implementation of sdiv x, pow2. 2151 SDValue Res = BuildSDIVPow2(N); 2152 if (Res.getNode()) 2153 return Res; 2154 2155 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2156 SDLoc DL(N); 2157 2158 // Splat the sign bit into the register 2159 SDValue SGN = 2160 DAG.getNode(ISD::SRA, DL, VT, N0, 2161 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2162 getShiftAmountTy(N0.getValueType()))); 2163 AddToWorklist(SGN.getNode()); 2164 2165 // Add (N0 < 0) ? abs2 - 1 : 0; 2166 SDValue SRL = 2167 DAG.getNode(ISD::SRL, DL, VT, SGN, 2168 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2169 getShiftAmountTy(SGN.getValueType()))); 2170 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2171 AddToWorklist(SRL.getNode()); 2172 AddToWorklist(ADD.getNode()); // Divide by pow2 2173 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2174 DAG.getConstant(lg2, DL, 2175 getShiftAmountTy(ADD.getValueType()))); 2176 2177 // If we're dividing by a positive value, we're done. Otherwise, we must 2178 // negate the result. 2179 if (N1C->getAPIntValue().isNonNegative()) 2180 return SRA; 2181 2182 AddToWorklist(SRA.getNode()); 2183 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2184 } 2185 2186 // If integer divide is expensive and we satisfy the requirements, emit an 2187 // alternate sequence. 2188 if (N1C && !TLI.isIntDivCheap()) { 2189 SDValue Op = BuildSDIV(N); 2190 if (Op.getNode()) return Op; 2191 } 2192 2193 // undef / X -> 0 2194 if (N0.getOpcode() == ISD::UNDEF) 2195 return DAG.getConstant(0, SDLoc(N), VT); 2196 // X / undef -> undef 2197 if (N1.getOpcode() == ISD::UNDEF) 2198 return N1; 2199 2200 return SDValue(); 2201 } 2202 2203 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2204 SDValue N0 = N->getOperand(0); 2205 SDValue N1 = N->getOperand(1); 2206 EVT VT = N->getValueType(0); 2207 2208 // fold vector ops 2209 if (VT.isVector()) 2210 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2211 return FoldedVOp; 2212 2213 // fold (udiv c1, c2) -> c1/c2 2214 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2215 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2216 if (N0C && N1C && !N1C->isNullValue()) 2217 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C); 2218 // fold (udiv x, (1 << c)) -> x >>u c 2219 if (N1C && N1C->getAPIntValue().isPowerOf2()) { 2220 SDLoc DL(N); 2221 return DAG.getNode(ISD::SRL, DL, VT, N0, 2222 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2223 getShiftAmountTy(N0.getValueType()))); 2224 } 2225 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2226 if (N1.getOpcode() == ISD::SHL) { 2227 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2228 if (SHC->getAPIntValue().isPowerOf2()) { 2229 EVT ADDVT = N1.getOperand(1).getValueType(); 2230 SDLoc DL(N); 2231 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2232 N1.getOperand(1), 2233 DAG.getConstant(SHC->getAPIntValue() 2234 .logBase2(), 2235 DL, ADDVT)); 2236 AddToWorklist(Add.getNode()); 2237 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2238 } 2239 } 2240 } 2241 // fold (udiv x, c) -> alternate 2242 if (N1C && !TLI.isIntDivCheap()) { 2243 SDValue Op = BuildUDIV(N); 2244 if (Op.getNode()) return Op; 2245 } 2246 2247 // undef / X -> 0 2248 if (N0.getOpcode() == ISD::UNDEF) 2249 return DAG.getConstant(0, SDLoc(N), VT); 2250 // X / undef -> undef 2251 if (N1.getOpcode() == ISD::UNDEF) 2252 return N1; 2253 2254 return SDValue(); 2255 } 2256 2257 SDValue DAGCombiner::visitSREM(SDNode *N) { 2258 SDValue N0 = N->getOperand(0); 2259 SDValue N1 = N->getOperand(1); 2260 EVT VT = N->getValueType(0); 2261 2262 // fold (srem c1, c2) -> c1%c2 2263 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2264 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2265 if (N0C && N1C && !N1C->isNullValue()) 2266 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C); 2267 // If we know the sign bits of both operands are zero, strength reduce to a 2268 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2269 if (!VT.isVector()) { 2270 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2271 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2272 } 2273 2274 // If X/C can be simplified by the division-by-constant logic, lower 2275 // X%C to the equivalent of X-X/C*C. 2276 if (N1C && !N1C->isNullValue()) { 2277 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2278 AddToWorklist(Div.getNode()); 2279 SDValue OptimizedDiv = combine(Div.getNode()); 2280 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2281 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2282 OptimizedDiv, N1); 2283 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2284 AddToWorklist(Mul.getNode()); 2285 return Sub; 2286 } 2287 } 2288 2289 // undef % X -> 0 2290 if (N0.getOpcode() == ISD::UNDEF) 2291 return DAG.getConstant(0, SDLoc(N), VT); 2292 // X % undef -> undef 2293 if (N1.getOpcode() == ISD::UNDEF) 2294 return N1; 2295 2296 return SDValue(); 2297 } 2298 2299 SDValue DAGCombiner::visitUREM(SDNode *N) { 2300 SDValue N0 = N->getOperand(0); 2301 SDValue N1 = N->getOperand(1); 2302 EVT VT = N->getValueType(0); 2303 2304 // fold (urem c1, c2) -> c1%c2 2305 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2306 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2307 if (N0C && N1C && !N1C->isNullValue()) 2308 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C); 2309 // fold (urem x, pow2) -> (and x, pow2-1) 2310 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) { 2311 SDLoc DL(N); 2312 return DAG.getNode(ISD::AND, DL, VT, N0, 2313 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2314 } 2315 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2316 if (N1.getOpcode() == ISD::SHL) { 2317 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2318 if (SHC->getAPIntValue().isPowerOf2()) { 2319 SDLoc DL(N); 2320 SDValue Add = 2321 DAG.getNode(ISD::ADD, DL, VT, N1, 2322 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2323 VT)); 2324 AddToWorklist(Add.getNode()); 2325 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2326 } 2327 } 2328 } 2329 2330 // If X/C can be simplified by the division-by-constant logic, lower 2331 // X%C to the equivalent of X-X/C*C. 2332 if (N1C && !N1C->isNullValue()) { 2333 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2334 AddToWorklist(Div.getNode()); 2335 SDValue OptimizedDiv = combine(Div.getNode()); 2336 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2337 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2338 OptimizedDiv, N1); 2339 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2340 AddToWorklist(Mul.getNode()); 2341 return Sub; 2342 } 2343 } 2344 2345 // undef % X -> 0 2346 if (N0.getOpcode() == ISD::UNDEF) 2347 return DAG.getConstant(0, SDLoc(N), VT); 2348 // X % undef -> undef 2349 if (N1.getOpcode() == ISD::UNDEF) 2350 return N1; 2351 2352 return SDValue(); 2353 } 2354 2355 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2356 SDValue N0 = N->getOperand(0); 2357 SDValue N1 = N->getOperand(1); 2358 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2359 EVT VT = N->getValueType(0); 2360 SDLoc DL(N); 2361 2362 // fold (mulhs x, 0) -> 0 2363 if (N1C && N1C->isNullValue()) 2364 return N1; 2365 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2366 if (N1C && N1C->getAPIntValue() == 1) { 2367 SDLoc DL(N); 2368 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2369 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2370 DL, 2371 getShiftAmountTy(N0.getValueType()))); 2372 } 2373 // fold (mulhs x, undef) -> 0 2374 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2375 return DAG.getConstant(0, SDLoc(N), VT); 2376 2377 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2378 // plus a shift. 2379 if (VT.isSimple() && !VT.isVector()) { 2380 MVT Simple = VT.getSimpleVT(); 2381 unsigned SimpleSize = Simple.getSizeInBits(); 2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2384 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2385 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2386 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2387 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2388 DAG.getConstant(SimpleSize, DL, 2389 getShiftAmountTy(N1.getValueType()))); 2390 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2391 } 2392 } 2393 2394 return SDValue(); 2395 } 2396 2397 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2398 SDValue N0 = N->getOperand(0); 2399 SDValue N1 = N->getOperand(1); 2400 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2401 EVT VT = N->getValueType(0); 2402 SDLoc DL(N); 2403 2404 // fold (mulhu x, 0) -> 0 2405 if (N1C && N1C->isNullValue()) 2406 return N1; 2407 // fold (mulhu x, 1) -> 0 2408 if (N1C && N1C->getAPIntValue() == 1) 2409 return DAG.getConstant(0, DL, N0.getValueType()); 2410 // fold (mulhu x, undef) -> 0 2411 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2412 return DAG.getConstant(0, DL, VT); 2413 2414 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2415 // plus a shift. 2416 if (VT.isSimple() && !VT.isVector()) { 2417 MVT Simple = VT.getSimpleVT(); 2418 unsigned SimpleSize = Simple.getSizeInBits(); 2419 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2420 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2421 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2422 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2423 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2424 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2425 DAG.getConstant(SimpleSize, DL, 2426 getShiftAmountTy(N1.getValueType()))); 2427 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2428 } 2429 } 2430 2431 return SDValue(); 2432 } 2433 2434 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2435 /// give the opcodes for the two computations that are being performed. Return 2436 /// true if a simplification was made. 2437 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2438 unsigned HiOp) { 2439 // If the high half is not needed, just compute the low half. 2440 bool HiExists = N->hasAnyUseOfValue(1); 2441 if (!HiExists && 2442 (!LegalOperations || 2443 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2444 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2445 return CombineTo(N, Res, Res); 2446 } 2447 2448 // If the low half is not needed, just compute the high half. 2449 bool LoExists = N->hasAnyUseOfValue(0); 2450 if (!LoExists && 2451 (!LegalOperations || 2452 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2453 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2454 return CombineTo(N, Res, Res); 2455 } 2456 2457 // If both halves are used, return as it is. 2458 if (LoExists && HiExists) 2459 return SDValue(); 2460 2461 // If the two computed results can be simplified separately, separate them. 2462 if (LoExists) { 2463 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2464 AddToWorklist(Lo.getNode()); 2465 SDValue LoOpt = combine(Lo.getNode()); 2466 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2467 (!LegalOperations || 2468 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2469 return CombineTo(N, LoOpt, LoOpt); 2470 } 2471 2472 if (HiExists) { 2473 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2474 AddToWorklist(Hi.getNode()); 2475 SDValue HiOpt = combine(Hi.getNode()); 2476 if (HiOpt.getNode() && HiOpt != Hi && 2477 (!LegalOperations || 2478 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2479 return CombineTo(N, HiOpt, HiOpt); 2480 } 2481 2482 return SDValue(); 2483 } 2484 2485 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2486 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2487 if (Res.getNode()) return Res; 2488 2489 EVT VT = N->getValueType(0); 2490 SDLoc DL(N); 2491 2492 // If the type is twice as wide is legal, transform the mulhu to a wider 2493 // multiply plus a shift. 2494 if (VT.isSimple() && !VT.isVector()) { 2495 MVT Simple = VT.getSimpleVT(); 2496 unsigned SimpleSize = Simple.getSizeInBits(); 2497 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2498 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2499 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2500 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2501 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2502 // Compute the high part as N1. 2503 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2504 DAG.getConstant(SimpleSize, DL, 2505 getShiftAmountTy(Lo.getValueType()))); 2506 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2507 // Compute the low part as N0. 2508 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2509 return CombineTo(N, Lo, Hi); 2510 } 2511 } 2512 2513 return SDValue(); 2514 } 2515 2516 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2517 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2518 if (Res.getNode()) return Res; 2519 2520 EVT VT = N->getValueType(0); 2521 SDLoc DL(N); 2522 2523 // If the type is twice as wide is legal, transform the mulhu to a wider 2524 // multiply plus a shift. 2525 if (VT.isSimple() && !VT.isVector()) { 2526 MVT Simple = VT.getSimpleVT(); 2527 unsigned SimpleSize = Simple.getSizeInBits(); 2528 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2529 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2530 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2531 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2532 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2533 // Compute the high part as N1. 2534 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2535 DAG.getConstant(SimpleSize, DL, 2536 getShiftAmountTy(Lo.getValueType()))); 2537 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2538 // Compute the low part as N0. 2539 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2540 return CombineTo(N, Lo, Hi); 2541 } 2542 } 2543 2544 return SDValue(); 2545 } 2546 2547 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2548 // (smulo x, 2) -> (saddo x, x) 2549 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2550 if (C2->getAPIntValue() == 2) 2551 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2552 N->getOperand(0), N->getOperand(0)); 2553 2554 return SDValue(); 2555 } 2556 2557 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2558 // (umulo x, 2) -> (uaddo x, x) 2559 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2560 if (C2->getAPIntValue() == 2) 2561 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2562 N->getOperand(0), N->getOperand(0)); 2563 2564 return SDValue(); 2565 } 2566 2567 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2568 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2569 if (Res.getNode()) return Res; 2570 2571 return SDValue(); 2572 } 2573 2574 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2575 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2576 if (Res.getNode()) return Res; 2577 2578 return SDValue(); 2579 } 2580 2581 /// If this is a binary operator with two operands of the same opcode, try to 2582 /// simplify it. 2583 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2584 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2585 EVT VT = N0.getValueType(); 2586 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2587 2588 // Bail early if none of these transforms apply. 2589 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2590 2591 // For each of OP in AND/OR/XOR: 2592 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2593 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2594 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2595 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2596 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2597 // 2598 // do not sink logical op inside of a vector extend, since it may combine 2599 // into a vsetcc. 2600 EVT Op0VT = N0.getOperand(0).getValueType(); 2601 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2602 N0.getOpcode() == ISD::SIGN_EXTEND || 2603 N0.getOpcode() == ISD::BSWAP || 2604 // Avoid infinite looping with PromoteIntBinOp. 2605 (N0.getOpcode() == ISD::ANY_EXTEND && 2606 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2607 (N0.getOpcode() == ISD::TRUNCATE && 2608 (!TLI.isZExtFree(VT, Op0VT) || 2609 !TLI.isTruncateFree(Op0VT, VT)) && 2610 TLI.isTypeLegal(Op0VT))) && 2611 !VT.isVector() && 2612 Op0VT == N1.getOperand(0).getValueType() && 2613 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2614 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2615 N0.getOperand(0).getValueType(), 2616 N0.getOperand(0), N1.getOperand(0)); 2617 AddToWorklist(ORNode.getNode()); 2618 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2619 } 2620 2621 // For each of OP in SHL/SRL/SRA/AND... 2622 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2623 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2624 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2625 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2626 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2627 N0.getOperand(1) == N1.getOperand(1)) { 2628 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2629 N0.getOperand(0).getValueType(), 2630 N0.getOperand(0), N1.getOperand(0)); 2631 AddToWorklist(ORNode.getNode()); 2632 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2633 ORNode, N0.getOperand(1)); 2634 } 2635 2636 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2637 // Only perform this optimization after type legalization and before 2638 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2639 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2640 // we don't want to undo this promotion. 2641 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2642 // on scalars. 2643 if ((N0.getOpcode() == ISD::BITCAST || 2644 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2645 Level == AfterLegalizeTypes) { 2646 SDValue In0 = N0.getOperand(0); 2647 SDValue In1 = N1.getOperand(0); 2648 EVT In0Ty = In0.getValueType(); 2649 EVT In1Ty = In1.getValueType(); 2650 SDLoc DL(N); 2651 // If both incoming values are integers, and the original types are the 2652 // same. 2653 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2654 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2655 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2656 AddToWorklist(Op.getNode()); 2657 return BC; 2658 } 2659 } 2660 2661 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2662 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2663 // If both shuffles use the same mask, and both shuffle within a single 2664 // vector, then it is worthwhile to move the swizzle after the operation. 2665 // The type-legalizer generates this pattern when loading illegal 2666 // vector types from memory. In many cases this allows additional shuffle 2667 // optimizations. 2668 // There are other cases where moving the shuffle after the xor/and/or 2669 // is profitable even if shuffles don't perform a swizzle. 2670 // If both shuffles use the same mask, and both shuffles have the same first 2671 // or second operand, then it might still be profitable to move the shuffle 2672 // after the xor/and/or operation. 2673 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2674 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2675 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2676 2677 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2678 "Inputs to shuffles are not the same type"); 2679 2680 // Check that both shuffles use the same mask. The masks are known to be of 2681 // the same length because the result vector type is the same. 2682 // Check also that shuffles have only one use to avoid introducing extra 2683 // instructions. 2684 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2685 SVN0->getMask().equals(SVN1->getMask())) { 2686 SDValue ShOp = N0->getOperand(1); 2687 2688 // Don't try to fold this node if it requires introducing a 2689 // build vector of all zeros that might be illegal at this stage. 2690 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2691 if (!LegalTypes) 2692 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2693 else 2694 ShOp = SDValue(); 2695 } 2696 2697 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2698 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2699 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2700 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2701 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2702 N0->getOperand(0), N1->getOperand(0)); 2703 AddToWorklist(NewNode.getNode()); 2704 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2705 &SVN0->getMask()[0]); 2706 } 2707 2708 // Don't try to fold this node if it requires introducing a 2709 // build vector of all zeros that might be illegal at this stage. 2710 ShOp = N0->getOperand(0); 2711 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2712 if (!LegalTypes) 2713 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2714 else 2715 ShOp = SDValue(); 2716 } 2717 2718 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2719 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2720 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2721 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2722 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2723 N0->getOperand(1), N1->getOperand(1)); 2724 AddToWorklist(NewNode.getNode()); 2725 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2726 &SVN0->getMask()[0]); 2727 } 2728 } 2729 } 2730 2731 return SDValue(); 2732 } 2733 2734 /// This contains all DAGCombine rules which reduce two values combined by 2735 /// an And operation to a single value. This makes them reusable in the context 2736 /// of visitSELECT(). Rules involving constants are not included as 2737 /// visitSELECT() already handles those cases. 2738 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2739 SDNode *LocReference) { 2740 EVT VT = N1.getValueType(); 2741 2742 // fold (and x, undef) -> 0 2743 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2744 return DAG.getConstant(0, SDLoc(LocReference), VT); 2745 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2746 SDValue LL, LR, RL, RR, CC0, CC1; 2747 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2748 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2749 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2750 2751 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2752 LL.getValueType().isInteger()) { 2753 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2754 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2755 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2756 LR.getValueType(), LL, RL); 2757 AddToWorklist(ORNode.getNode()); 2758 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2759 } 2760 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2761 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2762 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2763 LR.getValueType(), LL, RL); 2764 AddToWorklist(ANDNode.getNode()); 2765 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2766 } 2767 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2768 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2769 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2770 LR.getValueType(), LL, RL); 2771 AddToWorklist(ORNode.getNode()); 2772 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2773 } 2774 } 2775 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2776 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2777 Op0 == Op1 && LL.getValueType().isInteger() && 2778 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2779 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2780 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2781 cast<ConstantSDNode>(RR)->isNullValue()))) { 2782 SDLoc DL(N0); 2783 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2784 LL, DAG.getConstant(1, DL, 2785 LL.getValueType())); 2786 AddToWorklist(ADDNode.getNode()); 2787 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2788 DAG.getConstant(2, DL, LL.getValueType()), 2789 ISD::SETUGE); 2790 } 2791 // canonicalize equivalent to ll == rl 2792 if (LL == RR && LR == RL) { 2793 Op1 = ISD::getSetCCSwappedOperands(Op1); 2794 std::swap(RL, RR); 2795 } 2796 if (LL == RL && LR == RR) { 2797 bool isInteger = LL.getValueType().isInteger(); 2798 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2799 if (Result != ISD::SETCC_INVALID && 2800 (!LegalOperations || 2801 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2802 TLI.isOperationLegal(ISD::SETCC, 2803 getSetCCResultType(N0.getSimpleValueType()))))) 2804 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2805 LL, LR, Result); 2806 } 2807 } 2808 2809 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2810 VT.getSizeInBits() <= 64) { 2811 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2812 APInt ADDC = ADDI->getAPIntValue(); 2813 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2814 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2815 // immediate for an add, but it is legal if its top c2 bits are set, 2816 // transform the ADD so the immediate doesn't need to be materialized 2817 // in a register. 2818 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2819 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2820 SRLI->getZExtValue()); 2821 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2822 ADDC |= Mask; 2823 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2824 SDLoc DL(N0); 2825 SDValue NewAdd = 2826 DAG.getNode(ISD::ADD, DL, VT, 2827 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2828 CombineTo(N0.getNode(), NewAdd); 2829 // Return N so it doesn't get rechecked! 2830 return SDValue(LocReference, 0); 2831 } 2832 } 2833 } 2834 } 2835 } 2836 } 2837 2838 return SDValue(); 2839 } 2840 2841 SDValue DAGCombiner::visitAND(SDNode *N) { 2842 SDValue N0 = N->getOperand(0); 2843 SDValue N1 = N->getOperand(1); 2844 EVT VT = N1.getValueType(); 2845 2846 // fold vector ops 2847 if (VT.isVector()) { 2848 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2849 return FoldedVOp; 2850 2851 // fold (and x, 0) -> 0, vector edition 2852 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2853 // do not return N0, because undef node may exist in N0 2854 return DAG.getConstant( 2855 APInt::getNullValue( 2856 N0.getValueType().getScalarType().getSizeInBits()), 2857 SDLoc(N), N0.getValueType()); 2858 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2859 // do not return N1, because undef node may exist in N1 2860 return DAG.getConstant( 2861 APInt::getNullValue( 2862 N1.getValueType().getScalarType().getSizeInBits()), 2863 SDLoc(N), N1.getValueType()); 2864 2865 // fold (and x, -1) -> x, vector edition 2866 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2867 return N1; 2868 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2869 return N0; 2870 } 2871 2872 // fold (and c1, c2) -> c1&c2 2873 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2874 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2875 if (N0C && N1C) 2876 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 2877 // canonicalize constant to RHS 2878 if (isConstantIntBuildVectorOrConstantInt(N0) && 2879 !isConstantIntBuildVectorOrConstantInt(N1)) 2880 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2881 // fold (and x, -1) -> x 2882 if (N1C && N1C->isAllOnesValue()) 2883 return N0; 2884 // if (and x, c) is known to be zero, return 0 2885 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2886 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2887 APInt::getAllOnesValue(BitWidth))) 2888 return DAG.getConstant(0, SDLoc(N), VT); 2889 // reassociate and 2890 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 2891 return RAND; 2892 // fold (and (or x, C), D) -> D if (C & D) == D 2893 if (N1C && N0.getOpcode() == ISD::OR) 2894 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2895 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2896 return N1; 2897 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2898 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2899 SDValue N0Op0 = N0.getOperand(0); 2900 APInt Mask = ~N1C->getAPIntValue(); 2901 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2902 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2903 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2904 N0.getValueType(), N0Op0); 2905 2906 // Replace uses of the AND with uses of the Zero extend node. 2907 CombineTo(N, Zext); 2908 2909 // We actually want to replace all uses of the any_extend with the 2910 // zero_extend, to avoid duplicating things. This will later cause this 2911 // AND to be folded. 2912 CombineTo(N0.getNode(), Zext); 2913 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2914 } 2915 } 2916 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2917 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2918 // already be zero by virtue of the width of the base type of the load. 2919 // 2920 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2921 // more cases. 2922 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2923 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2924 N0.getOpcode() == ISD::LOAD) { 2925 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2926 N0 : N0.getOperand(0) ); 2927 2928 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2929 // This can be a pure constant or a vector splat, in which case we treat the 2930 // vector as a scalar and use the splat value. 2931 APInt Constant = APInt::getNullValue(1); 2932 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2933 Constant = C->getAPIntValue(); 2934 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2935 APInt SplatValue, SplatUndef; 2936 unsigned SplatBitSize; 2937 bool HasAnyUndefs; 2938 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2939 SplatBitSize, HasAnyUndefs); 2940 if (IsSplat) { 2941 // Undef bits can contribute to a possible optimisation if set, so 2942 // set them. 2943 SplatValue |= SplatUndef; 2944 2945 // The splat value may be something like "0x00FFFFFF", which means 0 for 2946 // the first vector value and FF for the rest, repeating. We need a mask 2947 // that will apply equally to all members of the vector, so AND all the 2948 // lanes of the constant together. 2949 EVT VT = Vector->getValueType(0); 2950 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2951 2952 // If the splat value has been compressed to a bitlength lower 2953 // than the size of the vector lane, we need to re-expand it to 2954 // the lane size. 2955 if (BitWidth > SplatBitSize) 2956 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2957 SplatBitSize < BitWidth; 2958 SplatBitSize = SplatBitSize * 2) 2959 SplatValue |= SplatValue.shl(SplatBitSize); 2960 2961 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 2962 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 2963 if (SplatBitSize % BitWidth == 0) { 2964 Constant = APInt::getAllOnesValue(BitWidth); 2965 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2966 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2967 } 2968 } 2969 } 2970 2971 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2972 // actually legal and isn't going to get expanded, else this is a false 2973 // optimisation. 2974 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2975 Load->getValueType(0), 2976 Load->getMemoryVT()); 2977 2978 // Resize the constant to the same size as the original memory access before 2979 // extension. If it is still the AllOnesValue then this AND is completely 2980 // unneeded. 2981 Constant = 2982 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2983 2984 bool B; 2985 switch (Load->getExtensionType()) { 2986 default: B = false; break; 2987 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2988 case ISD::ZEXTLOAD: 2989 case ISD::NON_EXTLOAD: B = true; break; 2990 } 2991 2992 if (B && Constant.isAllOnesValue()) { 2993 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2994 // preserve semantics once we get rid of the AND. 2995 SDValue NewLoad(Load, 0); 2996 if (Load->getExtensionType() == ISD::EXTLOAD) { 2997 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2998 Load->getValueType(0), SDLoc(Load), 2999 Load->getChain(), Load->getBasePtr(), 3000 Load->getOffset(), Load->getMemoryVT(), 3001 Load->getMemOperand()); 3002 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3003 if (Load->getNumValues() == 3) { 3004 // PRE/POST_INC loads have 3 values. 3005 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3006 NewLoad.getValue(2) }; 3007 CombineTo(Load, To, 3, true); 3008 } else { 3009 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3010 } 3011 } 3012 3013 // Fold the AND away, taking care not to fold to the old load node if we 3014 // replaced it. 3015 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3016 3017 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3018 } 3019 } 3020 3021 // fold (and (load x), 255) -> (zextload x, i8) 3022 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3023 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3024 if (N1C && (N0.getOpcode() == ISD::LOAD || 3025 (N0.getOpcode() == ISD::ANY_EXTEND && 3026 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3027 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3028 LoadSDNode *LN0 = HasAnyExt 3029 ? cast<LoadSDNode>(N0.getOperand(0)) 3030 : cast<LoadSDNode>(N0); 3031 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3032 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3033 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 3034 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 3035 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3036 EVT LoadedVT = LN0->getMemoryVT(); 3037 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3038 3039 if (ExtVT == LoadedVT && 3040 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3041 ExtVT))) { 3042 3043 SDValue NewLoad = 3044 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3045 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3046 LN0->getMemOperand()); 3047 AddToWorklist(N); 3048 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3049 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3050 } 3051 3052 // Do not change the width of a volatile load. 3053 // Do not generate loads of non-round integer types since these can 3054 // be expensive (and would be wrong if the type is not byte sized). 3055 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3056 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3057 ExtVT))) { 3058 EVT PtrType = LN0->getOperand(1).getValueType(); 3059 3060 unsigned Alignment = LN0->getAlignment(); 3061 SDValue NewPtr = LN0->getBasePtr(); 3062 3063 // For big endian targets, we need to add an offset to the pointer 3064 // to load the correct bytes. For little endian systems, we merely 3065 // need to read fewer bytes from the same pointer. 3066 if (TLI.isBigEndian()) { 3067 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3068 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3069 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3070 SDLoc DL(LN0); 3071 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3072 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3073 Alignment = MinAlign(Alignment, PtrOff); 3074 } 3075 3076 AddToWorklist(NewPtr.getNode()); 3077 3078 SDValue Load = 3079 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3080 LN0->getChain(), NewPtr, 3081 LN0->getPointerInfo(), 3082 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3083 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3084 AddToWorklist(N); 3085 CombineTo(LN0, Load, Load.getValue(1)); 3086 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3087 } 3088 } 3089 } 3090 } 3091 3092 if (SDValue Combined = visitANDLike(N0, N1, N)) 3093 return Combined; 3094 3095 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3096 if (N0.getOpcode() == N1.getOpcode()) { 3097 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3098 if (Tmp.getNode()) return Tmp; 3099 } 3100 3101 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3102 // fold (and (sra)) -> (and (srl)) when possible. 3103 if (!VT.isVector() && 3104 SimplifyDemandedBits(SDValue(N, 0))) 3105 return SDValue(N, 0); 3106 3107 // fold (zext_inreg (extload x)) -> (zextload x) 3108 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3109 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3110 EVT MemVT = LN0->getMemoryVT(); 3111 // If we zero all the possible extended bits, then we can turn this into 3112 // a zextload if we are running before legalize or the operation is legal. 3113 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3114 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3115 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3116 ((!LegalOperations && !LN0->isVolatile()) || 3117 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3118 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3119 LN0->getChain(), LN0->getBasePtr(), 3120 MemVT, LN0->getMemOperand()); 3121 AddToWorklist(N); 3122 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3123 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3124 } 3125 } 3126 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3127 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3128 N0.hasOneUse()) { 3129 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3130 EVT MemVT = LN0->getMemoryVT(); 3131 // If we zero all the possible extended bits, then we can turn this into 3132 // a zextload if we are running before legalize or the operation is legal. 3133 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3134 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3135 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3136 ((!LegalOperations && !LN0->isVolatile()) || 3137 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3138 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3139 LN0->getChain(), LN0->getBasePtr(), 3140 MemVT, LN0->getMemOperand()); 3141 AddToWorklist(N); 3142 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3143 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3144 } 3145 } 3146 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3147 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3148 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3149 N0.getOperand(1), false); 3150 if (BSwap.getNode()) 3151 return BSwap; 3152 } 3153 3154 return SDValue(); 3155 } 3156 3157 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3158 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3159 bool DemandHighBits) { 3160 if (!LegalOperations) 3161 return SDValue(); 3162 3163 EVT VT = N->getValueType(0); 3164 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3165 return SDValue(); 3166 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3167 return SDValue(); 3168 3169 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3170 bool LookPassAnd0 = false; 3171 bool LookPassAnd1 = false; 3172 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3173 std::swap(N0, N1); 3174 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3175 std::swap(N0, N1); 3176 if (N0.getOpcode() == ISD::AND) { 3177 if (!N0.getNode()->hasOneUse()) 3178 return SDValue(); 3179 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3180 if (!N01C || N01C->getZExtValue() != 0xFF00) 3181 return SDValue(); 3182 N0 = N0.getOperand(0); 3183 LookPassAnd0 = true; 3184 } 3185 3186 if (N1.getOpcode() == ISD::AND) { 3187 if (!N1.getNode()->hasOneUse()) 3188 return SDValue(); 3189 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3190 if (!N11C || N11C->getZExtValue() != 0xFF) 3191 return SDValue(); 3192 N1 = N1.getOperand(0); 3193 LookPassAnd1 = true; 3194 } 3195 3196 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3197 std::swap(N0, N1); 3198 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3199 return SDValue(); 3200 if (!N0.getNode()->hasOneUse() || 3201 !N1.getNode()->hasOneUse()) 3202 return SDValue(); 3203 3204 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3205 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3206 if (!N01C || !N11C) 3207 return SDValue(); 3208 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3209 return SDValue(); 3210 3211 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3212 SDValue N00 = N0->getOperand(0); 3213 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3214 if (!N00.getNode()->hasOneUse()) 3215 return SDValue(); 3216 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3217 if (!N001C || N001C->getZExtValue() != 0xFF) 3218 return SDValue(); 3219 N00 = N00.getOperand(0); 3220 LookPassAnd0 = true; 3221 } 3222 3223 SDValue N10 = N1->getOperand(0); 3224 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3225 if (!N10.getNode()->hasOneUse()) 3226 return SDValue(); 3227 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3228 if (!N101C || N101C->getZExtValue() != 0xFF00) 3229 return SDValue(); 3230 N10 = N10.getOperand(0); 3231 LookPassAnd1 = true; 3232 } 3233 3234 if (N00 != N10) 3235 return SDValue(); 3236 3237 // Make sure everything beyond the low halfword gets set to zero since the SRL 3238 // 16 will clear the top bits. 3239 unsigned OpSizeInBits = VT.getSizeInBits(); 3240 if (DemandHighBits && OpSizeInBits > 16) { 3241 // If the left-shift isn't masked out then the only way this is a bswap is 3242 // if all bits beyond the low 8 are 0. In that case the entire pattern 3243 // reduces to a left shift anyway: leave it for other parts of the combiner. 3244 if (!LookPassAnd0) 3245 return SDValue(); 3246 3247 // However, if the right shift isn't masked out then it might be because 3248 // it's not needed. See if we can spot that too. 3249 if (!LookPassAnd1 && 3250 !DAG.MaskedValueIsZero( 3251 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3252 return SDValue(); 3253 } 3254 3255 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3256 if (OpSizeInBits > 16) { 3257 SDLoc DL(N); 3258 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3259 DAG.getConstant(OpSizeInBits - 16, DL, 3260 getShiftAmountTy(VT))); 3261 } 3262 return Res; 3263 } 3264 3265 /// Return true if the specified node is an element that makes up a 32-bit 3266 /// packed halfword byteswap. 3267 /// ((x & 0x000000ff) << 8) | 3268 /// ((x & 0x0000ff00) >> 8) | 3269 /// ((x & 0x00ff0000) << 8) | 3270 /// ((x & 0xff000000) >> 8) 3271 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3272 if (!N.getNode()->hasOneUse()) 3273 return false; 3274 3275 unsigned Opc = N.getOpcode(); 3276 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3277 return false; 3278 3279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3280 if (!N1C) 3281 return false; 3282 3283 unsigned Num; 3284 switch (N1C->getZExtValue()) { 3285 default: 3286 return false; 3287 case 0xFF: Num = 0; break; 3288 case 0xFF00: Num = 1; break; 3289 case 0xFF0000: Num = 2; break; 3290 case 0xFF000000: Num = 3; break; 3291 } 3292 3293 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3294 SDValue N0 = N.getOperand(0); 3295 if (Opc == ISD::AND) { 3296 if (Num == 0 || Num == 2) { 3297 // (x >> 8) & 0xff 3298 // (x >> 8) & 0xff0000 3299 if (N0.getOpcode() != ISD::SRL) 3300 return false; 3301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3302 if (!C || C->getZExtValue() != 8) 3303 return false; 3304 } else { 3305 // (x << 8) & 0xff00 3306 // (x << 8) & 0xff000000 3307 if (N0.getOpcode() != ISD::SHL) 3308 return false; 3309 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3310 if (!C || C->getZExtValue() != 8) 3311 return false; 3312 } 3313 } else if (Opc == ISD::SHL) { 3314 // (x & 0xff) << 8 3315 // (x & 0xff0000) << 8 3316 if (Num != 0 && Num != 2) 3317 return false; 3318 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3319 if (!C || C->getZExtValue() != 8) 3320 return false; 3321 } else { // Opc == ISD::SRL 3322 // (x & 0xff00) >> 8 3323 // (x & 0xff000000) >> 8 3324 if (Num != 1 && Num != 3) 3325 return false; 3326 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3327 if (!C || C->getZExtValue() != 8) 3328 return false; 3329 } 3330 3331 if (Parts[Num]) 3332 return false; 3333 3334 Parts[Num] = N0.getOperand(0).getNode(); 3335 return true; 3336 } 3337 3338 /// Match a 32-bit packed halfword bswap. That is 3339 /// ((x & 0x000000ff) << 8) | 3340 /// ((x & 0x0000ff00) >> 8) | 3341 /// ((x & 0x00ff0000) << 8) | 3342 /// ((x & 0xff000000) >> 8) 3343 /// => (rotl (bswap x), 16) 3344 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3345 if (!LegalOperations) 3346 return SDValue(); 3347 3348 EVT VT = N->getValueType(0); 3349 if (VT != MVT::i32) 3350 return SDValue(); 3351 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3352 return SDValue(); 3353 3354 // Look for either 3355 // (or (or (and), (and)), (or (and), (and))) 3356 // (or (or (or (and), (and)), (and)), (and)) 3357 if (N0.getOpcode() != ISD::OR) 3358 return SDValue(); 3359 SDValue N00 = N0.getOperand(0); 3360 SDValue N01 = N0.getOperand(1); 3361 SDNode *Parts[4] = {}; 3362 3363 if (N1.getOpcode() == ISD::OR && 3364 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3365 // (or (or (and), (and)), (or (and), (and))) 3366 SDValue N000 = N00.getOperand(0); 3367 if (!isBSwapHWordElement(N000, Parts)) 3368 return SDValue(); 3369 3370 SDValue N001 = N00.getOperand(1); 3371 if (!isBSwapHWordElement(N001, Parts)) 3372 return SDValue(); 3373 SDValue N010 = N01.getOperand(0); 3374 if (!isBSwapHWordElement(N010, Parts)) 3375 return SDValue(); 3376 SDValue N011 = N01.getOperand(1); 3377 if (!isBSwapHWordElement(N011, Parts)) 3378 return SDValue(); 3379 } else { 3380 // (or (or (or (and), (and)), (and)), (and)) 3381 if (!isBSwapHWordElement(N1, Parts)) 3382 return SDValue(); 3383 if (!isBSwapHWordElement(N01, Parts)) 3384 return SDValue(); 3385 if (N00.getOpcode() != ISD::OR) 3386 return SDValue(); 3387 SDValue N000 = N00.getOperand(0); 3388 if (!isBSwapHWordElement(N000, Parts)) 3389 return SDValue(); 3390 SDValue N001 = N00.getOperand(1); 3391 if (!isBSwapHWordElement(N001, Parts)) 3392 return SDValue(); 3393 } 3394 3395 // Make sure the parts are all coming from the same node. 3396 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3397 return SDValue(); 3398 3399 SDLoc DL(N); 3400 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3401 SDValue(Parts[0], 0)); 3402 3403 // Result of the bswap should be rotated by 16. If it's not legal, then 3404 // do (x << 16) | (x >> 16). 3405 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3406 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3407 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3408 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3409 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3410 return DAG.getNode(ISD::OR, DL, VT, 3411 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3412 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3413 } 3414 3415 /// This contains all DAGCombine rules which reduce two values combined by 3416 /// an Or operation to a single value \see visitANDLike(). 3417 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3418 EVT VT = N1.getValueType(); 3419 // fold (or x, undef) -> -1 3420 if (!LegalOperations && 3421 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3422 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3423 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3424 SDLoc(LocReference), VT); 3425 } 3426 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3427 SDValue LL, LR, RL, RR, CC0, CC1; 3428 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3429 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3430 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3431 3432 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3433 LL.getValueType().isInteger()) { 3434 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3435 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3436 if (cast<ConstantSDNode>(LR)->isNullValue() && 3437 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3438 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3439 LR.getValueType(), LL, RL); 3440 AddToWorklist(ORNode.getNode()); 3441 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3442 } 3443 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3444 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3445 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3446 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3447 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3448 LR.getValueType(), LL, RL); 3449 AddToWorklist(ANDNode.getNode()); 3450 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3451 } 3452 } 3453 // canonicalize equivalent to ll == rl 3454 if (LL == RR && LR == RL) { 3455 Op1 = ISD::getSetCCSwappedOperands(Op1); 3456 std::swap(RL, RR); 3457 } 3458 if (LL == RL && LR == RR) { 3459 bool isInteger = LL.getValueType().isInteger(); 3460 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3461 if (Result != ISD::SETCC_INVALID && 3462 (!LegalOperations || 3463 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3464 TLI.isOperationLegal(ISD::SETCC, 3465 getSetCCResultType(N0.getValueType()))))) 3466 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3467 LL, LR, Result); 3468 } 3469 } 3470 3471 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3472 if (N0.getOpcode() == ISD::AND && 3473 N1.getOpcode() == ISD::AND && 3474 N0.getOperand(1).getOpcode() == ISD::Constant && 3475 N1.getOperand(1).getOpcode() == ISD::Constant && 3476 // Don't increase # computations. 3477 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3478 // We can only do this xform if we know that bits from X that are set in C2 3479 // but not in C1 are already zero. Likewise for Y. 3480 const APInt &LHSMask = 3481 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3482 const APInt &RHSMask = 3483 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3484 3485 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3486 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3487 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3488 N0.getOperand(0), N1.getOperand(0)); 3489 SDLoc DL(LocReference); 3490 return DAG.getNode(ISD::AND, DL, VT, X, 3491 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3492 } 3493 } 3494 3495 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3496 if (N0.getOpcode() == ISD::AND && 3497 N1.getOpcode() == ISD::AND && 3498 N0.getOperand(0) == N1.getOperand(0) && 3499 // Don't increase # computations. 3500 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3501 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3502 N0.getOperand(1), N1.getOperand(1)); 3503 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3504 } 3505 3506 return SDValue(); 3507 } 3508 3509 SDValue DAGCombiner::visitOR(SDNode *N) { 3510 SDValue N0 = N->getOperand(0); 3511 SDValue N1 = N->getOperand(1); 3512 EVT VT = N1.getValueType(); 3513 3514 // fold vector ops 3515 if (VT.isVector()) { 3516 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3517 return FoldedVOp; 3518 3519 // fold (or x, 0) -> x, vector edition 3520 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3521 return N1; 3522 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3523 return N0; 3524 3525 // fold (or x, -1) -> -1, vector edition 3526 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3527 // do not return N0, because undef node may exist in N0 3528 return DAG.getConstant( 3529 APInt::getAllOnesValue( 3530 N0.getValueType().getScalarType().getSizeInBits()), 3531 SDLoc(N), N0.getValueType()); 3532 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3533 // do not return N1, because undef node may exist in N1 3534 return DAG.getConstant( 3535 APInt::getAllOnesValue( 3536 N1.getValueType().getScalarType().getSizeInBits()), 3537 SDLoc(N), N1.getValueType()); 3538 3539 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3540 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3541 // Do this only if the resulting shuffle is legal. 3542 if (isa<ShuffleVectorSDNode>(N0) && 3543 isa<ShuffleVectorSDNode>(N1) && 3544 // Avoid folding a node with illegal type. 3545 TLI.isTypeLegal(VT) && 3546 N0->getOperand(1) == N1->getOperand(1) && 3547 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3548 bool CanFold = true; 3549 unsigned NumElts = VT.getVectorNumElements(); 3550 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3551 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3552 // We construct two shuffle masks: 3553 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3554 // and N1 as the second operand. 3555 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3556 // and N0 as the second operand. 3557 // We do this because OR is commutable and therefore there might be 3558 // two ways to fold this node into a shuffle. 3559 SmallVector<int,4> Mask1; 3560 SmallVector<int,4> Mask2; 3561 3562 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3563 int M0 = SV0->getMaskElt(i); 3564 int M1 = SV1->getMaskElt(i); 3565 3566 // Both shuffle indexes are undef. Propagate Undef. 3567 if (M0 < 0 && M1 < 0) { 3568 Mask1.push_back(M0); 3569 Mask2.push_back(M0); 3570 continue; 3571 } 3572 3573 if (M0 < 0 || M1 < 0 || 3574 (M0 < (int)NumElts && M1 < (int)NumElts) || 3575 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3576 CanFold = false; 3577 break; 3578 } 3579 3580 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3581 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3582 } 3583 3584 if (CanFold) { 3585 // Fold this sequence only if the resulting shuffle is 'legal'. 3586 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3587 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3588 N1->getOperand(0), &Mask1[0]); 3589 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3590 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3591 N0->getOperand(0), &Mask2[0]); 3592 } 3593 } 3594 } 3595 3596 // fold (or c1, c2) -> c1|c2 3597 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3598 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3599 if (N0C && N1C) 3600 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3601 // canonicalize constant to RHS 3602 if (isConstantIntBuildVectorOrConstantInt(N0) && 3603 !isConstantIntBuildVectorOrConstantInt(N1)) 3604 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3605 // fold (or x, 0) -> x 3606 if (N1C && N1C->isNullValue()) 3607 return N0; 3608 // fold (or x, -1) -> -1 3609 if (N1C && N1C->isAllOnesValue()) 3610 return N1; 3611 // fold (or x, c) -> c iff (x & ~c) == 0 3612 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3613 return N1; 3614 3615 if (SDValue Combined = visitORLike(N0, N1, N)) 3616 return Combined; 3617 3618 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3619 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3620 if (BSwap.getNode()) 3621 return BSwap; 3622 BSwap = MatchBSwapHWordLow(N, N0, N1); 3623 if (BSwap.getNode()) 3624 return BSwap; 3625 3626 // reassociate or 3627 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3628 return ROR; 3629 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3630 // iff (c1 & c2) == 0. 3631 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3632 isa<ConstantSDNode>(N0.getOperand(1))) { 3633 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3634 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3635 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3636 N1C, C1)) 3637 return DAG.getNode( 3638 ISD::AND, SDLoc(N), VT, 3639 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3640 return SDValue(); 3641 } 3642 } 3643 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3644 if (N0.getOpcode() == N1.getOpcode()) { 3645 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3646 if (Tmp.getNode()) return Tmp; 3647 } 3648 3649 // See if this is some rotate idiom. 3650 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3651 return SDValue(Rot, 0); 3652 3653 // Simplify the operands using demanded-bits information. 3654 if (!VT.isVector() && 3655 SimplifyDemandedBits(SDValue(N, 0))) 3656 return SDValue(N, 0); 3657 3658 return SDValue(); 3659 } 3660 3661 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3662 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3663 if (Op.getOpcode() == ISD::AND) { 3664 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3665 Mask = Op.getOperand(1); 3666 Op = Op.getOperand(0); 3667 } else { 3668 return false; 3669 } 3670 } 3671 3672 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3673 Shift = Op; 3674 return true; 3675 } 3676 3677 return false; 3678 } 3679 3680 // Return true if we can prove that, whenever Neg and Pos are both in the 3681 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3682 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3683 // 3684 // (or (shift1 X, Neg), (shift2 X, Pos)) 3685 // 3686 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3687 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3688 // to consider shift amounts with defined behavior. 3689 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3690 // If OpSize is a power of 2 then: 3691 // 3692 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3693 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3694 // 3695 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3696 // for the stronger condition: 3697 // 3698 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3699 // 3700 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3701 // we can just replace Neg with Neg' for the rest of the function. 3702 // 3703 // In other cases we check for the even stronger condition: 3704 // 3705 // Neg == OpSize - Pos [B] 3706 // 3707 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3708 // behavior if Pos == 0 (and consequently Neg == OpSize). 3709 // 3710 // We could actually use [A] whenever OpSize is a power of 2, but the 3711 // only extra cases that it would match are those uninteresting ones 3712 // where Neg and Pos are never in range at the same time. E.g. for 3713 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3714 // as well as (sub 32, Pos), but: 3715 // 3716 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3717 // 3718 // always invokes undefined behavior for 32-bit X. 3719 // 3720 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3721 unsigned MaskLoBits = 0; 3722 if (Neg.getOpcode() == ISD::AND && 3723 isPowerOf2_64(OpSize) && 3724 Neg.getOperand(1).getOpcode() == ISD::Constant && 3725 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3726 Neg = Neg.getOperand(0); 3727 MaskLoBits = Log2_64(OpSize); 3728 } 3729 3730 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3731 if (Neg.getOpcode() != ISD::SUB) 3732 return 0; 3733 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3734 if (!NegC) 3735 return 0; 3736 SDValue NegOp1 = Neg.getOperand(1); 3737 3738 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3739 // Pos'. The truncation is redundant for the purpose of the equality. 3740 if (MaskLoBits && 3741 Pos.getOpcode() == ISD::AND && 3742 Pos.getOperand(1).getOpcode() == ISD::Constant && 3743 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3744 Pos = Pos.getOperand(0); 3745 3746 // The condition we need is now: 3747 // 3748 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3749 // 3750 // If NegOp1 == Pos then we need: 3751 // 3752 // OpSize & Mask == NegC & Mask 3753 // 3754 // (because "x & Mask" is a truncation and distributes through subtraction). 3755 APInt Width; 3756 if (Pos == NegOp1) 3757 Width = NegC->getAPIntValue(); 3758 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3759 // Then the condition we want to prove becomes: 3760 // 3761 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3762 // 3763 // which, again because "x & Mask" is a truncation, becomes: 3764 // 3765 // NegC & Mask == (OpSize - PosC) & Mask 3766 // OpSize & Mask == (NegC + PosC) & Mask 3767 else if (Pos.getOpcode() == ISD::ADD && 3768 Pos.getOperand(0) == NegOp1 && 3769 Pos.getOperand(1).getOpcode() == ISD::Constant) 3770 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3771 NegC->getAPIntValue()); 3772 else 3773 return false; 3774 3775 // Now we just need to check that OpSize & Mask == Width & Mask. 3776 if (MaskLoBits) 3777 // Opsize & Mask is 0 since Mask is Opsize - 1. 3778 return Width.getLoBits(MaskLoBits) == 0; 3779 return Width == OpSize; 3780 } 3781 3782 // A subroutine of MatchRotate used once we have found an OR of two opposite 3783 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3784 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3785 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3786 // Neg with outer conversions stripped away. 3787 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3788 SDValue Neg, SDValue InnerPos, 3789 SDValue InnerNeg, unsigned PosOpcode, 3790 unsigned NegOpcode, SDLoc DL) { 3791 // fold (or (shl x, (*ext y)), 3792 // (srl x, (*ext (sub 32, y)))) -> 3793 // (rotl x, y) or (rotr x, (sub 32, y)) 3794 // 3795 // fold (or (shl x, (*ext (sub 32, y))), 3796 // (srl x, (*ext y))) -> 3797 // (rotr x, y) or (rotl x, (sub 32, y)) 3798 EVT VT = Shifted.getValueType(); 3799 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3800 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3801 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3802 HasPos ? Pos : Neg).getNode(); 3803 } 3804 3805 return nullptr; 3806 } 3807 3808 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3809 // idioms for rotate, and if the target supports rotation instructions, generate 3810 // a rot[lr]. 3811 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3812 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3813 EVT VT = LHS.getValueType(); 3814 if (!TLI.isTypeLegal(VT)) return nullptr; 3815 3816 // The target must have at least one rotate flavor. 3817 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3818 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3819 if (!HasROTL && !HasROTR) return nullptr; 3820 3821 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3822 SDValue LHSShift; // The shift. 3823 SDValue LHSMask; // AND value if any. 3824 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3825 return nullptr; // Not part of a rotate. 3826 3827 SDValue RHSShift; // The shift. 3828 SDValue RHSMask; // AND value if any. 3829 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3830 return nullptr; // Not part of a rotate. 3831 3832 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3833 return nullptr; // Not shifting the same value. 3834 3835 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3836 return nullptr; // Shifts must disagree. 3837 3838 // Canonicalize shl to left side in a shl/srl pair. 3839 if (RHSShift.getOpcode() == ISD::SHL) { 3840 std::swap(LHS, RHS); 3841 std::swap(LHSShift, RHSShift); 3842 std::swap(LHSMask , RHSMask ); 3843 } 3844 3845 unsigned OpSizeInBits = VT.getSizeInBits(); 3846 SDValue LHSShiftArg = LHSShift.getOperand(0); 3847 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3848 SDValue RHSShiftArg = RHSShift.getOperand(0); 3849 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3850 3851 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3852 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3853 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3854 RHSShiftAmt.getOpcode() == ISD::Constant) { 3855 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3856 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3857 if ((LShVal + RShVal) != OpSizeInBits) 3858 return nullptr; 3859 3860 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3861 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3862 3863 // If there is an AND of either shifted operand, apply it to the result. 3864 if (LHSMask.getNode() || RHSMask.getNode()) { 3865 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3866 3867 if (LHSMask.getNode()) { 3868 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3869 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3870 } 3871 if (RHSMask.getNode()) { 3872 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3873 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3874 } 3875 3876 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT)); 3877 } 3878 3879 return Rot.getNode(); 3880 } 3881 3882 // If there is a mask here, and we have a variable shift, we can't be sure 3883 // that we're masking out the right stuff. 3884 if (LHSMask.getNode() || RHSMask.getNode()) 3885 return nullptr; 3886 3887 // If the shift amount is sign/zext/any-extended just peel it off. 3888 SDValue LExtOp0 = LHSShiftAmt; 3889 SDValue RExtOp0 = RHSShiftAmt; 3890 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3891 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3892 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3893 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3894 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3895 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3896 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3897 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3898 LExtOp0 = LHSShiftAmt.getOperand(0); 3899 RExtOp0 = RHSShiftAmt.getOperand(0); 3900 } 3901 3902 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3903 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3904 if (TryL) 3905 return TryL; 3906 3907 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3908 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3909 if (TryR) 3910 return TryR; 3911 3912 return nullptr; 3913 } 3914 3915 SDValue DAGCombiner::visitXOR(SDNode *N) { 3916 SDValue N0 = N->getOperand(0); 3917 SDValue N1 = N->getOperand(1); 3918 EVT VT = N0.getValueType(); 3919 3920 // fold vector ops 3921 if (VT.isVector()) { 3922 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3923 return FoldedVOp; 3924 3925 // fold (xor x, 0) -> x, vector edition 3926 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3927 return N1; 3928 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3929 return N0; 3930 } 3931 3932 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3933 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3934 return DAG.getConstant(0, SDLoc(N), VT); 3935 // fold (xor x, undef) -> undef 3936 if (N0.getOpcode() == ISD::UNDEF) 3937 return N0; 3938 if (N1.getOpcode() == ISD::UNDEF) 3939 return N1; 3940 // fold (xor c1, c2) -> c1^c2 3941 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3942 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3943 if (N0C && N1C) 3944 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 3945 // canonicalize constant to RHS 3946 if (isConstantIntBuildVectorOrConstantInt(N0) && 3947 !isConstantIntBuildVectorOrConstantInt(N1)) 3948 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3949 // fold (xor x, 0) -> x 3950 if (N1C && N1C->isNullValue()) 3951 return N0; 3952 // reassociate xor 3953 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 3954 return RXOR; 3955 3956 // fold !(x cc y) -> (x !cc y) 3957 SDValue LHS, RHS, CC; 3958 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3959 bool isInt = LHS.getValueType().isInteger(); 3960 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3961 isInt); 3962 3963 if (!LegalOperations || 3964 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3965 switch (N0.getOpcode()) { 3966 default: 3967 llvm_unreachable("Unhandled SetCC Equivalent!"); 3968 case ISD::SETCC: 3969 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3970 case ISD::SELECT_CC: 3971 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3972 N0.getOperand(3), NotCC); 3973 } 3974 } 3975 } 3976 3977 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3978 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3979 N0.getNode()->hasOneUse() && 3980 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3981 SDValue V = N0.getOperand(0); 3982 SDLoc DL(N0); 3983 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 3984 DAG.getConstant(1, DL, V.getValueType())); 3985 AddToWorklist(V.getNode()); 3986 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3987 } 3988 3989 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3990 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3991 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3992 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3993 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3994 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3995 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3996 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3997 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3998 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3999 } 4000 } 4001 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4002 if (N1C && N1C->isAllOnesValue() && 4003 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4004 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4005 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4006 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4007 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4008 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4009 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4010 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4011 } 4012 } 4013 // fold (xor (and x, y), y) -> (and (not x), y) 4014 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4015 N0->getOperand(1) == N1) { 4016 SDValue X = N0->getOperand(0); 4017 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4018 AddToWorklist(NotX.getNode()); 4019 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4020 } 4021 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4022 if (N1C && N0.getOpcode() == ISD::XOR) { 4023 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 4024 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4025 if (N00C) { 4026 SDLoc DL(N); 4027 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4028 DAG.getConstant(N1C->getAPIntValue() ^ 4029 N00C->getAPIntValue(), DL, VT)); 4030 } 4031 if (N01C) { 4032 SDLoc DL(N); 4033 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4034 DAG.getConstant(N1C->getAPIntValue() ^ 4035 N01C->getAPIntValue(), DL, VT)); 4036 } 4037 } 4038 // fold (xor x, x) -> 0 4039 if (N0 == N1) 4040 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4041 4042 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4043 // Here is a concrete example of this equivalence: 4044 // i16 x == 14 4045 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4046 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4047 // 4048 // => 4049 // 4050 // i16 ~1 == 0b1111111111111110 4051 // i16 rol(~1, 14) == 0b1011111111111111 4052 // 4053 // Some additional tips to help conceptualize this transform: 4054 // - Try to see the operation as placing a single zero in a value of all ones. 4055 // - There exists no value for x which would allow the result to contain zero. 4056 // - Values of x larger than the bitwidth are undefined and do not require a 4057 // consistent result. 4058 // - Pushing the zero left requires shifting one bits in from the right. 4059 // A rotate left of ~1 is a nice way of achieving the desired result. 4060 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4061 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) 4062 if (N0.getOpcode() == ISD::SHL) 4063 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4064 if (N1C->isAllOnesValue() && ShlLHS->isOne()) { 4065 SDLoc DL(N); 4066 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4067 N0.getOperand(1)); 4068 } 4069 4070 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4071 if (N0.getOpcode() == N1.getOpcode()) { 4072 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 4073 if (Tmp.getNode()) return Tmp; 4074 } 4075 4076 // Simplify the expression using non-local knowledge. 4077 if (!VT.isVector() && 4078 SimplifyDemandedBits(SDValue(N, 0))) 4079 return SDValue(N, 0); 4080 4081 return SDValue(); 4082 } 4083 4084 /// Handle transforms common to the three shifts, when the shift amount is a 4085 /// constant. 4086 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4087 // We can't and shouldn't fold opaque constants. 4088 if (Amt->isOpaque()) 4089 return SDValue(); 4090 4091 SDNode *LHS = N->getOperand(0).getNode(); 4092 if (!LHS->hasOneUse()) return SDValue(); 4093 4094 // We want to pull some binops through shifts, so that we have (and (shift)) 4095 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4096 // thing happens with address calculations, so it's important to canonicalize 4097 // it. 4098 bool HighBitSet = false; // Can we transform this if the high bit is set? 4099 4100 switch (LHS->getOpcode()) { 4101 default: return SDValue(); 4102 case ISD::OR: 4103 case ISD::XOR: 4104 HighBitSet = false; // We can only transform sra if the high bit is clear. 4105 break; 4106 case ISD::AND: 4107 HighBitSet = true; // We can only transform sra if the high bit is set. 4108 break; 4109 case ISD::ADD: 4110 if (N->getOpcode() != ISD::SHL) 4111 return SDValue(); // only shl(add) not sr[al](add). 4112 HighBitSet = false; // We can only transform sra if the high bit is clear. 4113 break; 4114 } 4115 4116 // We require the RHS of the binop to be a constant and not opaque as well. 4117 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 4118 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 4119 4120 // FIXME: disable this unless the input to the binop is a shift by a constant. 4121 // If it is not a shift, it pessimizes some common cases like: 4122 // 4123 // void foo(int *X, int i) { X[i & 1235] = 1; } 4124 // int bar(int *X, int i) { return X[i & 255]; } 4125 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4126 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4127 BinOpLHSVal->getOpcode() != ISD::SRA && 4128 BinOpLHSVal->getOpcode() != ISD::SRL) || 4129 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4130 return SDValue(); 4131 4132 EVT VT = N->getValueType(0); 4133 4134 // If this is a signed shift right, and the high bit is modified by the 4135 // logical operation, do not perform the transformation. The highBitSet 4136 // boolean indicates the value of the high bit of the constant which would 4137 // cause it to be modified for this operation. 4138 if (N->getOpcode() == ISD::SRA) { 4139 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4140 if (BinOpRHSSignSet != HighBitSet) 4141 return SDValue(); 4142 } 4143 4144 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4145 return SDValue(); 4146 4147 // Fold the constants, shifting the binop RHS by the shift amount. 4148 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4149 N->getValueType(0), 4150 LHS->getOperand(1), N->getOperand(1)); 4151 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4152 4153 // Create the new shift. 4154 SDValue NewShift = DAG.getNode(N->getOpcode(), 4155 SDLoc(LHS->getOperand(0)), 4156 VT, LHS->getOperand(0), N->getOperand(1)); 4157 4158 // Create the new binop. 4159 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4160 } 4161 4162 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4163 assert(N->getOpcode() == ISD::TRUNCATE); 4164 assert(N->getOperand(0).getOpcode() == ISD::AND); 4165 4166 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4167 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4168 SDValue N01 = N->getOperand(0).getOperand(1); 4169 4170 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4171 EVT TruncVT = N->getValueType(0); 4172 SDValue N00 = N->getOperand(0).getOperand(0); 4173 APInt TruncC = N01C->getAPIntValue(); 4174 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4175 SDLoc DL(N); 4176 4177 return DAG.getNode(ISD::AND, DL, TruncVT, 4178 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4179 DAG.getConstant(TruncC, DL, TruncVT)); 4180 } 4181 } 4182 4183 return SDValue(); 4184 } 4185 4186 SDValue DAGCombiner::visitRotate(SDNode *N) { 4187 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4188 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4189 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4190 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4191 if (NewOp1.getNode()) 4192 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4193 N->getOperand(0), NewOp1); 4194 } 4195 return SDValue(); 4196 } 4197 4198 SDValue DAGCombiner::visitSHL(SDNode *N) { 4199 SDValue N0 = N->getOperand(0); 4200 SDValue N1 = N->getOperand(1); 4201 EVT VT = N0.getValueType(); 4202 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4203 4204 // fold vector ops 4205 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4206 if (VT.isVector()) { 4207 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4208 return FoldedVOp; 4209 4210 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4211 // If setcc produces all-one true value then: 4212 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4213 if (N1CV && N1CV->isConstant()) { 4214 if (N0.getOpcode() == ISD::AND) { 4215 SDValue N00 = N0->getOperand(0); 4216 SDValue N01 = N0->getOperand(1); 4217 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4218 4219 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4220 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4221 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4222 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4223 N01CV, N1CV)) 4224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4225 } 4226 } else { 4227 N1C = isConstOrConstSplat(N1); 4228 } 4229 } 4230 } 4231 4232 // fold (shl c1, c2) -> c1<<c2 4233 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4234 if (N0C && N1C) 4235 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4236 // fold (shl 0, x) -> 0 4237 if (N0C && N0C->isNullValue()) 4238 return N0; 4239 // fold (shl x, c >= size(x)) -> undef 4240 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4241 return DAG.getUNDEF(VT); 4242 // fold (shl x, 0) -> x 4243 if (N1C && N1C->isNullValue()) 4244 return N0; 4245 // fold (shl undef, x) -> 0 4246 if (N0.getOpcode() == ISD::UNDEF) 4247 return DAG.getConstant(0, SDLoc(N), VT); 4248 // if (shl x, c) is known to be zero, return 0 4249 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4250 APInt::getAllOnesValue(OpSizeInBits))) 4251 return DAG.getConstant(0, SDLoc(N), VT); 4252 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4253 if (N1.getOpcode() == ISD::TRUNCATE && 4254 N1.getOperand(0).getOpcode() == ISD::AND) { 4255 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4256 if (NewOp1.getNode()) 4257 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4258 } 4259 4260 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4261 return SDValue(N, 0); 4262 4263 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4264 if (N1C && N0.getOpcode() == ISD::SHL) { 4265 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4266 uint64_t c1 = N0C1->getZExtValue(); 4267 uint64_t c2 = N1C->getZExtValue(); 4268 SDLoc DL(N); 4269 if (c1 + c2 >= OpSizeInBits) 4270 return DAG.getConstant(0, DL, VT); 4271 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4272 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4273 } 4274 } 4275 4276 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4277 // For this to be valid, the second form must not preserve any of the bits 4278 // that are shifted out by the inner shift in the first form. This means 4279 // the outer shift size must be >= the number of bits added by the ext. 4280 // As a corollary, we don't care what kind of ext it is. 4281 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4282 N0.getOpcode() == ISD::ANY_EXTEND || 4283 N0.getOpcode() == ISD::SIGN_EXTEND) && 4284 N0.getOperand(0).getOpcode() == ISD::SHL) { 4285 SDValue N0Op0 = N0.getOperand(0); 4286 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4287 uint64_t c1 = N0Op0C1->getZExtValue(); 4288 uint64_t c2 = N1C->getZExtValue(); 4289 EVT InnerShiftVT = N0Op0.getValueType(); 4290 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4291 if (c2 >= OpSizeInBits - InnerShiftSize) { 4292 SDLoc DL(N0); 4293 if (c1 + c2 >= OpSizeInBits) 4294 return DAG.getConstant(0, DL, VT); 4295 return DAG.getNode(ISD::SHL, DL, VT, 4296 DAG.getNode(N0.getOpcode(), DL, VT, 4297 N0Op0->getOperand(0)), 4298 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4299 } 4300 } 4301 } 4302 4303 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4304 // Only fold this if the inner zext has no other uses to avoid increasing 4305 // the total number of instructions. 4306 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4307 N0.getOperand(0).getOpcode() == ISD::SRL) { 4308 SDValue N0Op0 = N0.getOperand(0); 4309 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4310 uint64_t c1 = N0Op0C1->getZExtValue(); 4311 if (c1 < VT.getScalarSizeInBits()) { 4312 uint64_t c2 = N1C->getZExtValue(); 4313 if (c1 == c2) { 4314 SDValue NewOp0 = N0.getOperand(0); 4315 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4316 SDLoc DL(N); 4317 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4318 NewOp0, 4319 DAG.getConstant(c2, DL, CountVT)); 4320 AddToWorklist(NewSHL.getNode()); 4321 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4322 } 4323 } 4324 } 4325 } 4326 4327 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4328 // (and (srl x, (sub c1, c2), MASK) 4329 // Only fold this if the inner shift has no other uses -- if it does, folding 4330 // this will increase the total number of instructions. 4331 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4332 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4333 uint64_t c1 = N0C1->getZExtValue(); 4334 if (c1 < OpSizeInBits) { 4335 uint64_t c2 = N1C->getZExtValue(); 4336 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4337 SDValue Shift; 4338 if (c2 > c1) { 4339 Mask = Mask.shl(c2 - c1); 4340 SDLoc DL(N); 4341 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4342 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4343 } else { 4344 Mask = Mask.lshr(c1 - c2); 4345 SDLoc DL(N); 4346 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4347 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4348 } 4349 SDLoc DL(N0); 4350 return DAG.getNode(ISD::AND, DL, VT, Shift, 4351 DAG.getConstant(Mask, DL, VT)); 4352 } 4353 } 4354 } 4355 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4356 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4357 unsigned BitSize = VT.getScalarSizeInBits(); 4358 SDLoc DL(N); 4359 SDValue HiBitsMask = 4360 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4361 BitSize - N1C->getZExtValue()), 4362 DL, VT); 4363 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4364 HiBitsMask); 4365 } 4366 4367 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4368 // Variant of version done on multiply, except mul by a power of 2 is turned 4369 // into a shift. 4370 APInt Val; 4371 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4372 (isa<ConstantSDNode>(N0.getOperand(1)) || 4373 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4374 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4375 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4376 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4377 } 4378 4379 if (N1C) { 4380 SDValue NewSHL = visitShiftByConstant(N, N1C); 4381 if (NewSHL.getNode()) 4382 return NewSHL; 4383 } 4384 4385 return SDValue(); 4386 } 4387 4388 SDValue DAGCombiner::visitSRA(SDNode *N) { 4389 SDValue N0 = N->getOperand(0); 4390 SDValue N1 = N->getOperand(1); 4391 EVT VT = N0.getValueType(); 4392 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4393 4394 // fold vector ops 4395 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4396 if (VT.isVector()) { 4397 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4398 return FoldedVOp; 4399 4400 N1C = isConstOrConstSplat(N1); 4401 } 4402 4403 // fold (sra c1, c2) -> (sra c1, c2) 4404 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4405 if (N0C && N1C) 4406 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4407 // fold (sra 0, x) -> 0 4408 if (N0C && N0C->isNullValue()) 4409 return N0; 4410 // fold (sra -1, x) -> -1 4411 if (N0C && N0C->isAllOnesValue()) 4412 return N0; 4413 // fold (sra x, (setge c, size(x))) -> undef 4414 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4415 return DAG.getUNDEF(VT); 4416 // fold (sra x, 0) -> x 4417 if (N1C && N1C->isNullValue()) 4418 return N0; 4419 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4420 // sext_inreg. 4421 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4422 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4423 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4424 if (VT.isVector()) 4425 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4426 ExtVT, VT.getVectorNumElements()); 4427 if ((!LegalOperations || 4428 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4429 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4430 N0.getOperand(0), DAG.getValueType(ExtVT)); 4431 } 4432 4433 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4434 if (N1C && N0.getOpcode() == ISD::SRA) { 4435 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4436 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4437 if (Sum >= OpSizeInBits) 4438 Sum = OpSizeInBits - 1; 4439 SDLoc DL(N); 4440 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4441 DAG.getConstant(Sum, DL, N1.getValueType())); 4442 } 4443 } 4444 4445 // fold (sra (shl X, m), (sub result_size, n)) 4446 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4447 // result_size - n != m. 4448 // If truncate is free for the target sext(shl) is likely to result in better 4449 // code. 4450 if (N0.getOpcode() == ISD::SHL && N1C) { 4451 // Get the two constanst of the shifts, CN0 = m, CN = n. 4452 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4453 if (N01C) { 4454 LLVMContext &Ctx = *DAG.getContext(); 4455 // Determine what the truncate's result bitsize and type would be. 4456 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4457 4458 if (VT.isVector()) 4459 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4460 4461 // Determine the residual right-shift amount. 4462 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4463 4464 // If the shift is not a no-op (in which case this should be just a sign 4465 // extend already), the truncated to type is legal, sign_extend is legal 4466 // on that type, and the truncate to that type is both legal and free, 4467 // perform the transform. 4468 if ((ShiftAmt > 0) && 4469 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4470 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4471 TLI.isTruncateFree(VT, TruncVT)) { 4472 4473 SDLoc DL(N); 4474 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4475 getShiftAmountTy(N0.getOperand(0).getValueType())); 4476 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4477 N0.getOperand(0), Amt); 4478 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4479 Shift); 4480 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4481 N->getValueType(0), Trunc); 4482 } 4483 } 4484 } 4485 4486 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4487 if (N1.getOpcode() == ISD::TRUNCATE && 4488 N1.getOperand(0).getOpcode() == ISD::AND) { 4489 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4490 if (NewOp1.getNode()) 4491 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4492 } 4493 4494 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4495 // if c1 is equal to the number of bits the trunc removes 4496 if (N0.getOpcode() == ISD::TRUNCATE && 4497 (N0.getOperand(0).getOpcode() == ISD::SRL || 4498 N0.getOperand(0).getOpcode() == ISD::SRA) && 4499 N0.getOperand(0).hasOneUse() && 4500 N0.getOperand(0).getOperand(1).hasOneUse() && 4501 N1C) { 4502 SDValue N0Op0 = N0.getOperand(0); 4503 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4504 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4505 EVT LargeVT = N0Op0.getValueType(); 4506 4507 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4508 SDLoc DL(N); 4509 SDValue Amt = 4510 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4511 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4512 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4513 N0Op0.getOperand(0), Amt); 4514 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4515 } 4516 } 4517 } 4518 4519 // Simplify, based on bits shifted out of the LHS. 4520 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4521 return SDValue(N, 0); 4522 4523 4524 // If the sign bit is known to be zero, switch this to a SRL. 4525 if (DAG.SignBitIsZero(N0)) 4526 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4527 4528 if (N1C) { 4529 SDValue NewSRA = visitShiftByConstant(N, N1C); 4530 if (NewSRA.getNode()) 4531 return NewSRA; 4532 } 4533 4534 return SDValue(); 4535 } 4536 4537 SDValue DAGCombiner::visitSRL(SDNode *N) { 4538 SDValue N0 = N->getOperand(0); 4539 SDValue N1 = N->getOperand(1); 4540 EVT VT = N0.getValueType(); 4541 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4542 4543 // fold vector ops 4544 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4545 if (VT.isVector()) { 4546 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4547 return FoldedVOp; 4548 4549 N1C = isConstOrConstSplat(N1); 4550 } 4551 4552 // fold (srl c1, c2) -> c1 >>u c2 4553 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4554 if (N0C && N1C) 4555 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4556 // fold (srl 0, x) -> 0 4557 if (N0C && N0C->isNullValue()) 4558 return N0; 4559 // fold (srl x, c >= size(x)) -> undef 4560 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4561 return DAG.getUNDEF(VT); 4562 // fold (srl x, 0) -> x 4563 if (N1C && N1C->isNullValue()) 4564 return N0; 4565 // if (srl x, c) is known to be zero, return 0 4566 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4567 APInt::getAllOnesValue(OpSizeInBits))) 4568 return DAG.getConstant(0, SDLoc(N), VT); 4569 4570 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4571 if (N1C && N0.getOpcode() == ISD::SRL) { 4572 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4573 uint64_t c1 = N01C->getZExtValue(); 4574 uint64_t c2 = N1C->getZExtValue(); 4575 SDLoc DL(N); 4576 if (c1 + c2 >= OpSizeInBits) 4577 return DAG.getConstant(0, DL, VT); 4578 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4579 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4580 } 4581 } 4582 4583 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4584 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4585 N0.getOperand(0).getOpcode() == ISD::SRL && 4586 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4587 uint64_t c1 = 4588 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4589 uint64_t c2 = N1C->getZExtValue(); 4590 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4591 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4592 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4593 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4594 if (c1 + OpSizeInBits == InnerShiftSize) { 4595 SDLoc DL(N0); 4596 if (c1 + c2 >= InnerShiftSize) 4597 return DAG.getConstant(0, DL, VT); 4598 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4599 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4600 N0.getOperand(0)->getOperand(0), 4601 DAG.getConstant(c1 + c2, DL, 4602 ShiftCountVT))); 4603 } 4604 } 4605 4606 // fold (srl (shl x, c), c) -> (and x, cst2) 4607 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4608 unsigned BitSize = N0.getScalarValueSizeInBits(); 4609 if (BitSize <= 64) { 4610 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4611 SDLoc DL(N); 4612 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4613 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4614 } 4615 } 4616 4617 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4618 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4619 // Shifting in all undef bits? 4620 EVT SmallVT = N0.getOperand(0).getValueType(); 4621 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4622 if (N1C->getZExtValue() >= BitSize) 4623 return DAG.getUNDEF(VT); 4624 4625 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4626 uint64_t ShiftAmt = N1C->getZExtValue(); 4627 SDLoc DL0(N0); 4628 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4629 N0.getOperand(0), 4630 DAG.getConstant(ShiftAmt, DL0, 4631 getShiftAmountTy(SmallVT))); 4632 AddToWorklist(SmallShift.getNode()); 4633 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4634 SDLoc DL(N); 4635 return DAG.getNode(ISD::AND, DL, VT, 4636 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4637 DAG.getConstant(Mask, DL, VT)); 4638 } 4639 } 4640 4641 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4642 // bit, which is unmodified by sra. 4643 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4644 if (N0.getOpcode() == ISD::SRA) 4645 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4646 } 4647 4648 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4649 if (N1C && N0.getOpcode() == ISD::CTLZ && 4650 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4651 APInt KnownZero, KnownOne; 4652 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4653 4654 // If any of the input bits are KnownOne, then the input couldn't be all 4655 // zeros, thus the result of the srl will always be zero. 4656 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4657 4658 // If all of the bits input the to ctlz node are known to be zero, then 4659 // the result of the ctlz is "32" and the result of the shift is one. 4660 APInt UnknownBits = ~KnownZero; 4661 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4662 4663 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4664 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4665 // Okay, we know that only that the single bit specified by UnknownBits 4666 // could be set on input to the CTLZ node. If this bit is set, the SRL 4667 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4668 // to an SRL/XOR pair, which is likely to simplify more. 4669 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4670 SDValue Op = N0.getOperand(0); 4671 4672 if (ShAmt) { 4673 SDLoc DL(N0); 4674 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4675 DAG.getConstant(ShAmt, DL, 4676 getShiftAmountTy(Op.getValueType()))); 4677 AddToWorklist(Op.getNode()); 4678 } 4679 4680 SDLoc DL(N); 4681 return DAG.getNode(ISD::XOR, DL, VT, 4682 Op, DAG.getConstant(1, DL, VT)); 4683 } 4684 } 4685 4686 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4687 if (N1.getOpcode() == ISD::TRUNCATE && 4688 N1.getOperand(0).getOpcode() == ISD::AND) { 4689 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4690 if (NewOp1.getNode()) 4691 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4692 } 4693 4694 // fold operands of srl based on knowledge that the low bits are not 4695 // demanded. 4696 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4697 return SDValue(N, 0); 4698 4699 if (N1C) { 4700 SDValue NewSRL = visitShiftByConstant(N, N1C); 4701 if (NewSRL.getNode()) 4702 return NewSRL; 4703 } 4704 4705 // Attempt to convert a srl of a load into a narrower zero-extending load. 4706 SDValue NarrowLoad = ReduceLoadWidth(N); 4707 if (NarrowLoad.getNode()) 4708 return NarrowLoad; 4709 4710 // Here is a common situation. We want to optimize: 4711 // 4712 // %a = ... 4713 // %b = and i32 %a, 2 4714 // %c = srl i32 %b, 1 4715 // brcond i32 %c ... 4716 // 4717 // into 4718 // 4719 // %a = ... 4720 // %b = and %a, 2 4721 // %c = setcc eq %b, 0 4722 // brcond %c ... 4723 // 4724 // However when after the source operand of SRL is optimized into AND, the SRL 4725 // itself may not be optimized further. Look for it and add the BRCOND into 4726 // the worklist. 4727 if (N->hasOneUse()) { 4728 SDNode *Use = *N->use_begin(); 4729 if (Use->getOpcode() == ISD::BRCOND) 4730 AddToWorklist(Use); 4731 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4732 // Also look pass the truncate. 4733 Use = *Use->use_begin(); 4734 if (Use->getOpcode() == ISD::BRCOND) 4735 AddToWorklist(Use); 4736 } 4737 } 4738 4739 return SDValue(); 4740 } 4741 4742 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4743 SDValue N0 = N->getOperand(0); 4744 EVT VT = N->getValueType(0); 4745 4746 // fold (ctlz c1) -> c2 4747 if (isa<ConstantSDNode>(N0)) 4748 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4749 return SDValue(); 4750 } 4751 4752 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4753 SDValue N0 = N->getOperand(0); 4754 EVT VT = N->getValueType(0); 4755 4756 // fold (ctlz_zero_undef c1) -> c2 4757 if (isa<ConstantSDNode>(N0)) 4758 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4759 return SDValue(); 4760 } 4761 4762 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4763 SDValue N0 = N->getOperand(0); 4764 EVT VT = N->getValueType(0); 4765 4766 // fold (cttz c1) -> c2 4767 if (isa<ConstantSDNode>(N0)) 4768 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4769 return SDValue(); 4770 } 4771 4772 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4773 SDValue N0 = N->getOperand(0); 4774 EVT VT = N->getValueType(0); 4775 4776 // fold (cttz_zero_undef c1) -> c2 4777 if (isa<ConstantSDNode>(N0)) 4778 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4779 return SDValue(); 4780 } 4781 4782 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4783 SDValue N0 = N->getOperand(0); 4784 EVT VT = N->getValueType(0); 4785 4786 // fold (ctpop c1) -> c2 4787 if (isa<ConstantSDNode>(N0)) 4788 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4789 return SDValue(); 4790 } 4791 4792 4793 /// \brief Generate Min/Max node 4794 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4795 SDValue True, SDValue False, 4796 ISD::CondCode CC, const TargetLowering &TLI, 4797 SelectionDAG &DAG) { 4798 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4799 return SDValue(); 4800 4801 switch (CC) { 4802 case ISD::SETOLT: 4803 case ISD::SETOLE: 4804 case ISD::SETLT: 4805 case ISD::SETLE: 4806 case ISD::SETULT: 4807 case ISD::SETULE: { 4808 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4809 if (TLI.isOperationLegal(Opcode, VT)) 4810 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4811 return SDValue(); 4812 } 4813 case ISD::SETOGT: 4814 case ISD::SETOGE: 4815 case ISD::SETGT: 4816 case ISD::SETGE: 4817 case ISD::SETUGT: 4818 case ISD::SETUGE: { 4819 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4820 if (TLI.isOperationLegal(Opcode, VT)) 4821 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4822 return SDValue(); 4823 } 4824 default: 4825 return SDValue(); 4826 } 4827 } 4828 4829 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4830 SDValue N0 = N->getOperand(0); 4831 SDValue N1 = N->getOperand(1); 4832 SDValue N2 = N->getOperand(2); 4833 EVT VT = N->getValueType(0); 4834 EVT VT0 = N0.getValueType(); 4835 4836 // fold (select C, X, X) -> X 4837 if (N1 == N2) 4838 return N1; 4839 // fold (select true, X, Y) -> X 4840 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4841 if (N0C && !N0C->isNullValue()) 4842 return N1; 4843 // fold (select false, X, Y) -> Y 4844 if (N0C && N0C->isNullValue()) 4845 return N2; 4846 // fold (select C, 1, X) -> (or C, X) 4847 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4848 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4849 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4850 // fold (select C, 0, 1) -> (xor C, 1) 4851 // We can't do this reliably if integer based booleans have different contents 4852 // to floating point based booleans. This is because we can't tell whether we 4853 // have an integer-based boolean or a floating-point-based boolean unless we 4854 // can find the SETCC that produced it and inspect its operands. This is 4855 // fairly easy if C is the SETCC node, but it can potentially be 4856 // undiscoverable (or not reasonably discoverable). For example, it could be 4857 // in another basic block or it could require searching a complicated 4858 // expression. 4859 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4860 if (VT.isInteger() && 4861 (VT0 == MVT::i1 || (VT0.isInteger() && 4862 TLI.getBooleanContents(false, false) == 4863 TLI.getBooleanContents(false, true) && 4864 TLI.getBooleanContents(false, false) == 4865 TargetLowering::ZeroOrOneBooleanContent)) && 4866 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4867 SDValue XORNode; 4868 if (VT == VT0) { 4869 SDLoc DL(N); 4870 return DAG.getNode(ISD::XOR, DL, VT0, 4871 N0, DAG.getConstant(1, DL, VT0)); 4872 } 4873 SDLoc DL0(N0); 4874 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 4875 N0, DAG.getConstant(1, DL0, VT0)); 4876 AddToWorklist(XORNode.getNode()); 4877 if (VT.bitsGT(VT0)) 4878 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4879 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4880 } 4881 // fold (select C, 0, X) -> (and (not C), X) 4882 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4883 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4884 AddToWorklist(NOTNode.getNode()); 4885 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4886 } 4887 // fold (select C, X, 1) -> (or (not C), X) 4888 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4889 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4890 AddToWorklist(NOTNode.getNode()); 4891 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4892 } 4893 // fold (select C, X, 0) -> (and C, X) 4894 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4895 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4896 // fold (select X, X, Y) -> (or X, Y) 4897 // fold (select X, 1, Y) -> (or X, Y) 4898 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4899 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4900 // fold (select X, Y, X) -> (and X, Y) 4901 // fold (select X, Y, 0) -> (and X, Y) 4902 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4903 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4904 4905 // If we can fold this based on the true/false value, do so. 4906 if (SimplifySelectOps(N, N1, N2)) 4907 return SDValue(N, 0); // Don't revisit N. 4908 4909 // fold selects based on a setcc into other things, such as min/max/abs 4910 if (N0.getOpcode() == ISD::SETCC) { 4911 // select x, y (fcmp lt x, y) -> fminnum x, y 4912 // select x, y (fcmp gt x, y) -> fmaxnum x, y 4913 // 4914 // This is OK if we don't care about what happens if either operand is a 4915 // NaN. 4916 // 4917 4918 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 4919 // no signed zeros as well as no nans. 4920 const TargetOptions &Options = DAG.getTarget().Options; 4921 if (Options.UnsafeFPMath && 4922 VT.isFloatingPoint() && N0.hasOneUse() && 4923 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 4924 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4925 4926 SDValue FMinMax = 4927 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1), 4928 N1, N2, CC, TLI, DAG); 4929 if (FMinMax) 4930 return FMinMax; 4931 } 4932 4933 if ((!LegalOperations && 4934 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4935 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4936 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4937 N0.getOperand(0), N0.getOperand(1), 4938 N1, N2, N0.getOperand(2)); 4939 return SimplifySelect(SDLoc(N), N0, N1, N2); 4940 } 4941 4942 if (VT0 == MVT::i1) { 4943 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4944 // select (and Cond0, Cond1), X, Y 4945 // -> select Cond0, (select Cond1, X, Y), Y 4946 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 4947 SDValue Cond0 = N0->getOperand(0); 4948 SDValue Cond1 = N0->getOperand(1); 4949 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4950 N1.getValueType(), Cond1, N1, N2); 4951 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 4952 InnerSelect, N2); 4953 } 4954 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 4955 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 4956 SDValue Cond0 = N0->getOperand(0); 4957 SDValue Cond1 = N0->getOperand(1); 4958 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4959 N1.getValueType(), Cond1, N1, N2); 4960 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 4961 InnerSelect); 4962 } 4963 } 4964 4965 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 4966 if (N1->getOpcode() == ISD::SELECT) { 4967 SDValue N1_0 = N1->getOperand(0); 4968 SDValue N1_1 = N1->getOperand(1); 4969 SDValue N1_2 = N1->getOperand(2); 4970 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 4971 // Create the actual and node if we can generate good code for it. 4972 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4973 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 4974 N0, N1_0); 4975 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 4976 N1_1, N2); 4977 } 4978 // Otherwise see if we can optimize the "and" to a better pattern. 4979 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 4980 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 4981 N1_1, N2); 4982 } 4983 } 4984 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 4985 if (N2->getOpcode() == ISD::SELECT) { 4986 SDValue N2_0 = N2->getOperand(0); 4987 SDValue N2_1 = N2->getOperand(1); 4988 SDValue N2_2 = N2->getOperand(2); 4989 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 4990 // Create the actual or node if we can generate good code for it. 4991 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4992 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 4993 N0, N2_0); 4994 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 4995 N1, N2_2); 4996 } 4997 // Otherwise see if we can optimize to a better pattern. 4998 if (SDValue Combined = visitORLike(N0, N2_0, N)) 4999 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5000 N1, N2_2); 5001 } 5002 } 5003 } 5004 5005 return SDValue(); 5006 } 5007 5008 static 5009 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5010 SDLoc DL(N); 5011 EVT LoVT, HiVT; 5012 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5013 5014 // Split the inputs. 5015 SDValue Lo, Hi, LL, LH, RL, RH; 5016 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5017 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5018 5019 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5020 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5021 5022 return std::make_pair(Lo, Hi); 5023 } 5024 5025 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5026 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5027 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5028 SDLoc dl(N); 5029 SDValue Cond = N->getOperand(0); 5030 SDValue LHS = N->getOperand(1); 5031 SDValue RHS = N->getOperand(2); 5032 EVT VT = N->getValueType(0); 5033 int NumElems = VT.getVectorNumElements(); 5034 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5035 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5036 Cond.getOpcode() == ISD::BUILD_VECTOR); 5037 5038 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5039 // binary ones here. 5040 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5041 return SDValue(); 5042 5043 // We're sure we have an even number of elements due to the 5044 // concat_vectors we have as arguments to vselect. 5045 // Skip BV elements until we find one that's not an UNDEF 5046 // After we find an UNDEF element, keep looping until we get to half the 5047 // length of the BV and see if all the non-undef nodes are the same. 5048 ConstantSDNode *BottomHalf = nullptr; 5049 for (int i = 0; i < NumElems / 2; ++i) { 5050 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5051 continue; 5052 5053 if (BottomHalf == nullptr) 5054 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5055 else if (Cond->getOperand(i).getNode() != BottomHalf) 5056 return SDValue(); 5057 } 5058 5059 // Do the same for the second half of the BuildVector 5060 ConstantSDNode *TopHalf = nullptr; 5061 for (int i = NumElems / 2; i < NumElems; ++i) { 5062 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5063 continue; 5064 5065 if (TopHalf == nullptr) 5066 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5067 else if (Cond->getOperand(i).getNode() != TopHalf) 5068 return SDValue(); 5069 } 5070 5071 assert(TopHalf && BottomHalf && 5072 "One half of the selector was all UNDEFs and the other was all the " 5073 "same value. This should have been addressed before this function."); 5074 return DAG.getNode( 5075 ISD::CONCAT_VECTORS, dl, VT, 5076 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5077 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5078 } 5079 5080 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5081 5082 if (Level >= AfterLegalizeTypes) 5083 return SDValue(); 5084 5085 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5086 SDValue Mask = MSC->getMask(); 5087 SDValue Data = MSC->getValue(); 5088 SDLoc DL(N); 5089 5090 // If the MSCATTER data type requires splitting and the mask is provided by a 5091 // SETCC, then split both nodes and its operands before legalization. This 5092 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5093 // and enables future optimizations (e.g. min/max pattern matching on X86). 5094 if (Mask.getOpcode() != ISD::SETCC) 5095 return SDValue(); 5096 5097 // Check if any splitting is required. 5098 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5099 TargetLowering::TypeSplitVector) 5100 return SDValue(); 5101 SDValue MaskLo, MaskHi, Lo, Hi; 5102 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5103 5104 EVT LoVT, HiVT; 5105 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5106 5107 SDValue Chain = MSC->getChain(); 5108 5109 EVT MemoryVT = MSC->getMemoryVT(); 5110 unsigned Alignment = MSC->getOriginalAlignment(); 5111 5112 EVT LoMemVT, HiMemVT; 5113 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5114 5115 SDValue DataLo, DataHi; 5116 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5117 5118 SDValue BasePtr = MSC->getBasePtr(); 5119 SDValue IndexLo, IndexHi; 5120 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5121 5122 MachineMemOperand *MMO = DAG.getMachineFunction(). 5123 getMachineMemOperand(MSC->getPointerInfo(), 5124 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5125 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5126 5127 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5128 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5129 DL, OpsLo, MMO); 5130 5131 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5132 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5133 DL, OpsHi, MMO); 5134 5135 AddToWorklist(Lo.getNode()); 5136 AddToWorklist(Hi.getNode()); 5137 5138 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5139 } 5140 5141 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5142 5143 if (Level >= AfterLegalizeTypes) 5144 return SDValue(); 5145 5146 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5147 SDValue Mask = MST->getMask(); 5148 SDValue Data = MST->getValue(); 5149 SDLoc DL(N); 5150 5151 // If the MSTORE data type requires splitting and the mask is provided by a 5152 // SETCC, then split both nodes and its operands before legalization. This 5153 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5154 // and enables future optimizations (e.g. min/max pattern matching on X86). 5155 if (Mask.getOpcode() == ISD::SETCC) { 5156 5157 // Check if any splitting is required. 5158 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5159 TargetLowering::TypeSplitVector) 5160 return SDValue(); 5161 5162 SDValue MaskLo, MaskHi, Lo, Hi; 5163 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5164 5165 EVT LoVT, HiVT; 5166 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5167 5168 SDValue Chain = MST->getChain(); 5169 SDValue Ptr = MST->getBasePtr(); 5170 5171 EVT MemoryVT = MST->getMemoryVT(); 5172 unsigned Alignment = MST->getOriginalAlignment(); 5173 5174 // if Alignment is equal to the vector size, 5175 // take the half of it for the second part 5176 unsigned SecondHalfAlignment = 5177 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5178 Alignment/2 : Alignment; 5179 5180 EVT LoMemVT, HiMemVT; 5181 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5182 5183 SDValue DataLo, DataHi; 5184 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5185 5186 MachineMemOperand *MMO = DAG.getMachineFunction(). 5187 getMachineMemOperand(MST->getPointerInfo(), 5188 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5189 Alignment, MST->getAAInfo(), MST->getRanges()); 5190 5191 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5192 MST->isTruncatingStore()); 5193 5194 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5195 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5196 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5197 5198 MMO = DAG.getMachineFunction(). 5199 getMachineMemOperand(MST->getPointerInfo(), 5200 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5201 SecondHalfAlignment, MST->getAAInfo(), 5202 MST->getRanges()); 5203 5204 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5205 MST->isTruncatingStore()); 5206 5207 AddToWorklist(Lo.getNode()); 5208 AddToWorklist(Hi.getNode()); 5209 5210 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5211 } 5212 return SDValue(); 5213 } 5214 5215 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5216 5217 if (Level >= AfterLegalizeTypes) 5218 return SDValue(); 5219 5220 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5221 SDValue Mask = MGT->getMask(); 5222 SDLoc DL(N); 5223 5224 // If the MGATHER result requires splitting and the mask is provided by a 5225 // SETCC, then split both nodes and its operands before legalization. This 5226 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5227 // and enables future optimizations (e.g. min/max pattern matching on X86). 5228 5229 if (Mask.getOpcode() != ISD::SETCC) 5230 return SDValue(); 5231 5232 EVT VT = N->getValueType(0); 5233 5234 // Check if any splitting is required. 5235 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5236 TargetLowering::TypeSplitVector) 5237 return SDValue(); 5238 5239 SDValue MaskLo, MaskHi, Lo, Hi; 5240 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5241 5242 SDValue Src0 = MGT->getValue(); 5243 SDValue Src0Lo, Src0Hi; 5244 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5245 5246 EVT LoVT, HiVT; 5247 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5248 5249 SDValue Chain = MGT->getChain(); 5250 EVT MemoryVT = MGT->getMemoryVT(); 5251 unsigned Alignment = MGT->getOriginalAlignment(); 5252 5253 EVT LoMemVT, HiMemVT; 5254 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5255 5256 SDValue BasePtr = MGT->getBasePtr(); 5257 SDValue Index = MGT->getIndex(); 5258 SDValue IndexLo, IndexHi; 5259 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5260 5261 MachineMemOperand *MMO = DAG.getMachineFunction(). 5262 getMachineMemOperand(MGT->getPointerInfo(), 5263 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5264 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5265 5266 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5267 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5268 MMO); 5269 5270 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5271 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5272 MMO); 5273 5274 AddToWorklist(Lo.getNode()); 5275 AddToWorklist(Hi.getNode()); 5276 5277 // Build a factor node to remember that this load is independent of the 5278 // other one. 5279 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5280 Hi.getValue(1)); 5281 5282 // Legalized the chain result - switch anything that used the old chain to 5283 // use the new one. 5284 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5285 5286 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5287 5288 SDValue RetOps[] = { GatherRes, Chain }; 5289 return DAG.getMergeValues(RetOps, DL); 5290 } 5291 5292 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5293 5294 if (Level >= AfterLegalizeTypes) 5295 return SDValue(); 5296 5297 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5298 SDValue Mask = MLD->getMask(); 5299 SDLoc DL(N); 5300 5301 // If the MLOAD result requires splitting and the mask is provided by a 5302 // SETCC, then split both nodes and its operands before legalization. This 5303 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5304 // and enables future optimizations (e.g. min/max pattern matching on X86). 5305 5306 if (Mask.getOpcode() == ISD::SETCC) { 5307 EVT VT = N->getValueType(0); 5308 5309 // Check if any splitting is required. 5310 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5311 TargetLowering::TypeSplitVector) 5312 return SDValue(); 5313 5314 SDValue MaskLo, MaskHi, Lo, Hi; 5315 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5316 5317 SDValue Src0 = MLD->getSrc0(); 5318 SDValue Src0Lo, Src0Hi; 5319 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5320 5321 EVT LoVT, HiVT; 5322 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5323 5324 SDValue Chain = MLD->getChain(); 5325 SDValue Ptr = MLD->getBasePtr(); 5326 EVT MemoryVT = MLD->getMemoryVT(); 5327 unsigned Alignment = MLD->getOriginalAlignment(); 5328 5329 // if Alignment is equal to the vector size, 5330 // take the half of it for the second part 5331 unsigned SecondHalfAlignment = 5332 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5333 Alignment/2 : Alignment; 5334 5335 EVT LoMemVT, HiMemVT; 5336 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5337 5338 MachineMemOperand *MMO = DAG.getMachineFunction(). 5339 getMachineMemOperand(MLD->getPointerInfo(), 5340 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5341 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5342 5343 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5344 ISD::NON_EXTLOAD); 5345 5346 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5347 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5348 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5349 5350 MMO = DAG.getMachineFunction(). 5351 getMachineMemOperand(MLD->getPointerInfo(), 5352 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5353 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5354 5355 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5356 ISD::NON_EXTLOAD); 5357 5358 AddToWorklist(Lo.getNode()); 5359 AddToWorklist(Hi.getNode()); 5360 5361 // Build a factor node to remember that this load is independent of the 5362 // other one. 5363 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5364 Hi.getValue(1)); 5365 5366 // Legalized the chain result - switch anything that used the old chain to 5367 // use the new one. 5368 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5369 5370 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5371 5372 SDValue RetOps[] = { LoadRes, Chain }; 5373 return DAG.getMergeValues(RetOps, DL); 5374 } 5375 return SDValue(); 5376 } 5377 5378 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5379 SDValue N0 = N->getOperand(0); 5380 SDValue N1 = N->getOperand(1); 5381 SDValue N2 = N->getOperand(2); 5382 SDLoc DL(N); 5383 5384 // Canonicalize integer abs. 5385 // vselect (setg[te] X, 0), X, -X -> 5386 // vselect (setgt X, -1), X, -X -> 5387 // vselect (setl[te] X, 0), -X, X -> 5388 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5389 if (N0.getOpcode() == ISD::SETCC) { 5390 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5391 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5392 bool isAbs = false; 5393 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5394 5395 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5396 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5397 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5398 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5399 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5400 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5401 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5402 5403 if (isAbs) { 5404 EVT VT = LHS.getValueType(); 5405 SDValue Shift = DAG.getNode( 5406 ISD::SRA, DL, VT, LHS, 5407 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5408 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5409 AddToWorklist(Shift.getNode()); 5410 AddToWorklist(Add.getNode()); 5411 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5412 } 5413 } 5414 5415 if (SimplifySelectOps(N, N1, N2)) 5416 return SDValue(N, 0); // Don't revisit N. 5417 5418 // If the VSELECT result requires splitting and the mask is provided by a 5419 // SETCC, then split both nodes and its operands before legalization. This 5420 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5421 // and enables future optimizations (e.g. min/max pattern matching on X86). 5422 if (N0.getOpcode() == ISD::SETCC) { 5423 EVT VT = N->getValueType(0); 5424 5425 // Check if any splitting is required. 5426 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5427 TargetLowering::TypeSplitVector) 5428 return SDValue(); 5429 5430 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5431 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5432 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5433 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5434 5435 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5436 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5437 5438 // Add the new VSELECT nodes to the work list in case they need to be split 5439 // again. 5440 AddToWorklist(Lo.getNode()); 5441 AddToWorklist(Hi.getNode()); 5442 5443 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5444 } 5445 5446 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5447 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5448 return N1; 5449 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5450 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5451 return N2; 5452 5453 // The ConvertSelectToConcatVector function is assuming both the above 5454 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5455 // and addressed. 5456 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5457 N2.getOpcode() == ISD::CONCAT_VECTORS && 5458 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5459 SDValue CV = ConvertSelectToConcatVector(N, DAG); 5460 if (CV.getNode()) 5461 return CV; 5462 } 5463 5464 return SDValue(); 5465 } 5466 5467 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5468 SDValue N0 = N->getOperand(0); 5469 SDValue N1 = N->getOperand(1); 5470 SDValue N2 = N->getOperand(2); 5471 SDValue N3 = N->getOperand(3); 5472 SDValue N4 = N->getOperand(4); 5473 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5474 5475 // fold select_cc lhs, rhs, x, x, cc -> x 5476 if (N2 == N3) 5477 return N2; 5478 5479 // Determine if the condition we're dealing with is constant 5480 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5481 N0, N1, CC, SDLoc(N), false); 5482 if (SCC.getNode()) { 5483 AddToWorklist(SCC.getNode()); 5484 5485 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5486 if (!SCCC->isNullValue()) 5487 return N2; // cond always true -> true val 5488 else 5489 return N3; // cond always false -> false val 5490 } else if (SCC->getOpcode() == ISD::UNDEF) { 5491 // When the condition is UNDEF, just return the first operand. This is 5492 // coherent the DAG creation, no setcc node is created in this case 5493 return N2; 5494 } else if (SCC.getOpcode() == ISD::SETCC) { 5495 // Fold to a simpler select_cc 5496 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5497 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5498 SCC.getOperand(2)); 5499 } 5500 } 5501 5502 // If we can fold this based on the true/false value, do so. 5503 if (SimplifySelectOps(N, N2, N3)) 5504 return SDValue(N, 0); // Don't revisit N. 5505 5506 // fold select_cc into other things, such as min/max/abs 5507 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5508 } 5509 5510 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5511 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5512 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5513 SDLoc(N)); 5514 } 5515 5516 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 5517 // dag node into a ConstantSDNode or a build_vector of constants. 5518 // This function is called by the DAGCombiner when visiting sext/zext/aext 5519 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5520 // Vector extends are not folded if operations are legal; this is to 5521 // avoid introducing illegal build_vector dag nodes. 5522 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5523 SelectionDAG &DAG, bool LegalTypes, 5524 bool LegalOperations) { 5525 unsigned Opcode = N->getOpcode(); 5526 SDValue N0 = N->getOperand(0); 5527 EVT VT = N->getValueType(0); 5528 5529 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5530 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 5531 5532 // fold (sext c1) -> c1 5533 // fold (zext c1) -> c1 5534 // fold (aext c1) -> c1 5535 if (isa<ConstantSDNode>(N0)) 5536 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5537 5538 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5539 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5540 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5541 EVT SVT = VT.getScalarType(); 5542 if (!(VT.isVector() && 5543 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5544 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5545 return nullptr; 5546 5547 // We can fold this node into a build_vector. 5548 unsigned VTBits = SVT.getSizeInBits(); 5549 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5550 unsigned ShAmt = VTBits - EVTBits; 5551 SmallVector<SDValue, 8> Elts; 5552 unsigned NumElts = N0->getNumOperands(); 5553 SDLoc DL(N); 5554 5555 for (unsigned i=0; i != NumElts; ++i) { 5556 SDValue Op = N0->getOperand(i); 5557 if (Op->getOpcode() == ISD::UNDEF) { 5558 Elts.push_back(DAG.getUNDEF(SVT)); 5559 continue; 5560 } 5561 5562 SDLoc DL(Op); 5563 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5564 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5565 if (Opcode == ISD::SIGN_EXTEND) 5566 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5567 DL, SVT)); 5568 else 5569 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 5570 DL, SVT)); 5571 } 5572 5573 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5574 } 5575 5576 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5577 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5578 // transformation. Returns true if extension are possible and the above 5579 // mentioned transformation is profitable. 5580 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5581 unsigned ExtOpc, 5582 SmallVectorImpl<SDNode *> &ExtendNodes, 5583 const TargetLowering &TLI) { 5584 bool HasCopyToRegUses = false; 5585 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5586 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5587 UE = N0.getNode()->use_end(); 5588 UI != UE; ++UI) { 5589 SDNode *User = *UI; 5590 if (User == N) 5591 continue; 5592 if (UI.getUse().getResNo() != N0.getResNo()) 5593 continue; 5594 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5595 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5596 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5597 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5598 // Sign bits will be lost after a zext. 5599 return false; 5600 bool Add = false; 5601 for (unsigned i = 0; i != 2; ++i) { 5602 SDValue UseOp = User->getOperand(i); 5603 if (UseOp == N0) 5604 continue; 5605 if (!isa<ConstantSDNode>(UseOp)) 5606 return false; 5607 Add = true; 5608 } 5609 if (Add) 5610 ExtendNodes.push_back(User); 5611 continue; 5612 } 5613 // If truncates aren't free and there are users we can't 5614 // extend, it isn't worthwhile. 5615 if (!isTruncFree) 5616 return false; 5617 // Remember if this value is live-out. 5618 if (User->getOpcode() == ISD::CopyToReg) 5619 HasCopyToRegUses = true; 5620 } 5621 5622 if (HasCopyToRegUses) { 5623 bool BothLiveOut = false; 5624 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5625 UI != UE; ++UI) { 5626 SDUse &Use = UI.getUse(); 5627 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5628 BothLiveOut = true; 5629 break; 5630 } 5631 } 5632 if (BothLiveOut) 5633 // Both unextended and extended values are live out. There had better be 5634 // a good reason for the transformation. 5635 return ExtendNodes.size(); 5636 } 5637 return true; 5638 } 5639 5640 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5641 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5642 ISD::NodeType ExtType) { 5643 // Extend SetCC uses if necessary. 5644 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5645 SDNode *SetCC = SetCCs[i]; 5646 SmallVector<SDValue, 4> Ops; 5647 5648 for (unsigned j = 0; j != 2; ++j) { 5649 SDValue SOp = SetCC->getOperand(j); 5650 if (SOp == Trunc) 5651 Ops.push_back(ExtLoad); 5652 else 5653 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5654 } 5655 5656 Ops.push_back(SetCC->getOperand(2)); 5657 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5658 } 5659 } 5660 5661 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5662 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5663 SDValue N0 = N->getOperand(0); 5664 EVT DstVT = N->getValueType(0); 5665 EVT SrcVT = N0.getValueType(); 5666 5667 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5668 N->getOpcode() == ISD::ZERO_EXTEND) && 5669 "Unexpected node type (not an extend)!"); 5670 5671 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5672 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5673 // (v8i32 (sext (v8i16 (load x)))) 5674 // into: 5675 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5676 // (v4i32 (sextload (x + 16))))) 5677 // Where uses of the original load, i.e.: 5678 // (v8i16 (load x)) 5679 // are replaced with: 5680 // (v8i16 (truncate 5681 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5682 // (v4i32 (sextload (x + 16))))))) 5683 // 5684 // This combine is only applicable to illegal, but splittable, vectors. 5685 // All legal types, and illegal non-vector types, are handled elsewhere. 5686 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5687 // 5688 if (N0->getOpcode() != ISD::LOAD) 5689 return SDValue(); 5690 5691 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5692 5693 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5694 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5695 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5696 return SDValue(); 5697 5698 SmallVector<SDNode *, 4> SetCCs; 5699 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5700 return SDValue(); 5701 5702 ISD::LoadExtType ExtType = 5703 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5704 5705 // Try to split the vector types to get down to legal types. 5706 EVT SplitSrcVT = SrcVT; 5707 EVT SplitDstVT = DstVT; 5708 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5709 SplitSrcVT.getVectorNumElements() > 1) { 5710 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5711 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5712 } 5713 5714 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5715 return SDValue(); 5716 5717 SDLoc DL(N); 5718 const unsigned NumSplits = 5719 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5720 const unsigned Stride = SplitSrcVT.getStoreSize(); 5721 SmallVector<SDValue, 4> Loads; 5722 SmallVector<SDValue, 4> Chains; 5723 5724 SDValue BasePtr = LN0->getBasePtr(); 5725 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5726 const unsigned Offset = Idx * Stride; 5727 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5728 5729 SDValue SplitLoad = DAG.getExtLoad( 5730 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5731 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5732 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5733 Align, LN0->getAAInfo()); 5734 5735 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5736 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5737 5738 Loads.push_back(SplitLoad.getValue(0)); 5739 Chains.push_back(SplitLoad.getValue(1)); 5740 } 5741 5742 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5743 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5744 5745 CombineTo(N, NewValue); 5746 5747 // Replace uses of the original load (before extension) 5748 // with a truncate of the concatenated sextloaded vectors. 5749 SDValue Trunc = 5750 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5751 CombineTo(N0.getNode(), Trunc, NewChain); 5752 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5753 (ISD::NodeType)N->getOpcode()); 5754 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5755 } 5756 5757 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5758 SDValue N0 = N->getOperand(0); 5759 EVT VT = N->getValueType(0); 5760 5761 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5762 LegalOperations)) 5763 return SDValue(Res, 0); 5764 5765 // fold (sext (sext x)) -> (sext x) 5766 // fold (sext (aext x)) -> (sext x) 5767 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5768 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5769 N0.getOperand(0)); 5770 5771 if (N0.getOpcode() == ISD::TRUNCATE) { 5772 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5773 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5774 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5775 if (NarrowLoad.getNode()) { 5776 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5777 if (NarrowLoad.getNode() != N0.getNode()) { 5778 CombineTo(N0.getNode(), NarrowLoad); 5779 // CombineTo deleted the truncate, if needed, but not what's under it. 5780 AddToWorklist(oye); 5781 } 5782 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5783 } 5784 5785 // See if the value being truncated is already sign extended. If so, just 5786 // eliminate the trunc/sext pair. 5787 SDValue Op = N0.getOperand(0); 5788 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5789 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5790 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5791 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5792 5793 if (OpBits == DestBits) { 5794 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5795 // bits, it is already ready. 5796 if (NumSignBits > DestBits-MidBits) 5797 return Op; 5798 } else if (OpBits < DestBits) { 5799 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5800 // bits, just sext from i32. 5801 if (NumSignBits > OpBits-MidBits) 5802 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5803 } else { 5804 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5805 // bits, just truncate to i32. 5806 if (NumSignBits > OpBits-MidBits) 5807 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5808 } 5809 5810 // fold (sext (truncate x)) -> (sextinreg x). 5811 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5812 N0.getValueType())) { 5813 if (OpBits < DestBits) 5814 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5815 else if (OpBits > DestBits) 5816 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5817 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5818 DAG.getValueType(N0.getValueType())); 5819 } 5820 } 5821 5822 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5823 // Only generate vector extloads when 1) they're legal, and 2) they are 5824 // deemed desirable by the target. 5825 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5826 ((!LegalOperations && !VT.isVector() && 5827 !cast<LoadSDNode>(N0)->isVolatile()) || 5828 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5829 bool DoXform = true; 5830 SmallVector<SDNode*, 4> SetCCs; 5831 if (!N0.hasOneUse()) 5832 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5833 if (VT.isVector()) 5834 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5835 if (DoXform) { 5836 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5837 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5838 LN0->getChain(), 5839 LN0->getBasePtr(), N0.getValueType(), 5840 LN0->getMemOperand()); 5841 CombineTo(N, ExtLoad); 5842 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5843 N0.getValueType(), ExtLoad); 5844 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5845 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5846 ISD::SIGN_EXTEND); 5847 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5848 } 5849 } 5850 5851 // fold (sext (load x)) to multiple smaller sextloads. 5852 // Only on illegal but splittable vectors. 5853 if (SDValue ExtLoad = CombineExtLoad(N)) 5854 return ExtLoad; 5855 5856 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5857 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5858 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5859 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5860 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5861 EVT MemVT = LN0->getMemoryVT(); 5862 if ((!LegalOperations && !LN0->isVolatile()) || 5863 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5864 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5865 LN0->getChain(), 5866 LN0->getBasePtr(), MemVT, 5867 LN0->getMemOperand()); 5868 CombineTo(N, ExtLoad); 5869 CombineTo(N0.getNode(), 5870 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5871 N0.getValueType(), ExtLoad), 5872 ExtLoad.getValue(1)); 5873 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5874 } 5875 } 5876 5877 // fold (sext (and/or/xor (load x), cst)) -> 5878 // (and/or/xor (sextload x), (sext cst)) 5879 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5880 N0.getOpcode() == ISD::XOR) && 5881 isa<LoadSDNode>(N0.getOperand(0)) && 5882 N0.getOperand(1).getOpcode() == ISD::Constant && 5883 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5884 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5885 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5886 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5887 bool DoXform = true; 5888 SmallVector<SDNode*, 4> SetCCs; 5889 if (!N0.hasOneUse()) 5890 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5891 SetCCs, TLI); 5892 if (DoXform) { 5893 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5894 LN0->getChain(), LN0->getBasePtr(), 5895 LN0->getMemoryVT(), 5896 LN0->getMemOperand()); 5897 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5898 Mask = Mask.sext(VT.getSizeInBits()); 5899 SDLoc DL(N); 5900 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 5901 ExtLoad, DAG.getConstant(Mask, DL, VT)); 5902 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5903 SDLoc(N0.getOperand(0)), 5904 N0.getOperand(0).getValueType(), ExtLoad); 5905 CombineTo(N, And); 5906 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5907 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 5908 ISD::SIGN_EXTEND); 5909 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5910 } 5911 } 5912 } 5913 5914 if (N0.getOpcode() == ISD::SETCC) { 5915 EVT N0VT = N0.getOperand(0).getValueType(); 5916 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5917 // Only do this before legalize for now. 5918 if (VT.isVector() && !LegalOperations && 5919 TLI.getBooleanContents(N0VT) == 5920 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5921 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5922 // of the same size as the compared operands. Only optimize sext(setcc()) 5923 // if this is the case. 5924 EVT SVT = getSetCCResultType(N0VT); 5925 5926 // We know that the # elements of the results is the same as the 5927 // # elements of the compare (and the # elements of the compare result 5928 // for that matter). Check to see that they are the same size. If so, 5929 // we know that the element size of the sext'd result matches the 5930 // element size of the compare operands. 5931 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5932 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5933 N0.getOperand(1), 5934 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5935 5936 // If the desired elements are smaller or larger than the source 5937 // elements we can use a matching integer vector type and then 5938 // truncate/sign extend 5939 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5940 if (SVT == MatchingVectorType) { 5941 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5942 N0.getOperand(0), N0.getOperand(1), 5943 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5944 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5945 } 5946 } 5947 5948 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5949 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5950 SDLoc DL(N); 5951 SDValue NegOne = 5952 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 5953 SDValue SCC = 5954 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 5955 NegOne, DAG.getConstant(0, DL, VT), 5956 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5957 if (SCC.getNode()) return SCC; 5958 5959 if (!VT.isVector()) { 5960 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5961 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5962 SDLoc DL(N); 5963 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5964 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 5965 N0.getOperand(0), N0.getOperand(1), CC); 5966 return DAG.getSelect(DL, VT, SetCC, 5967 NegOne, DAG.getConstant(0, DL, VT)); 5968 } 5969 } 5970 } 5971 5972 // fold (sext x) -> (zext x) if the sign bit is known zero. 5973 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5974 DAG.SignBitIsZero(N0)) 5975 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5976 5977 return SDValue(); 5978 } 5979 5980 // isTruncateOf - If N is a truncate of some other value, return true, record 5981 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5982 // This function computes KnownZero to avoid a duplicated call to 5983 // computeKnownBits in the caller. 5984 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5985 APInt &KnownZero) { 5986 APInt KnownOne; 5987 if (N->getOpcode() == ISD::TRUNCATE) { 5988 Op = N->getOperand(0); 5989 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5990 return true; 5991 } 5992 5993 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5994 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5995 return false; 5996 5997 SDValue Op0 = N->getOperand(0); 5998 SDValue Op1 = N->getOperand(1); 5999 assert(Op0.getValueType() == Op1.getValueType()); 6000 6001 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 6002 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 6003 if (COp0 && COp0->isNullValue()) 6004 Op = Op1; 6005 else if (COp1 && COp1->isNullValue()) 6006 Op = Op0; 6007 else 6008 return false; 6009 6010 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6011 6012 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6013 return false; 6014 6015 return true; 6016 } 6017 6018 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6019 SDValue N0 = N->getOperand(0); 6020 EVT VT = N->getValueType(0); 6021 6022 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6023 LegalOperations)) 6024 return SDValue(Res, 0); 6025 6026 // fold (zext (zext x)) -> (zext x) 6027 // fold (zext (aext x)) -> (zext x) 6028 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6029 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6030 N0.getOperand(0)); 6031 6032 // fold (zext (truncate x)) -> (zext x) or 6033 // (zext (truncate x)) -> (truncate x) 6034 // This is valid when the truncated bits of x are already zero. 6035 // FIXME: We should extend this to work for vectors too. 6036 SDValue Op; 6037 APInt KnownZero; 6038 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6039 APInt TruncatedBits = 6040 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6041 APInt(Op.getValueSizeInBits(), 0) : 6042 APInt::getBitsSet(Op.getValueSizeInBits(), 6043 N0.getValueSizeInBits(), 6044 std::min(Op.getValueSizeInBits(), 6045 VT.getSizeInBits())); 6046 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6047 if (VT.bitsGT(Op.getValueType())) 6048 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6049 if (VT.bitsLT(Op.getValueType())) 6050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6051 6052 return Op; 6053 } 6054 } 6055 6056 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6057 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6058 if (N0.getOpcode() == ISD::TRUNCATE) { 6059 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6060 if (NarrowLoad.getNode()) { 6061 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6062 if (NarrowLoad.getNode() != N0.getNode()) { 6063 CombineTo(N0.getNode(), NarrowLoad); 6064 // CombineTo deleted the truncate, if needed, but not what's under it. 6065 AddToWorklist(oye); 6066 } 6067 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6068 } 6069 } 6070 6071 // fold (zext (truncate x)) -> (and x, mask) 6072 if (N0.getOpcode() == ISD::TRUNCATE && 6073 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 6074 6075 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6076 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6077 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6078 if (NarrowLoad.getNode()) { 6079 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6080 if (NarrowLoad.getNode() != N0.getNode()) { 6081 CombineTo(N0.getNode(), NarrowLoad); 6082 // CombineTo deleted the truncate, if needed, but not what's under it. 6083 AddToWorklist(oye); 6084 } 6085 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6086 } 6087 6088 SDValue Op = N0.getOperand(0); 6089 if (Op.getValueType().bitsLT(VT)) { 6090 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6091 AddToWorklist(Op.getNode()); 6092 } else if (Op.getValueType().bitsGT(VT)) { 6093 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6094 AddToWorklist(Op.getNode()); 6095 } 6096 return DAG.getZeroExtendInReg(Op, SDLoc(N), 6097 N0.getValueType().getScalarType()); 6098 } 6099 6100 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6101 // if either of the casts is not free. 6102 if (N0.getOpcode() == ISD::AND && 6103 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6104 N0.getOperand(1).getOpcode() == ISD::Constant && 6105 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6106 N0.getValueType()) || 6107 !TLI.isZExtFree(N0.getValueType(), VT))) { 6108 SDValue X = N0.getOperand(0).getOperand(0); 6109 if (X.getValueType().bitsLT(VT)) { 6110 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6111 } else if (X.getValueType().bitsGT(VT)) { 6112 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6113 } 6114 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6115 Mask = Mask.zext(VT.getSizeInBits()); 6116 SDLoc DL(N); 6117 return DAG.getNode(ISD::AND, DL, VT, 6118 X, DAG.getConstant(Mask, DL, VT)); 6119 } 6120 6121 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6122 // Only generate vector extloads when 1) they're legal, and 2) they are 6123 // deemed desirable by the target. 6124 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6125 ((!LegalOperations && !VT.isVector() && 6126 !cast<LoadSDNode>(N0)->isVolatile()) || 6127 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6128 bool DoXform = true; 6129 SmallVector<SDNode*, 4> SetCCs; 6130 if (!N0.hasOneUse()) 6131 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6132 if (VT.isVector()) 6133 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6134 if (DoXform) { 6135 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6136 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6137 LN0->getChain(), 6138 LN0->getBasePtr(), N0.getValueType(), 6139 LN0->getMemOperand()); 6140 CombineTo(N, ExtLoad); 6141 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6142 N0.getValueType(), ExtLoad); 6143 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6144 6145 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6146 ISD::ZERO_EXTEND); 6147 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6148 } 6149 } 6150 6151 // fold (zext (load x)) to multiple smaller zextloads. 6152 // Only on illegal but splittable vectors. 6153 if (SDValue ExtLoad = CombineExtLoad(N)) 6154 return ExtLoad; 6155 6156 // fold (zext (and/or/xor (load x), cst)) -> 6157 // (and/or/xor (zextload x), (zext cst)) 6158 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6159 N0.getOpcode() == ISD::XOR) && 6160 isa<LoadSDNode>(N0.getOperand(0)) && 6161 N0.getOperand(1).getOpcode() == ISD::Constant && 6162 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6163 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6164 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6165 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6166 bool DoXform = true; 6167 SmallVector<SDNode*, 4> SetCCs; 6168 if (!N0.hasOneUse()) 6169 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 6170 SetCCs, TLI); 6171 if (DoXform) { 6172 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6173 LN0->getChain(), LN0->getBasePtr(), 6174 LN0->getMemoryVT(), 6175 LN0->getMemOperand()); 6176 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6177 Mask = Mask.zext(VT.getSizeInBits()); 6178 SDLoc DL(N); 6179 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6180 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6181 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6182 SDLoc(N0.getOperand(0)), 6183 N0.getOperand(0).getValueType(), ExtLoad); 6184 CombineTo(N, And); 6185 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6186 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6187 ISD::ZERO_EXTEND); 6188 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6189 } 6190 } 6191 } 6192 6193 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6194 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6195 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6196 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6197 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6198 EVT MemVT = LN0->getMemoryVT(); 6199 if ((!LegalOperations && !LN0->isVolatile()) || 6200 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6201 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6202 LN0->getChain(), 6203 LN0->getBasePtr(), MemVT, 6204 LN0->getMemOperand()); 6205 CombineTo(N, ExtLoad); 6206 CombineTo(N0.getNode(), 6207 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6208 ExtLoad), 6209 ExtLoad.getValue(1)); 6210 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6211 } 6212 } 6213 6214 if (N0.getOpcode() == ISD::SETCC) { 6215 if (!LegalOperations && VT.isVector() && 6216 N0.getValueType().getVectorElementType() == MVT::i1) { 6217 EVT N0VT = N0.getOperand(0).getValueType(); 6218 if (getSetCCResultType(N0VT) == N0.getValueType()) 6219 return SDValue(); 6220 6221 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6222 // Only do this before legalize for now. 6223 EVT EltVT = VT.getVectorElementType(); 6224 SDLoc DL(N); 6225 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6226 DAG.getConstant(1, DL, EltVT)); 6227 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6228 // We know that the # elements of the results is the same as the 6229 // # elements of the compare (and the # elements of the compare result 6230 // for that matter). Check to see that they are the same size. If so, 6231 // we know that the element size of the sext'd result matches the 6232 // element size of the compare operands. 6233 return DAG.getNode(ISD::AND, DL, VT, 6234 DAG.getSetCC(DL, VT, N0.getOperand(0), 6235 N0.getOperand(1), 6236 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6237 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6238 OneOps)); 6239 6240 // If the desired elements are smaller or larger than the source 6241 // elements we can use a matching integer vector type and then 6242 // truncate/sign extend 6243 EVT MatchingElementType = 6244 EVT::getIntegerVT(*DAG.getContext(), 6245 N0VT.getScalarType().getSizeInBits()); 6246 EVT MatchingVectorType = 6247 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6248 N0VT.getVectorNumElements()); 6249 SDValue VsetCC = 6250 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6251 N0.getOperand(1), 6252 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6253 return DAG.getNode(ISD::AND, DL, VT, 6254 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6255 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6256 } 6257 6258 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6259 SDLoc DL(N); 6260 SDValue SCC = 6261 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6262 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6263 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6264 if (SCC.getNode()) return SCC; 6265 } 6266 6267 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6268 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6269 isa<ConstantSDNode>(N0.getOperand(1)) && 6270 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6271 N0.hasOneUse()) { 6272 SDValue ShAmt = N0.getOperand(1); 6273 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6274 if (N0.getOpcode() == ISD::SHL) { 6275 SDValue InnerZExt = N0.getOperand(0); 6276 // If the original shl may be shifting out bits, do not perform this 6277 // transformation. 6278 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6279 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6280 if (ShAmtVal > KnownZeroBits) 6281 return SDValue(); 6282 } 6283 6284 SDLoc DL(N); 6285 6286 // Ensure that the shift amount is wide enough for the shifted value. 6287 if (VT.getSizeInBits() >= 256) 6288 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6289 6290 return DAG.getNode(N0.getOpcode(), DL, VT, 6291 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6292 ShAmt); 6293 } 6294 6295 return SDValue(); 6296 } 6297 6298 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6299 SDValue N0 = N->getOperand(0); 6300 EVT VT = N->getValueType(0); 6301 6302 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6303 LegalOperations)) 6304 return SDValue(Res, 0); 6305 6306 // fold (aext (aext x)) -> (aext x) 6307 // fold (aext (zext x)) -> (zext x) 6308 // fold (aext (sext x)) -> (sext x) 6309 if (N0.getOpcode() == ISD::ANY_EXTEND || 6310 N0.getOpcode() == ISD::ZERO_EXTEND || 6311 N0.getOpcode() == ISD::SIGN_EXTEND) 6312 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6313 6314 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6315 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6316 if (N0.getOpcode() == ISD::TRUNCATE) { 6317 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6318 if (NarrowLoad.getNode()) { 6319 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6320 if (NarrowLoad.getNode() != N0.getNode()) { 6321 CombineTo(N0.getNode(), NarrowLoad); 6322 // CombineTo deleted the truncate, if needed, but not what's under it. 6323 AddToWorklist(oye); 6324 } 6325 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6326 } 6327 } 6328 6329 // fold (aext (truncate x)) 6330 if (N0.getOpcode() == ISD::TRUNCATE) { 6331 SDValue TruncOp = N0.getOperand(0); 6332 if (TruncOp.getValueType() == VT) 6333 return TruncOp; // x iff x size == zext size. 6334 if (TruncOp.getValueType().bitsGT(VT)) 6335 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6336 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6337 } 6338 6339 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6340 // if the trunc is not free. 6341 if (N0.getOpcode() == ISD::AND && 6342 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6343 N0.getOperand(1).getOpcode() == ISD::Constant && 6344 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6345 N0.getValueType())) { 6346 SDValue X = N0.getOperand(0).getOperand(0); 6347 if (X.getValueType().bitsLT(VT)) { 6348 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6349 } else if (X.getValueType().bitsGT(VT)) { 6350 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6351 } 6352 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6353 Mask = Mask.zext(VT.getSizeInBits()); 6354 SDLoc DL(N); 6355 return DAG.getNode(ISD::AND, DL, VT, 6356 X, DAG.getConstant(Mask, DL, VT)); 6357 } 6358 6359 // fold (aext (load x)) -> (aext (truncate (extload x))) 6360 // None of the supported targets knows how to perform load and any_ext 6361 // on vectors in one instruction. We only perform this transformation on 6362 // scalars. 6363 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6364 ISD::isUNINDEXEDLoad(N0.getNode()) && 6365 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6366 bool DoXform = true; 6367 SmallVector<SDNode*, 4> SetCCs; 6368 if (!N0.hasOneUse()) 6369 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6370 if (DoXform) { 6371 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6372 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6373 LN0->getChain(), 6374 LN0->getBasePtr(), N0.getValueType(), 6375 LN0->getMemOperand()); 6376 CombineTo(N, ExtLoad); 6377 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6378 N0.getValueType(), ExtLoad); 6379 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6380 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6381 ISD::ANY_EXTEND); 6382 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6383 } 6384 } 6385 6386 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6387 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6388 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6389 if (N0.getOpcode() == ISD::LOAD && 6390 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6391 N0.hasOneUse()) { 6392 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6393 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6394 EVT MemVT = LN0->getMemoryVT(); 6395 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6396 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6397 VT, LN0->getChain(), LN0->getBasePtr(), 6398 MemVT, LN0->getMemOperand()); 6399 CombineTo(N, ExtLoad); 6400 CombineTo(N0.getNode(), 6401 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6402 N0.getValueType(), ExtLoad), 6403 ExtLoad.getValue(1)); 6404 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6405 } 6406 } 6407 6408 if (N0.getOpcode() == ISD::SETCC) { 6409 // For vectors: 6410 // aext(setcc) -> vsetcc 6411 // aext(setcc) -> truncate(vsetcc) 6412 // aext(setcc) -> aext(vsetcc) 6413 // Only do this before legalize for now. 6414 if (VT.isVector() && !LegalOperations) { 6415 EVT N0VT = N0.getOperand(0).getValueType(); 6416 // We know that the # elements of the results is the same as the 6417 // # elements of the compare (and the # elements of the compare result 6418 // for that matter). Check to see that they are the same size. If so, 6419 // we know that the element size of the sext'd result matches the 6420 // element size of the compare operands. 6421 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6422 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6423 N0.getOperand(1), 6424 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6425 // If the desired elements are smaller or larger than the source 6426 // elements we can use a matching integer vector type and then 6427 // truncate/any extend 6428 else { 6429 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6430 SDValue VsetCC = 6431 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6432 N0.getOperand(1), 6433 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6434 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6435 } 6436 } 6437 6438 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6439 SDLoc DL(N); 6440 SDValue SCC = 6441 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6442 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6443 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6444 if (SCC.getNode()) 6445 return SCC; 6446 } 6447 6448 return SDValue(); 6449 } 6450 6451 /// See if the specified operand can be simplified with the knowledge that only 6452 /// the bits specified by Mask are used. If so, return the simpler operand, 6453 /// otherwise return a null SDValue. 6454 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6455 switch (V.getOpcode()) { 6456 default: break; 6457 case ISD::Constant: { 6458 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6459 assert(CV && "Const value should be ConstSDNode."); 6460 const APInt &CVal = CV->getAPIntValue(); 6461 APInt NewVal = CVal & Mask; 6462 if (NewVal != CVal) 6463 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6464 break; 6465 } 6466 case ISD::OR: 6467 case ISD::XOR: 6468 // If the LHS or RHS don't contribute bits to the or, drop them. 6469 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6470 return V.getOperand(1); 6471 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6472 return V.getOperand(0); 6473 break; 6474 case ISD::SRL: 6475 // Only look at single-use SRLs. 6476 if (!V.getNode()->hasOneUse()) 6477 break; 6478 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 6479 // See if we can recursively simplify the LHS. 6480 unsigned Amt = RHSC->getZExtValue(); 6481 6482 // Watch out for shift count overflow though. 6483 if (Amt >= Mask.getBitWidth()) break; 6484 APInt NewMask = Mask << Amt; 6485 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 6486 if (SimplifyLHS.getNode()) 6487 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6488 SimplifyLHS, V.getOperand(1)); 6489 } 6490 } 6491 return SDValue(); 6492 } 6493 6494 /// If the result of a wider load is shifted to right of N bits and then 6495 /// truncated to a narrower type and where N is a multiple of number of bits of 6496 /// the narrower type, transform it to a narrower load from address + N / num of 6497 /// bits of new type. If the result is to be extended, also fold the extension 6498 /// to form a extending load. 6499 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6500 unsigned Opc = N->getOpcode(); 6501 6502 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6503 SDValue N0 = N->getOperand(0); 6504 EVT VT = N->getValueType(0); 6505 EVT ExtVT = VT; 6506 6507 // This transformation isn't valid for vector loads. 6508 if (VT.isVector()) 6509 return SDValue(); 6510 6511 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6512 // extended to VT. 6513 if (Opc == ISD::SIGN_EXTEND_INREG) { 6514 ExtType = ISD::SEXTLOAD; 6515 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6516 } else if (Opc == ISD::SRL) { 6517 // Another special-case: SRL is basically zero-extending a narrower value. 6518 ExtType = ISD::ZEXTLOAD; 6519 N0 = SDValue(N, 0); 6520 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6521 if (!N01) return SDValue(); 6522 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6523 VT.getSizeInBits() - N01->getZExtValue()); 6524 } 6525 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6526 return SDValue(); 6527 6528 unsigned EVTBits = ExtVT.getSizeInBits(); 6529 6530 // Do not generate loads of non-round integer types since these can 6531 // be expensive (and would be wrong if the type is not byte sized). 6532 if (!ExtVT.isRound()) 6533 return SDValue(); 6534 6535 unsigned ShAmt = 0; 6536 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6537 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6538 ShAmt = N01->getZExtValue(); 6539 // Is the shift amount a multiple of size of VT? 6540 if ((ShAmt & (EVTBits-1)) == 0) { 6541 N0 = N0.getOperand(0); 6542 // Is the load width a multiple of size of VT? 6543 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6544 return SDValue(); 6545 } 6546 6547 // At this point, we must have a load or else we can't do the transform. 6548 if (!isa<LoadSDNode>(N0)) return SDValue(); 6549 6550 // Because a SRL must be assumed to *need* to zero-extend the high bits 6551 // (as opposed to anyext the high bits), we can't combine the zextload 6552 // lowering of SRL and an sextload. 6553 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6554 return SDValue(); 6555 6556 // If the shift amount is larger than the input type then we're not 6557 // accessing any of the loaded bytes. If the load was a zextload/extload 6558 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6559 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6560 return SDValue(); 6561 } 6562 } 6563 6564 // If the load is shifted left (and the result isn't shifted back right), 6565 // we can fold the truncate through the shift. 6566 unsigned ShLeftAmt = 0; 6567 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6568 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6569 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6570 ShLeftAmt = N01->getZExtValue(); 6571 N0 = N0.getOperand(0); 6572 } 6573 } 6574 6575 // If we haven't found a load, we can't narrow it. Don't transform one with 6576 // multiple uses, this would require adding a new load. 6577 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6578 return SDValue(); 6579 6580 // Don't change the width of a volatile load. 6581 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6582 if (LN0->isVolatile()) 6583 return SDValue(); 6584 6585 // Verify that we are actually reducing a load width here. 6586 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6587 return SDValue(); 6588 6589 // For the transform to be legal, the load must produce only two values 6590 // (the value loaded and the chain). Don't transform a pre-increment 6591 // load, for example, which produces an extra value. Otherwise the 6592 // transformation is not equivalent, and the downstream logic to replace 6593 // uses gets things wrong. 6594 if (LN0->getNumValues() > 2) 6595 return SDValue(); 6596 6597 // If the load that we're shrinking is an extload and we're not just 6598 // discarding the extension we can't simply shrink the load. Bail. 6599 // TODO: It would be possible to merge the extensions in some cases. 6600 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6601 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6602 return SDValue(); 6603 6604 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6605 return SDValue(); 6606 6607 EVT PtrType = N0.getOperand(1).getValueType(); 6608 6609 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6610 // It's not possible to generate a constant of extended or untyped type. 6611 return SDValue(); 6612 6613 // For big endian targets, we need to adjust the offset to the pointer to 6614 // load the correct bytes. 6615 if (TLI.isBigEndian()) { 6616 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6617 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6618 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6619 } 6620 6621 uint64_t PtrOff = ShAmt / 8; 6622 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6623 SDLoc DL(LN0); 6624 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6625 PtrType, LN0->getBasePtr(), 6626 DAG.getConstant(PtrOff, DL, PtrType)); 6627 AddToWorklist(NewPtr.getNode()); 6628 6629 SDValue Load; 6630 if (ExtType == ISD::NON_EXTLOAD) 6631 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6632 LN0->getPointerInfo().getWithOffset(PtrOff), 6633 LN0->isVolatile(), LN0->isNonTemporal(), 6634 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6635 else 6636 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6637 LN0->getPointerInfo().getWithOffset(PtrOff), 6638 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6639 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6640 6641 // Replace the old load's chain with the new load's chain. 6642 WorklistRemover DeadNodes(*this); 6643 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6644 6645 // Shift the result left, if we've swallowed a left shift. 6646 SDValue Result = Load; 6647 if (ShLeftAmt != 0) { 6648 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6649 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6650 ShImmTy = VT; 6651 // If the shift amount is as large as the result size (but, presumably, 6652 // no larger than the source) then the useful bits of the result are 6653 // zero; we can't simply return the shortened shift, because the result 6654 // of that operation is undefined. 6655 SDLoc DL(N0); 6656 if (ShLeftAmt >= VT.getSizeInBits()) 6657 Result = DAG.getConstant(0, DL, VT); 6658 else 6659 Result = DAG.getNode(ISD::SHL, DL, VT, 6660 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6661 } 6662 6663 // Return the new loaded value. 6664 return Result; 6665 } 6666 6667 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6668 SDValue N0 = N->getOperand(0); 6669 SDValue N1 = N->getOperand(1); 6670 EVT VT = N->getValueType(0); 6671 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6672 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6673 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6674 6675 // fold (sext_in_reg c1) -> c1 6676 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6677 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6678 6679 // If the input is already sign extended, just drop the extension. 6680 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6681 return N0; 6682 6683 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6684 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6685 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6686 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6687 N0.getOperand(0), N1); 6688 6689 // fold (sext_in_reg (sext x)) -> (sext x) 6690 // fold (sext_in_reg (aext x)) -> (sext x) 6691 // if x is small enough. 6692 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6693 SDValue N00 = N0.getOperand(0); 6694 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6695 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6696 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6697 } 6698 6699 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6700 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6701 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6702 6703 // fold operands of sext_in_reg based on knowledge that the top bits are not 6704 // demanded. 6705 if (SimplifyDemandedBits(SDValue(N, 0))) 6706 return SDValue(N, 0); 6707 6708 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6709 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6710 SDValue NarrowLoad = ReduceLoadWidth(N); 6711 if (NarrowLoad.getNode()) 6712 return NarrowLoad; 6713 6714 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6715 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6716 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6717 if (N0.getOpcode() == ISD::SRL) { 6718 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6719 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6720 // We can turn this into an SRA iff the input to the SRL is already sign 6721 // extended enough. 6722 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6723 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6724 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6725 N0.getOperand(0), N0.getOperand(1)); 6726 } 6727 } 6728 6729 // fold (sext_inreg (extload x)) -> (sextload x) 6730 if (ISD::isEXTLoad(N0.getNode()) && 6731 ISD::isUNINDEXEDLoad(N0.getNode()) && 6732 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6733 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6734 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6735 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6736 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6737 LN0->getChain(), 6738 LN0->getBasePtr(), EVT, 6739 LN0->getMemOperand()); 6740 CombineTo(N, ExtLoad); 6741 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6742 AddToWorklist(ExtLoad.getNode()); 6743 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6744 } 6745 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6746 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6747 N0.hasOneUse() && 6748 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6749 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6750 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6751 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6752 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6753 LN0->getChain(), 6754 LN0->getBasePtr(), EVT, 6755 LN0->getMemOperand()); 6756 CombineTo(N, ExtLoad); 6757 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6758 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6759 } 6760 6761 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6762 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6763 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6764 N0.getOperand(1), false); 6765 if (BSwap.getNode()) 6766 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6767 BSwap, N1); 6768 } 6769 6770 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6771 // into a build_vector. 6772 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6773 SmallVector<SDValue, 8> Elts; 6774 unsigned NumElts = N0->getNumOperands(); 6775 unsigned ShAmt = VTBits - EVTBits; 6776 6777 for (unsigned i = 0; i != NumElts; ++i) { 6778 SDValue Op = N0->getOperand(i); 6779 if (Op->getOpcode() == ISD::UNDEF) { 6780 Elts.push_back(Op); 6781 continue; 6782 } 6783 6784 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6785 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6786 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6787 SDLoc(Op), Op.getValueType())); 6788 } 6789 6790 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6791 } 6792 6793 return SDValue(); 6794 } 6795 6796 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6797 SDValue N0 = N->getOperand(0); 6798 EVT VT = N->getValueType(0); 6799 bool isLE = TLI.isLittleEndian(); 6800 6801 // noop truncate 6802 if (N0.getValueType() == N->getValueType(0)) 6803 return N0; 6804 // fold (truncate c1) -> c1 6805 if (isConstantIntBuildVectorOrConstantInt(N0)) 6806 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6807 // fold (truncate (truncate x)) -> (truncate x) 6808 if (N0.getOpcode() == ISD::TRUNCATE) 6809 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6810 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6811 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6812 N0.getOpcode() == ISD::SIGN_EXTEND || 6813 N0.getOpcode() == ISD::ANY_EXTEND) { 6814 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6815 // if the source is smaller than the dest, we still need an extend 6816 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6817 N0.getOperand(0)); 6818 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6819 // if the source is larger than the dest, than we just need the truncate 6820 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6821 // if the source and dest are the same type, we can drop both the extend 6822 // and the truncate. 6823 return N0.getOperand(0); 6824 } 6825 6826 // Fold extract-and-trunc into a narrow extract. For example: 6827 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6828 // i32 y = TRUNCATE(i64 x) 6829 // -- becomes -- 6830 // v16i8 b = BITCAST (v2i64 val) 6831 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6832 // 6833 // Note: We only run this optimization after type legalization (which often 6834 // creates this pattern) and before operation legalization after which 6835 // we need to be more careful about the vector instructions that we generate. 6836 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6837 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6838 6839 EVT VecTy = N0.getOperand(0).getValueType(); 6840 EVT ExTy = N0.getValueType(); 6841 EVT TrTy = N->getValueType(0); 6842 6843 unsigned NumElem = VecTy.getVectorNumElements(); 6844 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6845 6846 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6847 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6848 6849 SDValue EltNo = N0->getOperand(1); 6850 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6851 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6852 EVT IndexTy = TLI.getVectorIdxTy(); 6853 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6854 6855 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6856 NVT, N0.getOperand(0)); 6857 6858 SDLoc DL(N); 6859 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6860 DL, TrTy, V, 6861 DAG.getConstant(Index, DL, IndexTy)); 6862 } 6863 } 6864 6865 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6866 if (N0.getOpcode() == ISD::SELECT) { 6867 EVT SrcVT = N0.getValueType(); 6868 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6869 TLI.isTruncateFree(SrcVT, VT)) { 6870 SDLoc SL(N0); 6871 SDValue Cond = N0.getOperand(0); 6872 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6873 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6874 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6875 } 6876 } 6877 6878 // Fold a series of buildvector, bitcast, and truncate if possible. 6879 // For example fold 6880 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6881 // (2xi32 (buildvector x, y)). 6882 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6883 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6884 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6885 N0.getOperand(0).hasOneUse()) { 6886 6887 SDValue BuildVect = N0.getOperand(0); 6888 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6889 EVT TruncVecEltTy = VT.getVectorElementType(); 6890 6891 // Check that the element types match. 6892 if (BuildVectEltTy == TruncVecEltTy) { 6893 // Now we only need to compute the offset of the truncated elements. 6894 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6895 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6896 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6897 6898 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6899 "Invalid number of elements"); 6900 6901 SmallVector<SDValue, 8> Opnds; 6902 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6903 Opnds.push_back(BuildVect.getOperand(i)); 6904 6905 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6906 } 6907 } 6908 6909 // See if we can simplify the input to this truncate through knowledge that 6910 // only the low bits are being used. 6911 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6912 // Currently we only perform this optimization on scalars because vectors 6913 // may have different active low bits. 6914 if (!VT.isVector()) { 6915 SDValue Shorter = 6916 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6917 VT.getSizeInBits())); 6918 if (Shorter.getNode()) 6919 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6920 } 6921 // fold (truncate (load x)) -> (smaller load x) 6922 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6923 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6924 SDValue Reduced = ReduceLoadWidth(N); 6925 if (Reduced.getNode()) 6926 return Reduced; 6927 // Handle the case where the load remains an extending load even 6928 // after truncation. 6929 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6930 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6931 if (!LN0->isVolatile() && 6932 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6933 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6934 VT, LN0->getChain(), LN0->getBasePtr(), 6935 LN0->getMemoryVT(), 6936 LN0->getMemOperand()); 6937 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6938 return NewLoad; 6939 } 6940 } 6941 } 6942 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6943 // where ... are all 'undef'. 6944 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6945 SmallVector<EVT, 8> VTs; 6946 SDValue V; 6947 unsigned Idx = 0; 6948 unsigned NumDefs = 0; 6949 6950 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6951 SDValue X = N0.getOperand(i); 6952 if (X.getOpcode() != ISD::UNDEF) { 6953 V = X; 6954 Idx = i; 6955 NumDefs++; 6956 } 6957 // Stop if more than one members are non-undef. 6958 if (NumDefs > 1) 6959 break; 6960 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6961 VT.getVectorElementType(), 6962 X.getValueType().getVectorNumElements())); 6963 } 6964 6965 if (NumDefs == 0) 6966 return DAG.getUNDEF(VT); 6967 6968 if (NumDefs == 1) { 6969 assert(V.getNode() && "The single defined operand is empty!"); 6970 SmallVector<SDValue, 8> Opnds; 6971 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6972 if (i != Idx) { 6973 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6974 continue; 6975 } 6976 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6977 AddToWorklist(NV.getNode()); 6978 Opnds.push_back(NV); 6979 } 6980 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6981 } 6982 } 6983 6984 // Simplify the operands using demanded-bits information. 6985 if (!VT.isVector() && 6986 SimplifyDemandedBits(SDValue(N, 0))) 6987 return SDValue(N, 0); 6988 6989 return SDValue(); 6990 } 6991 6992 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6993 SDValue Elt = N->getOperand(i); 6994 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6995 return Elt.getNode(); 6996 return Elt.getOperand(Elt.getResNo()).getNode(); 6997 } 6998 6999 /// build_pair (load, load) -> load 7000 /// if load locations are consecutive. 7001 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7002 assert(N->getOpcode() == ISD::BUILD_PAIR); 7003 7004 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7005 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7006 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7007 LD1->getAddressSpace() != LD2->getAddressSpace()) 7008 return SDValue(); 7009 EVT LD1VT = LD1->getValueType(0); 7010 7011 if (ISD::isNON_EXTLoad(LD2) && 7012 LD2->hasOneUse() && 7013 // If both are volatile this would reduce the number of volatile loads. 7014 // If one is volatile it might be ok, but play conservative and bail out. 7015 !LD1->isVolatile() && 7016 !LD2->isVolatile() && 7017 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7018 unsigned Align = LD1->getAlignment(); 7019 unsigned NewAlign = TLI.getDataLayout()-> 7020 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 7021 7022 if (NewAlign <= Align && 7023 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7024 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7025 LD1->getBasePtr(), LD1->getPointerInfo(), 7026 false, false, false, Align); 7027 } 7028 7029 return SDValue(); 7030 } 7031 7032 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7033 SDValue N0 = N->getOperand(0); 7034 EVT VT = N->getValueType(0); 7035 7036 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7037 // Only do this before legalize, since afterward the target may be depending 7038 // on the bitconvert. 7039 // First check to see if this is all constant. 7040 if (!LegalTypes && 7041 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7042 VT.isVector()) { 7043 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7044 7045 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7046 assert(!DestEltVT.isVector() && 7047 "Element type of vector ValueType must not be vector!"); 7048 if (isSimple) 7049 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7050 } 7051 7052 // If the input is a constant, let getNode fold it. 7053 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7054 // If we can't allow illegal operations, we need to check that this is just 7055 // a fp -> int or int -> conversion and that the resulting operation will 7056 // be legal. 7057 if (!LegalOperations || 7058 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7059 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7060 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7061 TLI.isOperationLegal(ISD::Constant, VT))) 7062 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7063 } 7064 7065 // (conv (conv x, t1), t2) -> (conv x, t2) 7066 if (N0.getOpcode() == ISD::BITCAST) 7067 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7068 N0.getOperand(0)); 7069 7070 // fold (conv (load x)) -> (load (conv*)x) 7071 // If the resultant load doesn't need a higher alignment than the original! 7072 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7073 // Do not change the width of a volatile load. 7074 !cast<LoadSDNode>(N0)->isVolatile() && 7075 // Do not remove the cast if the types differ in endian layout. 7076 TLI.hasBigEndianPartOrdering(N0.getValueType()) == 7077 TLI.hasBigEndianPartOrdering(VT) && 7078 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7079 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7080 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7081 unsigned Align = TLI.getDataLayout()-> 7082 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 7083 unsigned OrigAlign = LN0->getAlignment(); 7084 7085 if (Align <= OrigAlign) { 7086 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7087 LN0->getBasePtr(), LN0->getPointerInfo(), 7088 LN0->isVolatile(), LN0->isNonTemporal(), 7089 LN0->isInvariant(), OrigAlign, 7090 LN0->getAAInfo()); 7091 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7092 return Load; 7093 } 7094 } 7095 7096 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7097 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7098 // This often reduces constant pool loads. 7099 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7100 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7101 N0.getNode()->hasOneUse() && VT.isInteger() && 7102 !VT.isVector() && !N0.getValueType().isVector()) { 7103 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7104 N0.getOperand(0)); 7105 AddToWorklist(NewConv.getNode()); 7106 7107 SDLoc DL(N); 7108 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7109 if (N0.getOpcode() == ISD::FNEG) 7110 return DAG.getNode(ISD::XOR, DL, VT, 7111 NewConv, DAG.getConstant(SignBit, DL, VT)); 7112 assert(N0.getOpcode() == ISD::FABS); 7113 return DAG.getNode(ISD::AND, DL, VT, 7114 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7115 } 7116 7117 // fold (bitconvert (fcopysign cst, x)) -> 7118 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7119 // Note that we don't handle (copysign x, cst) because this can always be 7120 // folded to an fneg or fabs. 7121 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7122 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7123 VT.isInteger() && !VT.isVector()) { 7124 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7125 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7126 if (isTypeLegal(IntXVT)) { 7127 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7128 IntXVT, N0.getOperand(1)); 7129 AddToWorklist(X.getNode()); 7130 7131 // If X has a different width than the result/lhs, sext it or truncate it. 7132 unsigned VTWidth = VT.getSizeInBits(); 7133 if (OrigXWidth < VTWidth) { 7134 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7135 AddToWorklist(X.getNode()); 7136 } else if (OrigXWidth > VTWidth) { 7137 // To get the sign bit in the right place, we have to shift it right 7138 // before truncating. 7139 SDLoc DL(X); 7140 X = DAG.getNode(ISD::SRL, DL, 7141 X.getValueType(), X, 7142 DAG.getConstant(OrigXWidth-VTWidth, DL, 7143 X.getValueType())); 7144 AddToWorklist(X.getNode()); 7145 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7146 AddToWorklist(X.getNode()); 7147 } 7148 7149 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7150 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7151 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7152 AddToWorklist(X.getNode()); 7153 7154 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7155 VT, N0.getOperand(0)); 7156 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7157 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7158 AddToWorklist(Cst.getNode()); 7159 7160 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7161 } 7162 } 7163 7164 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7165 if (N0.getOpcode() == ISD::BUILD_PAIR) { 7166 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 7167 if (CombineLD.getNode()) 7168 return CombineLD; 7169 } 7170 7171 // Remove double bitcasts from shuffles - this is often a legacy of 7172 // XformToShuffleWithZero being used to combine bitmaskings (of 7173 // float vectors bitcast to integer vectors) into shuffles. 7174 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7175 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7176 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7177 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7178 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7179 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7180 7181 // If operands are a bitcast, peek through if it casts the original VT. 7182 // If operands are a UNDEF or constant, just bitcast back to original VT. 7183 auto PeekThroughBitcast = [&](SDValue Op) { 7184 if (Op.getOpcode() == ISD::BITCAST && 7185 Op.getOperand(0)->getValueType(0) == VT) 7186 return SDValue(Op.getOperand(0)); 7187 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7188 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7189 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7190 return SDValue(); 7191 }; 7192 7193 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7194 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7195 if (!(SV0 && SV1)) 7196 return SDValue(); 7197 7198 int MaskScale = 7199 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7200 SmallVector<int, 8> NewMask; 7201 for (int M : SVN->getMask()) 7202 for (int i = 0; i != MaskScale; ++i) 7203 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7204 7205 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7206 if (!LegalMask) { 7207 std::swap(SV0, SV1); 7208 ShuffleVectorSDNode::commuteMask(NewMask); 7209 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7210 } 7211 7212 if (LegalMask) 7213 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7214 } 7215 7216 return SDValue(); 7217 } 7218 7219 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7220 EVT VT = N->getValueType(0); 7221 return CombineConsecutiveLoads(N, VT); 7222 } 7223 7224 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7225 /// operands. DstEltVT indicates the destination element value type. 7226 SDValue DAGCombiner:: 7227 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7228 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7229 7230 // If this is already the right type, we're done. 7231 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7232 7233 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7234 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7235 7236 // If this is a conversion of N elements of one type to N elements of another 7237 // type, convert each element. This handles FP<->INT cases. 7238 if (SrcBitSize == DstBitSize) { 7239 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7240 BV->getValueType(0).getVectorNumElements()); 7241 7242 // Due to the FP element handling below calling this routine recursively, 7243 // we can end up with a scalar-to-vector node here. 7244 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7245 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7246 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7247 DstEltVT, BV->getOperand(0))); 7248 7249 SmallVector<SDValue, 8> Ops; 7250 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 7251 SDValue Op = BV->getOperand(i); 7252 // If the vector element type is not legal, the BUILD_VECTOR operands 7253 // are promoted and implicitly truncated. Make that explicit here. 7254 if (Op.getValueType() != SrcEltVT) 7255 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7256 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7257 DstEltVT, Op)); 7258 AddToWorklist(Ops.back().getNode()); 7259 } 7260 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7261 } 7262 7263 // Otherwise, we're growing or shrinking the elements. To avoid having to 7264 // handle annoying details of growing/shrinking FP values, we convert them to 7265 // int first. 7266 if (SrcEltVT.isFloatingPoint()) { 7267 // Convert the input float vector to a int vector where the elements are the 7268 // same sizes. 7269 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7270 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7271 SrcEltVT = IntVT; 7272 } 7273 7274 // Now we know the input is an integer vector. If the output is a FP type, 7275 // convert to integer first, then to FP of the right size. 7276 if (DstEltVT.isFloatingPoint()) { 7277 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7278 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7279 7280 // Next, convert to FP elements of the same size. 7281 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7282 } 7283 7284 SDLoc DL(BV); 7285 7286 // Okay, we know the src/dst types are both integers of differing types. 7287 // Handling growing first. 7288 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7289 if (SrcBitSize < DstBitSize) { 7290 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7291 7292 SmallVector<SDValue, 8> Ops; 7293 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7294 i += NumInputsPerOutput) { 7295 bool isLE = TLI.isLittleEndian(); 7296 APInt NewBits = APInt(DstBitSize, 0); 7297 bool EltIsUndef = true; 7298 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7299 // Shift the previously computed bits over. 7300 NewBits <<= SrcBitSize; 7301 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7302 if (Op.getOpcode() == ISD::UNDEF) continue; 7303 EltIsUndef = false; 7304 7305 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7306 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7307 } 7308 7309 if (EltIsUndef) 7310 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7311 else 7312 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7313 } 7314 7315 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7316 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7317 } 7318 7319 // Finally, this must be the case where we are shrinking elements: each input 7320 // turns into multiple outputs. 7321 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7322 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7323 NumOutputsPerInput*BV->getNumOperands()); 7324 SmallVector<SDValue, 8> Ops; 7325 7326 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 7327 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 7328 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7329 continue; 7330 } 7331 7332 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 7333 getAPIntValue().zextOrTrunc(SrcBitSize); 7334 7335 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7336 APInt ThisVal = OpVal.trunc(DstBitSize); 7337 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7338 OpVal = OpVal.lshr(DstBitSize); 7339 } 7340 7341 // For big endian targets, swap the order of the pieces of each element. 7342 if (TLI.isBigEndian()) 7343 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7344 } 7345 7346 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7347 } 7348 7349 /// Try to perform FMA combining on a given FADD node. 7350 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7351 SDValue N0 = N->getOperand(0); 7352 SDValue N1 = N->getOperand(1); 7353 EVT VT = N->getValueType(0); 7354 SDLoc SL(N); 7355 7356 const TargetOptions &Options = DAG.getTarget().Options; 7357 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7358 Options.UnsafeFPMath); 7359 7360 // Floating-point multiply-add with intermediate rounding. 7361 bool HasFMAD = (LegalOperations && 7362 TLI.isOperationLegal(ISD::FMAD, VT)); 7363 7364 // Floating-point multiply-add without intermediate rounding. 7365 bool HasFMA = ((!LegalOperations || 7366 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7367 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7368 UnsafeFPMath); 7369 7370 // No valid opcode, do not combine. 7371 if (!HasFMAD && !HasFMA) 7372 return SDValue(); 7373 7374 // Always prefer FMAD to FMA for precision. 7375 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7376 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7377 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7378 7379 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7380 if (N0.getOpcode() == ISD::FMUL && 7381 (Aggressive || N0->hasOneUse())) { 7382 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7383 N0.getOperand(0), N0.getOperand(1), N1); 7384 } 7385 7386 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7387 // Note: Commutes FADD operands. 7388 if (N1.getOpcode() == ISD::FMUL && 7389 (Aggressive || N1->hasOneUse())) { 7390 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7391 N1.getOperand(0), N1.getOperand(1), N0); 7392 } 7393 7394 // Look through FP_EXTEND nodes to do more combining. 7395 if (UnsafeFPMath && LookThroughFPExt) { 7396 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7397 if (N0.getOpcode() == ISD::FP_EXTEND) { 7398 SDValue N00 = N0.getOperand(0); 7399 if (N00.getOpcode() == ISD::FMUL) 7400 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7401 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7402 N00.getOperand(0)), 7403 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7404 N00.getOperand(1)), N1); 7405 } 7406 7407 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7408 // Note: Commutes FADD operands. 7409 if (N1.getOpcode() == ISD::FP_EXTEND) { 7410 SDValue N10 = N1.getOperand(0); 7411 if (N10.getOpcode() == ISD::FMUL) 7412 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7413 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7414 N10.getOperand(0)), 7415 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7416 N10.getOperand(1)), N0); 7417 } 7418 } 7419 7420 // More folding opportunities when target permits. 7421 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7422 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7423 if (N0.getOpcode() == PreferredFusedOpcode && 7424 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7425 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7426 N0.getOperand(0), N0.getOperand(1), 7427 DAG.getNode(PreferredFusedOpcode, SL, VT, 7428 N0.getOperand(2).getOperand(0), 7429 N0.getOperand(2).getOperand(1), 7430 N1)); 7431 } 7432 7433 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7434 if (N1->getOpcode() == PreferredFusedOpcode && 7435 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7436 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7437 N1.getOperand(0), N1.getOperand(1), 7438 DAG.getNode(PreferredFusedOpcode, SL, VT, 7439 N1.getOperand(2).getOperand(0), 7440 N1.getOperand(2).getOperand(1), 7441 N0)); 7442 } 7443 7444 if (UnsafeFPMath && LookThroughFPExt) { 7445 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7446 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7447 auto FoldFAddFMAFPExtFMul = [&] ( 7448 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7449 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7450 DAG.getNode(PreferredFusedOpcode, SL, VT, 7451 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7452 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7453 Z)); 7454 }; 7455 if (N0.getOpcode() == PreferredFusedOpcode) { 7456 SDValue N02 = N0.getOperand(2); 7457 if (N02.getOpcode() == ISD::FP_EXTEND) { 7458 SDValue N020 = N02.getOperand(0); 7459 if (N020.getOpcode() == ISD::FMUL) 7460 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7461 N020.getOperand(0), N020.getOperand(1), 7462 N1); 7463 } 7464 } 7465 7466 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7467 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7468 // FIXME: This turns two single-precision and one double-precision 7469 // operation into two double-precision operations, which might not be 7470 // interesting for all targets, especially GPUs. 7471 auto FoldFAddFPExtFMAFMul = [&] ( 7472 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7473 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7474 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7475 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7476 DAG.getNode(PreferredFusedOpcode, SL, VT, 7477 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7478 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7479 Z)); 7480 }; 7481 if (N0.getOpcode() == ISD::FP_EXTEND) { 7482 SDValue N00 = N0.getOperand(0); 7483 if (N00.getOpcode() == PreferredFusedOpcode) { 7484 SDValue N002 = N00.getOperand(2); 7485 if (N002.getOpcode() == ISD::FMUL) 7486 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7487 N002.getOperand(0), N002.getOperand(1), 7488 N1); 7489 } 7490 } 7491 7492 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7493 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7494 if (N1.getOpcode() == PreferredFusedOpcode) { 7495 SDValue N12 = N1.getOperand(2); 7496 if (N12.getOpcode() == ISD::FP_EXTEND) { 7497 SDValue N120 = N12.getOperand(0); 7498 if (N120.getOpcode() == ISD::FMUL) 7499 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7500 N120.getOperand(0), N120.getOperand(1), 7501 N0); 7502 } 7503 } 7504 7505 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7506 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7507 // FIXME: This turns two single-precision and one double-precision 7508 // operation into two double-precision operations, which might not be 7509 // interesting for all targets, especially GPUs. 7510 if (N1.getOpcode() == ISD::FP_EXTEND) { 7511 SDValue N10 = N1.getOperand(0); 7512 if (N10.getOpcode() == PreferredFusedOpcode) { 7513 SDValue N102 = N10.getOperand(2); 7514 if (N102.getOpcode() == ISD::FMUL) 7515 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7516 N102.getOperand(0), N102.getOperand(1), 7517 N0); 7518 } 7519 } 7520 } 7521 } 7522 7523 return SDValue(); 7524 } 7525 7526 /// Try to perform FMA combining on a given FSUB node. 7527 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7528 SDValue N0 = N->getOperand(0); 7529 SDValue N1 = N->getOperand(1); 7530 EVT VT = N->getValueType(0); 7531 SDLoc SL(N); 7532 7533 const TargetOptions &Options = DAG.getTarget().Options; 7534 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7535 Options.UnsafeFPMath); 7536 7537 // Floating-point multiply-add with intermediate rounding. 7538 bool HasFMAD = (LegalOperations && 7539 TLI.isOperationLegal(ISD::FMAD, VT)); 7540 7541 // Floating-point multiply-add without intermediate rounding. 7542 bool HasFMA = ((!LegalOperations || 7543 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7544 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7545 UnsafeFPMath); 7546 7547 // No valid opcode, do not combine. 7548 if (!HasFMAD && !HasFMA) 7549 return SDValue(); 7550 7551 // Always prefer FMAD to FMA for precision. 7552 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7553 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7554 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7555 7556 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7557 if (N0.getOpcode() == ISD::FMUL && 7558 (Aggressive || N0->hasOneUse())) { 7559 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7560 N0.getOperand(0), N0.getOperand(1), 7561 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7562 } 7563 7564 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7565 // Note: Commutes FSUB operands. 7566 if (N1.getOpcode() == ISD::FMUL && 7567 (Aggressive || N1->hasOneUse())) 7568 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7569 DAG.getNode(ISD::FNEG, SL, VT, 7570 N1.getOperand(0)), 7571 N1.getOperand(1), N0); 7572 7573 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7574 if (N0.getOpcode() == ISD::FNEG && 7575 N0.getOperand(0).getOpcode() == ISD::FMUL && 7576 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7577 SDValue N00 = N0.getOperand(0).getOperand(0); 7578 SDValue N01 = N0.getOperand(0).getOperand(1); 7579 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7580 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7581 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7582 } 7583 7584 // Look through FP_EXTEND nodes to do more combining. 7585 if (UnsafeFPMath && LookThroughFPExt) { 7586 // fold (fsub (fpext (fmul x, y)), z) 7587 // -> (fma (fpext x), (fpext y), (fneg z)) 7588 if (N0.getOpcode() == ISD::FP_EXTEND) { 7589 SDValue N00 = N0.getOperand(0); 7590 if (N00.getOpcode() == ISD::FMUL) 7591 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7592 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7593 N00.getOperand(0)), 7594 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7595 N00.getOperand(1)), 7596 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7597 } 7598 7599 // fold (fsub x, (fpext (fmul y, z))) 7600 // -> (fma (fneg (fpext y)), (fpext z), x) 7601 // Note: Commutes FSUB operands. 7602 if (N1.getOpcode() == ISD::FP_EXTEND) { 7603 SDValue N10 = N1.getOperand(0); 7604 if (N10.getOpcode() == ISD::FMUL) 7605 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7606 DAG.getNode(ISD::FNEG, SL, VT, 7607 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7608 N10.getOperand(0))), 7609 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7610 N10.getOperand(1)), 7611 N0); 7612 } 7613 7614 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7615 // -> (fneg (fma (fpext x), (fpext y), z)) 7616 // Note: This could be removed with appropriate canonicalization of the 7617 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7618 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7619 // from implementing the canonicalization in visitFSUB. 7620 if (N0.getOpcode() == ISD::FP_EXTEND) { 7621 SDValue N00 = N0.getOperand(0); 7622 if (N00.getOpcode() == ISD::FNEG) { 7623 SDValue N000 = N00.getOperand(0); 7624 if (N000.getOpcode() == ISD::FMUL) { 7625 return DAG.getNode(ISD::FNEG, SL, VT, 7626 DAG.getNode(PreferredFusedOpcode, SL, VT, 7627 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7628 N000.getOperand(0)), 7629 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7630 N000.getOperand(1)), 7631 N1)); 7632 } 7633 } 7634 } 7635 7636 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7637 // -> (fneg (fma (fpext x)), (fpext y), z) 7638 // Note: This could be removed with appropriate canonicalization of the 7639 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7640 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7641 // from implementing the canonicalization in visitFSUB. 7642 if (N0.getOpcode() == ISD::FNEG) { 7643 SDValue N00 = N0.getOperand(0); 7644 if (N00.getOpcode() == ISD::FP_EXTEND) { 7645 SDValue N000 = N00.getOperand(0); 7646 if (N000.getOpcode() == ISD::FMUL) { 7647 return DAG.getNode(ISD::FNEG, SL, VT, 7648 DAG.getNode(PreferredFusedOpcode, SL, VT, 7649 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7650 N000.getOperand(0)), 7651 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7652 N000.getOperand(1)), 7653 N1)); 7654 } 7655 } 7656 } 7657 7658 } 7659 7660 // More folding opportunities when target permits. 7661 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7662 // fold (fsub (fma x, y, (fmul u, v)), z) 7663 // -> (fma x, y (fma u, v, (fneg z))) 7664 if (N0.getOpcode() == PreferredFusedOpcode && 7665 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7666 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7667 N0.getOperand(0), N0.getOperand(1), 7668 DAG.getNode(PreferredFusedOpcode, SL, VT, 7669 N0.getOperand(2).getOperand(0), 7670 N0.getOperand(2).getOperand(1), 7671 DAG.getNode(ISD::FNEG, SL, VT, 7672 N1))); 7673 } 7674 7675 // fold (fsub x, (fma y, z, (fmul u, v))) 7676 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7677 if (N1.getOpcode() == PreferredFusedOpcode && 7678 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7679 SDValue N20 = N1.getOperand(2).getOperand(0); 7680 SDValue N21 = N1.getOperand(2).getOperand(1); 7681 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7682 DAG.getNode(ISD::FNEG, SL, VT, 7683 N1.getOperand(0)), 7684 N1.getOperand(1), 7685 DAG.getNode(PreferredFusedOpcode, SL, VT, 7686 DAG.getNode(ISD::FNEG, SL, VT, N20), 7687 7688 N21, N0)); 7689 } 7690 7691 if (UnsafeFPMath && LookThroughFPExt) { 7692 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7693 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7694 if (N0.getOpcode() == PreferredFusedOpcode) { 7695 SDValue N02 = N0.getOperand(2); 7696 if (N02.getOpcode() == ISD::FP_EXTEND) { 7697 SDValue N020 = N02.getOperand(0); 7698 if (N020.getOpcode() == ISD::FMUL) 7699 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7700 N0.getOperand(0), N0.getOperand(1), 7701 DAG.getNode(PreferredFusedOpcode, SL, VT, 7702 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7703 N020.getOperand(0)), 7704 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7705 N020.getOperand(1)), 7706 DAG.getNode(ISD::FNEG, SL, VT, 7707 N1))); 7708 } 7709 } 7710 7711 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7712 // -> (fma (fpext x), (fpext y), 7713 // (fma (fpext u), (fpext v), (fneg z))) 7714 // FIXME: This turns two single-precision and one double-precision 7715 // operation into two double-precision operations, which might not be 7716 // interesting for all targets, especially GPUs. 7717 if (N0.getOpcode() == ISD::FP_EXTEND) { 7718 SDValue N00 = N0.getOperand(0); 7719 if (N00.getOpcode() == PreferredFusedOpcode) { 7720 SDValue N002 = N00.getOperand(2); 7721 if (N002.getOpcode() == ISD::FMUL) 7722 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7723 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7724 N00.getOperand(0)), 7725 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7726 N00.getOperand(1)), 7727 DAG.getNode(PreferredFusedOpcode, SL, VT, 7728 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7729 N002.getOperand(0)), 7730 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7731 N002.getOperand(1)), 7732 DAG.getNode(ISD::FNEG, SL, VT, 7733 N1))); 7734 } 7735 } 7736 7737 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7738 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7739 if (N1.getOpcode() == PreferredFusedOpcode && 7740 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7741 SDValue N120 = N1.getOperand(2).getOperand(0); 7742 if (N120.getOpcode() == ISD::FMUL) { 7743 SDValue N1200 = N120.getOperand(0); 7744 SDValue N1201 = N120.getOperand(1); 7745 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7746 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7747 N1.getOperand(1), 7748 DAG.getNode(PreferredFusedOpcode, SL, VT, 7749 DAG.getNode(ISD::FNEG, SL, VT, 7750 DAG.getNode(ISD::FP_EXTEND, SL, 7751 VT, N1200)), 7752 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7753 N1201), 7754 N0)); 7755 } 7756 } 7757 7758 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7759 // -> (fma (fneg (fpext y)), (fpext z), 7760 // (fma (fneg (fpext u)), (fpext v), x)) 7761 // FIXME: This turns two single-precision and one double-precision 7762 // operation into two double-precision operations, which might not be 7763 // interesting for all targets, especially GPUs. 7764 if (N1.getOpcode() == ISD::FP_EXTEND && 7765 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 7766 SDValue N100 = N1.getOperand(0).getOperand(0); 7767 SDValue N101 = N1.getOperand(0).getOperand(1); 7768 SDValue N102 = N1.getOperand(0).getOperand(2); 7769 if (N102.getOpcode() == ISD::FMUL) { 7770 SDValue N1020 = N102.getOperand(0); 7771 SDValue N1021 = N102.getOperand(1); 7772 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7773 DAG.getNode(ISD::FNEG, SL, VT, 7774 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7775 N100)), 7776 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 7777 DAG.getNode(PreferredFusedOpcode, SL, VT, 7778 DAG.getNode(ISD::FNEG, SL, VT, 7779 DAG.getNode(ISD::FP_EXTEND, SL, 7780 VT, N1020)), 7781 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7782 N1021), 7783 N0)); 7784 } 7785 } 7786 } 7787 } 7788 7789 return SDValue(); 7790 } 7791 7792 SDValue DAGCombiner::visitFADD(SDNode *N) { 7793 SDValue N0 = N->getOperand(0); 7794 SDValue N1 = N->getOperand(1); 7795 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7796 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7797 EVT VT = N->getValueType(0); 7798 SDLoc DL(N); 7799 const TargetOptions &Options = DAG.getTarget().Options; 7800 7801 // fold vector ops 7802 if (VT.isVector()) 7803 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7804 return FoldedVOp; 7805 7806 // fold (fadd c1, c2) -> c1 + c2 7807 if (N0CFP && N1CFP) 7808 return DAG.getNode(ISD::FADD, DL, VT, N0, N1); 7809 7810 // canonicalize constant to RHS 7811 if (N0CFP && !N1CFP) 7812 return DAG.getNode(ISD::FADD, DL, VT, N1, N0); 7813 7814 // fold (fadd A, (fneg B)) -> (fsub A, B) 7815 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7816 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 7817 return DAG.getNode(ISD::FSUB, DL, VT, N0, 7818 GetNegatedExpression(N1, DAG, LegalOperations)); 7819 7820 // fold (fadd (fneg A), B) -> (fsub B, A) 7821 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7822 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 7823 return DAG.getNode(ISD::FSUB, DL, VT, N1, 7824 GetNegatedExpression(N0, DAG, LegalOperations)); 7825 7826 // If 'unsafe math' is enabled, fold lots of things. 7827 if (Options.UnsafeFPMath) { 7828 // No FP constant should be created after legalization as Instruction 7829 // Selection pass has a hard time dealing with FP constants. 7830 bool AllowNewConst = (Level < AfterLegalizeDAG); 7831 7832 // fold (fadd A, 0) -> A 7833 if (N1CFP && N1CFP->getValueAPF().isZero()) 7834 return N0; 7835 7836 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 7837 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 7838 isa<ConstantFPSDNode>(N0.getOperand(1))) 7839 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 7840 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1)); 7841 7842 // If allowed, fold (fadd (fneg x), x) -> 0.0 7843 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 7844 return DAG.getConstantFP(0.0, DL, VT); 7845 7846 // If allowed, fold (fadd x, (fneg x)) -> 0.0 7847 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 7848 return DAG.getConstantFP(0.0, DL, VT); 7849 7850 // We can fold chains of FADD's of the same value into multiplications. 7851 // This transform is not safe in general because we are reducing the number 7852 // of rounding steps. 7853 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 7854 if (N0.getOpcode() == ISD::FMUL) { 7855 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7856 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7857 7858 // (fadd (fmul x, c), x) -> (fmul x, c+1) 7859 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 7860 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 7861 DAG.getConstantFP(1.0, DL, VT)); 7862 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP); 7863 } 7864 7865 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 7866 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 7867 N1.getOperand(0) == N1.getOperand(1) && 7868 N0.getOperand(0) == N1.getOperand(0)) { 7869 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 7870 DAG.getConstantFP(2.0, DL, VT)); 7871 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP); 7872 } 7873 } 7874 7875 if (N1.getOpcode() == ISD::FMUL) { 7876 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7877 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 7878 7879 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 7880 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 7881 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 7882 DAG.getConstantFP(1.0, DL, VT)); 7883 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP); 7884 } 7885 7886 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 7887 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 7888 N0.getOperand(0) == N0.getOperand(1) && 7889 N1.getOperand(0) == N0.getOperand(0)) { 7890 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 7891 DAG.getConstantFP(2.0, DL, VT)); 7892 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP); 7893 } 7894 } 7895 7896 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 7897 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7898 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 7899 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 7900 (N0.getOperand(0) == N1)) { 7901 return DAG.getNode(ISD::FMUL, DL, VT, 7902 N1, DAG.getConstantFP(3.0, DL, VT)); 7903 } 7904 } 7905 7906 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 7907 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7908 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 7909 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 7910 N1.getOperand(0) == N0) { 7911 return DAG.getNode(ISD::FMUL, DL, VT, 7912 N0, DAG.getConstantFP(3.0, DL, VT)); 7913 } 7914 } 7915 7916 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 7917 if (AllowNewConst && 7918 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 7919 N0.getOperand(0) == N0.getOperand(1) && 7920 N1.getOperand(0) == N1.getOperand(1) && 7921 N0.getOperand(0) == N1.getOperand(0)) { 7922 return DAG.getNode(ISD::FMUL, DL, VT, 7923 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT)); 7924 } 7925 } 7926 } // enable-unsafe-fp-math 7927 7928 // FADD -> FMA combines: 7929 SDValue Fused = visitFADDForFMACombine(N); 7930 if (Fused) { 7931 AddToWorklist(Fused.getNode()); 7932 return Fused; 7933 } 7934 7935 return SDValue(); 7936 } 7937 7938 SDValue DAGCombiner::visitFSUB(SDNode *N) { 7939 SDValue N0 = N->getOperand(0); 7940 SDValue N1 = N->getOperand(1); 7941 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7942 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7943 EVT VT = N->getValueType(0); 7944 SDLoc dl(N); 7945 const TargetOptions &Options = DAG.getTarget().Options; 7946 7947 // fold vector ops 7948 if (VT.isVector()) 7949 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7950 return FoldedVOp; 7951 7952 // fold (fsub c1, c2) -> c1-c2 7953 if (N0CFP && N1CFP) 7954 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1); 7955 7956 // fold (fsub A, (fneg B)) -> (fadd A, B) 7957 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7958 return DAG.getNode(ISD::FADD, dl, VT, N0, 7959 GetNegatedExpression(N1, DAG, LegalOperations)); 7960 7961 // If 'unsafe math' is enabled, fold lots of things. 7962 if (Options.UnsafeFPMath) { 7963 // (fsub A, 0) -> A 7964 if (N1CFP && N1CFP->getValueAPF().isZero()) 7965 return N0; 7966 7967 // (fsub 0, B) -> -B 7968 if (N0CFP && N0CFP->getValueAPF().isZero()) { 7969 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7970 return GetNegatedExpression(N1, DAG, LegalOperations); 7971 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7972 return DAG.getNode(ISD::FNEG, dl, VT, N1); 7973 } 7974 7975 // (fsub x, x) -> 0.0 7976 if (N0 == N1) 7977 return DAG.getConstantFP(0.0f, dl, VT); 7978 7979 // (fsub x, (fadd x, y)) -> (fneg y) 7980 // (fsub x, (fadd y, x)) -> (fneg y) 7981 if (N1.getOpcode() == ISD::FADD) { 7982 SDValue N10 = N1->getOperand(0); 7983 SDValue N11 = N1->getOperand(1); 7984 7985 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 7986 return GetNegatedExpression(N11, DAG, LegalOperations); 7987 7988 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 7989 return GetNegatedExpression(N10, DAG, LegalOperations); 7990 } 7991 } 7992 7993 // FSUB -> FMA combines: 7994 SDValue Fused = visitFSUBForFMACombine(N); 7995 if (Fused) { 7996 AddToWorklist(Fused.getNode()); 7997 return Fused; 7998 } 7999 8000 return SDValue(); 8001 } 8002 8003 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8004 SDValue N0 = N->getOperand(0); 8005 SDValue N1 = N->getOperand(1); 8006 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8007 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8008 EVT VT = N->getValueType(0); 8009 SDLoc DL(N); 8010 const TargetOptions &Options = DAG.getTarget().Options; 8011 8012 // fold vector ops 8013 if (VT.isVector()) { 8014 // This just handles C1 * C2 for vectors. Other vector folds are below. 8015 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8016 return FoldedVOp; 8017 } 8018 8019 // fold (fmul c1, c2) -> c1*c2 8020 if (N0CFP && N1CFP) 8021 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1); 8022 8023 // canonicalize constant to RHS 8024 if (isConstantFPBuildVectorOrConstantFP(N0) && 8025 !isConstantFPBuildVectorOrConstantFP(N1)) 8026 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0); 8027 8028 // fold (fmul A, 1.0) -> A 8029 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8030 return N0; 8031 8032 if (Options.UnsafeFPMath) { 8033 // fold (fmul A, 0) -> 0 8034 if (N1CFP && N1CFP->getValueAPF().isZero()) 8035 return N1; 8036 8037 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8038 if (N0.getOpcode() == ISD::FMUL) { 8039 // Fold scalars or any vector constants (not just splats). 8040 // This fold is done in general by InstCombine, but extra fmul insts 8041 // may have been generated during lowering. 8042 SDValue N00 = N0.getOperand(0); 8043 SDValue N01 = N0.getOperand(1); 8044 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8045 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8046 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8047 8048 // Check 1: Make sure that the first operand of the inner multiply is NOT 8049 // a constant. Otherwise, we may induce infinite looping. 8050 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8051 // Check 2: Make sure that the second operand of the inner multiply and 8052 // the second operand of the outer multiply are constants. 8053 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8054 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8055 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1); 8056 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts); 8057 } 8058 } 8059 } 8060 8061 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8062 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8063 // during an early run of DAGCombiner can prevent folding with fmuls 8064 // inserted during lowering. 8065 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) { 8066 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8067 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1); 8068 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts); 8069 } 8070 } 8071 8072 // fold (fmul X, 2.0) -> (fadd X, X) 8073 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8074 return DAG.getNode(ISD::FADD, DL, VT, N0, N0); 8075 8076 // fold (fmul X, -1.0) -> (fneg X) 8077 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8078 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8079 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8080 8081 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8082 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8083 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8084 // Both can be negated for free, check to see if at least one is cheaper 8085 // negated. 8086 if (LHSNeg == 2 || RHSNeg == 2) 8087 return DAG.getNode(ISD::FMUL, DL, VT, 8088 GetNegatedExpression(N0, DAG, LegalOperations), 8089 GetNegatedExpression(N1, DAG, LegalOperations)); 8090 } 8091 } 8092 8093 return SDValue(); 8094 } 8095 8096 SDValue DAGCombiner::visitFMA(SDNode *N) { 8097 SDValue N0 = N->getOperand(0); 8098 SDValue N1 = N->getOperand(1); 8099 SDValue N2 = N->getOperand(2); 8100 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8101 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8102 EVT VT = N->getValueType(0); 8103 SDLoc dl(N); 8104 const TargetOptions &Options = DAG.getTarget().Options; 8105 8106 // Constant fold FMA. 8107 if (isa<ConstantFPSDNode>(N0) && 8108 isa<ConstantFPSDNode>(N1) && 8109 isa<ConstantFPSDNode>(N2)) { 8110 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8111 } 8112 8113 if (Options.UnsafeFPMath) { 8114 if (N0CFP && N0CFP->isZero()) 8115 return N2; 8116 if (N1CFP && N1CFP->isZero()) 8117 return N2; 8118 } 8119 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8120 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8121 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8122 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8123 8124 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8125 if (N0CFP && !N1CFP) 8126 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8127 8128 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8129 if (Options.UnsafeFPMath && N1CFP && 8130 N2.getOpcode() == ISD::FMUL && 8131 N0 == N2.getOperand(0) && 8132 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 8133 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8134 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 8135 } 8136 8137 8138 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8139 if (Options.UnsafeFPMath && 8140 N0.getOpcode() == ISD::FMUL && N1CFP && 8141 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 8142 return DAG.getNode(ISD::FMA, dl, VT, 8143 N0.getOperand(0), 8144 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 8145 N2); 8146 } 8147 8148 // (fma x, 1, y) -> (fadd x, y) 8149 // (fma x, -1, y) -> (fadd (fneg x), y) 8150 if (N1CFP) { 8151 if (N1CFP->isExactlyValue(1.0)) 8152 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8153 8154 if (N1CFP->isExactlyValue(-1.0) && 8155 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8156 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8157 AddToWorklist(RHSNeg.getNode()); 8158 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8159 } 8160 } 8161 8162 // (fma x, c, x) -> (fmul x, (c+1)) 8163 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 8164 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8165 DAG.getNode(ISD::FADD, dl, VT, 8166 N1, DAG.getConstantFP(1.0, dl, VT))); 8167 8168 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8169 if (Options.UnsafeFPMath && N1CFP && 8170 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 8171 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8172 DAG.getNode(ISD::FADD, dl, VT, 8173 N1, DAG.getConstantFP(-1.0, dl, VT))); 8174 8175 8176 return SDValue(); 8177 } 8178 8179 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8180 SDValue N0 = N->getOperand(0); 8181 SDValue N1 = N->getOperand(1); 8182 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8183 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8184 EVT VT = N->getValueType(0); 8185 SDLoc DL(N); 8186 const TargetOptions &Options = DAG.getTarget().Options; 8187 8188 // fold vector ops 8189 if (VT.isVector()) 8190 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8191 return FoldedVOp; 8192 8193 // fold (fdiv c1, c2) -> c1/c2 8194 if (N0CFP && N1CFP) 8195 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 8196 8197 if (Options.UnsafeFPMath) { 8198 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8199 if (N1CFP) { 8200 // Compute the reciprocal 1.0 / c2. 8201 APFloat N1APF = N1CFP->getValueAPF(); 8202 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8203 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8204 // Only do the transform if the reciprocal is a legal fp immediate that 8205 // isn't too nasty (eg NaN, denormal, ...). 8206 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8207 (!LegalOperations || 8208 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8209 // backend)... we should handle this gracefully after Legalize. 8210 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8211 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8212 TLI.isFPImmLegal(Recip, VT))) 8213 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8214 DAG.getConstantFP(Recip, DL, VT)); 8215 } 8216 8217 // If this FDIV is part of a reciprocal square root, it may be folded 8218 // into a target-specific square root estimate instruction. 8219 if (N1.getOpcode() == ISD::FSQRT) { 8220 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) { 8221 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8222 } 8223 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8224 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8225 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 8226 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8227 AddToWorklist(RV.getNode()); 8228 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8229 } 8230 } else if (N1.getOpcode() == ISD::FP_ROUND && 8231 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8232 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 8233 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8234 AddToWorklist(RV.getNode()); 8235 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8236 } 8237 } else if (N1.getOpcode() == ISD::FMUL) { 8238 // Look through an FMUL. Even though this won't remove the FDIV directly, 8239 // it's still worthwhile to get rid of the FSQRT if possible. 8240 SDValue SqrtOp; 8241 SDValue OtherOp; 8242 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8243 SqrtOp = N1.getOperand(0); 8244 OtherOp = N1.getOperand(1); 8245 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8246 SqrtOp = N1.getOperand(1); 8247 OtherOp = N1.getOperand(0); 8248 } 8249 if (SqrtOp.getNode()) { 8250 // We found a FSQRT, so try to make this fold: 8251 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8252 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) { 8253 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp); 8254 AddToWorklist(RV.getNode()); 8255 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8256 } 8257 } 8258 } 8259 8260 // Fold into a reciprocal estimate and multiply instead of a real divide. 8261 if (SDValue RV = BuildReciprocalEstimate(N1)) { 8262 AddToWorklist(RV.getNode()); 8263 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8264 } 8265 } 8266 8267 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8268 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8269 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8270 // Both can be negated for free, check to see if at least one is cheaper 8271 // negated. 8272 if (LHSNeg == 2 || RHSNeg == 2) 8273 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8274 GetNegatedExpression(N0, DAG, LegalOperations), 8275 GetNegatedExpression(N1, DAG, LegalOperations)); 8276 } 8277 } 8278 8279 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8280 // reciprocal. 8281 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8282 // Notice that this is not always beneficial. One reason is different target 8283 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8284 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8285 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8286 if (Options.UnsafeFPMath) { 8287 // Skip if current node is a reciprocal. 8288 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8289 return SDValue(); 8290 8291 SmallVector<SDNode *, 4> Users; 8292 // Find all FDIV users of the same divisor. 8293 for (SDNode::use_iterator UI = N1.getNode()->use_begin(), 8294 UE = N1.getNode()->use_end(); 8295 UI != UE; ++UI) { 8296 SDNode *User = UI.getUse().getUser(); 8297 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1) 8298 Users.push_back(User); 8299 } 8300 8301 if (TLI.combineRepeatedFPDivisors(Users.size())) { 8302 SDLoc DL(N); 8303 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0 8304 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1); 8305 8306 // Dividend / Divisor -> Dividend * Reciprocal 8307 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) { 8308 if ((*I)->getOperand(0) != FPOne) { 8309 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT, 8310 (*I)->getOperand(0), Reciprocal); 8311 DAG.ReplaceAllUsesWith(*I, NewNode.getNode()); 8312 } 8313 } 8314 return SDValue(); 8315 } 8316 } 8317 8318 return SDValue(); 8319 } 8320 8321 SDValue DAGCombiner::visitFREM(SDNode *N) { 8322 SDValue N0 = N->getOperand(0); 8323 SDValue N1 = N->getOperand(1); 8324 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8325 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8326 EVT VT = N->getValueType(0); 8327 8328 // fold (frem c1, c2) -> fmod(c1,c2) 8329 if (N0CFP && N1CFP) 8330 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 8331 8332 return SDValue(); 8333 } 8334 8335 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8336 if (DAG.getTarget().Options.UnsafeFPMath && 8337 !TLI.isFsqrtCheap()) { 8338 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8339 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) { 8340 EVT VT = RV.getValueType(); 8341 SDLoc DL(N); 8342 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV); 8343 AddToWorklist(RV.getNode()); 8344 8345 // Unfortunately, RV is now NaN if the input was exactly 0. 8346 // Select out this case and force the answer to 0. 8347 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8348 SDValue ZeroCmp = 8349 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT), 8350 N->getOperand(0), Zero, ISD::SETEQ); 8351 AddToWorklist(ZeroCmp.getNode()); 8352 AddToWorklist(RV.getNode()); 8353 8354 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, 8355 DL, VT, ZeroCmp, Zero, RV); 8356 return RV; 8357 } 8358 } 8359 return SDValue(); 8360 } 8361 8362 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8363 SDValue N0 = N->getOperand(0); 8364 SDValue N1 = N->getOperand(1); 8365 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8366 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8367 EVT VT = N->getValueType(0); 8368 8369 if (N0CFP && N1CFP) // Constant fold 8370 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8371 8372 if (N1CFP) { 8373 const APFloat& V = N1CFP->getValueAPF(); 8374 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8375 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8376 if (!V.isNegative()) { 8377 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8378 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8379 } else { 8380 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8381 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8382 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8383 } 8384 } 8385 8386 // copysign(fabs(x), y) -> copysign(x, y) 8387 // copysign(fneg(x), y) -> copysign(x, y) 8388 // copysign(copysign(x,z), y) -> copysign(x, y) 8389 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8390 N0.getOpcode() == ISD::FCOPYSIGN) 8391 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8392 N0.getOperand(0), N1); 8393 8394 // copysign(x, abs(y)) -> abs(x) 8395 if (N1.getOpcode() == ISD::FABS) 8396 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8397 8398 // copysign(x, copysign(y,z)) -> copysign(x, z) 8399 if (N1.getOpcode() == ISD::FCOPYSIGN) 8400 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8401 N0, N1.getOperand(1)); 8402 8403 // copysign(x, fp_extend(y)) -> copysign(x, y) 8404 // copysign(x, fp_round(y)) -> copysign(x, y) 8405 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8406 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8407 N0, N1.getOperand(0)); 8408 8409 return SDValue(); 8410 } 8411 8412 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8413 SDValue N0 = N->getOperand(0); 8414 EVT VT = N->getValueType(0); 8415 EVT OpVT = N0.getValueType(); 8416 8417 // fold (sint_to_fp c1) -> c1fp 8418 if (isConstantIntBuildVectorOrConstantInt(N0) && 8419 // ...but only if the target supports immediate floating-point values 8420 (!LegalOperations || 8421 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8422 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8423 8424 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8425 // but UINT_TO_FP is legal on this target, try to convert. 8426 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8427 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8428 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8429 if (DAG.SignBitIsZero(N0)) 8430 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8431 } 8432 8433 // The next optimizations are desirable only if SELECT_CC can be lowered. 8434 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8435 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8436 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8437 !VT.isVector() && 8438 (!LegalOperations || 8439 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8440 SDLoc DL(N); 8441 SDValue Ops[] = 8442 { N0.getOperand(0), N0.getOperand(1), 8443 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8444 N0.getOperand(2) }; 8445 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8446 } 8447 8448 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8449 // (select_cc x, y, 1.0, 0.0,, cc) 8450 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8451 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8452 (!LegalOperations || 8453 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8454 SDLoc DL(N); 8455 SDValue Ops[] = 8456 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8457 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8458 N0.getOperand(0).getOperand(2) }; 8459 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8460 } 8461 } 8462 8463 return SDValue(); 8464 } 8465 8466 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8467 SDValue N0 = N->getOperand(0); 8468 EVT VT = N->getValueType(0); 8469 EVT OpVT = N0.getValueType(); 8470 8471 // fold (uint_to_fp c1) -> c1fp 8472 if (isConstantIntBuildVectorOrConstantInt(N0) && 8473 // ...but only if the target supports immediate floating-point values 8474 (!LegalOperations || 8475 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8476 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8477 8478 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8479 // but SINT_TO_FP is legal on this target, try to convert. 8480 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8481 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8482 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8483 if (DAG.SignBitIsZero(N0)) 8484 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8485 } 8486 8487 // The next optimizations are desirable only if SELECT_CC can be lowered. 8488 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8489 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8490 8491 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8492 (!LegalOperations || 8493 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8494 SDLoc DL(N); 8495 SDValue Ops[] = 8496 { N0.getOperand(0), N0.getOperand(1), 8497 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8498 N0.getOperand(2) }; 8499 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8500 } 8501 } 8502 8503 return SDValue(); 8504 } 8505 8506 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8507 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8508 SDValue N0 = N->getOperand(0); 8509 EVT VT = N->getValueType(0); 8510 8511 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8512 return SDValue(); 8513 8514 SDValue Src = N0.getOperand(0); 8515 EVT SrcVT = Src.getValueType(); 8516 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8517 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8518 8519 // We can safely assume the conversion won't overflow the output range, 8520 // because (for example) (uint8_t)18293.f is undefined behavior. 8521 8522 // Since we can assume the conversion won't overflow, our decision as to 8523 // whether the input will fit in the float should depend on the minimum 8524 // of the input range and output range. 8525 8526 // This means this is also safe for a signed input and unsigned output, since 8527 // a negative input would lead to undefined behavior. 8528 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8529 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8530 unsigned ActualSize = std::min(InputSize, OutputSize); 8531 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8532 8533 // We can only fold away the float conversion if the input range can be 8534 // represented exactly in the float range. 8535 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8536 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8537 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8538 : ISD::ZERO_EXTEND; 8539 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8540 } 8541 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8542 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8543 if (SrcVT == VT) 8544 return Src; 8545 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8546 } 8547 return SDValue(); 8548 } 8549 8550 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8551 SDValue N0 = N->getOperand(0); 8552 EVT VT = N->getValueType(0); 8553 8554 // fold (fp_to_sint c1fp) -> c1 8555 if (isConstantFPBuildVectorOrConstantFP(N0)) 8556 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8557 8558 return FoldIntToFPToInt(N, DAG); 8559 } 8560 8561 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8562 SDValue N0 = N->getOperand(0); 8563 EVT VT = N->getValueType(0); 8564 8565 // fold (fp_to_uint c1fp) -> c1 8566 if (isConstantFPBuildVectorOrConstantFP(N0)) 8567 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8568 8569 return FoldIntToFPToInt(N, DAG); 8570 } 8571 8572 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8573 SDValue N0 = N->getOperand(0); 8574 SDValue N1 = N->getOperand(1); 8575 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8576 EVT VT = N->getValueType(0); 8577 8578 // fold (fp_round c1fp) -> c1fp 8579 if (N0CFP) 8580 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8581 8582 // fold (fp_round (fp_extend x)) -> x 8583 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8584 return N0.getOperand(0); 8585 8586 // fold (fp_round (fp_round x)) -> (fp_round x) 8587 if (N0.getOpcode() == ISD::FP_ROUND) { 8588 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8589 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8590 // If the first fp_round isn't a value preserving truncation, it might 8591 // introduce a tie in the second fp_round, that wouldn't occur in the 8592 // single-step fp_round we want to fold to. 8593 // In other words, double rounding isn't the same as rounding. 8594 // Also, this is a value preserving truncation iff both fp_round's are. 8595 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 8596 SDLoc DL(N); 8597 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 8598 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 8599 } 8600 } 8601 8602 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8603 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8604 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8605 N0.getOperand(0), N1); 8606 AddToWorklist(Tmp.getNode()); 8607 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8608 Tmp, N0.getOperand(1)); 8609 } 8610 8611 return SDValue(); 8612 } 8613 8614 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8615 SDValue N0 = N->getOperand(0); 8616 EVT VT = N->getValueType(0); 8617 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8618 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8619 8620 // fold (fp_round_inreg c1fp) -> c1fp 8621 if (N0CFP && isTypeLegal(EVT)) { 8622 SDLoc DL(N); 8623 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 8624 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 8625 } 8626 8627 return SDValue(); 8628 } 8629 8630 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8631 SDValue N0 = N->getOperand(0); 8632 EVT VT = N->getValueType(0); 8633 8634 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8635 if (N->hasOneUse() && 8636 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8637 return SDValue(); 8638 8639 // fold (fp_extend c1fp) -> c1fp 8640 if (isConstantFPBuildVectorOrConstantFP(N0)) 8641 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8642 8643 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 8644 if (N0.getOpcode() == ISD::FP16_TO_FP && 8645 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 8646 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 8647 8648 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8649 // value of X. 8650 if (N0.getOpcode() == ISD::FP_ROUND 8651 && N0.getNode()->getConstantOperandVal(1) == 1) { 8652 SDValue In = N0.getOperand(0); 8653 if (In.getValueType() == VT) return In; 8654 if (VT.bitsLT(In.getValueType())) 8655 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8656 In, N0.getOperand(1)); 8657 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8658 } 8659 8660 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8661 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8662 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8663 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8664 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8665 LN0->getChain(), 8666 LN0->getBasePtr(), N0.getValueType(), 8667 LN0->getMemOperand()); 8668 CombineTo(N, ExtLoad); 8669 CombineTo(N0.getNode(), 8670 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8671 N0.getValueType(), ExtLoad, 8672 DAG.getIntPtrConstant(1, SDLoc(N0))), 8673 ExtLoad.getValue(1)); 8674 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8675 } 8676 8677 return SDValue(); 8678 } 8679 8680 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8681 SDValue N0 = N->getOperand(0); 8682 EVT VT = N->getValueType(0); 8683 8684 // fold (fceil c1) -> fceil(c1) 8685 if (isConstantFPBuildVectorOrConstantFP(N0)) 8686 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8687 8688 return SDValue(); 8689 } 8690 8691 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8692 SDValue N0 = N->getOperand(0); 8693 EVT VT = N->getValueType(0); 8694 8695 // fold (ftrunc c1) -> ftrunc(c1) 8696 if (isConstantFPBuildVectorOrConstantFP(N0)) 8697 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8698 8699 return SDValue(); 8700 } 8701 8702 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8703 SDValue N0 = N->getOperand(0); 8704 EVT VT = N->getValueType(0); 8705 8706 // fold (ffloor c1) -> ffloor(c1) 8707 if (isConstantFPBuildVectorOrConstantFP(N0)) 8708 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8709 8710 return SDValue(); 8711 } 8712 8713 // FIXME: FNEG and FABS have a lot in common; refactor. 8714 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8715 SDValue N0 = N->getOperand(0); 8716 EVT VT = N->getValueType(0); 8717 8718 // Constant fold FNEG. 8719 if (isConstantFPBuildVectorOrConstantFP(N0)) 8720 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 8721 8722 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8723 &DAG.getTarget().Options)) 8724 return GetNegatedExpression(N0, DAG, LegalOperations); 8725 8726 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8727 // constant pool values. 8728 if (!TLI.isFNegFree(VT) && 8729 N0.getOpcode() == ISD::BITCAST && 8730 N0.getNode()->hasOneUse()) { 8731 SDValue Int = N0.getOperand(0); 8732 EVT IntVT = Int.getValueType(); 8733 if (IntVT.isInteger() && !IntVT.isVector()) { 8734 APInt SignMask; 8735 if (N0.getValueType().isVector()) { 8736 // For a vector, get a mask such as 0x80... per scalar element 8737 // and splat it. 8738 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8739 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8740 } else { 8741 // For a scalar, just generate 0x80... 8742 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 8743 } 8744 SDLoc DL0(N0); 8745 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 8746 DAG.getConstant(SignMask, DL0, IntVT)); 8747 AddToWorklist(Int.getNode()); 8748 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 8749 } 8750 } 8751 8752 // (fneg (fmul c, x)) -> (fmul -c, x) 8753 if (N0.getOpcode() == ISD::FMUL) { 8754 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8755 if (CFP1) { 8756 APFloat CVal = CFP1->getValueAPF(); 8757 CVal.changeSign(); 8758 if (Level >= AfterLegalizeDAG && 8759 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 8760 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 8761 return DAG.getNode( 8762 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 8763 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 8764 } 8765 } 8766 8767 return SDValue(); 8768 } 8769 8770 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 8771 SDValue N0 = N->getOperand(0); 8772 SDValue N1 = N->getOperand(1); 8773 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8774 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8775 8776 if (N0CFP && N1CFP) { 8777 const APFloat &C0 = N0CFP->getValueAPF(); 8778 const APFloat &C1 = N1CFP->getValueAPF(); 8779 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0)); 8780 } 8781 8782 if (N0CFP) { 8783 EVT VT = N->getValueType(0); 8784 // Canonicalize to constant on RHS. 8785 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 8786 } 8787 8788 return SDValue(); 8789 } 8790 8791 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 8792 SDValue N0 = N->getOperand(0); 8793 SDValue N1 = N->getOperand(1); 8794 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8795 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8796 8797 if (N0CFP && N1CFP) { 8798 const APFloat &C0 = N0CFP->getValueAPF(); 8799 const APFloat &C1 = N1CFP->getValueAPF(); 8800 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0)); 8801 } 8802 8803 if (N0CFP) { 8804 EVT VT = N->getValueType(0); 8805 // Canonicalize to constant on RHS. 8806 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 8807 } 8808 8809 return SDValue(); 8810 } 8811 8812 SDValue DAGCombiner::visitFABS(SDNode *N) { 8813 SDValue N0 = N->getOperand(0); 8814 EVT VT = N->getValueType(0); 8815 8816 // fold (fabs c1) -> fabs(c1) 8817 if (isConstantFPBuildVectorOrConstantFP(N0)) 8818 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8819 8820 // fold (fabs (fabs x)) -> (fabs x) 8821 if (N0.getOpcode() == ISD::FABS) 8822 return N->getOperand(0); 8823 8824 // fold (fabs (fneg x)) -> (fabs x) 8825 // fold (fabs (fcopysign x, y)) -> (fabs x) 8826 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 8827 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 8828 8829 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 8830 // constant pool values. 8831 if (!TLI.isFAbsFree(VT) && 8832 N0.getOpcode() == ISD::BITCAST && 8833 N0.getNode()->hasOneUse()) { 8834 SDValue Int = N0.getOperand(0); 8835 EVT IntVT = Int.getValueType(); 8836 if (IntVT.isInteger() && !IntVT.isVector()) { 8837 APInt SignMask; 8838 if (N0.getValueType().isVector()) { 8839 // For a vector, get a mask such as 0x7f... per scalar element 8840 // and splat it. 8841 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8842 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8843 } else { 8844 // For a scalar, just generate 0x7f... 8845 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 8846 } 8847 SDLoc DL(N0); 8848 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 8849 DAG.getConstant(SignMask, DL, IntVT)); 8850 AddToWorklist(Int.getNode()); 8851 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 8852 } 8853 } 8854 8855 return SDValue(); 8856 } 8857 8858 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 8859 SDValue Chain = N->getOperand(0); 8860 SDValue N1 = N->getOperand(1); 8861 SDValue N2 = N->getOperand(2); 8862 8863 // If N is a constant we could fold this into a fallthrough or unconditional 8864 // branch. However that doesn't happen very often in normal code, because 8865 // Instcombine/SimplifyCFG should have handled the available opportunities. 8866 // If we did this folding here, it would be necessary to update the 8867 // MachineBasicBlock CFG, which is awkward. 8868 8869 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 8870 // on the target. 8871 if (N1.getOpcode() == ISD::SETCC && 8872 TLI.isOperationLegalOrCustom(ISD::BR_CC, 8873 N1.getOperand(0).getValueType())) { 8874 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8875 Chain, N1.getOperand(2), 8876 N1.getOperand(0), N1.getOperand(1), N2); 8877 } 8878 8879 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 8880 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 8881 (N1.getOperand(0).hasOneUse() && 8882 N1.getOperand(0).getOpcode() == ISD::SRL))) { 8883 SDNode *Trunc = nullptr; 8884 if (N1.getOpcode() == ISD::TRUNCATE) { 8885 // Look pass the truncate. 8886 Trunc = N1.getNode(); 8887 N1 = N1.getOperand(0); 8888 } 8889 8890 // Match this pattern so that we can generate simpler code: 8891 // 8892 // %a = ... 8893 // %b = and i32 %a, 2 8894 // %c = srl i32 %b, 1 8895 // brcond i32 %c ... 8896 // 8897 // into 8898 // 8899 // %a = ... 8900 // %b = and i32 %a, 2 8901 // %c = setcc eq %b, 0 8902 // brcond %c ... 8903 // 8904 // This applies only when the AND constant value has one bit set and the 8905 // SRL constant is equal to the log2 of the AND constant. The back-end is 8906 // smart enough to convert the result into a TEST/JMP sequence. 8907 SDValue Op0 = N1.getOperand(0); 8908 SDValue Op1 = N1.getOperand(1); 8909 8910 if (Op0.getOpcode() == ISD::AND && 8911 Op1.getOpcode() == ISD::Constant) { 8912 SDValue AndOp1 = Op0.getOperand(1); 8913 8914 if (AndOp1.getOpcode() == ISD::Constant) { 8915 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 8916 8917 if (AndConst.isPowerOf2() && 8918 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 8919 SDLoc DL(N); 8920 SDValue SetCC = 8921 DAG.getSetCC(DL, 8922 getSetCCResultType(Op0.getValueType()), 8923 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 8924 ISD::SETNE); 8925 8926 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 8927 MVT::Other, Chain, SetCC, N2); 8928 // Don't add the new BRCond into the worklist or else SimplifySelectCC 8929 // will convert it back to (X & C1) >> C2. 8930 CombineTo(N, NewBRCond, false); 8931 // Truncate is dead. 8932 if (Trunc) 8933 deleteAndRecombine(Trunc); 8934 // Replace the uses of SRL with SETCC 8935 WorklistRemover DeadNodes(*this); 8936 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8937 deleteAndRecombine(N1.getNode()); 8938 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8939 } 8940 } 8941 } 8942 8943 if (Trunc) 8944 // Restore N1 if the above transformation doesn't match. 8945 N1 = N->getOperand(1); 8946 } 8947 8948 // Transform br(xor(x, y)) -> br(x != y) 8949 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 8950 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 8951 SDNode *TheXor = N1.getNode(); 8952 SDValue Op0 = TheXor->getOperand(0); 8953 SDValue Op1 = TheXor->getOperand(1); 8954 if (Op0.getOpcode() == Op1.getOpcode()) { 8955 // Avoid missing important xor optimizations. 8956 SDValue Tmp = visitXOR(TheXor); 8957 if (Tmp.getNode()) { 8958 if (Tmp.getNode() != TheXor) { 8959 DEBUG(dbgs() << "\nReplacing.8 "; 8960 TheXor->dump(&DAG); 8961 dbgs() << "\nWith: "; 8962 Tmp.getNode()->dump(&DAG); 8963 dbgs() << '\n'); 8964 WorklistRemover DeadNodes(*this); 8965 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 8966 deleteAndRecombine(TheXor); 8967 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8968 MVT::Other, Chain, Tmp, N2); 8969 } 8970 8971 // visitXOR has changed XOR's operands or replaced the XOR completely, 8972 // bail out. 8973 return SDValue(N, 0); 8974 } 8975 } 8976 8977 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 8978 bool Equal = false; 8979 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 8980 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 8981 Op0.getOpcode() == ISD::XOR) { 8982 TheXor = Op0.getNode(); 8983 Equal = true; 8984 } 8985 8986 EVT SetCCVT = N1.getValueType(); 8987 if (LegalTypes) 8988 SetCCVT = getSetCCResultType(SetCCVT); 8989 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 8990 SetCCVT, 8991 Op0, Op1, 8992 Equal ? ISD::SETEQ : ISD::SETNE); 8993 // Replace the uses of XOR with SETCC 8994 WorklistRemover DeadNodes(*this); 8995 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8996 deleteAndRecombine(N1.getNode()); 8997 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8998 MVT::Other, Chain, SetCC, N2); 8999 } 9000 } 9001 9002 return SDValue(); 9003 } 9004 9005 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9006 // 9007 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9008 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9009 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9010 9011 // If N is a constant we could fold this into a fallthrough or unconditional 9012 // branch. However that doesn't happen very often in normal code, because 9013 // Instcombine/SimplifyCFG should have handled the available opportunities. 9014 // If we did this folding here, it would be necessary to update the 9015 // MachineBasicBlock CFG, which is awkward. 9016 9017 // Use SimplifySetCC to simplify SETCC's. 9018 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9019 CondLHS, CondRHS, CC->get(), SDLoc(N), 9020 false); 9021 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9022 9023 // fold to a simpler setcc 9024 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9025 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9026 N->getOperand(0), Simp.getOperand(2), 9027 Simp.getOperand(0), Simp.getOperand(1), 9028 N->getOperand(4)); 9029 9030 return SDValue(); 9031 } 9032 9033 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9034 /// and that N may be folded in the load / store addressing mode. 9035 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9036 SelectionDAG &DAG, 9037 const TargetLowering &TLI) { 9038 EVT VT; 9039 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9040 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9041 return false; 9042 VT = LD->getMemoryVT(); 9043 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9044 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9045 return false; 9046 VT = ST->getMemoryVT(); 9047 } else 9048 return false; 9049 9050 TargetLowering::AddrMode AM; 9051 if (N->getOpcode() == ISD::ADD) { 9052 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9053 if (Offset) 9054 // [reg +/- imm] 9055 AM.BaseOffs = Offset->getSExtValue(); 9056 else 9057 // [reg +/- reg] 9058 AM.Scale = 1; 9059 } else if (N->getOpcode() == ISD::SUB) { 9060 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9061 if (Offset) 9062 // [reg +/- imm] 9063 AM.BaseOffs = -Offset->getSExtValue(); 9064 else 9065 // [reg +/- reg] 9066 AM.Scale = 1; 9067 } else 9068 return false; 9069 9070 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 9071 } 9072 9073 /// Try turning a load/store into a pre-indexed load/store when the base 9074 /// pointer is an add or subtract and it has other uses besides the load/store. 9075 /// After the transformation, the new indexed load/store has effectively folded 9076 /// the add/subtract in and all of its other uses are redirected to the 9077 /// new load/store. 9078 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9079 if (Level < AfterLegalizeDAG) 9080 return false; 9081 9082 bool isLoad = true; 9083 SDValue Ptr; 9084 EVT VT; 9085 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9086 if (LD->isIndexed()) 9087 return false; 9088 VT = LD->getMemoryVT(); 9089 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9090 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9091 return false; 9092 Ptr = LD->getBasePtr(); 9093 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9094 if (ST->isIndexed()) 9095 return false; 9096 VT = ST->getMemoryVT(); 9097 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9098 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9099 return false; 9100 Ptr = ST->getBasePtr(); 9101 isLoad = false; 9102 } else { 9103 return false; 9104 } 9105 9106 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9107 // out. There is no reason to make this a preinc/predec. 9108 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9109 Ptr.getNode()->hasOneUse()) 9110 return false; 9111 9112 // Ask the target to do addressing mode selection. 9113 SDValue BasePtr; 9114 SDValue Offset; 9115 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9116 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9117 return false; 9118 9119 // Backends without true r+i pre-indexed forms may need to pass a 9120 // constant base with a variable offset so that constant coercion 9121 // will work with the patterns in canonical form. 9122 bool Swapped = false; 9123 if (isa<ConstantSDNode>(BasePtr)) { 9124 std::swap(BasePtr, Offset); 9125 Swapped = true; 9126 } 9127 9128 // Don't create a indexed load / store with zero offset. 9129 if (isa<ConstantSDNode>(Offset) && 9130 cast<ConstantSDNode>(Offset)->isNullValue()) 9131 return false; 9132 9133 // Try turning it into a pre-indexed load / store except when: 9134 // 1) The new base ptr is a frame index. 9135 // 2) If N is a store and the new base ptr is either the same as or is a 9136 // predecessor of the value being stored. 9137 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9138 // that would create a cycle. 9139 // 4) All uses are load / store ops that use it as old base ptr. 9140 9141 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9142 // (plus the implicit offset) to a register to preinc anyway. 9143 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9144 return false; 9145 9146 // Check #2. 9147 if (!isLoad) { 9148 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9149 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9150 return false; 9151 } 9152 9153 // If the offset is a constant, there may be other adds of constants that 9154 // can be folded with this one. We should do this to avoid having to keep 9155 // a copy of the original base pointer. 9156 SmallVector<SDNode *, 16> OtherUses; 9157 if (isa<ConstantSDNode>(Offset)) 9158 for (SDNode *Use : BasePtr.getNode()->uses()) { 9159 if (Use == Ptr.getNode()) 9160 continue; 9161 9162 if (Use->isPredecessorOf(N)) 9163 continue; 9164 9165 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 9166 OtherUses.clear(); 9167 break; 9168 } 9169 9170 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 9171 if (Op1.getNode() == BasePtr.getNode()) 9172 std::swap(Op0, Op1); 9173 assert(Op0.getNode() == BasePtr.getNode() && 9174 "Use of ADD/SUB but not an operand"); 9175 9176 if (!isa<ConstantSDNode>(Op1)) { 9177 OtherUses.clear(); 9178 break; 9179 } 9180 9181 // FIXME: In some cases, we can be smarter about this. 9182 if (Op1.getValueType() != Offset.getValueType()) { 9183 OtherUses.clear(); 9184 break; 9185 } 9186 9187 OtherUses.push_back(Use); 9188 } 9189 9190 if (Swapped) 9191 std::swap(BasePtr, Offset); 9192 9193 // Now check for #3 and #4. 9194 bool RealUse = false; 9195 9196 // Caches for hasPredecessorHelper 9197 SmallPtrSet<const SDNode *, 32> Visited; 9198 SmallVector<const SDNode *, 16> Worklist; 9199 9200 for (SDNode *Use : Ptr.getNode()->uses()) { 9201 if (Use == N) 9202 continue; 9203 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9204 return false; 9205 9206 // If Ptr may be folded in addressing mode of other use, then it's 9207 // not profitable to do this transformation. 9208 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9209 RealUse = true; 9210 } 9211 9212 if (!RealUse) 9213 return false; 9214 9215 SDValue Result; 9216 if (isLoad) 9217 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9218 BasePtr, Offset, AM); 9219 else 9220 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9221 BasePtr, Offset, AM); 9222 ++PreIndexedNodes; 9223 ++NodesCombined; 9224 DEBUG(dbgs() << "\nReplacing.4 "; 9225 N->dump(&DAG); 9226 dbgs() << "\nWith: "; 9227 Result.getNode()->dump(&DAG); 9228 dbgs() << '\n'); 9229 WorklistRemover DeadNodes(*this); 9230 if (isLoad) { 9231 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9232 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9233 } else { 9234 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9235 } 9236 9237 // Finally, since the node is now dead, remove it from the graph. 9238 deleteAndRecombine(N); 9239 9240 if (Swapped) 9241 std::swap(BasePtr, Offset); 9242 9243 // Replace other uses of BasePtr that can be updated to use Ptr 9244 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9245 unsigned OffsetIdx = 1; 9246 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9247 OffsetIdx = 0; 9248 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9249 BasePtr.getNode() && "Expected BasePtr operand"); 9250 9251 // We need to replace ptr0 in the following expression: 9252 // x0 * offset0 + y0 * ptr0 = t0 9253 // knowing that 9254 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9255 // 9256 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9257 // indexed load/store and the expresion that needs to be re-written. 9258 // 9259 // Therefore, we have: 9260 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9261 9262 ConstantSDNode *CN = 9263 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9264 int X0, X1, Y0, Y1; 9265 APInt Offset0 = CN->getAPIntValue(); 9266 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9267 9268 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9269 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9270 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9271 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9272 9273 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9274 9275 APInt CNV = Offset0; 9276 if (X0 < 0) CNV = -CNV; 9277 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9278 else CNV = CNV - Offset1; 9279 9280 SDLoc DL(OtherUses[i]); 9281 9282 // We can now generate the new expression. 9283 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9284 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9285 9286 SDValue NewUse = DAG.getNode(Opcode, 9287 DL, 9288 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9289 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9290 deleteAndRecombine(OtherUses[i]); 9291 } 9292 9293 // Replace the uses of Ptr with uses of the updated base value. 9294 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9295 deleteAndRecombine(Ptr.getNode()); 9296 9297 return true; 9298 } 9299 9300 /// Try to combine a load/store with a add/sub of the base pointer node into a 9301 /// post-indexed load/store. The transformation folded the add/subtract into the 9302 /// new indexed load/store effectively and all of its uses are redirected to the 9303 /// new load/store. 9304 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9305 if (Level < AfterLegalizeDAG) 9306 return false; 9307 9308 bool isLoad = true; 9309 SDValue Ptr; 9310 EVT VT; 9311 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9312 if (LD->isIndexed()) 9313 return false; 9314 VT = LD->getMemoryVT(); 9315 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9316 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9317 return false; 9318 Ptr = LD->getBasePtr(); 9319 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9320 if (ST->isIndexed()) 9321 return false; 9322 VT = ST->getMemoryVT(); 9323 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9324 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9325 return false; 9326 Ptr = ST->getBasePtr(); 9327 isLoad = false; 9328 } else { 9329 return false; 9330 } 9331 9332 if (Ptr.getNode()->hasOneUse()) 9333 return false; 9334 9335 for (SDNode *Op : Ptr.getNode()->uses()) { 9336 if (Op == N || 9337 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9338 continue; 9339 9340 SDValue BasePtr; 9341 SDValue Offset; 9342 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9343 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9344 // Don't create a indexed load / store with zero offset. 9345 if (isa<ConstantSDNode>(Offset) && 9346 cast<ConstantSDNode>(Offset)->isNullValue()) 9347 continue; 9348 9349 // Try turning it into a post-indexed load / store except when 9350 // 1) All uses are load / store ops that use it as base ptr (and 9351 // it may be folded as addressing mmode). 9352 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9353 // nor a successor of N. Otherwise, if Op is folded that would 9354 // create a cycle. 9355 9356 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9357 continue; 9358 9359 // Check for #1. 9360 bool TryNext = false; 9361 for (SDNode *Use : BasePtr.getNode()->uses()) { 9362 if (Use == Ptr.getNode()) 9363 continue; 9364 9365 // If all the uses are load / store addresses, then don't do the 9366 // transformation. 9367 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9368 bool RealUse = false; 9369 for (SDNode *UseUse : Use->uses()) { 9370 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9371 RealUse = true; 9372 } 9373 9374 if (!RealUse) { 9375 TryNext = true; 9376 break; 9377 } 9378 } 9379 } 9380 9381 if (TryNext) 9382 continue; 9383 9384 // Check for #2 9385 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9386 SDValue Result = isLoad 9387 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9388 BasePtr, Offset, AM) 9389 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9390 BasePtr, Offset, AM); 9391 ++PostIndexedNodes; 9392 ++NodesCombined; 9393 DEBUG(dbgs() << "\nReplacing.5 "; 9394 N->dump(&DAG); 9395 dbgs() << "\nWith: "; 9396 Result.getNode()->dump(&DAG); 9397 dbgs() << '\n'); 9398 WorklistRemover DeadNodes(*this); 9399 if (isLoad) { 9400 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9401 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9402 } else { 9403 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9404 } 9405 9406 // Finally, since the node is now dead, remove it from the graph. 9407 deleteAndRecombine(N); 9408 9409 // Replace the uses of Use with uses of the updated base value. 9410 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9411 Result.getValue(isLoad ? 1 : 0)); 9412 deleteAndRecombine(Op); 9413 return true; 9414 } 9415 } 9416 } 9417 9418 return false; 9419 } 9420 9421 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9422 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9423 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9424 assert(AM != ISD::UNINDEXED); 9425 SDValue BP = LD->getOperand(1); 9426 SDValue Inc = LD->getOperand(2); 9427 9428 // Some backends use TargetConstants for load offsets, but don't expect 9429 // TargetConstants in general ADD nodes. We can convert these constants into 9430 // regular Constants (if the constant is not opaque). 9431 assert((Inc.getOpcode() != ISD::TargetConstant || 9432 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9433 "Cannot split out indexing using opaque target constants"); 9434 if (Inc.getOpcode() == ISD::TargetConstant) { 9435 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9436 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9437 ConstInc->getValueType(0)); 9438 } 9439 9440 unsigned Opc = 9441 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9442 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9443 } 9444 9445 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9446 LoadSDNode *LD = cast<LoadSDNode>(N); 9447 SDValue Chain = LD->getChain(); 9448 SDValue Ptr = LD->getBasePtr(); 9449 9450 // If load is not volatile and there are no uses of the loaded value (and 9451 // the updated indexed value in case of indexed loads), change uses of the 9452 // chain value into uses of the chain input (i.e. delete the dead load). 9453 if (!LD->isVolatile()) { 9454 if (N->getValueType(1) == MVT::Other) { 9455 // Unindexed loads. 9456 if (!N->hasAnyUseOfValue(0)) { 9457 // It's not safe to use the two value CombineTo variant here. e.g. 9458 // v1, chain2 = load chain1, loc 9459 // v2, chain3 = load chain2, loc 9460 // v3 = add v2, c 9461 // Now we replace use of chain2 with chain1. This makes the second load 9462 // isomorphic to the one we are deleting, and thus makes this load live. 9463 DEBUG(dbgs() << "\nReplacing.6 "; 9464 N->dump(&DAG); 9465 dbgs() << "\nWith chain: "; 9466 Chain.getNode()->dump(&DAG); 9467 dbgs() << "\n"); 9468 WorklistRemover DeadNodes(*this); 9469 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9470 9471 if (N->use_empty()) 9472 deleteAndRecombine(N); 9473 9474 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9475 } 9476 } else { 9477 // Indexed loads. 9478 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9479 9480 // If this load has an opaque TargetConstant offset, then we cannot split 9481 // the indexing into an add/sub directly (that TargetConstant may not be 9482 // valid for a different type of node, and we cannot convert an opaque 9483 // target constant into a regular constant). 9484 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9485 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9486 9487 if (!N->hasAnyUseOfValue(0) && 9488 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9489 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9490 SDValue Index; 9491 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9492 Index = SplitIndexingFromLoad(LD); 9493 // Try to fold the base pointer arithmetic into subsequent loads and 9494 // stores. 9495 AddUsersToWorklist(N); 9496 } else 9497 Index = DAG.getUNDEF(N->getValueType(1)); 9498 DEBUG(dbgs() << "\nReplacing.7 "; 9499 N->dump(&DAG); 9500 dbgs() << "\nWith: "; 9501 Undef.getNode()->dump(&DAG); 9502 dbgs() << " and 2 other values\n"); 9503 WorklistRemover DeadNodes(*this); 9504 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9505 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9506 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9507 deleteAndRecombine(N); 9508 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9509 } 9510 } 9511 } 9512 9513 // If this load is directly stored, replace the load value with the stored 9514 // value. 9515 // TODO: Handle store large -> read small portion. 9516 // TODO: Handle TRUNCSTORE/LOADEXT 9517 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9518 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9519 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9520 if (PrevST->getBasePtr() == Ptr && 9521 PrevST->getValue().getValueType() == N->getValueType(0)) 9522 return CombineTo(N, Chain.getOperand(1), Chain); 9523 } 9524 } 9525 9526 // Try to infer better alignment information than the load already has. 9527 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9528 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9529 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9530 SDValue NewLoad = 9531 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9532 LD->getValueType(0), 9533 Chain, Ptr, LD->getPointerInfo(), 9534 LD->getMemoryVT(), 9535 LD->isVolatile(), LD->isNonTemporal(), 9536 LD->isInvariant(), Align, LD->getAAInfo()); 9537 if (NewLoad.getNode() != N) 9538 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9539 } 9540 } 9541 } 9542 9543 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9544 : DAG.getSubtarget().useAA(); 9545 #ifndef NDEBUG 9546 if (CombinerAAOnlyFunc.getNumOccurrences() && 9547 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9548 UseAA = false; 9549 #endif 9550 if (UseAA && LD->isUnindexed()) { 9551 // Walk up chain skipping non-aliasing memory nodes. 9552 SDValue BetterChain = FindBetterChain(N, Chain); 9553 9554 // If there is a better chain. 9555 if (Chain != BetterChain) { 9556 SDValue ReplLoad; 9557 9558 // Replace the chain to void dependency. 9559 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9560 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9561 BetterChain, Ptr, LD->getMemOperand()); 9562 } else { 9563 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9564 LD->getValueType(0), 9565 BetterChain, Ptr, LD->getMemoryVT(), 9566 LD->getMemOperand()); 9567 } 9568 9569 // Create token factor to keep old chain connected. 9570 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9571 MVT::Other, Chain, ReplLoad.getValue(1)); 9572 9573 // Make sure the new and old chains are cleaned up. 9574 AddToWorklist(Token.getNode()); 9575 9576 // Replace uses with load result and token factor. Don't add users 9577 // to work list. 9578 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9579 } 9580 } 9581 9582 // Try transforming N to an indexed load. 9583 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9584 return SDValue(N, 0); 9585 9586 // Try to slice up N to more direct loads if the slices are mapped to 9587 // different register banks or pairing can take place. 9588 if (SliceUpLoad(N)) 9589 return SDValue(N, 0); 9590 9591 return SDValue(); 9592 } 9593 9594 namespace { 9595 /// \brief Helper structure used to slice a load in smaller loads. 9596 /// Basically a slice is obtained from the following sequence: 9597 /// Origin = load Ty1, Base 9598 /// Shift = srl Ty1 Origin, CstTy Amount 9599 /// Inst = trunc Shift to Ty2 9600 /// 9601 /// Then, it will be rewriten into: 9602 /// Slice = load SliceTy, Base + SliceOffset 9603 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9604 /// 9605 /// SliceTy is deduced from the number of bits that are actually used to 9606 /// build Inst. 9607 struct LoadedSlice { 9608 /// \brief Helper structure used to compute the cost of a slice. 9609 struct Cost { 9610 /// Are we optimizing for code size. 9611 bool ForCodeSize; 9612 /// Various cost. 9613 unsigned Loads; 9614 unsigned Truncates; 9615 unsigned CrossRegisterBanksCopies; 9616 unsigned ZExts; 9617 unsigned Shift; 9618 9619 Cost(bool ForCodeSize = false) 9620 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9621 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9622 9623 /// \brief Get the cost of one isolated slice. 9624 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9625 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9626 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9627 EVT TruncType = LS.Inst->getValueType(0); 9628 EVT LoadedType = LS.getLoadedType(); 9629 if (TruncType != LoadedType && 9630 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9631 ZExts = 1; 9632 } 9633 9634 /// \brief Account for slicing gain in the current cost. 9635 /// Slicing provide a few gains like removing a shift or a 9636 /// truncate. This method allows to grow the cost of the original 9637 /// load with the gain from this slice. 9638 void addSliceGain(const LoadedSlice &LS) { 9639 // Each slice saves a truncate. 9640 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9641 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 9642 LS.Inst->getOperand(0).getValueType())) 9643 ++Truncates; 9644 // If there is a shift amount, this slice gets rid of it. 9645 if (LS.Shift) 9646 ++Shift; 9647 // If this slice can merge a cross register bank copy, account for it. 9648 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9649 ++CrossRegisterBanksCopies; 9650 } 9651 9652 Cost &operator+=(const Cost &RHS) { 9653 Loads += RHS.Loads; 9654 Truncates += RHS.Truncates; 9655 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9656 ZExts += RHS.ZExts; 9657 Shift += RHS.Shift; 9658 return *this; 9659 } 9660 9661 bool operator==(const Cost &RHS) const { 9662 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9663 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9664 ZExts == RHS.ZExts && Shift == RHS.Shift; 9665 } 9666 9667 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9668 9669 bool operator<(const Cost &RHS) const { 9670 // Assume cross register banks copies are as expensive as loads. 9671 // FIXME: Do we want some more target hooks? 9672 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9673 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9674 // Unless we are optimizing for code size, consider the 9675 // expensive operation first. 9676 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9677 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9678 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9679 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9680 } 9681 9682 bool operator>(const Cost &RHS) const { return RHS < *this; } 9683 9684 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9685 9686 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9687 }; 9688 // The last instruction that represent the slice. This should be a 9689 // truncate instruction. 9690 SDNode *Inst; 9691 // The original load instruction. 9692 LoadSDNode *Origin; 9693 // The right shift amount in bits from the original load. 9694 unsigned Shift; 9695 // The DAG from which Origin came from. 9696 // This is used to get some contextual information about legal types, etc. 9697 SelectionDAG *DAG; 9698 9699 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9700 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9701 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9702 9703 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9704 /// \return Result is \p BitWidth and has used bits set to 1 and 9705 /// not used bits set to 0. 9706 APInt getUsedBits() const { 9707 // Reproduce the trunc(lshr) sequence: 9708 // - Start from the truncated value. 9709 // - Zero extend to the desired bit width. 9710 // - Shift left. 9711 assert(Origin && "No original load to compare against."); 9712 unsigned BitWidth = Origin->getValueSizeInBits(0); 9713 assert(Inst && "This slice is not bound to an instruction"); 9714 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9715 "Extracted slice is bigger than the whole type!"); 9716 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9717 UsedBits.setAllBits(); 9718 UsedBits = UsedBits.zext(BitWidth); 9719 UsedBits <<= Shift; 9720 return UsedBits; 9721 } 9722 9723 /// \brief Get the size of the slice to be loaded in bytes. 9724 unsigned getLoadedSize() const { 9725 unsigned SliceSize = getUsedBits().countPopulation(); 9726 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 9727 return SliceSize / 8; 9728 } 9729 9730 /// \brief Get the type that will be loaded for this slice. 9731 /// Note: This may not be the final type for the slice. 9732 EVT getLoadedType() const { 9733 assert(DAG && "Missing context"); 9734 LLVMContext &Ctxt = *DAG->getContext(); 9735 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 9736 } 9737 9738 /// \brief Get the alignment of the load used for this slice. 9739 unsigned getAlignment() const { 9740 unsigned Alignment = Origin->getAlignment(); 9741 unsigned Offset = getOffsetFromBase(); 9742 if (Offset != 0) 9743 Alignment = MinAlign(Alignment, Alignment + Offset); 9744 return Alignment; 9745 } 9746 9747 /// \brief Check if this slice can be rewritten with legal operations. 9748 bool isLegal() const { 9749 // An invalid slice is not legal. 9750 if (!Origin || !Inst || !DAG) 9751 return false; 9752 9753 // Offsets are for indexed load only, we do not handle that. 9754 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 9755 return false; 9756 9757 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9758 9759 // Check that the type is legal. 9760 EVT SliceType = getLoadedType(); 9761 if (!TLI.isTypeLegal(SliceType)) 9762 return false; 9763 9764 // Check that the load is legal for this type. 9765 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 9766 return false; 9767 9768 // Check that the offset can be computed. 9769 // 1. Check its type. 9770 EVT PtrType = Origin->getBasePtr().getValueType(); 9771 if (PtrType == MVT::Untyped || PtrType.isExtended()) 9772 return false; 9773 9774 // 2. Check that it fits in the immediate. 9775 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 9776 return false; 9777 9778 // 3. Check that the computation is legal. 9779 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 9780 return false; 9781 9782 // Check that the zext is legal if it needs one. 9783 EVT TruncateType = Inst->getValueType(0); 9784 if (TruncateType != SliceType && 9785 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 9786 return false; 9787 9788 return true; 9789 } 9790 9791 /// \brief Get the offset in bytes of this slice in the original chunk of 9792 /// bits. 9793 /// \pre DAG != nullptr. 9794 uint64_t getOffsetFromBase() const { 9795 assert(DAG && "Missing context."); 9796 bool IsBigEndian = 9797 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 9798 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 9799 uint64_t Offset = Shift / 8; 9800 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 9801 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 9802 "The size of the original loaded type is not a multiple of a" 9803 " byte."); 9804 // If Offset is bigger than TySizeInBytes, it means we are loading all 9805 // zeros. This should have been optimized before in the process. 9806 assert(TySizeInBytes > Offset && 9807 "Invalid shift amount for given loaded size"); 9808 if (IsBigEndian) 9809 Offset = TySizeInBytes - Offset - getLoadedSize(); 9810 return Offset; 9811 } 9812 9813 /// \brief Generate the sequence of instructions to load the slice 9814 /// represented by this object and redirect the uses of this slice to 9815 /// this new sequence of instructions. 9816 /// \pre this->Inst && this->Origin are valid Instructions and this 9817 /// object passed the legal check: LoadedSlice::isLegal returned true. 9818 /// \return The last instruction of the sequence used to load the slice. 9819 SDValue loadSlice() const { 9820 assert(Inst && Origin && "Unable to replace a non-existing slice."); 9821 const SDValue &OldBaseAddr = Origin->getBasePtr(); 9822 SDValue BaseAddr = OldBaseAddr; 9823 // Get the offset in that chunk of bytes w.r.t. the endianess. 9824 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 9825 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 9826 if (Offset) { 9827 // BaseAddr = BaseAddr + Offset. 9828 EVT ArithType = BaseAddr.getValueType(); 9829 SDLoc DL(Origin); 9830 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 9831 DAG->getConstant(Offset, DL, ArithType)); 9832 } 9833 9834 // Create the type of the loaded slice according to its size. 9835 EVT SliceType = getLoadedType(); 9836 9837 // Create the load for the slice. 9838 SDValue LastInst = DAG->getLoad( 9839 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 9840 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 9841 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 9842 // If the final type is not the same as the loaded type, this means that 9843 // we have to pad with zero. Create a zero extend for that. 9844 EVT FinalType = Inst->getValueType(0); 9845 if (SliceType != FinalType) 9846 LastInst = 9847 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 9848 return LastInst; 9849 } 9850 9851 /// \brief Check if this slice can be merged with an expensive cross register 9852 /// bank copy. E.g., 9853 /// i = load i32 9854 /// f = bitcast i32 i to float 9855 bool canMergeExpensiveCrossRegisterBankCopy() const { 9856 if (!Inst || !Inst->hasOneUse()) 9857 return false; 9858 SDNode *Use = *Inst->use_begin(); 9859 if (Use->getOpcode() != ISD::BITCAST) 9860 return false; 9861 assert(DAG && "Missing context"); 9862 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9863 EVT ResVT = Use->getValueType(0); 9864 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 9865 const TargetRegisterClass *ArgRC = 9866 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 9867 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 9868 return false; 9869 9870 // At this point, we know that we perform a cross-register-bank copy. 9871 // Check if it is expensive. 9872 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 9873 // Assume bitcasts are cheap, unless both register classes do not 9874 // explicitly share a common sub class. 9875 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 9876 return false; 9877 9878 // Check if it will be merged with the load. 9879 // 1. Check the alignment constraint. 9880 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 9881 ResVT.getTypeForEVT(*DAG->getContext())); 9882 9883 if (RequiredAlignment > getAlignment()) 9884 return false; 9885 9886 // 2. Check that the load is a legal operation for that type. 9887 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 9888 return false; 9889 9890 // 3. Check that we do not have a zext in the way. 9891 if (Inst->getValueType(0) != getLoadedType()) 9892 return false; 9893 9894 return true; 9895 } 9896 }; 9897 } 9898 9899 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 9900 /// \p UsedBits looks like 0..0 1..1 0..0. 9901 static bool areUsedBitsDense(const APInt &UsedBits) { 9902 // If all the bits are one, this is dense! 9903 if (UsedBits.isAllOnesValue()) 9904 return true; 9905 9906 // Get rid of the unused bits on the right. 9907 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 9908 // Get rid of the unused bits on the left. 9909 if (NarrowedUsedBits.countLeadingZeros()) 9910 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 9911 // Check that the chunk of bits is completely used. 9912 return NarrowedUsedBits.isAllOnesValue(); 9913 } 9914 9915 /// \brief Check whether or not \p First and \p Second are next to each other 9916 /// in memory. This means that there is no hole between the bits loaded 9917 /// by \p First and the bits loaded by \p Second. 9918 static bool areSlicesNextToEachOther(const LoadedSlice &First, 9919 const LoadedSlice &Second) { 9920 assert(First.Origin == Second.Origin && First.Origin && 9921 "Unable to match different memory origins."); 9922 APInt UsedBits = First.getUsedBits(); 9923 assert((UsedBits & Second.getUsedBits()) == 0 && 9924 "Slices are not supposed to overlap."); 9925 UsedBits |= Second.getUsedBits(); 9926 return areUsedBitsDense(UsedBits); 9927 } 9928 9929 /// \brief Adjust the \p GlobalLSCost according to the target 9930 /// paring capabilities and the layout of the slices. 9931 /// \pre \p GlobalLSCost should account for at least as many loads as 9932 /// there is in the slices in \p LoadedSlices. 9933 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9934 LoadedSlice::Cost &GlobalLSCost) { 9935 unsigned NumberOfSlices = LoadedSlices.size(); 9936 // If there is less than 2 elements, no pairing is possible. 9937 if (NumberOfSlices < 2) 9938 return; 9939 9940 // Sort the slices so that elements that are likely to be next to each 9941 // other in memory are next to each other in the list. 9942 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 9943 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 9944 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 9945 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 9946 }); 9947 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 9948 // First (resp. Second) is the first (resp. Second) potentially candidate 9949 // to be placed in a paired load. 9950 const LoadedSlice *First = nullptr; 9951 const LoadedSlice *Second = nullptr; 9952 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 9953 // Set the beginning of the pair. 9954 First = Second) { 9955 9956 Second = &LoadedSlices[CurrSlice]; 9957 9958 // If First is NULL, it means we start a new pair. 9959 // Get to the next slice. 9960 if (!First) 9961 continue; 9962 9963 EVT LoadedType = First->getLoadedType(); 9964 9965 // If the types of the slices are different, we cannot pair them. 9966 if (LoadedType != Second->getLoadedType()) 9967 continue; 9968 9969 // Check if the target supplies paired loads for this type. 9970 unsigned RequiredAlignment = 0; 9971 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 9972 // move to the next pair, this type is hopeless. 9973 Second = nullptr; 9974 continue; 9975 } 9976 // Check if we meet the alignment requirement. 9977 if (RequiredAlignment > First->getAlignment()) 9978 continue; 9979 9980 // Check that both loads are next to each other in memory. 9981 if (!areSlicesNextToEachOther(*First, *Second)) 9982 continue; 9983 9984 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 9985 --GlobalLSCost.Loads; 9986 // Move to the next pair. 9987 Second = nullptr; 9988 } 9989 } 9990 9991 /// \brief Check the profitability of all involved LoadedSlice. 9992 /// Currently, it is considered profitable if there is exactly two 9993 /// involved slices (1) which are (2) next to each other in memory, and 9994 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 9995 /// 9996 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 9997 /// the elements themselves. 9998 /// 9999 /// FIXME: When the cost model will be mature enough, we can relax 10000 /// constraints (1) and (2). 10001 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10002 const APInt &UsedBits, bool ForCodeSize) { 10003 unsigned NumberOfSlices = LoadedSlices.size(); 10004 if (StressLoadSlicing) 10005 return NumberOfSlices > 1; 10006 10007 // Check (1). 10008 if (NumberOfSlices != 2) 10009 return false; 10010 10011 // Check (2). 10012 if (!areUsedBitsDense(UsedBits)) 10013 return false; 10014 10015 // Check (3). 10016 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10017 // The original code has one big load. 10018 OrigCost.Loads = 1; 10019 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10020 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10021 // Accumulate the cost of all the slices. 10022 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10023 GlobalSlicingCost += SliceCost; 10024 10025 // Account as cost in the original configuration the gain obtained 10026 // with the current slices. 10027 OrigCost.addSliceGain(LS); 10028 } 10029 10030 // If the target supports paired load, adjust the cost accordingly. 10031 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10032 return OrigCost > GlobalSlicingCost; 10033 } 10034 10035 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10036 /// operations, split it in the various pieces being extracted. 10037 /// 10038 /// This sort of thing is introduced by SROA. 10039 /// This slicing takes care not to insert overlapping loads. 10040 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10041 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10042 if (Level < AfterLegalizeDAG) 10043 return false; 10044 10045 LoadSDNode *LD = cast<LoadSDNode>(N); 10046 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10047 !LD->getValueType(0).isInteger()) 10048 return false; 10049 10050 // Keep track of already used bits to detect overlapping values. 10051 // In that case, we will just abort the transformation. 10052 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10053 10054 SmallVector<LoadedSlice, 4> LoadedSlices; 10055 10056 // Check if this load is used as several smaller chunks of bits. 10057 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10058 // of computation for each trunc. 10059 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10060 UI != UIEnd; ++UI) { 10061 // Skip the uses of the chain. 10062 if (UI.getUse().getResNo() != 0) 10063 continue; 10064 10065 SDNode *User = *UI; 10066 unsigned Shift = 0; 10067 10068 // Check if this is a trunc(lshr). 10069 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10070 isa<ConstantSDNode>(User->getOperand(1))) { 10071 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10072 User = *User->use_begin(); 10073 } 10074 10075 // At this point, User is a Truncate, iff we encountered, trunc or 10076 // trunc(lshr). 10077 if (User->getOpcode() != ISD::TRUNCATE) 10078 return false; 10079 10080 // The width of the type must be a power of 2 and greater than 8-bits. 10081 // Otherwise the load cannot be represented in LLVM IR. 10082 // Moreover, if we shifted with a non-8-bits multiple, the slice 10083 // will be across several bytes. We do not support that. 10084 unsigned Width = User->getValueSizeInBits(0); 10085 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10086 return 0; 10087 10088 // Build the slice for this chain of computations. 10089 LoadedSlice LS(User, LD, Shift, &DAG); 10090 APInt CurrentUsedBits = LS.getUsedBits(); 10091 10092 // Check if this slice overlaps with another. 10093 if ((CurrentUsedBits & UsedBits) != 0) 10094 return false; 10095 // Update the bits used globally. 10096 UsedBits |= CurrentUsedBits; 10097 10098 // Check if the new slice would be legal. 10099 if (!LS.isLegal()) 10100 return false; 10101 10102 // Record the slice. 10103 LoadedSlices.push_back(LS); 10104 } 10105 10106 // Abort slicing if it does not seem to be profitable. 10107 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10108 return false; 10109 10110 ++SlicedLoads; 10111 10112 // Rewrite each chain to use an independent load. 10113 // By construction, each chain can be represented by a unique load. 10114 10115 // Prepare the argument for the new token factor for all the slices. 10116 SmallVector<SDValue, 8> ArgChains; 10117 for (SmallVectorImpl<LoadedSlice>::const_iterator 10118 LSIt = LoadedSlices.begin(), 10119 LSItEnd = LoadedSlices.end(); 10120 LSIt != LSItEnd; ++LSIt) { 10121 SDValue SliceInst = LSIt->loadSlice(); 10122 CombineTo(LSIt->Inst, SliceInst, true); 10123 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10124 SliceInst = SliceInst.getOperand(0); 10125 assert(SliceInst->getOpcode() == ISD::LOAD && 10126 "It takes more than a zext to get to the loaded slice!!"); 10127 ArgChains.push_back(SliceInst.getValue(1)); 10128 } 10129 10130 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10131 ArgChains); 10132 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10133 return true; 10134 } 10135 10136 /// Check to see if V is (and load (ptr), imm), where the load is having 10137 /// specific bytes cleared out. If so, return the byte size being masked out 10138 /// and the shift amount. 10139 static std::pair<unsigned, unsigned> 10140 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10141 std::pair<unsigned, unsigned> Result(0, 0); 10142 10143 // Check for the structure we're looking for. 10144 if (V->getOpcode() != ISD::AND || 10145 !isa<ConstantSDNode>(V->getOperand(1)) || 10146 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10147 return Result; 10148 10149 // Check the chain and pointer. 10150 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10151 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10152 10153 // The store should be chained directly to the load or be an operand of a 10154 // tokenfactor. 10155 if (LD == Chain.getNode()) 10156 ; // ok. 10157 else if (Chain->getOpcode() != ISD::TokenFactor) 10158 return Result; // Fail. 10159 else { 10160 bool isOk = false; 10161 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 10162 if (Chain->getOperand(i).getNode() == LD) { 10163 isOk = true; 10164 break; 10165 } 10166 if (!isOk) return Result; 10167 } 10168 10169 // This only handles simple types. 10170 if (V.getValueType() != MVT::i16 && 10171 V.getValueType() != MVT::i32 && 10172 V.getValueType() != MVT::i64) 10173 return Result; 10174 10175 // Check the constant mask. Invert it so that the bits being masked out are 10176 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10177 // follow the sign bit for uniformity. 10178 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10179 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10180 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10181 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10182 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10183 if (NotMaskLZ == 64) return Result; // All zero mask. 10184 10185 // See if we have a continuous run of bits. If so, we have 0*1+0* 10186 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10187 return Result; 10188 10189 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10190 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10191 NotMaskLZ -= 64-V.getValueSizeInBits(); 10192 10193 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10194 switch (MaskedBytes) { 10195 case 1: 10196 case 2: 10197 case 4: break; 10198 default: return Result; // All one mask, or 5-byte mask. 10199 } 10200 10201 // Verify that the first bit starts at a multiple of mask so that the access 10202 // is aligned the same as the access width. 10203 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10204 10205 Result.first = MaskedBytes; 10206 Result.second = NotMaskTZ/8; 10207 return Result; 10208 } 10209 10210 10211 /// Check to see if IVal is something that provides a value as specified by 10212 /// MaskInfo. If so, replace the specified store with a narrower store of 10213 /// truncated IVal. 10214 static SDNode * 10215 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10216 SDValue IVal, StoreSDNode *St, 10217 DAGCombiner *DC) { 10218 unsigned NumBytes = MaskInfo.first; 10219 unsigned ByteShift = MaskInfo.second; 10220 SelectionDAG &DAG = DC->getDAG(); 10221 10222 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10223 // that uses this. If not, this is not a replacement. 10224 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10225 ByteShift*8, (ByteShift+NumBytes)*8); 10226 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10227 10228 // Check that it is legal on the target to do this. It is legal if the new 10229 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10230 // legalization. 10231 MVT VT = MVT::getIntegerVT(NumBytes*8); 10232 if (!DC->isTypeLegal(VT)) 10233 return nullptr; 10234 10235 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10236 // shifted by ByteShift and truncated down to NumBytes. 10237 if (ByteShift) { 10238 SDLoc DL(IVal); 10239 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10240 DAG.getConstant(ByteShift*8, DL, 10241 DC->getShiftAmountTy(IVal.getValueType()))); 10242 } 10243 10244 // Figure out the offset for the store and the alignment of the access. 10245 unsigned StOffset; 10246 unsigned NewAlign = St->getAlignment(); 10247 10248 if (DAG.getTargetLoweringInfo().isLittleEndian()) 10249 StOffset = ByteShift; 10250 else 10251 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10252 10253 SDValue Ptr = St->getBasePtr(); 10254 if (StOffset) { 10255 SDLoc DL(IVal); 10256 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10257 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10258 NewAlign = MinAlign(NewAlign, StOffset); 10259 } 10260 10261 // Truncate down to the new size. 10262 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10263 10264 ++OpsNarrowed; 10265 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10266 St->getPointerInfo().getWithOffset(StOffset), 10267 false, false, NewAlign).getNode(); 10268 } 10269 10270 10271 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10272 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10273 /// narrowing the load and store if it would end up being a win for performance 10274 /// or code size. 10275 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10276 StoreSDNode *ST = cast<StoreSDNode>(N); 10277 if (ST->isVolatile()) 10278 return SDValue(); 10279 10280 SDValue Chain = ST->getChain(); 10281 SDValue Value = ST->getValue(); 10282 SDValue Ptr = ST->getBasePtr(); 10283 EVT VT = Value.getValueType(); 10284 10285 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10286 return SDValue(); 10287 10288 unsigned Opc = Value.getOpcode(); 10289 10290 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10291 // is a byte mask indicating a consecutive number of bytes, check to see if 10292 // Y is known to provide just those bytes. If so, we try to replace the 10293 // load + replace + store sequence with a single (narrower) store, which makes 10294 // the load dead. 10295 if (Opc == ISD::OR) { 10296 std::pair<unsigned, unsigned> MaskedLoad; 10297 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10298 if (MaskedLoad.first) 10299 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10300 Value.getOperand(1), ST,this)) 10301 return SDValue(NewST, 0); 10302 10303 // Or is commutative, so try swapping X and Y. 10304 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10305 if (MaskedLoad.first) 10306 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10307 Value.getOperand(0), ST,this)) 10308 return SDValue(NewST, 0); 10309 } 10310 10311 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10312 Value.getOperand(1).getOpcode() != ISD::Constant) 10313 return SDValue(); 10314 10315 SDValue N0 = Value.getOperand(0); 10316 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10317 Chain == SDValue(N0.getNode(), 1)) { 10318 LoadSDNode *LD = cast<LoadSDNode>(N0); 10319 if (LD->getBasePtr() != Ptr || 10320 LD->getPointerInfo().getAddrSpace() != 10321 ST->getPointerInfo().getAddrSpace()) 10322 return SDValue(); 10323 10324 // Find the type to narrow it the load / op / store to. 10325 SDValue N1 = Value.getOperand(1); 10326 unsigned BitWidth = N1.getValueSizeInBits(); 10327 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10328 if (Opc == ISD::AND) 10329 Imm ^= APInt::getAllOnesValue(BitWidth); 10330 if (Imm == 0 || Imm.isAllOnesValue()) 10331 return SDValue(); 10332 unsigned ShAmt = Imm.countTrailingZeros(); 10333 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10334 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10335 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10336 // The narrowing should be profitable, the load/store operation should be 10337 // legal (or custom) and the store size should be equal to the NewVT width. 10338 while (NewBW < BitWidth && 10339 (NewVT.getStoreSizeInBits() != NewBW || 10340 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10341 !TLI.isNarrowingProfitable(VT, NewVT))) { 10342 NewBW = NextPowerOf2(NewBW); 10343 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10344 } 10345 if (NewBW >= BitWidth) 10346 return SDValue(); 10347 10348 // If the lsb changed does not start at the type bitwidth boundary, 10349 // start at the previous one. 10350 if (ShAmt % NewBW) 10351 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10352 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10353 std::min(BitWidth, ShAmt + NewBW)); 10354 if ((Imm & Mask) == Imm) { 10355 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10356 if (Opc == ISD::AND) 10357 NewImm ^= APInt::getAllOnesValue(NewBW); 10358 uint64_t PtrOff = ShAmt / 8; 10359 // For big endian targets, we need to adjust the offset to the pointer to 10360 // load the correct bytes. 10361 if (TLI.isBigEndian()) 10362 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10363 10364 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10365 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10366 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 10367 return SDValue(); 10368 10369 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10370 Ptr.getValueType(), Ptr, 10371 DAG.getConstant(PtrOff, SDLoc(LD), 10372 Ptr.getValueType())); 10373 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10374 LD->getChain(), NewPtr, 10375 LD->getPointerInfo().getWithOffset(PtrOff), 10376 LD->isVolatile(), LD->isNonTemporal(), 10377 LD->isInvariant(), NewAlign, 10378 LD->getAAInfo()); 10379 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10380 DAG.getConstant(NewImm, SDLoc(Value), 10381 NewVT)); 10382 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10383 NewVal, NewPtr, 10384 ST->getPointerInfo().getWithOffset(PtrOff), 10385 false, false, NewAlign); 10386 10387 AddToWorklist(NewPtr.getNode()); 10388 AddToWorklist(NewLD.getNode()); 10389 AddToWorklist(NewVal.getNode()); 10390 WorklistRemover DeadNodes(*this); 10391 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10392 ++OpsNarrowed; 10393 return NewST; 10394 } 10395 } 10396 10397 return SDValue(); 10398 } 10399 10400 /// For a given floating point load / store pair, if the load value isn't used 10401 /// by any other operations, then consider transforming the pair to integer 10402 /// load / store operations if the target deems the transformation profitable. 10403 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10404 StoreSDNode *ST = cast<StoreSDNode>(N); 10405 SDValue Chain = ST->getChain(); 10406 SDValue Value = ST->getValue(); 10407 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10408 Value.hasOneUse() && 10409 Chain == SDValue(Value.getNode(), 1)) { 10410 LoadSDNode *LD = cast<LoadSDNode>(Value); 10411 EVT VT = LD->getMemoryVT(); 10412 if (!VT.isFloatingPoint() || 10413 VT != ST->getMemoryVT() || 10414 LD->isNonTemporal() || 10415 ST->isNonTemporal() || 10416 LD->getPointerInfo().getAddrSpace() != 0 || 10417 ST->getPointerInfo().getAddrSpace() != 0) 10418 return SDValue(); 10419 10420 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10421 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10422 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10423 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10424 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10425 return SDValue(); 10426 10427 unsigned LDAlign = LD->getAlignment(); 10428 unsigned STAlign = ST->getAlignment(); 10429 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10430 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 10431 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10432 return SDValue(); 10433 10434 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10435 LD->getChain(), LD->getBasePtr(), 10436 LD->getPointerInfo(), 10437 false, false, false, LDAlign); 10438 10439 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10440 NewLD, ST->getBasePtr(), 10441 ST->getPointerInfo(), 10442 false, false, STAlign); 10443 10444 AddToWorklist(NewLD.getNode()); 10445 AddToWorklist(NewST.getNode()); 10446 WorklistRemover DeadNodes(*this); 10447 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10448 ++LdStFP2Int; 10449 return NewST; 10450 } 10451 10452 return SDValue(); 10453 } 10454 10455 namespace { 10456 /// Helper struct to parse and store a memory address as base + index + offset. 10457 /// We ignore sign extensions when it is safe to do so. 10458 /// The following two expressions are not equivalent. To differentiate we need 10459 /// to store whether there was a sign extension involved in the index 10460 /// computation. 10461 /// (load (i64 add (i64 copyfromreg %c) 10462 /// (i64 signextend (add (i8 load %index) 10463 /// (i8 1)))) 10464 /// vs 10465 /// 10466 /// (load (i64 add (i64 copyfromreg %c) 10467 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10468 /// (i32 1))))) 10469 struct BaseIndexOffset { 10470 SDValue Base; 10471 SDValue Index; 10472 int64_t Offset; 10473 bool IsIndexSignExt; 10474 10475 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10476 10477 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10478 bool IsIndexSignExt) : 10479 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10480 10481 bool equalBaseIndex(const BaseIndexOffset &Other) { 10482 return Other.Base == Base && Other.Index == Index && 10483 Other.IsIndexSignExt == IsIndexSignExt; 10484 } 10485 10486 /// Parses tree in Ptr for base, index, offset addresses. 10487 static BaseIndexOffset match(SDValue Ptr) { 10488 bool IsIndexSignExt = false; 10489 10490 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10491 // instruction, then it could be just the BASE or everything else we don't 10492 // know how to handle. Just use Ptr as BASE and give up. 10493 if (Ptr->getOpcode() != ISD::ADD) 10494 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10495 10496 // We know that we have at least an ADD instruction. Try to pattern match 10497 // the simple case of BASE + OFFSET. 10498 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10499 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10500 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10501 IsIndexSignExt); 10502 } 10503 10504 // Inside a loop the current BASE pointer is calculated using an ADD and a 10505 // MUL instruction. In this case Ptr is the actual BASE pointer. 10506 // (i64 add (i64 %array_ptr) 10507 // (i64 mul (i64 %induction_var) 10508 // (i64 %element_size))) 10509 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10510 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10511 10512 // Look at Base + Index + Offset cases. 10513 SDValue Base = Ptr->getOperand(0); 10514 SDValue IndexOffset = Ptr->getOperand(1); 10515 10516 // Skip signextends. 10517 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10518 IndexOffset = IndexOffset->getOperand(0); 10519 IsIndexSignExt = true; 10520 } 10521 10522 // Either the case of Base + Index (no offset) or something else. 10523 if (IndexOffset->getOpcode() != ISD::ADD) 10524 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10525 10526 // Now we have the case of Base + Index + offset. 10527 SDValue Index = IndexOffset->getOperand(0); 10528 SDValue Offset = IndexOffset->getOperand(1); 10529 10530 if (!isa<ConstantSDNode>(Offset)) 10531 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10532 10533 // Ignore signextends. 10534 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10535 Index = Index->getOperand(0); 10536 IsIndexSignExt = true; 10537 } else IsIndexSignExt = false; 10538 10539 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10540 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10541 } 10542 }; 10543 } // namespace 10544 10545 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10546 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10547 unsigned NumElem, bool IsConstantSrc, bool UseVector) { 10548 // Make sure we have something to merge. 10549 if (NumElem < 2) 10550 return false; 10551 10552 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10553 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10554 unsigned LatestNodeUsed = 0; 10555 10556 for (unsigned i=0; i < NumElem; ++i) { 10557 // Find a chain for the new wide-store operand. Notice that some 10558 // of the store nodes that we found may not be selected for inclusion 10559 // in the wide store. The chain we use needs to be the chain of the 10560 // latest store node which is *used* and replaced by the wide store. 10561 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10562 LatestNodeUsed = i; 10563 } 10564 10565 // The latest Node in the DAG. 10566 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10567 SDLoc DL(StoreNodes[0].MemNode); 10568 10569 SDValue StoredVal; 10570 if (UseVector) { 10571 // Find a legal type for the vector store. 10572 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10573 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 10574 if (IsConstantSrc) { 10575 // A vector store with a constant source implies that the constant is 10576 // zero; we only handle merging stores of constant zeros because the zero 10577 // can be materialized without a load. 10578 // It may be beneficial to loosen this restriction to allow non-zero 10579 // store merging. 10580 StoredVal = DAG.getConstant(0, DL, Ty); 10581 } else { 10582 SmallVector<SDValue, 8> Ops; 10583 for (unsigned i = 0; i < NumElem ; ++i) { 10584 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10585 SDValue Val = St->getValue(); 10586 // All of the operands of a BUILD_VECTOR must have the same type. 10587 if (Val.getValueType() != MemVT) 10588 return false; 10589 Ops.push_back(Val); 10590 } 10591 10592 // Build the extracted vector elements back into a vector. 10593 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops); 10594 } 10595 } else { 10596 // We should always use a vector store when merging extracted vector 10597 // elements, so this path implies a store of constants. 10598 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10599 10600 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10601 APInt StoreInt(StoreBW, 0); 10602 10603 // Construct a single integer constant which is made of the smaller 10604 // constant inputs. 10605 bool IsLE = TLI.isLittleEndian(); 10606 for (unsigned i = 0; i < NumElem ; ++i) { 10607 unsigned Idx = IsLE ? (NumElem - 1 - i) : i; 10608 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10609 SDValue Val = St->getValue(); 10610 StoreInt <<= ElementSizeBytes*8; 10611 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10612 StoreInt |= C->getAPIntValue().zext(StoreBW); 10613 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10614 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 10615 } else { 10616 llvm_unreachable("Invalid constant element type"); 10617 } 10618 } 10619 10620 // Create the new Load and Store operations. 10621 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10622 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 10623 } 10624 10625 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal, 10626 FirstInChain->getBasePtr(), 10627 FirstInChain->getPointerInfo(), 10628 false, false, 10629 FirstInChain->getAlignment()); 10630 10631 // Replace the last store with the new store 10632 CombineTo(LatestOp, NewStore); 10633 // Erase all other stores. 10634 for (unsigned i = 0; i < NumElem ; ++i) { 10635 if (StoreNodes[i].MemNode == LatestOp) 10636 continue; 10637 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10638 // ReplaceAllUsesWith will replace all uses that existed when it was 10639 // called, but graph optimizations may cause new ones to appear. For 10640 // example, the case in pr14333 looks like 10641 // 10642 // St's chain -> St -> another store -> X 10643 // 10644 // And the only difference from St to the other store is the chain. 10645 // When we change it's chain to be St's chain they become identical, 10646 // get CSEed and the net result is that X is now a use of St. 10647 // Since we know that St is redundant, just iterate. 10648 while (!St->use_empty()) 10649 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10650 deleteAndRecombine(St); 10651 } 10652 10653 return true; 10654 } 10655 10656 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 10657 if (OptLevel == CodeGenOpt::None) 10658 return false; 10659 10660 EVT MemVT = St->getMemoryVT(); 10661 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 10662 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 10663 Attribute::NoImplicitFloat); 10664 10665 // Don't merge vectors into wider inputs. 10666 if (MemVT.isVector() || !MemVT.isSimple()) 10667 return false; 10668 10669 // Perform an early exit check. Do not bother looking at stored values that 10670 // are not constants, loads, or extracted vector elements. 10671 SDValue StoredVal = St->getValue(); 10672 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 10673 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 10674 isa<ConstantFPSDNode>(StoredVal); 10675 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 10676 10677 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 10678 return false; 10679 10680 // Only look at ends of store sequences. 10681 SDValue Chain = SDValue(St, 0); 10682 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 10683 return false; 10684 10685 // This holds the base pointer, index, and the offset in bytes from the base 10686 // pointer. 10687 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10688 10689 // We must have a base and an offset. 10690 if (!BasePtr.Base.getNode()) 10691 return false; 10692 10693 // Do not handle stores to undef base pointers. 10694 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10695 return false; 10696 10697 // Save the LoadSDNodes that we find in the chain. 10698 // We need to make sure that these nodes do not interfere with 10699 // any of the store nodes. 10700 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 10701 10702 // Save the StoreSDNodes that we find in the chain. 10703 SmallVector<MemOpLink, 8> StoreNodes; 10704 10705 // Walk up the chain and look for nodes with offsets from the same 10706 // base pointer. Stop when reaching an instruction with a different kind 10707 // or instruction which has a different base pointer. 10708 unsigned Seq = 0; 10709 StoreSDNode *Index = St; 10710 while (Index) { 10711 // If the chain has more than one use, then we can't reorder the mem ops. 10712 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10713 break; 10714 10715 // Find the base pointer and offset for this memory node. 10716 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 10717 10718 // Check that the base pointer is the same as the original one. 10719 if (!Ptr.equalBaseIndex(BasePtr)) 10720 break; 10721 10722 // Check that the alignment is the same. 10723 if (Index->getAlignment() != St->getAlignment()) 10724 break; 10725 10726 // The memory operands must not be volatile. 10727 if (Index->isVolatile() || Index->isIndexed()) 10728 break; 10729 10730 // No truncation. 10731 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 10732 if (St->isTruncatingStore()) 10733 break; 10734 10735 // The stored memory type must be the same. 10736 if (Index->getMemoryVT() != MemVT) 10737 break; 10738 10739 // We do not allow unaligned stores because we want to prevent overriding 10740 // stores. 10741 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 10742 break; 10743 10744 // We found a potential memory operand to merge. 10745 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 10746 10747 // Find the next memory operand in the chain. If the next operand in the 10748 // chain is a store then move up and continue the scan with the next 10749 // memory operand. If the next operand is a load save it and use alias 10750 // information to check if it interferes with anything. 10751 SDNode *NextInChain = Index->getChain().getNode(); 10752 while (1) { 10753 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 10754 // We found a store node. Use it for the next iteration. 10755 Index = STn; 10756 break; 10757 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 10758 if (Ldn->isVolatile()) { 10759 Index = nullptr; 10760 break; 10761 } 10762 10763 // Save the load node for later. Continue the scan. 10764 AliasLoadNodes.push_back(Ldn); 10765 NextInChain = Ldn->getChain().getNode(); 10766 continue; 10767 } else { 10768 Index = nullptr; 10769 break; 10770 } 10771 } 10772 } 10773 10774 // Check if there is anything to merge. 10775 if (StoreNodes.size() < 2) 10776 return false; 10777 10778 // Sort the memory operands according to their distance from the base pointer. 10779 std::sort(StoreNodes.begin(), StoreNodes.end(), 10780 [](MemOpLink LHS, MemOpLink RHS) { 10781 return LHS.OffsetFromBase < RHS.OffsetFromBase || 10782 (LHS.OffsetFromBase == RHS.OffsetFromBase && 10783 LHS.SequenceNum > RHS.SequenceNum); 10784 }); 10785 10786 // Scan the memory operations on the chain and find the first non-consecutive 10787 // store memory address. 10788 unsigned LastConsecutiveStore = 0; 10789 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 10790 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 10791 10792 // Check that the addresses are consecutive starting from the second 10793 // element in the list of stores. 10794 if (i > 0) { 10795 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 10796 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10797 break; 10798 } 10799 10800 bool Alias = false; 10801 // Check if this store interferes with any of the loads that we found. 10802 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 10803 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 10804 Alias = true; 10805 break; 10806 } 10807 // We found a load that alias with this store. Stop the sequence. 10808 if (Alias) 10809 break; 10810 10811 // Mark this node as useful. 10812 LastConsecutiveStore = i; 10813 } 10814 10815 // The node with the lowest store address. 10816 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10817 10818 // Store the constants into memory as one consecutive store. 10819 if (IsConstantSrc) { 10820 unsigned LastLegalType = 0; 10821 unsigned LastLegalVectorType = 0; 10822 bool NonZero = false; 10823 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10824 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10825 SDValue StoredVal = St->getValue(); 10826 10827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 10828 NonZero |= !C->isNullValue(); 10829 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 10830 NonZero |= !C->getConstantFPValue()->isNullValue(); 10831 } else { 10832 // Non-constant. 10833 break; 10834 } 10835 10836 // Find a legal type for the constant store. 10837 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10838 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10839 if (TLI.isTypeLegal(StoreTy)) 10840 LastLegalType = i+1; 10841 // Or check whether a truncstore is legal. 10842 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10843 TargetLowering::TypePromoteInteger) { 10844 EVT LegalizedStoredValueTy = 10845 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 10846 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 10847 LastLegalType = i+1; 10848 } 10849 10850 // Find a legal type for the vector store. 10851 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10852 if (TLI.isTypeLegal(Ty)) 10853 LastLegalVectorType = i + 1; 10854 } 10855 10856 // We only use vectors if the constant is known to be zero and the 10857 // function is not marked with the noimplicitfloat attribute. 10858 if (NonZero || NoVectors) 10859 LastLegalVectorType = 0; 10860 10861 // Check if we found a legal integer type to store. 10862 if (LastLegalType == 0 && LastLegalVectorType == 0) 10863 return false; 10864 10865 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 10866 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 10867 10868 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10869 true, UseVector); 10870 } 10871 10872 // When extracting multiple vector elements, try to store them 10873 // in one vector store rather than a sequence of scalar stores. 10874 if (IsExtractVecEltSrc) { 10875 unsigned NumElem = 0; 10876 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 10877 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10878 SDValue StoredVal = St->getValue(); 10879 // This restriction could be loosened. 10880 // Bail out if any stored values are not elements extracted from a vector. 10881 // It should be possible to handle mixed sources, but load sources need 10882 // more careful handling (see the block of code below that handles 10883 // consecutive loads). 10884 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10885 return false; 10886 10887 // Find a legal type for the vector store. 10888 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10889 if (TLI.isTypeLegal(Ty)) 10890 NumElem = i + 1; 10891 } 10892 10893 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10894 false, true); 10895 } 10896 10897 // Below we handle the case of multiple consecutive stores that 10898 // come from multiple consecutive loads. We merge them into a single 10899 // wide load and a single wide store. 10900 10901 // Look for load nodes which are used by the stored values. 10902 SmallVector<MemOpLink, 8> LoadNodes; 10903 10904 // Find acceptable loads. Loads need to have the same chain (token factor), 10905 // must not be zext, volatile, indexed, and they must be consecutive. 10906 BaseIndexOffset LdBasePtr; 10907 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10908 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10909 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 10910 if (!Ld) break; 10911 10912 // Loads must only have one use. 10913 if (!Ld->hasNUsesOfValue(1, 0)) 10914 break; 10915 10916 // Check that the alignment is the same as the stores. 10917 if (Ld->getAlignment() != St->getAlignment()) 10918 break; 10919 10920 // The memory operands must not be volatile. 10921 if (Ld->isVolatile() || Ld->isIndexed()) 10922 break; 10923 10924 // We do not accept ext loads. 10925 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 10926 break; 10927 10928 // The stored memory type must be the same. 10929 if (Ld->getMemoryVT() != MemVT) 10930 break; 10931 10932 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 10933 // If this is not the first ptr that we check. 10934 if (LdBasePtr.Base.getNode()) { 10935 // The base ptr must be the same. 10936 if (!LdPtr.equalBaseIndex(LdBasePtr)) 10937 break; 10938 } else { 10939 // Check that all other base pointers are the same as this one. 10940 LdBasePtr = LdPtr; 10941 } 10942 10943 // We found a potential memory operand to merge. 10944 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 10945 } 10946 10947 if (LoadNodes.size() < 2) 10948 return false; 10949 10950 // If we have load/store pair instructions and we only have two values, 10951 // don't bother. 10952 unsigned RequiredAlignment; 10953 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 10954 St->getAlignment() >= RequiredAlignment) 10955 return false; 10956 10957 // Scan the memory operations on the chain and find the first non-consecutive 10958 // load memory address. These variables hold the index in the store node 10959 // array. 10960 unsigned LastConsecutiveLoad = 0; 10961 // This variable refers to the size and not index in the array. 10962 unsigned LastLegalVectorType = 0; 10963 unsigned LastLegalIntegerType = 0; 10964 StartAddress = LoadNodes[0].OffsetFromBase; 10965 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 10966 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 10967 // All loads much share the same chain. 10968 if (LoadNodes[i].MemNode->getChain() != FirstChain) 10969 break; 10970 10971 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 10972 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10973 break; 10974 LastConsecutiveLoad = i; 10975 10976 // Find a legal type for the vector store. 10977 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10978 if (TLI.isTypeLegal(StoreTy)) 10979 LastLegalVectorType = i + 1; 10980 10981 // Find a legal type for the integer store. 10982 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10983 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10984 if (TLI.isTypeLegal(StoreTy)) 10985 LastLegalIntegerType = i + 1; 10986 // Or check whether a truncstore and extload is legal. 10987 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10988 TargetLowering::TypePromoteInteger) { 10989 EVT LegalizedStoredValueTy = 10990 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 10991 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10992 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10993 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10994 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy)) 10995 LastLegalIntegerType = i+1; 10996 } 10997 } 10998 10999 // Only use vector types if the vector type is larger than the integer type. 11000 // If they are the same, use integers. 11001 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11002 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11003 11004 // We add +1 here because the LastXXX variables refer to location while 11005 // the NumElem refers to array/index size. 11006 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11007 NumElem = std::min(LastLegalType, NumElem); 11008 11009 if (NumElem < 2) 11010 return false; 11011 11012 // The latest Node in the DAG. 11013 unsigned LatestNodeUsed = 0; 11014 for (unsigned i=1; i<NumElem; ++i) { 11015 // Find a chain for the new wide-store operand. Notice that some 11016 // of the store nodes that we found may not be selected for inclusion 11017 // in the wide store. The chain we use needs to be the chain of the 11018 // latest store node which is *used* and replaced by the wide store. 11019 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11020 LatestNodeUsed = i; 11021 } 11022 11023 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11024 11025 // Find if it is better to use vectors or integers to load and store 11026 // to memory. 11027 EVT JointMemOpVT; 11028 if (UseVectorTy) { 11029 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 11030 } else { 11031 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 11032 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 11033 } 11034 11035 SDLoc LoadDL(LoadNodes[0].MemNode); 11036 SDLoc StoreDL(StoreNodes[0].MemNode); 11037 11038 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11039 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 11040 FirstLoad->getChain(), 11041 FirstLoad->getBasePtr(), 11042 FirstLoad->getPointerInfo(), 11043 false, false, false, 11044 FirstLoad->getAlignment()); 11045 11046 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad, 11047 FirstInChain->getBasePtr(), 11048 FirstInChain->getPointerInfo(), false, false, 11049 FirstInChain->getAlignment()); 11050 11051 // Replace one of the loads with the new load. 11052 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 11053 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11054 SDValue(NewLoad.getNode(), 1)); 11055 11056 // Remove the rest of the load chains. 11057 for (unsigned i = 1; i < NumElem ; ++i) { 11058 // Replace all chain users of the old load nodes with the chain of the new 11059 // load node. 11060 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11061 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 11062 } 11063 11064 // Replace the last store with the new store. 11065 CombineTo(LatestOp, NewStore); 11066 // Erase all other stores. 11067 for (unsigned i = 0; i < NumElem ; ++i) { 11068 // Remove all Store nodes. 11069 if (StoreNodes[i].MemNode == LatestOp) 11070 continue; 11071 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11072 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11073 deleteAndRecombine(St); 11074 } 11075 11076 return true; 11077 } 11078 11079 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11080 StoreSDNode *ST = cast<StoreSDNode>(N); 11081 SDValue Chain = ST->getChain(); 11082 SDValue Value = ST->getValue(); 11083 SDValue Ptr = ST->getBasePtr(); 11084 11085 // If this is a store of a bit convert, store the input value if the 11086 // resultant store does not need a higher alignment than the original. 11087 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11088 ST->isUnindexed()) { 11089 unsigned OrigAlign = ST->getAlignment(); 11090 EVT SVT = Value.getOperand(0).getValueType(); 11091 unsigned Align = TLI.getDataLayout()-> 11092 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 11093 if (Align <= OrigAlign && 11094 ((!LegalOperations && !ST->isVolatile()) || 11095 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11096 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11097 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11098 ST->isNonTemporal(), OrigAlign, 11099 ST->getAAInfo()); 11100 } 11101 11102 // Turn 'store undef, Ptr' -> nothing. 11103 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11104 return Chain; 11105 11106 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11107 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 11108 // NOTE: If the original store is volatile, this transform must not increase 11109 // the number of stores. For example, on x86-32 an f64 can be stored in one 11110 // processor operation but an i64 (which is not legal) requires two. So the 11111 // transform should not be done in this case. 11112 if (Value.getOpcode() != ISD::TargetConstantFP) { 11113 SDValue Tmp; 11114 switch (CFP->getSimpleValueType(0).SimpleTy) { 11115 default: llvm_unreachable("Unknown FP type"); 11116 case MVT::f16: // We don't do this for these yet. 11117 case MVT::f80: 11118 case MVT::f128: 11119 case MVT::ppcf128: 11120 break; 11121 case MVT::f32: 11122 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11123 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11124 ; 11125 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11126 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11127 MVT::i32); 11128 return DAG.getStore(Chain, SDLoc(N), Tmp, 11129 Ptr, ST->getMemOperand()); 11130 } 11131 break; 11132 case MVT::f64: 11133 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11134 !ST->isVolatile()) || 11135 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11136 ; 11137 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11138 getZExtValue(), SDLoc(CFP), MVT::i64); 11139 return DAG.getStore(Chain, SDLoc(N), Tmp, 11140 Ptr, ST->getMemOperand()); 11141 } 11142 11143 if (!ST->isVolatile() && 11144 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11145 // Many FP stores are not made apparent until after legalize, e.g. for 11146 // argument passing. Since this is so common, custom legalize the 11147 // 64-bit integer store into two 32-bit stores. 11148 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11149 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11150 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11151 if (TLI.isBigEndian()) std::swap(Lo, Hi); 11152 11153 unsigned Alignment = ST->getAlignment(); 11154 bool isVolatile = ST->isVolatile(); 11155 bool isNonTemporal = ST->isNonTemporal(); 11156 AAMDNodes AAInfo = ST->getAAInfo(); 11157 11158 SDLoc DL(N); 11159 11160 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 11161 Ptr, ST->getPointerInfo(), 11162 isVolatile, isNonTemporal, 11163 ST->getAlignment(), AAInfo); 11164 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11165 DAG.getConstant(4, DL, Ptr.getValueType())); 11166 Alignment = MinAlign(Alignment, 4U); 11167 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 11168 Ptr, ST->getPointerInfo().getWithOffset(4), 11169 isVolatile, isNonTemporal, 11170 Alignment, AAInfo); 11171 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11172 St0, St1); 11173 } 11174 11175 break; 11176 } 11177 } 11178 } 11179 11180 // Try to infer better alignment information than the store already has. 11181 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11182 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11183 if (Align > ST->getAlignment()) { 11184 SDValue NewStore = 11185 DAG.getTruncStore(Chain, SDLoc(N), Value, 11186 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11187 ST->isVolatile(), ST->isNonTemporal(), Align, 11188 ST->getAAInfo()); 11189 if (NewStore.getNode() != N) 11190 return CombineTo(ST, NewStore, true); 11191 } 11192 } 11193 } 11194 11195 // Try transforming a pair floating point load / store ops to integer 11196 // load / store ops. 11197 SDValue NewST = TransformFPLoadStorePair(N); 11198 if (NewST.getNode()) 11199 return NewST; 11200 11201 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11202 : DAG.getSubtarget().useAA(); 11203 #ifndef NDEBUG 11204 if (CombinerAAOnlyFunc.getNumOccurrences() && 11205 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11206 UseAA = false; 11207 #endif 11208 if (UseAA && ST->isUnindexed()) { 11209 // Walk up chain skipping non-aliasing memory nodes. 11210 SDValue BetterChain = FindBetterChain(N, Chain); 11211 11212 // If there is a better chain. 11213 if (Chain != BetterChain) { 11214 SDValue ReplStore; 11215 11216 // Replace the chain to avoid dependency. 11217 if (ST->isTruncatingStore()) { 11218 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 11219 ST->getMemoryVT(), ST->getMemOperand()); 11220 } else { 11221 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 11222 ST->getMemOperand()); 11223 } 11224 11225 // Create token to keep both nodes around. 11226 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11227 MVT::Other, Chain, ReplStore); 11228 11229 // Make sure the new and old chains are cleaned up. 11230 AddToWorklist(Token.getNode()); 11231 11232 // Don't add users to work list. 11233 return CombineTo(N, Token, false); 11234 } 11235 } 11236 11237 // Try transforming N to an indexed store. 11238 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11239 return SDValue(N, 0); 11240 11241 // FIXME: is there such a thing as a truncating indexed store? 11242 if (ST->isTruncatingStore() && ST->isUnindexed() && 11243 Value.getValueType().isInteger()) { 11244 // See if we can simplify the input to this truncstore with knowledge that 11245 // only the low bits are being used. For example: 11246 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11247 SDValue Shorter = 11248 GetDemandedBits(Value, 11249 APInt::getLowBitsSet( 11250 Value.getValueType().getScalarType().getSizeInBits(), 11251 ST->getMemoryVT().getScalarType().getSizeInBits())); 11252 AddToWorklist(Value.getNode()); 11253 if (Shorter.getNode()) 11254 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11255 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11256 11257 // Otherwise, see if we can simplify the operation with 11258 // SimplifyDemandedBits, which only works if the value has a single use. 11259 if (SimplifyDemandedBits(Value, 11260 APInt::getLowBitsSet( 11261 Value.getValueType().getScalarType().getSizeInBits(), 11262 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11263 return SDValue(N, 0); 11264 } 11265 11266 // If this is a load followed by a store to the same location, then the store 11267 // is dead/noop. 11268 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11269 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11270 ST->isUnindexed() && !ST->isVolatile() && 11271 // There can't be any side effects between the load and store, such as 11272 // a call or store. 11273 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11274 // The store is dead, remove it. 11275 return Chain; 11276 } 11277 } 11278 11279 // If this is a store followed by a store with the same value to the same 11280 // location, then the store is dead/noop. 11281 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11282 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11283 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11284 ST1->isUnindexed() && !ST1->isVolatile()) { 11285 // The store is dead, remove it. 11286 return Chain; 11287 } 11288 } 11289 11290 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11291 // truncating store. We can do this even if this is already a truncstore. 11292 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11293 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11294 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11295 ST->getMemoryVT())) { 11296 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11297 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11298 } 11299 11300 // Only perform this optimization before the types are legal, because we 11301 // don't want to perform this optimization on every DAGCombine invocation. 11302 if (!LegalTypes) { 11303 bool EverChanged = false; 11304 11305 do { 11306 // There can be multiple store sequences on the same chain. 11307 // Keep trying to merge store sequences until we are unable to do so 11308 // or until we merge the last store on the chain. 11309 bool Changed = MergeConsecutiveStores(ST); 11310 EverChanged |= Changed; 11311 if (!Changed) break; 11312 } while (ST->getOpcode() != ISD::DELETED_NODE); 11313 11314 if (EverChanged) 11315 return SDValue(N, 0); 11316 } 11317 11318 return ReduceLoadOpStoreWidth(N); 11319 } 11320 11321 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11322 SDValue InVec = N->getOperand(0); 11323 SDValue InVal = N->getOperand(1); 11324 SDValue EltNo = N->getOperand(2); 11325 SDLoc dl(N); 11326 11327 // If the inserted element is an UNDEF, just use the input vector. 11328 if (InVal.getOpcode() == ISD::UNDEF) 11329 return InVec; 11330 11331 EVT VT = InVec.getValueType(); 11332 11333 // If we can't generate a legal BUILD_VECTOR, exit 11334 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11335 return SDValue(); 11336 11337 // Check that we know which element is being inserted 11338 if (!isa<ConstantSDNode>(EltNo)) 11339 return SDValue(); 11340 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11341 11342 // Canonicalize insert_vector_elt dag nodes. 11343 // Example: 11344 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11345 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11346 // 11347 // Do this only if the child insert_vector node has one use; also 11348 // do this only if indices are both constants and Idx1 < Idx0. 11349 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11350 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11351 unsigned OtherElt = 11352 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11353 if (Elt < OtherElt) { 11354 // Swap nodes. 11355 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11356 InVec.getOperand(0), InVal, EltNo); 11357 AddToWorklist(NewOp.getNode()); 11358 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11359 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11360 } 11361 } 11362 11363 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11364 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11365 // vector elements. 11366 SmallVector<SDValue, 8> Ops; 11367 // Do not combine these two vectors if the output vector will not replace 11368 // the input vector. 11369 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11370 Ops.append(InVec.getNode()->op_begin(), 11371 InVec.getNode()->op_end()); 11372 } else if (InVec.getOpcode() == ISD::UNDEF) { 11373 unsigned NElts = VT.getVectorNumElements(); 11374 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11375 } else { 11376 return SDValue(); 11377 } 11378 11379 // Insert the element 11380 if (Elt < Ops.size()) { 11381 // All the operands of BUILD_VECTOR must have the same type; 11382 // we enforce that here. 11383 EVT OpVT = Ops[0].getValueType(); 11384 if (InVal.getValueType() != OpVT) 11385 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11386 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11387 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11388 Ops[Elt] = InVal; 11389 } 11390 11391 // Return the new vector 11392 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 11393 } 11394 11395 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 11396 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 11397 EVT ResultVT = EVE->getValueType(0); 11398 EVT VecEltVT = InVecVT.getVectorElementType(); 11399 unsigned Align = OriginalLoad->getAlignment(); 11400 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 11401 VecEltVT.getTypeForEVT(*DAG.getContext())); 11402 11403 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 11404 return SDValue(); 11405 11406 Align = NewAlign; 11407 11408 SDValue NewPtr = OriginalLoad->getBasePtr(); 11409 SDValue Offset; 11410 EVT PtrType = NewPtr.getValueType(); 11411 MachinePointerInfo MPI; 11412 SDLoc DL(EVE); 11413 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 11414 int Elt = ConstEltNo->getZExtValue(); 11415 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 11416 if (TLI.isBigEndian()) 11417 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff; 11418 Offset = DAG.getConstant(PtrOff, DL, PtrType); 11419 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 11420 } else { 11421 Offset = DAG.getNode( 11422 ISD::MUL, DL, EltNo.getValueType(), EltNo, 11423 DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType())); 11424 if (TLI.isBigEndian()) 11425 Offset = DAG.getNode( 11426 ISD::SUB, DL, EltNo.getValueType(), 11427 DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()), 11428 Offset); 11429 MPI = OriginalLoad->getPointerInfo(); 11430 } 11431 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 11432 11433 // The replacement we need to do here is a little tricky: we need to 11434 // replace an extractelement of a load with a load. 11435 // Use ReplaceAllUsesOfValuesWith to do the replacement. 11436 // Note that this replacement assumes that the extractvalue is the only 11437 // use of the load; that's okay because we don't want to perform this 11438 // transformation in other cases anyway. 11439 SDValue Load; 11440 SDValue Chain; 11441 if (ResultVT.bitsGT(VecEltVT)) { 11442 // If the result type of vextract is wider than the load, then issue an 11443 // extending load instead. 11444 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 11445 VecEltVT) 11446 ? ISD::ZEXTLOAD 11447 : ISD::EXTLOAD; 11448 Load = DAG.getExtLoad( 11449 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 11450 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11451 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11452 Chain = Load.getValue(1); 11453 } else { 11454 Load = DAG.getLoad( 11455 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 11456 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11457 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11458 Chain = Load.getValue(1); 11459 if (ResultVT.bitsLT(VecEltVT)) 11460 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 11461 else 11462 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 11463 } 11464 WorklistRemover DeadNodes(*this); 11465 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 11466 SDValue To[] = { Load, Chain }; 11467 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 11468 // Since we're explicitly calling ReplaceAllUses, add the new node to the 11469 // worklist explicitly as well. 11470 AddToWorklist(Load.getNode()); 11471 AddUsersToWorklist(Load.getNode()); // Add users too 11472 // Make sure to revisit this node to clean it up; it will usually be dead. 11473 AddToWorklist(EVE); 11474 ++OpsNarrowed; 11475 return SDValue(EVE, 0); 11476 } 11477 11478 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 11479 // (vextract (scalar_to_vector val, 0) -> val 11480 SDValue InVec = N->getOperand(0); 11481 EVT VT = InVec.getValueType(); 11482 EVT NVT = N->getValueType(0); 11483 11484 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 11485 // Check if the result type doesn't match the inserted element type. A 11486 // SCALAR_TO_VECTOR may truncate the inserted element and the 11487 // EXTRACT_VECTOR_ELT may widen the extracted vector. 11488 SDValue InOp = InVec.getOperand(0); 11489 if (InOp.getValueType() != NVT) { 11490 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11491 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 11492 } 11493 return InOp; 11494 } 11495 11496 SDValue EltNo = N->getOperand(1); 11497 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 11498 11499 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 11500 // We only perform this optimization before the op legalization phase because 11501 // we may introduce new vector instructions which are not backed by TD 11502 // patterns. For example on AVX, extracting elements from a wide vector 11503 // without using extract_subvector. However, if we can find an underlying 11504 // scalar value, then we can always use that. 11505 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 11506 && ConstEltNo) { 11507 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11508 int NumElem = VT.getVectorNumElements(); 11509 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 11510 // Find the new index to extract from. 11511 int OrigElt = SVOp->getMaskElt(Elt); 11512 11513 // Extracting an undef index is undef. 11514 if (OrigElt == -1) 11515 return DAG.getUNDEF(NVT); 11516 11517 // Select the right vector half to extract from. 11518 SDValue SVInVec; 11519 if (OrigElt < NumElem) { 11520 SVInVec = InVec->getOperand(0); 11521 } else { 11522 SVInVec = InVec->getOperand(1); 11523 OrigElt -= NumElem; 11524 } 11525 11526 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 11527 SDValue InOp = SVInVec.getOperand(OrigElt); 11528 if (InOp.getValueType() != NVT) { 11529 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11530 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 11531 } 11532 11533 return InOp; 11534 } 11535 11536 // FIXME: We should handle recursing on other vector shuffles and 11537 // scalar_to_vector here as well. 11538 11539 if (!LegalOperations) { 11540 EVT IndexTy = TLI.getVectorIdxTy(); 11541 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 11542 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 11543 } 11544 } 11545 11546 bool BCNumEltsChanged = false; 11547 EVT ExtVT = VT.getVectorElementType(); 11548 EVT LVT = ExtVT; 11549 11550 // If the result of load has to be truncated, then it's not necessarily 11551 // profitable. 11552 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 11553 return SDValue(); 11554 11555 if (InVec.getOpcode() == ISD::BITCAST) { 11556 // Don't duplicate a load with other uses. 11557 if (!InVec.hasOneUse()) 11558 return SDValue(); 11559 11560 EVT BCVT = InVec.getOperand(0).getValueType(); 11561 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 11562 return SDValue(); 11563 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 11564 BCNumEltsChanged = true; 11565 InVec = InVec.getOperand(0); 11566 ExtVT = BCVT.getVectorElementType(); 11567 } 11568 11569 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 11570 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 11571 ISD::isNormalLoad(InVec.getNode()) && 11572 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 11573 SDValue Index = N->getOperand(1); 11574 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 11575 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 11576 OrigLoad); 11577 } 11578 11579 // Perform only after legalization to ensure build_vector / vector_shuffle 11580 // optimizations have already been done. 11581 if (!LegalOperations) return SDValue(); 11582 11583 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 11584 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 11585 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 11586 11587 if (ConstEltNo) { 11588 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11589 11590 LoadSDNode *LN0 = nullptr; 11591 const ShuffleVectorSDNode *SVN = nullptr; 11592 if (ISD::isNormalLoad(InVec.getNode())) { 11593 LN0 = cast<LoadSDNode>(InVec); 11594 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 11595 InVec.getOperand(0).getValueType() == ExtVT && 11596 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 11597 // Don't duplicate a load with other uses. 11598 if (!InVec.hasOneUse()) 11599 return SDValue(); 11600 11601 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11602 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11603 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11604 // => 11605 // (load $addr+1*size) 11606 11607 // Don't duplicate a load with other uses. 11608 if (!InVec.hasOneUse()) 11609 return SDValue(); 11610 11611 // If the bit convert changed the number of elements, it is unsafe 11612 // to examine the mask. 11613 if (BCNumEltsChanged) 11614 return SDValue(); 11615 11616 // Select the input vector, guarding against out of range extract vector. 11617 unsigned NumElems = VT.getVectorNumElements(); 11618 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 11619 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 11620 11621 if (InVec.getOpcode() == ISD::BITCAST) { 11622 // Don't duplicate a load with other uses. 11623 if (!InVec.hasOneUse()) 11624 return SDValue(); 11625 11626 InVec = InVec.getOperand(0); 11627 } 11628 if (ISD::isNormalLoad(InVec.getNode())) { 11629 LN0 = cast<LoadSDNode>(InVec); 11630 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 11631 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 11632 } 11633 } 11634 11635 // Make sure we found a non-volatile load and the extractelement is 11636 // the only use. 11637 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 11638 return SDValue(); 11639 11640 // If Idx was -1 above, Elt is going to be -1, so just return undef. 11641 if (Elt == -1) 11642 return DAG.getUNDEF(LVT); 11643 11644 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 11645 } 11646 11647 return SDValue(); 11648 } 11649 11650 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 11651 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 11652 // We perform this optimization post type-legalization because 11653 // the type-legalizer often scalarizes integer-promoted vectors. 11654 // Performing this optimization before may create bit-casts which 11655 // will be type-legalized to complex code sequences. 11656 // We perform this optimization only before the operation legalizer because we 11657 // may introduce illegal operations. 11658 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 11659 return SDValue(); 11660 11661 unsigned NumInScalars = N->getNumOperands(); 11662 SDLoc dl(N); 11663 EVT VT = N->getValueType(0); 11664 11665 // Check to see if this is a BUILD_VECTOR of a bunch of values 11666 // which come from any_extend or zero_extend nodes. If so, we can create 11667 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 11668 // optimizations. We do not handle sign-extend because we can't fill the sign 11669 // using shuffles. 11670 EVT SourceType = MVT::Other; 11671 bool AllAnyExt = true; 11672 11673 for (unsigned i = 0; i != NumInScalars; ++i) { 11674 SDValue In = N->getOperand(i); 11675 // Ignore undef inputs. 11676 if (In.getOpcode() == ISD::UNDEF) continue; 11677 11678 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 11679 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 11680 11681 // Abort if the element is not an extension. 11682 if (!ZeroExt && !AnyExt) { 11683 SourceType = MVT::Other; 11684 break; 11685 } 11686 11687 // The input is a ZeroExt or AnyExt. Check the original type. 11688 EVT InTy = In.getOperand(0).getValueType(); 11689 11690 // Check that all of the widened source types are the same. 11691 if (SourceType == MVT::Other) 11692 // First time. 11693 SourceType = InTy; 11694 else if (InTy != SourceType) { 11695 // Multiple income types. Abort. 11696 SourceType = MVT::Other; 11697 break; 11698 } 11699 11700 // Check if all of the extends are ANY_EXTENDs. 11701 AllAnyExt &= AnyExt; 11702 } 11703 11704 // In order to have valid types, all of the inputs must be extended from the 11705 // same source type and all of the inputs must be any or zero extend. 11706 // Scalar sizes must be a power of two. 11707 EVT OutScalarTy = VT.getScalarType(); 11708 bool ValidTypes = SourceType != MVT::Other && 11709 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 11710 isPowerOf2_32(SourceType.getSizeInBits()); 11711 11712 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 11713 // turn into a single shuffle instruction. 11714 if (!ValidTypes) 11715 return SDValue(); 11716 11717 bool isLE = TLI.isLittleEndian(); 11718 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 11719 assert(ElemRatio > 1 && "Invalid element size ratio"); 11720 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 11721 DAG.getConstant(0, SDLoc(N), SourceType); 11722 11723 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 11724 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 11725 11726 // Populate the new build_vector 11727 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11728 SDValue Cast = N->getOperand(i); 11729 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 11730 Cast.getOpcode() == ISD::ZERO_EXTEND || 11731 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 11732 SDValue In; 11733 if (Cast.getOpcode() == ISD::UNDEF) 11734 In = DAG.getUNDEF(SourceType); 11735 else 11736 In = Cast->getOperand(0); 11737 unsigned Index = isLE ? (i * ElemRatio) : 11738 (i * ElemRatio + (ElemRatio - 1)); 11739 11740 assert(Index < Ops.size() && "Invalid index"); 11741 Ops[Index] = In; 11742 } 11743 11744 // The type of the new BUILD_VECTOR node. 11745 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 11746 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 11747 "Invalid vector size"); 11748 // Check if the new vector type is legal. 11749 if (!isTypeLegal(VecVT)) return SDValue(); 11750 11751 // Make the new BUILD_VECTOR. 11752 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 11753 11754 // The new BUILD_VECTOR node has the potential to be further optimized. 11755 AddToWorklist(BV.getNode()); 11756 // Bitcast to the desired type. 11757 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11758 } 11759 11760 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 11761 EVT VT = N->getValueType(0); 11762 11763 unsigned NumInScalars = N->getNumOperands(); 11764 SDLoc dl(N); 11765 11766 EVT SrcVT = MVT::Other; 11767 unsigned Opcode = ISD::DELETED_NODE; 11768 unsigned NumDefs = 0; 11769 11770 for (unsigned i = 0; i != NumInScalars; ++i) { 11771 SDValue In = N->getOperand(i); 11772 unsigned Opc = In.getOpcode(); 11773 11774 if (Opc == ISD::UNDEF) 11775 continue; 11776 11777 // If all scalar values are floats and converted from integers. 11778 if (Opcode == ISD::DELETED_NODE && 11779 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 11780 Opcode = Opc; 11781 } 11782 11783 if (Opc != Opcode) 11784 return SDValue(); 11785 11786 EVT InVT = In.getOperand(0).getValueType(); 11787 11788 // If all scalar values are typed differently, bail out. It's chosen to 11789 // simplify BUILD_VECTOR of integer types. 11790 if (SrcVT == MVT::Other) 11791 SrcVT = InVT; 11792 if (SrcVT != InVT) 11793 return SDValue(); 11794 NumDefs++; 11795 } 11796 11797 // If the vector has just one element defined, it's not worth to fold it into 11798 // a vectorized one. 11799 if (NumDefs < 2) 11800 return SDValue(); 11801 11802 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 11803 && "Should only handle conversion from integer to float."); 11804 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 11805 11806 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 11807 11808 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 11809 return SDValue(); 11810 11811 // Just because the floating-point vector type is legal does not necessarily 11812 // mean that the corresponding integer vector type is. 11813 if (!isTypeLegal(NVT)) 11814 return SDValue(); 11815 11816 SmallVector<SDValue, 8> Opnds; 11817 for (unsigned i = 0; i != NumInScalars; ++i) { 11818 SDValue In = N->getOperand(i); 11819 11820 if (In.getOpcode() == ISD::UNDEF) 11821 Opnds.push_back(DAG.getUNDEF(SrcVT)); 11822 else 11823 Opnds.push_back(In.getOperand(0)); 11824 } 11825 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 11826 AddToWorklist(BV.getNode()); 11827 11828 return DAG.getNode(Opcode, dl, VT, BV); 11829 } 11830 11831 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 11832 unsigned NumInScalars = N->getNumOperands(); 11833 SDLoc dl(N); 11834 EVT VT = N->getValueType(0); 11835 11836 // A vector built entirely of undefs is undef. 11837 if (ISD::allOperandsUndef(N)) 11838 return DAG.getUNDEF(VT); 11839 11840 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 11841 return V; 11842 11843 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 11844 return V; 11845 11846 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 11847 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 11848 // at most two distinct vectors, turn this into a shuffle node. 11849 11850 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 11851 if (!isTypeLegal(VT)) 11852 return SDValue(); 11853 11854 // May only combine to shuffle after legalize if shuffle is legal. 11855 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 11856 return SDValue(); 11857 11858 SDValue VecIn1, VecIn2; 11859 bool UsesZeroVector = false; 11860 for (unsigned i = 0; i != NumInScalars; ++i) { 11861 SDValue Op = N->getOperand(i); 11862 // Ignore undef inputs. 11863 if (Op.getOpcode() == ISD::UNDEF) continue; 11864 11865 // See if we can combine this build_vector into a blend with a zero vector. 11866 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant && 11867 cast<ConstantSDNode>(Op.getNode())->isNullValue()) || 11868 (Op.getOpcode() == ISD::ConstantFP && 11869 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) { 11870 UsesZeroVector = true; 11871 continue; 11872 } 11873 11874 // If this input is something other than a EXTRACT_VECTOR_ELT with a 11875 // constant index, bail out. 11876 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11877 !isa<ConstantSDNode>(Op.getOperand(1))) { 11878 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11879 break; 11880 } 11881 11882 // We allow up to two distinct input vectors. 11883 SDValue ExtractedFromVec = Op.getOperand(0); 11884 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 11885 continue; 11886 11887 if (!VecIn1.getNode()) { 11888 VecIn1 = ExtractedFromVec; 11889 } else if (!VecIn2.getNode() && !UsesZeroVector) { 11890 VecIn2 = ExtractedFromVec; 11891 } else { 11892 // Too many inputs. 11893 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11894 break; 11895 } 11896 } 11897 11898 // If everything is good, we can make a shuffle operation. 11899 if (VecIn1.getNode()) { 11900 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 11901 SmallVector<int, 8> Mask; 11902 for (unsigned i = 0; i != NumInScalars; ++i) { 11903 unsigned Opcode = N->getOperand(i).getOpcode(); 11904 if (Opcode == ISD::UNDEF) { 11905 Mask.push_back(-1); 11906 continue; 11907 } 11908 11909 // Operands can also be zero. 11910 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 11911 assert(UsesZeroVector && 11912 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 11913 "Unexpected node found!"); 11914 Mask.push_back(NumInScalars+i); 11915 continue; 11916 } 11917 11918 // If extracting from the first vector, just use the index directly. 11919 SDValue Extract = N->getOperand(i); 11920 SDValue ExtVal = Extract.getOperand(1); 11921 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 11922 if (Extract.getOperand(0) == VecIn1) { 11923 Mask.push_back(ExtIndex); 11924 continue; 11925 } 11926 11927 // Otherwise, use InIdx + InputVecSize 11928 Mask.push_back(InNumElements + ExtIndex); 11929 } 11930 11931 // Avoid introducing illegal shuffles with zero. 11932 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 11933 return SDValue(); 11934 11935 // We can't generate a shuffle node with mismatched input and output types. 11936 // Attempt to transform a single input vector to the correct type. 11937 if ((VT != VecIn1.getValueType())) { 11938 // If the input vector type has a different base type to the output 11939 // vector type, bail out. 11940 EVT VTElemType = VT.getVectorElementType(); 11941 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 11942 (VecIn2.getNode() && 11943 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 11944 return SDValue(); 11945 11946 // If the input vector is too small, widen it. 11947 // We only support widening of vectors which are half the size of the 11948 // output registers. For example XMM->YMM widening on X86 with AVX. 11949 EVT VecInT = VecIn1.getValueType(); 11950 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 11951 // If we only have one small input, widen it by adding undef values. 11952 if (!VecIn2.getNode()) 11953 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 11954 DAG.getUNDEF(VecIn1.getValueType())); 11955 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 11956 // If we have two small inputs of the same type, try to concat them. 11957 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 11958 VecIn2 = SDValue(nullptr, 0); 11959 } else 11960 return SDValue(); 11961 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 11962 // If the input vector is too large, try to split it. 11963 // We don't support having two input vectors that are too large. 11964 // If the zero vector was used, we can not split the vector, 11965 // since we'd need 3 inputs. 11966 if (UsesZeroVector || VecIn2.getNode()) 11967 return SDValue(); 11968 11969 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 11970 return SDValue(); 11971 11972 // Try to replace VecIn1 with two extract_subvectors 11973 // No need to update the masks, they should still be correct. 11974 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11975 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy())); 11976 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11977 DAG.getConstant(0, dl, TLI.getVectorIdxTy())); 11978 } else 11979 return SDValue(); 11980 } 11981 11982 if (UsesZeroVector) 11983 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 11984 DAG.getConstantFP(0.0, dl, VT); 11985 else 11986 // If VecIn2 is unused then change it to undef. 11987 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 11988 11989 // Check that we were able to transform all incoming values to the same 11990 // type. 11991 if (VecIn2.getValueType() != VecIn1.getValueType() || 11992 VecIn1.getValueType() != VT) 11993 return SDValue(); 11994 11995 // Return the new VECTOR_SHUFFLE node. 11996 SDValue Ops[2]; 11997 Ops[0] = VecIn1; 11998 Ops[1] = VecIn2; 11999 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12000 } 12001 12002 return SDValue(); 12003 } 12004 12005 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12007 EVT OpVT = N->getOperand(0).getValueType(); 12008 12009 // If the operands are legal vectors, leave them alone. 12010 if (TLI.isTypeLegal(OpVT)) 12011 return SDValue(); 12012 12013 SDLoc DL(N); 12014 EVT VT = N->getValueType(0); 12015 SmallVector<SDValue, 8> Ops; 12016 12017 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12018 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12019 12020 // Keep track of what we encounter. 12021 bool AnyInteger = false; 12022 bool AnyFP = false; 12023 for (const SDValue &Op : N->ops()) { 12024 if (ISD::BITCAST == Op.getOpcode() && 12025 !Op.getOperand(0).getValueType().isVector()) 12026 Ops.push_back(Op.getOperand(0)); 12027 else if (ISD::UNDEF == Op.getOpcode()) 12028 Ops.push_back(ScalarUndef); 12029 else 12030 return SDValue(); 12031 12032 // Note whether we encounter an integer or floating point scalar. 12033 // If it's neither, bail out, it could be something weird like x86mmx. 12034 EVT LastOpVT = Ops.back().getValueType(); 12035 if (LastOpVT.isFloatingPoint()) 12036 AnyFP = true; 12037 else if (LastOpVT.isInteger()) 12038 AnyInteger = true; 12039 else 12040 return SDValue(); 12041 } 12042 12043 // If any of the operands is a floating point scalar bitcast to a vector, 12044 // use floating point types throughout, and bitcast everything. 12045 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12046 if (AnyFP) { 12047 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12048 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12049 if (AnyInteger) { 12050 for (SDValue &Op : Ops) { 12051 if (Op.getValueType() == SVT) 12052 continue; 12053 if (Op.getOpcode() == ISD::UNDEF) 12054 Op = ScalarUndef; 12055 else 12056 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12057 } 12058 } 12059 } 12060 12061 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12062 VT.getSizeInBits() / SVT.getSizeInBits()); 12063 return DAG.getNode(ISD::BITCAST, DL, VT, 12064 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12065 } 12066 12067 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12068 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 12069 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 12070 // inputs come from at most two distinct vectors, turn this into a shuffle 12071 // node. 12072 12073 // If we only have one input vector, we don't need to do any concatenation. 12074 if (N->getNumOperands() == 1) 12075 return N->getOperand(0); 12076 12077 // Check if all of the operands are undefs. 12078 EVT VT = N->getValueType(0); 12079 if (ISD::allOperandsUndef(N)) 12080 return DAG.getUNDEF(VT); 12081 12082 // Optimize concat_vectors where all but the first of the vectors are undef. 12083 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12084 return Op.getOpcode() == ISD::UNDEF; 12085 })) { 12086 SDValue In = N->getOperand(0); 12087 assert(In.getValueType().isVector() && "Must concat vectors"); 12088 12089 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12090 if (In->getOpcode() == ISD::BITCAST && 12091 !In->getOperand(0)->getValueType(0).isVector()) { 12092 SDValue Scalar = In->getOperand(0); 12093 12094 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12095 // look through the trunc so we can still do the transform: 12096 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12097 if (Scalar->getOpcode() == ISD::TRUNCATE && 12098 !TLI.isTypeLegal(Scalar.getValueType()) && 12099 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12100 Scalar = Scalar->getOperand(0); 12101 12102 EVT SclTy = Scalar->getValueType(0); 12103 12104 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12105 return SDValue(); 12106 12107 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12108 VT.getSizeInBits() / SclTy.getSizeInBits()); 12109 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12110 return SDValue(); 12111 12112 SDLoc dl = SDLoc(N); 12113 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12114 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12115 } 12116 } 12117 12118 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12119 // We have already tested above for an UNDEF only concatenation. 12120 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12121 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12122 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12123 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12124 }; 12125 bool AllBuildVectorsOrUndefs = 12126 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12127 if (AllBuildVectorsOrUndefs) { 12128 SmallVector<SDValue, 8> Opnds; 12129 EVT SVT = VT.getScalarType(); 12130 12131 EVT MinVT = SVT; 12132 if (!SVT.isFloatingPoint()) { 12133 // If BUILD_VECTOR are from built from integer, they may have different 12134 // operand types. Get the smallest type and truncate all operands to it. 12135 bool FoundMinVT = false; 12136 for (const SDValue &Op : N->ops()) 12137 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12138 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12139 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12140 FoundMinVT = true; 12141 } 12142 assert(FoundMinVT && "Concat vector type mismatch"); 12143 } 12144 12145 for (const SDValue &Op : N->ops()) { 12146 EVT OpVT = Op.getValueType(); 12147 unsigned NumElts = OpVT.getVectorNumElements(); 12148 12149 if (ISD::UNDEF == Op.getOpcode()) 12150 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12151 12152 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12153 if (SVT.isFloatingPoint()) { 12154 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12155 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12156 } else { 12157 for (unsigned i = 0; i != NumElts; ++i) 12158 Opnds.push_back( 12159 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12160 } 12161 } 12162 } 12163 12164 assert(VT.getVectorNumElements() == Opnds.size() && 12165 "Concat vector type mismatch"); 12166 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12167 } 12168 12169 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12170 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12171 return V; 12172 12173 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12174 // nodes often generate nop CONCAT_VECTOR nodes. 12175 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12176 // place the incoming vectors at the exact same location. 12177 SDValue SingleSource = SDValue(); 12178 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12179 12180 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12181 SDValue Op = N->getOperand(i); 12182 12183 if (Op.getOpcode() == ISD::UNDEF) 12184 continue; 12185 12186 // Check if this is the identity extract: 12187 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12188 return SDValue(); 12189 12190 // Find the single incoming vector for the extract_subvector. 12191 if (SingleSource.getNode()) { 12192 if (Op.getOperand(0) != SingleSource) 12193 return SDValue(); 12194 } else { 12195 SingleSource = Op.getOperand(0); 12196 12197 // Check the source type is the same as the type of the result. 12198 // If not, this concat may extend the vector, so we can not 12199 // optimize it away. 12200 if (SingleSource.getValueType() != N->getValueType(0)) 12201 return SDValue(); 12202 } 12203 12204 unsigned IdentityIndex = i * PartNumElem; 12205 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12206 // The extract index must be constant. 12207 if (!CS) 12208 return SDValue(); 12209 12210 // Check that we are reading from the identity index. 12211 if (CS->getZExtValue() != IdentityIndex) 12212 return SDValue(); 12213 } 12214 12215 if (SingleSource.getNode()) 12216 return SingleSource; 12217 12218 return SDValue(); 12219 } 12220 12221 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12222 EVT NVT = N->getValueType(0); 12223 SDValue V = N->getOperand(0); 12224 12225 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12226 // Combine: 12227 // (extract_subvec (concat V1, V2, ...), i) 12228 // Into: 12229 // Vi if possible 12230 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12231 // type. 12232 if (V->getOperand(0).getValueType() != NVT) 12233 return SDValue(); 12234 unsigned Idx = N->getConstantOperandVal(1); 12235 unsigned NumElems = NVT.getVectorNumElements(); 12236 assert((Idx % NumElems) == 0 && 12237 "IDX in concat is not a multiple of the result vector length."); 12238 return V->getOperand(Idx / NumElems); 12239 } 12240 12241 // Skip bitcasting 12242 if (V->getOpcode() == ISD::BITCAST) 12243 V = V.getOperand(0); 12244 12245 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 12246 SDLoc dl(N); 12247 // Handle only simple case where vector being inserted and vector 12248 // being extracted are of same type, and are half size of larger vectors. 12249 EVT BigVT = V->getOperand(0).getValueType(); 12250 EVT SmallVT = V->getOperand(1).getValueType(); 12251 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 12252 return SDValue(); 12253 12254 // Only handle cases where both indexes are constants with the same type. 12255 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12256 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12257 12258 if (InsIdx && ExtIdx && 12259 InsIdx->getValueType(0).getSizeInBits() <= 64 && 12260 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 12261 // Combine: 12262 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 12263 // Into: 12264 // indices are equal or bit offsets are equal => V1 12265 // otherwise => (extract_subvec V1, ExtIdx) 12266 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 12267 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 12268 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 12269 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 12270 DAG.getNode(ISD::BITCAST, dl, 12271 N->getOperand(0).getValueType(), 12272 V->getOperand(0)), N->getOperand(1)); 12273 } 12274 } 12275 12276 return SDValue(); 12277 } 12278 12279 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 12280 SDValue V, SelectionDAG &DAG) { 12281 SDLoc DL(V); 12282 EVT VT = V.getValueType(); 12283 12284 switch (V.getOpcode()) { 12285 default: 12286 return V; 12287 12288 case ISD::CONCAT_VECTORS: { 12289 EVT OpVT = V->getOperand(0).getValueType(); 12290 int OpSize = OpVT.getVectorNumElements(); 12291 SmallBitVector OpUsedElements(OpSize, false); 12292 bool FoundSimplification = false; 12293 SmallVector<SDValue, 4> NewOps; 12294 NewOps.reserve(V->getNumOperands()); 12295 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12296 SDValue Op = V->getOperand(i); 12297 bool OpUsed = false; 12298 for (int j = 0; j < OpSize; ++j) 12299 if (UsedElements[i * OpSize + j]) { 12300 OpUsedElements[j] = true; 12301 OpUsed = true; 12302 } 12303 NewOps.push_back( 12304 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 12305 : DAG.getUNDEF(OpVT)); 12306 FoundSimplification |= Op == NewOps.back(); 12307 OpUsedElements.reset(); 12308 } 12309 if (FoundSimplification) 12310 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 12311 return V; 12312 } 12313 12314 case ISD::INSERT_SUBVECTOR: { 12315 SDValue BaseV = V->getOperand(0); 12316 SDValue SubV = V->getOperand(1); 12317 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12318 if (!IdxN) 12319 return V; 12320 12321 int SubSize = SubV.getValueType().getVectorNumElements(); 12322 int Idx = IdxN->getZExtValue(); 12323 bool SubVectorUsed = false; 12324 SmallBitVector SubUsedElements(SubSize, false); 12325 for (int i = 0; i < SubSize; ++i) 12326 if (UsedElements[i + Idx]) { 12327 SubVectorUsed = true; 12328 SubUsedElements[i] = true; 12329 UsedElements[i + Idx] = false; 12330 } 12331 12332 // Now recurse on both the base and sub vectors. 12333 SDValue SimplifiedSubV = 12334 SubVectorUsed 12335 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 12336 : DAG.getUNDEF(SubV.getValueType()); 12337 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 12338 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 12339 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 12340 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 12341 return V; 12342 } 12343 } 12344 } 12345 12346 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 12347 SDValue N1, SelectionDAG &DAG) { 12348 EVT VT = SVN->getValueType(0); 12349 int NumElts = VT.getVectorNumElements(); 12350 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 12351 for (int M : SVN->getMask()) 12352 if (M >= 0 && M < NumElts) 12353 N0UsedElements[M] = true; 12354 else if (M >= NumElts) 12355 N1UsedElements[M - NumElts] = true; 12356 12357 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 12358 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 12359 if (S0 == N0 && S1 == N1) 12360 return SDValue(); 12361 12362 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 12363 } 12364 12365 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 12366 // or turn a shuffle of a single concat into simpler shuffle then concat. 12367 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 12368 EVT VT = N->getValueType(0); 12369 unsigned NumElts = VT.getVectorNumElements(); 12370 12371 SDValue N0 = N->getOperand(0); 12372 SDValue N1 = N->getOperand(1); 12373 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12374 12375 SmallVector<SDValue, 4> Ops; 12376 EVT ConcatVT = N0.getOperand(0).getValueType(); 12377 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 12378 unsigned NumConcats = NumElts / NumElemsPerConcat; 12379 12380 // Special case: shuffle(concat(A,B)) can be more efficiently represented 12381 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 12382 // half vector elements. 12383 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 12384 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 12385 SVN->getMask().end(), [](int i) { return i == -1; })) { 12386 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 12387 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat)); 12388 N1 = DAG.getUNDEF(ConcatVT); 12389 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 12390 } 12391 12392 // Look at every vector that's inserted. We're looking for exact 12393 // subvector-sized copies from a concatenated vector 12394 for (unsigned I = 0; I != NumConcats; ++I) { 12395 // Make sure we're dealing with a copy. 12396 unsigned Begin = I * NumElemsPerConcat; 12397 bool AllUndef = true, NoUndef = true; 12398 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 12399 if (SVN->getMaskElt(J) >= 0) 12400 AllUndef = false; 12401 else 12402 NoUndef = false; 12403 } 12404 12405 if (NoUndef) { 12406 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 12407 return SDValue(); 12408 12409 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 12410 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 12411 return SDValue(); 12412 12413 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 12414 if (FirstElt < N0.getNumOperands()) 12415 Ops.push_back(N0.getOperand(FirstElt)); 12416 else 12417 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 12418 12419 } else if (AllUndef) { 12420 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 12421 } else { // Mixed with general masks and undefs, can't do optimization. 12422 return SDValue(); 12423 } 12424 } 12425 12426 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 12427 } 12428 12429 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 12430 EVT VT = N->getValueType(0); 12431 unsigned NumElts = VT.getVectorNumElements(); 12432 12433 SDValue N0 = N->getOperand(0); 12434 SDValue N1 = N->getOperand(1); 12435 12436 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 12437 12438 // Canonicalize shuffle undef, undef -> undef 12439 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 12440 return DAG.getUNDEF(VT); 12441 12442 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12443 12444 // Canonicalize shuffle v, v -> v, undef 12445 if (N0 == N1) { 12446 SmallVector<int, 8> NewMask; 12447 for (unsigned i = 0; i != NumElts; ++i) { 12448 int Idx = SVN->getMaskElt(i); 12449 if (Idx >= (int)NumElts) Idx -= NumElts; 12450 NewMask.push_back(Idx); 12451 } 12452 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 12453 &NewMask[0]); 12454 } 12455 12456 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 12457 if (N0.getOpcode() == ISD::UNDEF) { 12458 SmallVector<int, 8> NewMask; 12459 for (unsigned i = 0; i != NumElts; ++i) { 12460 int Idx = SVN->getMaskElt(i); 12461 if (Idx >= 0) { 12462 if (Idx >= (int)NumElts) 12463 Idx -= NumElts; 12464 else 12465 Idx = -1; // remove reference to lhs 12466 } 12467 NewMask.push_back(Idx); 12468 } 12469 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 12470 &NewMask[0]); 12471 } 12472 12473 // Remove references to rhs if it is undef 12474 if (N1.getOpcode() == ISD::UNDEF) { 12475 bool Changed = false; 12476 SmallVector<int, 8> NewMask; 12477 for (unsigned i = 0; i != NumElts; ++i) { 12478 int Idx = SVN->getMaskElt(i); 12479 if (Idx >= (int)NumElts) { 12480 Idx = -1; 12481 Changed = true; 12482 } 12483 NewMask.push_back(Idx); 12484 } 12485 if (Changed) 12486 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 12487 } 12488 12489 // If it is a splat, check if the argument vector is another splat or a 12490 // build_vector. 12491 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 12492 SDNode *V = N0.getNode(); 12493 12494 // If this is a bit convert that changes the element type of the vector but 12495 // not the number of vector elements, look through it. Be careful not to 12496 // look though conversions that change things like v4f32 to v2f64. 12497 if (V->getOpcode() == ISD::BITCAST) { 12498 SDValue ConvInput = V->getOperand(0); 12499 if (ConvInput.getValueType().isVector() && 12500 ConvInput.getValueType().getVectorNumElements() == NumElts) 12501 V = ConvInput.getNode(); 12502 } 12503 12504 if (V->getOpcode() == ISD::BUILD_VECTOR) { 12505 assert(V->getNumOperands() == NumElts && 12506 "BUILD_VECTOR has wrong number of operands"); 12507 SDValue Base; 12508 bool AllSame = true; 12509 for (unsigned i = 0; i != NumElts; ++i) { 12510 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 12511 Base = V->getOperand(i); 12512 break; 12513 } 12514 } 12515 // Splat of <u, u, u, u>, return <u, u, u, u> 12516 if (!Base.getNode()) 12517 return N0; 12518 for (unsigned i = 0; i != NumElts; ++i) { 12519 if (V->getOperand(i) != Base) { 12520 AllSame = false; 12521 break; 12522 } 12523 } 12524 // Splat of <x, x, x, x>, return <x, x, x, x> 12525 if (AllSame) 12526 return N0; 12527 12528 // Canonicalize any other splat as a build_vector. 12529 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 12530 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 12531 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 12532 V->getValueType(0), Ops); 12533 12534 // We may have jumped through bitcasts, so the type of the 12535 // BUILD_VECTOR may not match the type of the shuffle. 12536 if (V->getValueType(0) != VT) 12537 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 12538 return NewBV; 12539 } 12540 } 12541 12542 // There are various patterns used to build up a vector from smaller vectors, 12543 // subvectors, or elements. Scan chains of these and replace unused insertions 12544 // or components with undef. 12545 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 12546 return S; 12547 12548 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12549 Level < AfterLegalizeVectorOps && 12550 (N1.getOpcode() == ISD::UNDEF || 12551 (N1.getOpcode() == ISD::CONCAT_VECTORS && 12552 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 12553 SDValue V = partitionShuffleOfConcats(N, DAG); 12554 12555 if (V.getNode()) 12556 return V; 12557 } 12558 12559 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 12560 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 12561 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 12562 SmallVector<SDValue, 8> Ops; 12563 for (int M : SVN->getMask()) { 12564 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 12565 if (M >= 0) { 12566 int Idx = M % NumElts; 12567 SDValue &S = (M < (int)NumElts ? N0 : N1); 12568 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 12569 Op = S.getOperand(Idx); 12570 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 12571 if (Idx == 0) 12572 Op = S.getOperand(0); 12573 } else { 12574 // Operand can't be combined - bail out. 12575 break; 12576 } 12577 } 12578 Ops.push_back(Op); 12579 } 12580 if (Ops.size() == VT.getVectorNumElements()) { 12581 // BUILD_VECTOR requires all inputs to be of the same type, find the 12582 // maximum type and extend them all. 12583 EVT SVT = VT.getScalarType(); 12584 if (SVT.isInteger()) 12585 for (SDValue &Op : Ops) 12586 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 12587 if (SVT != VT.getScalarType()) 12588 for (SDValue &Op : Ops) 12589 Op = TLI.isZExtFree(Op.getValueType(), SVT) 12590 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 12591 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 12592 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 12593 } 12594 } 12595 12596 // If this shuffle only has a single input that is a bitcasted shuffle, 12597 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 12598 // back to their original types. 12599 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 12600 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 12601 TLI.isTypeLegal(VT)) { 12602 12603 // Peek through the bitcast only if there is one user. 12604 SDValue BC0 = N0; 12605 while (BC0.getOpcode() == ISD::BITCAST) { 12606 if (!BC0.hasOneUse()) 12607 break; 12608 BC0 = BC0.getOperand(0); 12609 } 12610 12611 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 12612 if (Scale == 1) 12613 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 12614 12615 SmallVector<int, 8> NewMask; 12616 for (int M : Mask) 12617 for (int s = 0; s != Scale; ++s) 12618 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 12619 return NewMask; 12620 }; 12621 12622 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 12623 EVT SVT = VT.getScalarType(); 12624 EVT InnerVT = BC0->getValueType(0); 12625 EVT InnerSVT = InnerVT.getScalarType(); 12626 12627 // Determine which shuffle works with the smaller scalar type. 12628 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 12629 EVT ScaleSVT = ScaleVT.getScalarType(); 12630 12631 if (TLI.isTypeLegal(ScaleVT) && 12632 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 12633 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 12634 12635 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12636 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12637 12638 // Scale the shuffle masks to the smaller scalar type. 12639 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 12640 SmallVector<int, 8> InnerMask = 12641 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 12642 SmallVector<int, 8> OuterMask = 12643 ScaleShuffleMask(SVN->getMask(), OuterScale); 12644 12645 // Merge the shuffle masks. 12646 SmallVector<int, 8> NewMask; 12647 for (int M : OuterMask) 12648 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 12649 12650 // Test for shuffle mask legality over both commutations. 12651 SDValue SV0 = BC0->getOperand(0); 12652 SDValue SV1 = BC0->getOperand(1); 12653 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12654 if (!LegalMask) { 12655 std::swap(SV0, SV1); 12656 ShuffleVectorSDNode::commuteMask(NewMask); 12657 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12658 } 12659 12660 if (LegalMask) { 12661 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 12662 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 12663 return DAG.getNode( 12664 ISD::BITCAST, SDLoc(N), VT, 12665 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 12666 } 12667 } 12668 } 12669 } 12670 12671 // Canonicalize shuffles according to rules: 12672 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 12673 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 12674 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 12675 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 12676 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 12677 TLI.isTypeLegal(VT)) { 12678 // The incoming shuffle must be of the same type as the result of the 12679 // current shuffle. 12680 assert(N1->getOperand(0).getValueType() == VT && 12681 "Shuffle types don't match"); 12682 12683 SDValue SV0 = N1->getOperand(0); 12684 SDValue SV1 = N1->getOperand(1); 12685 bool HasSameOp0 = N0 == SV0; 12686 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 12687 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 12688 // Commute the operands of this shuffle so that next rule 12689 // will trigger. 12690 return DAG.getCommutedVectorShuffle(*SVN); 12691 } 12692 12693 // Try to fold according to rules: 12694 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12695 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12696 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12697 // Don't try to fold shuffles with illegal type. 12698 // Only fold if this shuffle is the only user of the other shuffle. 12699 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 12700 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 12701 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 12702 12703 // The incoming shuffle must be of the same type as the result of the 12704 // current shuffle. 12705 assert(OtherSV->getOperand(0).getValueType() == VT && 12706 "Shuffle types don't match"); 12707 12708 SDValue SV0, SV1; 12709 SmallVector<int, 4> Mask; 12710 // Compute the combined shuffle mask for a shuffle with SV0 as the first 12711 // operand, and SV1 as the second operand. 12712 for (unsigned i = 0; i != NumElts; ++i) { 12713 int Idx = SVN->getMaskElt(i); 12714 if (Idx < 0) { 12715 // Propagate Undef. 12716 Mask.push_back(Idx); 12717 continue; 12718 } 12719 12720 SDValue CurrentVec; 12721 if (Idx < (int)NumElts) { 12722 // This shuffle index refers to the inner shuffle N0. Lookup the inner 12723 // shuffle mask to identify which vector is actually referenced. 12724 Idx = OtherSV->getMaskElt(Idx); 12725 if (Idx < 0) { 12726 // Propagate Undef. 12727 Mask.push_back(Idx); 12728 continue; 12729 } 12730 12731 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 12732 : OtherSV->getOperand(1); 12733 } else { 12734 // This shuffle index references an element within N1. 12735 CurrentVec = N1; 12736 } 12737 12738 // Simple case where 'CurrentVec' is UNDEF. 12739 if (CurrentVec.getOpcode() == ISD::UNDEF) { 12740 Mask.push_back(-1); 12741 continue; 12742 } 12743 12744 // Canonicalize the shuffle index. We don't know yet if CurrentVec 12745 // will be the first or second operand of the combined shuffle. 12746 Idx = Idx % NumElts; 12747 if (!SV0.getNode() || SV0 == CurrentVec) { 12748 // Ok. CurrentVec is the left hand side. 12749 // Update the mask accordingly. 12750 SV0 = CurrentVec; 12751 Mask.push_back(Idx); 12752 continue; 12753 } 12754 12755 // Bail out if we cannot convert the shuffle pair into a single shuffle. 12756 if (SV1.getNode() && SV1 != CurrentVec) 12757 return SDValue(); 12758 12759 // Ok. CurrentVec is the right hand side. 12760 // Update the mask accordingly. 12761 SV1 = CurrentVec; 12762 Mask.push_back(Idx + NumElts); 12763 } 12764 12765 // Check if all indices in Mask are Undef. In case, propagate Undef. 12766 bool isUndefMask = true; 12767 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 12768 isUndefMask &= Mask[i] < 0; 12769 12770 if (isUndefMask) 12771 return DAG.getUNDEF(VT); 12772 12773 if (!SV0.getNode()) 12774 SV0 = DAG.getUNDEF(VT); 12775 if (!SV1.getNode()) 12776 SV1 = DAG.getUNDEF(VT); 12777 12778 // Avoid introducing shuffles with illegal mask. 12779 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 12780 ShuffleVectorSDNode::commuteMask(Mask); 12781 12782 if (!TLI.isShuffleMaskLegal(Mask, VT)) 12783 return SDValue(); 12784 12785 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 12786 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 12787 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 12788 std::swap(SV0, SV1); 12789 } 12790 12791 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12792 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12793 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12794 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 12795 } 12796 12797 return SDValue(); 12798 } 12799 12800 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 12801 SDValue InVal = N->getOperand(0); 12802 EVT VT = N->getValueType(0); 12803 12804 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 12805 // with a VECTOR_SHUFFLE. 12806 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12807 SDValue InVec = InVal->getOperand(0); 12808 SDValue EltNo = InVal->getOperand(1); 12809 12810 // FIXME: We could support implicit truncation if the shuffle can be 12811 // scaled to a smaller vector scalar type. 12812 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 12813 if (C0 && VT == InVec.getValueType() && 12814 VT.getScalarType() == InVal.getValueType()) { 12815 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 12816 int Elt = C0->getZExtValue(); 12817 NewMask[0] = Elt; 12818 12819 if (TLI.isShuffleMaskLegal(NewMask, VT)) 12820 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 12821 NewMask); 12822 } 12823 } 12824 12825 return SDValue(); 12826 } 12827 12828 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 12829 SDValue N0 = N->getOperand(0); 12830 SDValue N2 = N->getOperand(2); 12831 12832 // If the input vector is a concatenation, and the insert replaces 12833 // one of the halves, we can optimize into a single concat_vectors. 12834 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12835 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 12836 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 12837 EVT VT = N->getValueType(0); 12838 12839 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12840 // (concat_vectors Z, Y) 12841 if (InsIdx == 0) 12842 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12843 N->getOperand(1), N0.getOperand(1)); 12844 12845 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12846 // (concat_vectors X, Z) 12847 if (InsIdx == VT.getVectorNumElements()/2) 12848 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12849 N0.getOperand(0), N->getOperand(1)); 12850 } 12851 12852 return SDValue(); 12853 } 12854 12855 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 12856 SDValue N0 = N->getOperand(0); 12857 12858 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 12859 if (N0->getOpcode() == ISD::FP16_TO_FP) 12860 return N0->getOperand(0); 12861 12862 return SDValue(); 12863 } 12864 12865 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 12866 /// with the destination vector and a zero vector. 12867 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 12868 /// vector_shuffle V, Zero, <0, 4, 2, 4> 12869 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 12870 EVT VT = N->getValueType(0); 12871 SDValue LHS = N->getOperand(0); 12872 SDValue RHS = N->getOperand(1); 12873 SDLoc dl(N); 12874 12875 // Make sure we're not running after operation legalization where it 12876 // may have custom lowered the vector shuffles. 12877 if (LegalOperations) 12878 return SDValue(); 12879 12880 if (N->getOpcode() != ISD::AND) 12881 return SDValue(); 12882 12883 if (RHS.getOpcode() == ISD::BITCAST) 12884 RHS = RHS.getOperand(0); 12885 12886 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 12887 SmallVector<int, 8> Indices; 12888 unsigned NumElts = RHS.getNumOperands(); 12889 12890 for (unsigned i = 0; i != NumElts; ++i) { 12891 SDValue Elt = RHS.getOperand(i); 12892 if (!isa<ConstantSDNode>(Elt)) 12893 return SDValue(); 12894 12895 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 12896 Indices.push_back(i); 12897 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 12898 Indices.push_back(NumElts+i); 12899 else 12900 return SDValue(); 12901 } 12902 12903 // Let's see if the target supports this vector_shuffle. 12904 EVT RVT = RHS.getValueType(); 12905 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 12906 return SDValue(); 12907 12908 // Return the new VECTOR_SHUFFLE node. 12909 EVT EltVT = RVT.getVectorElementType(); 12910 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 12911 DAG.getConstant(0, dl, EltVT)); 12912 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps); 12913 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 12914 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 12915 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 12916 } 12917 12918 return SDValue(); 12919 } 12920 12921 /// Visit a binary vector operation, like ADD. 12922 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 12923 assert(N->getValueType(0).isVector() && 12924 "SimplifyVBinOp only works on vectors!"); 12925 12926 SDValue LHS = N->getOperand(0); 12927 SDValue RHS = N->getOperand(1); 12928 12929 if (SDValue Shuffle = XformToShuffleWithZero(N)) 12930 return Shuffle; 12931 12932 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 12933 // this operation. 12934 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 12935 RHS.getOpcode() == ISD::BUILD_VECTOR) { 12936 // Check if both vectors are constants. If not bail out. 12937 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 12938 cast<BuildVectorSDNode>(RHS)->isConstant())) 12939 return SDValue(); 12940 12941 SmallVector<SDValue, 8> Ops; 12942 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 12943 SDValue LHSOp = LHS.getOperand(i); 12944 SDValue RHSOp = RHS.getOperand(i); 12945 12946 // Can't fold divide by zero. 12947 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 12948 N->getOpcode() == ISD::FDIV) { 12949 if ((RHSOp.getOpcode() == ISD::Constant && 12950 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 12951 (RHSOp.getOpcode() == ISD::ConstantFP && 12952 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 12953 break; 12954 } 12955 12956 EVT VT = LHSOp.getValueType(); 12957 EVT RVT = RHSOp.getValueType(); 12958 if (RVT != VT) { 12959 // Integer BUILD_VECTOR operands may have types larger than the element 12960 // size (e.g., when the element type is not legal). Prior to type 12961 // legalization, the types may not match between the two BUILD_VECTORS. 12962 // Truncate one of the operands to make them match. 12963 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 12964 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 12965 } else { 12966 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 12967 VT = RVT; 12968 } 12969 } 12970 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 12971 LHSOp, RHSOp); 12972 if (FoldOp.getOpcode() != ISD::UNDEF && 12973 FoldOp.getOpcode() != ISD::Constant && 12974 FoldOp.getOpcode() != ISD::ConstantFP) 12975 break; 12976 Ops.push_back(FoldOp); 12977 AddToWorklist(FoldOp.getNode()); 12978 } 12979 12980 if (Ops.size() == LHS.getNumOperands()) 12981 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 12982 } 12983 12984 // Type legalization might introduce new shuffles in the DAG. 12985 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 12986 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 12987 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 12988 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 12989 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 12990 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 12991 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 12992 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 12993 12994 if (SVN0->getMask().equals(SVN1->getMask())) { 12995 EVT VT = N->getValueType(0); 12996 SDValue UndefVector = LHS.getOperand(1); 12997 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 12998 LHS.getOperand(0), RHS.getOperand(0)); 12999 AddUsersToWorklist(N); 13000 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13001 &SVN0->getMask()[0]); 13002 } 13003 } 13004 13005 return SDValue(); 13006 } 13007 13008 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13009 SDValue N1, SDValue N2){ 13010 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13011 13012 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13013 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13014 13015 // If we got a simplified select_cc node back from SimplifySelectCC, then 13016 // break it down into a new SETCC node, and a new SELECT node, and then return 13017 // the SELECT node, since we were called with a SELECT node. 13018 if (SCC.getNode()) { 13019 // Check to see if we got a select_cc back (to turn into setcc/select). 13020 // Otherwise, just return whatever node we got back, like fabs. 13021 if (SCC.getOpcode() == ISD::SELECT_CC) { 13022 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13023 N0.getValueType(), 13024 SCC.getOperand(0), SCC.getOperand(1), 13025 SCC.getOperand(4)); 13026 AddToWorklist(SETCC.getNode()); 13027 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13028 SCC.getOperand(2), SCC.getOperand(3)); 13029 } 13030 13031 return SCC; 13032 } 13033 return SDValue(); 13034 } 13035 13036 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13037 /// being selected between, see if we can simplify the select. Callers of this 13038 /// should assume that TheSelect is deleted if this returns true. As such, they 13039 /// should return the appropriate thing (e.g. the node) back to the top-level of 13040 /// the DAG combiner loop to avoid it being looked at. 13041 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13042 SDValue RHS) { 13043 13044 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13045 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13046 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13047 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13048 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13049 SDValue Sqrt = RHS; 13050 ISD::CondCode CC; 13051 SDValue CmpLHS; 13052 const ConstantFPSDNode *NegZero = nullptr; 13053 13054 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13055 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13056 CmpLHS = TheSelect->getOperand(0); 13057 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13058 } else { 13059 // SELECT or VSELECT 13060 SDValue Cmp = TheSelect->getOperand(0); 13061 if (Cmp.getOpcode() == ISD::SETCC) { 13062 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13063 CmpLHS = Cmp.getOperand(0); 13064 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13065 } 13066 } 13067 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13068 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13069 CC == ISD::SETULT || CC == ISD::SETLT)) { 13070 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13071 CombineTo(TheSelect, Sqrt); 13072 return true; 13073 } 13074 } 13075 } 13076 // Cannot simplify select with vector condition 13077 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13078 13079 // If this is a select from two identical things, try to pull the operation 13080 // through the select. 13081 if (LHS.getOpcode() != RHS.getOpcode() || 13082 !LHS.hasOneUse() || !RHS.hasOneUse()) 13083 return false; 13084 13085 // If this is a load and the token chain is identical, replace the select 13086 // of two loads with a load through a select of the address to load from. 13087 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13088 // constants have been dropped into the constant pool. 13089 if (LHS.getOpcode() == ISD::LOAD) { 13090 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13091 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13092 13093 // Token chains must be identical. 13094 if (LHS.getOperand(0) != RHS.getOperand(0) || 13095 // Do not let this transformation reduce the number of volatile loads. 13096 LLD->isVolatile() || RLD->isVolatile() || 13097 // FIXME: If either is a pre/post inc/dec load, 13098 // we'd need to split out the address adjustment. 13099 LLD->isIndexed() || RLD->isIndexed() || 13100 // If this is an EXTLOAD, the VT's must match. 13101 LLD->getMemoryVT() != RLD->getMemoryVT() || 13102 // If this is an EXTLOAD, the kind of extension must match. 13103 (LLD->getExtensionType() != RLD->getExtensionType() && 13104 // The only exception is if one of the extensions is anyext. 13105 LLD->getExtensionType() != ISD::EXTLOAD && 13106 RLD->getExtensionType() != ISD::EXTLOAD) || 13107 // FIXME: this discards src value information. This is 13108 // over-conservative. It would be beneficial to be able to remember 13109 // both potential memory locations. Since we are discarding 13110 // src value info, don't do the transformation if the memory 13111 // locations are not in the default address space. 13112 LLD->getPointerInfo().getAddrSpace() != 0 || 13113 RLD->getPointerInfo().getAddrSpace() != 0 || 13114 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13115 LLD->getBasePtr().getValueType())) 13116 return false; 13117 13118 // Check that the select condition doesn't reach either load. If so, 13119 // folding this will induce a cycle into the DAG. If not, this is safe to 13120 // xform, so create a select of the addresses. 13121 SDValue Addr; 13122 if (TheSelect->getOpcode() == ISD::SELECT) { 13123 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13124 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13125 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13126 return false; 13127 // The loads must not depend on one another. 13128 if (LLD->isPredecessorOf(RLD) || 13129 RLD->isPredecessorOf(LLD)) 13130 return false; 13131 Addr = DAG.getSelect(SDLoc(TheSelect), 13132 LLD->getBasePtr().getValueType(), 13133 TheSelect->getOperand(0), LLD->getBasePtr(), 13134 RLD->getBasePtr()); 13135 } else { // Otherwise SELECT_CC 13136 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13137 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13138 13139 if ((LLD->hasAnyUseOfValue(1) && 13140 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13141 (RLD->hasAnyUseOfValue(1) && 13142 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13143 return false; 13144 13145 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13146 LLD->getBasePtr().getValueType(), 13147 TheSelect->getOperand(0), 13148 TheSelect->getOperand(1), 13149 LLD->getBasePtr(), RLD->getBasePtr(), 13150 TheSelect->getOperand(4)); 13151 } 13152 13153 SDValue Load; 13154 // It is safe to replace the two loads if they have different alignments, 13155 // but the new load must be the minimum (most restrictive) alignment of the 13156 // inputs. 13157 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13158 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13159 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13160 Load = DAG.getLoad(TheSelect->getValueType(0), 13161 SDLoc(TheSelect), 13162 // FIXME: Discards pointer and AA info. 13163 LLD->getChain(), Addr, MachinePointerInfo(), 13164 LLD->isVolatile(), LLD->isNonTemporal(), 13165 isInvariant, Alignment); 13166 } else { 13167 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13168 RLD->getExtensionType() : LLD->getExtensionType(), 13169 SDLoc(TheSelect), 13170 TheSelect->getValueType(0), 13171 // FIXME: Discards pointer and AA info. 13172 LLD->getChain(), Addr, MachinePointerInfo(), 13173 LLD->getMemoryVT(), LLD->isVolatile(), 13174 LLD->isNonTemporal(), isInvariant, Alignment); 13175 } 13176 13177 // Users of the select now use the result of the load. 13178 CombineTo(TheSelect, Load); 13179 13180 // Users of the old loads now use the new load's chain. We know the 13181 // old-load value is dead now. 13182 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13183 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13184 return true; 13185 } 13186 13187 return false; 13188 } 13189 13190 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13191 /// where 'cond' is the comparison specified by CC. 13192 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13193 SDValue N2, SDValue N3, 13194 ISD::CondCode CC, bool NotExtCompare) { 13195 // (x ? y : y) -> y. 13196 if (N2 == N3) return N2; 13197 13198 EVT VT = N2.getValueType(); 13199 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13200 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13201 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 13202 13203 // Determine if the condition we're dealing with is constant 13204 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13205 N0, N1, CC, DL, false); 13206 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13207 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 13208 13209 // fold select_cc true, x, y -> x 13210 if (SCCC && !SCCC->isNullValue()) 13211 return N2; 13212 // fold select_cc false, x, y -> y 13213 if (SCCC && SCCC->isNullValue()) 13214 return N3; 13215 13216 // Check to see if we can simplify the select into an fabs node 13217 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13218 // Allow either -0.0 or 0.0 13219 if (CFP->getValueAPF().isZero()) { 13220 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13221 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13222 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13223 N2 == N3.getOperand(0)) 13224 return DAG.getNode(ISD::FABS, DL, VT, N0); 13225 13226 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 13227 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 13228 N0 == N3 && N2.getOpcode() == ISD::FNEG && 13229 N2.getOperand(0) == N3) 13230 return DAG.getNode(ISD::FABS, DL, VT, N3); 13231 } 13232 } 13233 13234 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 13235 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 13236 // in it. This is a win when the constant is not otherwise available because 13237 // it replaces two constant pool loads with one. We only do this if the FP 13238 // type is known to be legal, because if it isn't, then we are before legalize 13239 // types an we want the other legalization to happen first (e.g. to avoid 13240 // messing with soft float) and if the ConstantFP is not legal, because if 13241 // it is legal, we may not need to store the FP constant in a constant pool. 13242 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 13243 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 13244 if (TLI.isTypeLegal(N2.getValueType()) && 13245 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 13246 TargetLowering::Legal && 13247 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 13248 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 13249 // If both constants have multiple uses, then we won't need to do an 13250 // extra load, they are likely around in registers for other users. 13251 (TV->hasOneUse() || FV->hasOneUse())) { 13252 Constant *Elts[] = { 13253 const_cast<ConstantFP*>(FV->getConstantFPValue()), 13254 const_cast<ConstantFP*>(TV->getConstantFPValue()) 13255 }; 13256 Type *FPTy = Elts[0]->getType(); 13257 const DataLayout &TD = *TLI.getDataLayout(); 13258 13259 // Create a ConstantArray of the two constants. 13260 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 13261 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 13262 TD.getPrefTypeAlignment(FPTy)); 13263 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 13264 13265 // Get the offsets to the 0 and 1 element of the array so that we can 13266 // select between them. 13267 SDValue Zero = DAG.getIntPtrConstant(0, DL); 13268 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 13269 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 13270 13271 SDValue Cond = DAG.getSetCC(DL, 13272 getSetCCResultType(N0.getValueType()), 13273 N0, N1, CC); 13274 AddToWorklist(Cond.getNode()); 13275 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 13276 Cond, One, Zero); 13277 AddToWorklist(CstOffset.getNode()); 13278 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 13279 CstOffset); 13280 AddToWorklist(CPIdx.getNode()); 13281 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 13282 MachinePointerInfo::getConstantPool(), false, 13283 false, false, Alignment); 13284 } 13285 } 13286 13287 // Check to see if we can perform the "gzip trick", transforming 13288 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 13289 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 13290 (N1C->isNullValue() || // (a < 0) ? b : 0 13291 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 13292 EVT XType = N0.getValueType(); 13293 EVT AType = N2.getValueType(); 13294 if (XType.bitsGE(AType)) { 13295 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 13296 // single-bit constant. 13297 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 13298 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 13299 ShCtV = XType.getSizeInBits() - ShCtV - 1; 13300 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 13301 getShiftAmountTy(N0.getValueType())); 13302 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 13303 XType, N0, ShCt); 13304 AddToWorklist(Shift.getNode()); 13305 13306 if (XType.bitsGT(AType)) { 13307 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13308 AddToWorklist(Shift.getNode()); 13309 } 13310 13311 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13312 } 13313 13314 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 13315 XType, N0, 13316 DAG.getConstant(XType.getSizeInBits() - 1, 13317 SDLoc(N0), 13318 getShiftAmountTy(N0.getValueType()))); 13319 AddToWorklist(Shift.getNode()); 13320 13321 if (XType.bitsGT(AType)) { 13322 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13323 AddToWorklist(Shift.getNode()); 13324 } 13325 13326 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13327 } 13328 } 13329 13330 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 13331 // where y is has a single bit set. 13332 // A plaintext description would be, we can turn the SELECT_CC into an AND 13333 // when the condition can be materialized as an all-ones register. Any 13334 // single bit-test can be materialized as an all-ones register with 13335 // shift-left and shift-right-arith. 13336 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 13337 N0->getValueType(0) == VT && 13338 N1C && N1C->isNullValue() && 13339 N2C && N2C->isNullValue()) { 13340 SDValue AndLHS = N0->getOperand(0); 13341 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13342 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 13343 // Shift the tested bit over the sign bit. 13344 APInt AndMask = ConstAndRHS->getAPIntValue(); 13345 SDValue ShlAmt = 13346 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 13347 getShiftAmountTy(AndLHS.getValueType())); 13348 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 13349 13350 // Now arithmetic right shift it all the way over, so the result is either 13351 // all-ones, or zero. 13352 SDValue ShrAmt = 13353 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 13354 getShiftAmountTy(Shl.getValueType())); 13355 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 13356 13357 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 13358 } 13359 } 13360 13361 // fold select C, 16, 0 -> shl C, 4 13362 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 13363 TLI.getBooleanContents(N0.getValueType()) == 13364 TargetLowering::ZeroOrOneBooleanContent) { 13365 13366 // If the caller doesn't want us to simplify this into a zext of a compare, 13367 // don't do it. 13368 if (NotExtCompare && N2C->getAPIntValue() == 1) 13369 return SDValue(); 13370 13371 // Get a SetCC of the condition 13372 // NOTE: Don't create a SETCC if it's not legal on this target. 13373 if (!LegalOperations || 13374 TLI.isOperationLegal(ISD::SETCC, 13375 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 13376 SDValue Temp, SCC; 13377 // cast from setcc result type to select result type 13378 if (LegalTypes) { 13379 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 13380 N0, N1, CC); 13381 if (N2.getValueType().bitsLT(SCC.getValueType())) 13382 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 13383 N2.getValueType()); 13384 else 13385 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13386 N2.getValueType(), SCC); 13387 } else { 13388 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 13389 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13390 N2.getValueType(), SCC); 13391 } 13392 13393 AddToWorklist(SCC.getNode()); 13394 AddToWorklist(Temp.getNode()); 13395 13396 if (N2C->getAPIntValue() == 1) 13397 return Temp; 13398 13399 // shl setcc result by log2 n2c 13400 return DAG.getNode( 13401 ISD::SHL, DL, N2.getValueType(), Temp, 13402 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 13403 getShiftAmountTy(Temp.getValueType()))); 13404 } 13405 } 13406 13407 // Check to see if this is the equivalent of setcc 13408 // FIXME: Turn all of these into setcc if setcc if setcc is legal 13409 // otherwise, go ahead with the folds. 13410 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 13411 EVT XType = N0.getValueType(); 13412 if (!LegalOperations || 13413 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 13414 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 13415 if (Res.getValueType() != VT) 13416 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 13417 return Res; 13418 } 13419 13420 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 13421 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 13422 (!LegalOperations || 13423 TLI.isOperationLegal(ISD::CTLZ, XType))) { 13424 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 13425 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 13426 DAG.getConstant(Log2_32(XType.getSizeInBits()), 13427 SDLoc(Ctlz), 13428 getShiftAmountTy(Ctlz.getValueType()))); 13429 } 13430 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 13431 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 13432 SDLoc DL(N0); 13433 SDValue NegN0 = DAG.getNode(ISD::SUB, DL, 13434 XType, DAG.getConstant(0, DL, XType), N0); 13435 SDValue NotN0 = DAG.getNOT(DL, N0, XType); 13436 return DAG.getNode(ISD::SRL, DL, XType, 13437 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 13438 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13439 getShiftAmountTy(XType))); 13440 } 13441 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 13442 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 13443 SDLoc DL(N0); 13444 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0, 13445 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13446 getShiftAmountTy(N0.getValueType()))); 13447 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL, 13448 XType)); 13449 } 13450 } 13451 13452 // Check to see if this is an integer abs. 13453 // select_cc setg[te] X, 0, X, -X -> 13454 // select_cc setgt X, -1, X, -X -> 13455 // select_cc setl[te] X, 0, -X, X -> 13456 // select_cc setlt X, 1, -X, X -> 13457 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 13458 if (N1C) { 13459 ConstantSDNode *SubC = nullptr; 13460 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 13461 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 13462 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 13463 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 13464 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 13465 (N1C->isOne() && CC == ISD::SETLT)) && 13466 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 13467 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 13468 13469 EVT XType = N0.getValueType(); 13470 if (SubC && SubC->isNullValue() && XType.isInteger()) { 13471 SDLoc DL(N0); 13472 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 13473 N0, 13474 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13475 getShiftAmountTy(N0.getValueType()))); 13476 SDValue Add = DAG.getNode(ISD::ADD, DL, 13477 XType, N0, Shift); 13478 AddToWorklist(Shift.getNode()); 13479 AddToWorklist(Add.getNode()); 13480 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 13481 } 13482 } 13483 13484 return SDValue(); 13485 } 13486 13487 /// This is a stub for TargetLowering::SimplifySetCC. 13488 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 13489 SDValue N1, ISD::CondCode Cond, 13490 SDLoc DL, bool foldBooleans) { 13491 TargetLowering::DAGCombinerInfo 13492 DagCombineInfo(DAG, Level, false, this); 13493 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 13494 } 13495 13496 /// Given an ISD::SDIV node expressing a divide by constant, return 13497 /// a DAG expression to select that will generate the same value by multiplying 13498 /// by a magic number. 13499 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13500 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 13501 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13502 if (!C) 13503 return SDValue(); 13504 13505 // Avoid division by zero. 13506 if (!C->getAPIntValue()) 13507 return SDValue(); 13508 13509 std::vector<SDNode*> Built; 13510 SDValue S = 13511 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13512 13513 for (SDNode *N : Built) 13514 AddToWorklist(N); 13515 return S; 13516 } 13517 13518 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 13519 /// DAG expression that will generate the same value by right shifting. 13520 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 13521 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13522 if (!C) 13523 return SDValue(); 13524 13525 // Avoid division by zero. 13526 if (!C->getAPIntValue()) 13527 return SDValue(); 13528 13529 std::vector<SDNode *> Built; 13530 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 13531 13532 for (SDNode *N : Built) 13533 AddToWorklist(N); 13534 return S; 13535 } 13536 13537 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 13538 /// expression that will generate the same value by multiplying by a magic 13539 /// number. 13540 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13541 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 13542 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13543 if (!C) 13544 return SDValue(); 13545 13546 // Avoid division by zero. 13547 if (!C->getAPIntValue()) 13548 return SDValue(); 13549 13550 std::vector<SDNode*> Built; 13551 SDValue S = 13552 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13553 13554 for (SDNode *N : Built) 13555 AddToWorklist(N); 13556 return S; 13557 } 13558 13559 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) { 13560 if (Level >= AfterLegalizeDAG) 13561 return SDValue(); 13562 13563 // Expose the DAG combiner to the target combiner implementations. 13564 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13565 13566 unsigned Iterations = 0; 13567 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 13568 if (Iterations) { 13569 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13570 // For the reciprocal, we need to find the zero of the function: 13571 // F(X) = A X - 1 [which has a zero at X = 1/A] 13572 // => 13573 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 13574 // does not require additional intermediate precision] 13575 EVT VT = Op.getValueType(); 13576 SDLoc DL(Op); 13577 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 13578 13579 AddToWorklist(Est.getNode()); 13580 13581 // Newton iterations: Est = Est + Est (1 - Arg * Est) 13582 for (unsigned i = 0; i < Iterations; ++i) { 13583 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est); 13584 AddToWorklist(NewEst.getNode()); 13585 13586 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst); 13587 AddToWorklist(NewEst.getNode()); 13588 13589 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13590 AddToWorklist(NewEst.getNode()); 13591 13592 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst); 13593 AddToWorklist(Est.getNode()); 13594 } 13595 } 13596 return Est; 13597 } 13598 13599 return SDValue(); 13600 } 13601 13602 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13603 /// For the reciprocal sqrt, we need to find the zero of the function: 13604 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13605 /// => 13606 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 13607 /// As a result, we precompute A/2 prior to the iteration loop. 13608 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 13609 unsigned Iterations) { 13610 EVT VT = Arg.getValueType(); 13611 SDLoc DL(Arg); 13612 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 13613 13614 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 13615 // this entire sequence requires only one FP constant. 13616 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg); 13617 AddToWorklist(HalfArg.getNode()); 13618 13619 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg); 13620 AddToWorklist(HalfArg.getNode()); 13621 13622 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 13623 for (unsigned i = 0; i < Iterations; ++i) { 13624 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13625 AddToWorklist(NewEst.getNode()); 13626 13627 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst); 13628 AddToWorklist(NewEst.getNode()); 13629 13630 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst); 13631 AddToWorklist(NewEst.getNode()); 13632 13633 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13634 AddToWorklist(Est.getNode()); 13635 } 13636 return Est; 13637 } 13638 13639 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13640 /// For the reciprocal sqrt, we need to find the zero of the function: 13641 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13642 /// => 13643 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 13644 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 13645 unsigned Iterations) { 13646 EVT VT = Arg.getValueType(); 13647 SDLoc DL(Arg); 13648 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 13649 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 13650 13651 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 13652 for (unsigned i = 0; i < Iterations; ++i) { 13653 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf); 13654 AddToWorklist(HalfEst.getNode()); 13655 13656 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13657 AddToWorklist(Est.getNode()); 13658 13659 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg); 13660 AddToWorklist(Est.getNode()); 13661 13662 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree); 13663 AddToWorklist(Est.getNode()); 13664 13665 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst); 13666 AddToWorklist(Est.getNode()); 13667 } 13668 return Est; 13669 } 13670 13671 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) { 13672 if (Level >= AfterLegalizeDAG) 13673 return SDValue(); 13674 13675 // Expose the DAG combiner to the target combiner implementations. 13676 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13677 unsigned Iterations = 0; 13678 bool UseOneConstNR = false; 13679 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 13680 AddToWorklist(Est.getNode()); 13681 if (Iterations) { 13682 Est = UseOneConstNR ? 13683 BuildRsqrtNROneConst(Op, Est, Iterations) : 13684 BuildRsqrtNRTwoConst(Op, Est, Iterations); 13685 } 13686 return Est; 13687 } 13688 13689 return SDValue(); 13690 } 13691 13692 /// Return true if base is a frame index, which is known not to alias with 13693 /// anything but itself. Provides base object and offset as results. 13694 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 13695 const GlobalValue *&GV, const void *&CV) { 13696 // Assume it is a primitive operation. 13697 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 13698 13699 // If it's an adding a simple constant then integrate the offset. 13700 if (Base.getOpcode() == ISD::ADD) { 13701 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 13702 Base = Base.getOperand(0); 13703 Offset += C->getZExtValue(); 13704 } 13705 } 13706 13707 // Return the underlying GlobalValue, and update the Offset. Return false 13708 // for GlobalAddressSDNode since the same GlobalAddress may be represented 13709 // by multiple nodes with different offsets. 13710 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 13711 GV = G->getGlobal(); 13712 Offset += G->getOffset(); 13713 return false; 13714 } 13715 13716 // Return the underlying Constant value, and update the Offset. Return false 13717 // for ConstantSDNodes since the same constant pool entry may be represented 13718 // by multiple nodes with different offsets. 13719 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 13720 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 13721 : (const void *)C->getConstVal(); 13722 Offset += C->getOffset(); 13723 return false; 13724 } 13725 // If it's any of the following then it can't alias with anything but itself. 13726 return isa<FrameIndexSDNode>(Base); 13727 } 13728 13729 /// Return true if there is any possibility that the two addresses overlap. 13730 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 13731 // If they are the same then they must be aliases. 13732 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 13733 13734 // If they are both volatile then they cannot be reordered. 13735 if (Op0->isVolatile() && Op1->isVolatile()) return true; 13736 13737 // Gather base node and offset information. 13738 SDValue Base1, Base2; 13739 int64_t Offset1, Offset2; 13740 const GlobalValue *GV1, *GV2; 13741 const void *CV1, *CV2; 13742 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 13743 Base1, Offset1, GV1, CV1); 13744 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 13745 Base2, Offset2, GV2, CV2); 13746 13747 // If they have a same base address then check to see if they overlap. 13748 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 13749 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13750 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13751 13752 // It is possible for different frame indices to alias each other, mostly 13753 // when tail call optimization reuses return address slots for arguments. 13754 // To catch this case, look up the actual index of frame indices to compute 13755 // the real alias relationship. 13756 if (isFrameIndex1 && isFrameIndex2) { 13757 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 13758 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 13759 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 13760 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13761 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13762 } 13763 13764 // Otherwise, if we know what the bases are, and they aren't identical, then 13765 // we know they cannot alias. 13766 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 13767 return false; 13768 13769 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 13770 // compared to the size and offset of the access, we may be able to prove they 13771 // do not alias. This check is conservative for now to catch cases created by 13772 // splitting vector types. 13773 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 13774 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 13775 (Op0->getMemoryVT().getSizeInBits() >> 3 == 13776 Op1->getMemoryVT().getSizeInBits() >> 3) && 13777 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 13778 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 13779 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 13780 13781 // There is no overlap between these relatively aligned accesses of similar 13782 // size, return no alias. 13783 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 13784 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 13785 return false; 13786 } 13787 13788 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 13789 ? CombinerGlobalAA 13790 : DAG.getSubtarget().useAA(); 13791 #ifndef NDEBUG 13792 if (CombinerAAOnlyFunc.getNumOccurrences() && 13793 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 13794 UseAA = false; 13795 #endif 13796 if (UseAA && 13797 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 13798 // Use alias analysis information. 13799 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 13800 Op1->getSrcValueOffset()); 13801 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 13802 Op0->getSrcValueOffset() - MinOffset; 13803 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 13804 Op1->getSrcValueOffset() - MinOffset; 13805 AliasAnalysis::AliasResult AAResult = 13806 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 13807 Overlap1, 13808 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 13809 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 13810 Overlap2, 13811 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 13812 if (AAResult == AliasAnalysis::NoAlias) 13813 return false; 13814 } 13815 13816 // Otherwise we have to assume they alias. 13817 return true; 13818 } 13819 13820 /// Walk up chain skipping non-aliasing memory nodes, 13821 /// looking for aliasing nodes and adding them to the Aliases vector. 13822 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 13823 SmallVectorImpl<SDValue> &Aliases) { 13824 SmallVector<SDValue, 8> Chains; // List of chains to visit. 13825 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 13826 13827 // Get alias information for node. 13828 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 13829 13830 // Starting off. 13831 Chains.push_back(OriginalChain); 13832 unsigned Depth = 0; 13833 13834 // Look at each chain and determine if it is an alias. If so, add it to the 13835 // aliases list. If not, then continue up the chain looking for the next 13836 // candidate. 13837 while (!Chains.empty()) { 13838 SDValue Chain = Chains.back(); 13839 Chains.pop_back(); 13840 13841 // For TokenFactor nodes, look at each operand and only continue up the 13842 // chain until we find two aliases. If we've seen two aliases, assume we'll 13843 // find more and revert to original chain since the xform is unlikely to be 13844 // profitable. 13845 // 13846 // FIXME: The depth check could be made to return the last non-aliasing 13847 // chain we found before we hit a tokenfactor rather than the original 13848 // chain. 13849 if (Depth > 6 || Aliases.size() == 2) { 13850 Aliases.clear(); 13851 Aliases.push_back(OriginalChain); 13852 return; 13853 } 13854 13855 // Don't bother if we've been before. 13856 if (!Visited.insert(Chain.getNode()).second) 13857 continue; 13858 13859 switch (Chain.getOpcode()) { 13860 case ISD::EntryToken: 13861 // Entry token is ideal chain operand, but handled in FindBetterChain. 13862 break; 13863 13864 case ISD::LOAD: 13865 case ISD::STORE: { 13866 // Get alias information for Chain. 13867 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 13868 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 13869 13870 // If chain is alias then stop here. 13871 if (!(IsLoad && IsOpLoad) && 13872 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 13873 Aliases.push_back(Chain); 13874 } else { 13875 // Look further up the chain. 13876 Chains.push_back(Chain.getOperand(0)); 13877 ++Depth; 13878 } 13879 break; 13880 } 13881 13882 case ISD::TokenFactor: 13883 // We have to check each of the operands of the token factor for "small" 13884 // token factors, so we queue them up. Adding the operands to the queue 13885 // (stack) in reverse order maintains the original order and increases the 13886 // likelihood that getNode will find a matching token factor (CSE.) 13887 if (Chain.getNumOperands() > 16) { 13888 Aliases.push_back(Chain); 13889 break; 13890 } 13891 for (unsigned n = Chain.getNumOperands(); n;) 13892 Chains.push_back(Chain.getOperand(--n)); 13893 ++Depth; 13894 break; 13895 13896 default: 13897 // For all other instructions we will just have to take what we can get. 13898 Aliases.push_back(Chain); 13899 break; 13900 } 13901 } 13902 13903 // We need to be careful here to also search for aliases through the 13904 // value operand of a store, etc. Consider the following situation: 13905 // Token1 = ... 13906 // L1 = load Token1, %52 13907 // S1 = store Token1, L1, %51 13908 // L2 = load Token1, %52+8 13909 // S2 = store Token1, L2, %51+8 13910 // Token2 = Token(S1, S2) 13911 // L3 = load Token2, %53 13912 // S3 = store Token2, L3, %52 13913 // L4 = load Token2, %53+8 13914 // S4 = store Token2, L4, %52+8 13915 // If we search for aliases of S3 (which loads address %52), and we look 13916 // only through the chain, then we'll miss the trivial dependence on L1 13917 // (which also loads from %52). We then might change all loads and 13918 // stores to use Token1 as their chain operand, which could result in 13919 // copying %53 into %52 before copying %52 into %51 (which should 13920 // happen first). 13921 // 13922 // The problem is, however, that searching for such data dependencies 13923 // can become expensive, and the cost is not directly related to the 13924 // chain depth. Instead, we'll rule out such configurations here by 13925 // insisting that we've visited all chain users (except for users 13926 // of the original chain, which is not necessary). When doing this, 13927 // we need to look through nodes we don't care about (otherwise, things 13928 // like register copies will interfere with trivial cases). 13929 13930 SmallVector<const SDNode *, 16> Worklist; 13931 for (const SDNode *N : Visited) 13932 if (N != OriginalChain.getNode()) 13933 Worklist.push_back(N); 13934 13935 while (!Worklist.empty()) { 13936 const SDNode *M = Worklist.pop_back_val(); 13937 13938 // We have already visited M, and want to make sure we've visited any uses 13939 // of M that we care about. For uses that we've not visisted, and don't 13940 // care about, queue them to the worklist. 13941 13942 for (SDNode::use_iterator UI = M->use_begin(), 13943 UIE = M->use_end(); UI != UIE; ++UI) 13944 if (UI.getUse().getValueType() == MVT::Other && 13945 Visited.insert(*UI).second) { 13946 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 13947 // We've not visited this use, and we care about it (it could have an 13948 // ordering dependency with the original node). 13949 Aliases.clear(); 13950 Aliases.push_back(OriginalChain); 13951 return; 13952 } 13953 13954 // We've not visited this use, but we don't care about it. Mark it as 13955 // visited and enqueue it to the worklist. 13956 Worklist.push_back(*UI); 13957 } 13958 } 13959 } 13960 13961 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 13962 /// (aliasing node.) 13963 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 13964 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 13965 13966 // Accumulate all the aliases to this node. 13967 GatherAllAliases(N, OldChain, Aliases); 13968 13969 // If no operands then chain to entry token. 13970 if (Aliases.size() == 0) 13971 return DAG.getEntryNode(); 13972 13973 // If a single operand then chain to it. We don't need to revisit it. 13974 if (Aliases.size() == 1) 13975 return Aliases[0]; 13976 13977 // Construct a custom tailored token factor. 13978 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 13979 } 13980 13981 /// This is the entry point for the file. 13982 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 13983 CodeGenOpt::Level OptLevel) { 13984 /// This is the main entry point to this class. 13985 DAGCombiner(*this, AA, OptLevel).Run(Level); 13986 } 13987