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 visitOR(SDNode *N); 250 SDValue visitXOR(SDNode *N); 251 SDValue SimplifyVBinOp(SDNode *N); 252 SDValue SimplifyVUnaryOp(SDNode *N); 253 SDValue visitSHL(SDNode *N); 254 SDValue visitSRA(SDNode *N); 255 SDValue visitSRL(SDNode *N); 256 SDValue visitRotate(SDNode *N); 257 SDValue visitCTLZ(SDNode *N); 258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 259 SDValue visitCTTZ(SDNode *N); 260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 261 SDValue visitCTPOP(SDNode *N); 262 SDValue visitSELECT(SDNode *N); 263 SDValue visitVSELECT(SDNode *N); 264 SDValue visitSELECT_CC(SDNode *N); 265 SDValue visitSETCC(SDNode *N); 266 SDValue visitSIGN_EXTEND(SDNode *N); 267 SDValue visitZERO_EXTEND(SDNode *N); 268 SDValue visitANY_EXTEND(SDNode *N); 269 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 270 SDValue visitTRUNCATE(SDNode *N); 271 SDValue visitBITCAST(SDNode *N); 272 SDValue visitBUILD_PAIR(SDNode *N); 273 SDValue visitFADD(SDNode *N); 274 SDValue visitFSUB(SDNode *N); 275 SDValue visitFMUL(SDNode *N); 276 SDValue visitFMA(SDNode *N); 277 SDValue visitFDIV(SDNode *N); 278 SDValue visitFREM(SDNode *N); 279 SDValue visitFSQRT(SDNode *N); 280 SDValue visitFCOPYSIGN(SDNode *N); 281 SDValue visitSINT_TO_FP(SDNode *N); 282 SDValue visitUINT_TO_FP(SDNode *N); 283 SDValue visitFP_TO_SINT(SDNode *N); 284 SDValue visitFP_TO_UINT(SDNode *N); 285 SDValue visitFP_ROUND(SDNode *N); 286 SDValue visitFP_ROUND_INREG(SDNode *N); 287 SDValue visitFP_EXTEND(SDNode *N); 288 SDValue visitFNEG(SDNode *N); 289 SDValue visitFABS(SDNode *N); 290 SDValue visitFCEIL(SDNode *N); 291 SDValue visitFTRUNC(SDNode *N); 292 SDValue visitFFLOOR(SDNode *N); 293 SDValue visitFMINNUM(SDNode *N); 294 SDValue visitFMAXNUM(SDNode *N); 295 SDValue visitBRCOND(SDNode *N); 296 SDValue visitBR_CC(SDNode *N); 297 SDValue visitLOAD(SDNode *N); 298 SDValue visitSTORE(SDNode *N); 299 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 301 SDValue visitBUILD_VECTOR(SDNode *N); 302 SDValue visitCONCAT_VECTORS(SDNode *N); 303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 304 SDValue visitVECTOR_SHUFFLE(SDNode *N); 305 SDValue visitINSERT_SUBVECTOR(SDNode *N); 306 SDValue visitMLOAD(SDNode *N); 307 SDValue visitMSTORE(SDNode *N); 308 309 SDValue XformToShuffleWithZero(SDNode *N); 310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 311 312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 313 314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 318 SDValue N3, ISD::CondCode CC, 319 bool NotExtCompare = false); 320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 321 SDLoc DL, bool foldBooleans = true); 322 323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 324 SDValue &CC) const; 325 bool isOneUseSetCC(SDValue N) const; 326 327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 328 unsigned HiOp); 329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 330 SDValue CombineExtLoad(SDNode *N); 331 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 332 SDValue BuildSDIV(SDNode *N); 333 SDValue BuildSDIVPow2(SDNode *N); 334 SDValue BuildUDIV(SDNode *N); 335 SDValue BuildReciprocalEstimate(SDValue Op); 336 SDValue BuildRsqrtEstimate(SDValue Op); 337 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations); 338 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations); 339 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 340 bool DemandHighBits = true); 341 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 342 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 343 SDValue InnerPos, SDValue InnerNeg, 344 unsigned PosOpcode, unsigned NegOpcode, 345 SDLoc DL); 346 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 347 SDValue ReduceLoadWidth(SDNode *N); 348 SDValue ReduceLoadOpStoreWidth(SDNode *N); 349 SDValue TransformFPLoadStorePair(SDNode *N); 350 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 351 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 352 353 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 354 355 /// Walk up chain skipping non-aliasing memory nodes, 356 /// looking for aliasing nodes and adding them to the Aliases vector. 357 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 358 SmallVectorImpl<SDValue> &Aliases); 359 360 /// Return true if there is any possibility that the two addresses overlap. 361 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 362 363 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 364 /// chain (aliasing node.) 365 SDValue FindBetterChain(SDNode *N, SDValue Chain); 366 367 /// Holds a pointer to an LSBaseSDNode as well as information on where it 368 /// is located in a sequence of memory operations connected by a chain. 369 struct MemOpLink { 370 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 371 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 372 // Ptr to the mem node. 373 LSBaseSDNode *MemNode; 374 // Offset from the base ptr. 375 int64_t OffsetFromBase; 376 // What is the sequence number of this mem node. 377 // Lowest mem operand in the DAG starts at zero. 378 unsigned SequenceNum; 379 }; 380 381 /// This is a helper function for MergeConsecutiveStores. When the source 382 /// elements of the consecutive stores are all constants or all extracted 383 /// vector elements, try to merge them into one larger store. 384 /// \return True if a merged store was created. 385 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 386 EVT MemVT, unsigned NumElem, 387 bool IsConstantSrc, bool UseVector); 388 389 /// Merge consecutive store operations into a wide store. 390 /// This optimization uses wide integers or vectors when possible. 391 /// \return True if some memory operations were changed. 392 bool MergeConsecutiveStores(StoreSDNode *N); 393 394 /// \brief Try to transform a truncation where C is a constant: 395 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 396 /// 397 /// \p N needs to be a truncation and its first operand an AND. Other 398 /// requirements are checked by the function (e.g. that trunc is 399 /// single-use) and if missed an empty SDValue is returned. 400 SDValue distributeTruncateThroughAnd(SDNode *N); 401 402 public: 403 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 404 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 405 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 406 auto *F = DAG.getMachineFunction().getFunction(); 407 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) || 408 F->hasFnAttribute(Attribute::MinSize); 409 } 410 411 /// Runs the dag combiner on all nodes in the work list 412 void Run(CombineLevel AtLevel); 413 414 SelectionDAG &getDAG() const { return DAG; } 415 416 /// Returns a type large enough to hold any valid shift amount - before type 417 /// legalization these can be huge. 418 EVT getShiftAmountTy(EVT LHSTy) { 419 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 420 if (LHSTy.isVector()) 421 return LHSTy; 422 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 423 : TLI.getPointerTy(); 424 } 425 426 /// This method returns true if we are running before type legalization or 427 /// if the specified VT is legal. 428 bool isTypeLegal(const EVT &VT) { 429 if (!LegalTypes) return true; 430 return TLI.isTypeLegal(VT); 431 } 432 433 /// Convenience wrapper around TargetLowering::getSetCCResultType 434 EVT getSetCCResultType(EVT VT) const { 435 return TLI.getSetCCResultType(*DAG.getContext(), VT); 436 } 437 }; 438 } 439 440 441 namespace { 442 /// This class is a DAGUpdateListener that removes any deleted 443 /// nodes from the worklist. 444 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 445 DAGCombiner &DC; 446 public: 447 explicit WorklistRemover(DAGCombiner &dc) 448 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 449 450 void NodeDeleted(SDNode *N, SDNode *E) override { 451 DC.removeFromWorklist(N); 452 } 453 }; 454 } 455 456 //===----------------------------------------------------------------------===// 457 // TargetLowering::DAGCombinerInfo implementation 458 //===----------------------------------------------------------------------===// 459 460 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 461 ((DAGCombiner*)DC)->AddToWorklist(N); 462 } 463 464 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 465 ((DAGCombiner*)DC)->removeFromWorklist(N); 466 } 467 468 SDValue TargetLowering::DAGCombinerInfo:: 469 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 470 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 471 } 472 473 SDValue TargetLowering::DAGCombinerInfo:: 474 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 475 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 476 } 477 478 479 SDValue TargetLowering::DAGCombinerInfo:: 480 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 481 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 482 } 483 484 void TargetLowering::DAGCombinerInfo:: 485 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 486 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 487 } 488 489 //===----------------------------------------------------------------------===// 490 // Helper Functions 491 //===----------------------------------------------------------------------===// 492 493 void DAGCombiner::deleteAndRecombine(SDNode *N) { 494 removeFromWorklist(N); 495 496 // If the operands of this node are only used by the node, they will now be 497 // dead. Make sure to re-visit them and recursively delete dead nodes. 498 for (const SDValue &Op : N->ops()) 499 // For an operand generating multiple values, one of the values may 500 // become dead allowing further simplification (e.g. split index 501 // arithmetic from an indexed load). 502 if (Op->hasOneUse() || Op->getNumValues() > 1) 503 AddToWorklist(Op.getNode()); 504 505 DAG.DeleteNode(N); 506 } 507 508 /// Return 1 if we can compute the negated form of the specified expression for 509 /// the same cost as the expression itself, or 2 if we can compute the negated 510 /// form more cheaply than the expression itself. 511 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 512 const TargetLowering &TLI, 513 const TargetOptions *Options, 514 unsigned Depth = 0) { 515 // fneg is removable even if it has multiple uses. 516 if (Op.getOpcode() == ISD::FNEG) return 2; 517 518 // Don't allow anything with multiple uses. 519 if (!Op.hasOneUse()) return 0; 520 521 // Don't recurse exponentially. 522 if (Depth > 6) return 0; 523 524 switch (Op.getOpcode()) { 525 default: return false; 526 case ISD::ConstantFP: 527 // Don't invert constant FP values after legalize. The negated constant 528 // isn't necessarily legal. 529 return LegalOperations ? 0 : 1; 530 case ISD::FADD: 531 // FIXME: determine better conditions for this xform. 532 if (!Options->UnsafeFPMath) return 0; 533 534 // After operation legalization, it might not be legal to create new FSUBs. 535 if (LegalOperations && 536 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 537 return 0; 538 539 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 540 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 541 Options, Depth + 1)) 542 return V; 543 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 544 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 545 Depth + 1); 546 case ISD::FSUB: 547 // We can't turn -(A-B) into B-A when we honor signed zeros. 548 if (!Options->UnsafeFPMath) return 0; 549 550 // fold (fneg (fsub A, B)) -> (fsub B, A) 551 return 1; 552 553 case ISD::FMUL: 554 case ISD::FDIV: 555 if (Options->HonorSignDependentRoundingFPMath()) return 0; 556 557 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 558 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 559 Options, Depth + 1)) 560 return V; 561 562 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 563 Depth + 1); 564 565 case ISD::FP_EXTEND: 566 case ISD::FP_ROUND: 567 case ISD::FSIN: 568 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 569 Depth + 1); 570 } 571 } 572 573 /// If isNegatibleForFree returns true, return the newly negated expression. 574 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 575 bool LegalOperations, unsigned Depth = 0) { 576 const TargetOptions &Options = DAG.getTarget().Options; 577 // fneg is removable even if it has multiple uses. 578 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 579 580 // Don't allow anything with multiple uses. 581 assert(Op.hasOneUse() && "Unknown reuse!"); 582 583 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 584 switch (Op.getOpcode()) { 585 default: llvm_unreachable("Unknown code"); 586 case ISD::ConstantFP: { 587 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 588 V.changeSign(); 589 return DAG.getConstantFP(V, Op.getValueType()); 590 } 591 case ISD::FADD: 592 // FIXME: determine better conditions for this xform. 593 assert(Options.UnsafeFPMath); 594 595 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 596 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 597 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 598 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 599 GetNegatedExpression(Op.getOperand(0), DAG, 600 LegalOperations, Depth+1), 601 Op.getOperand(1)); 602 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 603 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 604 GetNegatedExpression(Op.getOperand(1), DAG, 605 LegalOperations, Depth+1), 606 Op.getOperand(0)); 607 case ISD::FSUB: 608 // We can't turn -(A-B) into B-A when we honor signed zeros. 609 assert(Options.UnsafeFPMath); 610 611 // fold (fneg (fsub 0, B)) -> B 612 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 613 if (N0CFP->getValueAPF().isZero()) 614 return Op.getOperand(1); 615 616 // fold (fneg (fsub A, B)) -> (fsub B, A) 617 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 618 Op.getOperand(1), Op.getOperand(0)); 619 620 case ISD::FMUL: 621 case ISD::FDIV: 622 assert(!Options.HonorSignDependentRoundingFPMath()); 623 624 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 625 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 626 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 627 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 628 GetNegatedExpression(Op.getOperand(0), DAG, 629 LegalOperations, Depth+1), 630 Op.getOperand(1)); 631 632 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 633 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 634 Op.getOperand(0), 635 GetNegatedExpression(Op.getOperand(1), DAG, 636 LegalOperations, Depth+1)); 637 638 case ISD::FP_EXTEND: 639 case ISD::FSIN: 640 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 641 GetNegatedExpression(Op.getOperand(0), DAG, 642 LegalOperations, Depth+1)); 643 case ISD::FP_ROUND: 644 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 645 GetNegatedExpression(Op.getOperand(0), DAG, 646 LegalOperations, Depth+1), 647 Op.getOperand(1)); 648 } 649 } 650 651 // Return true if this node is a setcc, or is a select_cc 652 // that selects between the target values used for true and false, making it 653 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 654 // the appropriate nodes based on the type of node we are checking. This 655 // simplifies life a bit for the callers. 656 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 657 SDValue &CC) const { 658 if (N.getOpcode() == ISD::SETCC) { 659 LHS = N.getOperand(0); 660 RHS = N.getOperand(1); 661 CC = N.getOperand(2); 662 return true; 663 } 664 665 if (N.getOpcode() != ISD::SELECT_CC || 666 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 667 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 668 return false; 669 670 if (TLI.getBooleanContents(N.getValueType()) == 671 TargetLowering::UndefinedBooleanContent) 672 return false; 673 674 LHS = N.getOperand(0); 675 RHS = N.getOperand(1); 676 CC = N.getOperand(4); 677 return true; 678 } 679 680 /// Return true if this is a SetCC-equivalent operation with only one use. 681 /// If this is true, it allows the users to invert the operation for free when 682 /// it is profitable to do so. 683 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 684 SDValue N0, N1, N2; 685 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 686 return true; 687 return false; 688 } 689 690 /// Returns true if N is a BUILD_VECTOR node whose 691 /// elements are all the same constant or undefined. 692 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 693 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 694 if (!C) 695 return false; 696 697 APInt SplatUndef; 698 unsigned SplatBitSize; 699 bool HasAnyUndefs; 700 EVT EltVT = N->getValueType(0).getVectorElementType(); 701 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 702 HasAnyUndefs) && 703 EltVT.getSizeInBits() >= SplatBitSize); 704 } 705 706 // \brief Returns the SDNode if it is a constant BuildVector or constant. 707 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) { 708 if (isa<ConstantSDNode>(N)) 709 return N.getNode(); 710 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 711 if (BV && BV->isConstant()) 712 return BV; 713 return nullptr; 714 } 715 716 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 717 // int. 718 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 719 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 720 return CN; 721 722 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 723 BitVector UndefElements; 724 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 725 726 // BuildVectors can truncate their operands. Ignore that case here. 727 // FIXME: We blindly ignore splats which include undef which is overly 728 // pessimistic. 729 if (CN && UndefElements.none() && 730 CN->getValueType(0) == N.getValueType().getScalarType()) 731 return CN; 732 } 733 734 return nullptr; 735 } 736 737 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 738 // float. 739 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 740 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 741 return CN; 742 743 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 744 BitVector UndefElements; 745 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 746 747 if (CN && UndefElements.none()) 748 return CN; 749 } 750 751 return nullptr; 752 } 753 754 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 755 SDValue N0, SDValue N1) { 756 EVT VT = N0.getValueType(); 757 if (N0.getOpcode() == Opc) { 758 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) { 759 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) { 760 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 761 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R)) 762 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 763 return SDValue(); 764 } 765 if (N0.hasOneUse()) { 766 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 767 // use 768 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 769 if (!OpNode.getNode()) 770 return SDValue(); 771 AddToWorklist(OpNode.getNode()); 772 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 773 } 774 } 775 } 776 777 if (N1.getOpcode() == Opc) { 778 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) { 779 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) { 780 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 781 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L)) 782 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 783 return SDValue(); 784 } 785 if (N1.hasOneUse()) { 786 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 787 // use 788 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 789 if (!OpNode.getNode()) 790 return SDValue(); 791 AddToWorklist(OpNode.getNode()); 792 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 793 } 794 } 795 } 796 797 return SDValue(); 798 } 799 800 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 801 bool AddTo) { 802 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 803 ++NodesCombined; 804 DEBUG(dbgs() << "\nReplacing.1 "; 805 N->dump(&DAG); 806 dbgs() << "\nWith: "; 807 To[0].getNode()->dump(&DAG); 808 dbgs() << " and " << NumTo-1 << " other values\n"); 809 for (unsigned i = 0, e = NumTo; i != e; ++i) 810 assert((!To[i].getNode() || 811 N->getValueType(i) == To[i].getValueType()) && 812 "Cannot combine value to value of different type!"); 813 814 WorklistRemover DeadNodes(*this); 815 DAG.ReplaceAllUsesWith(N, To); 816 if (AddTo) { 817 // Push the new nodes and any users onto the worklist 818 for (unsigned i = 0, e = NumTo; i != e; ++i) { 819 if (To[i].getNode()) { 820 AddToWorklist(To[i].getNode()); 821 AddUsersToWorklist(To[i].getNode()); 822 } 823 } 824 } 825 826 // Finally, if the node is now dead, remove it from the graph. The node 827 // may not be dead if the replacement process recursively simplified to 828 // something else needing this node. 829 if (N->use_empty()) 830 deleteAndRecombine(N); 831 return SDValue(N, 0); 832 } 833 834 void DAGCombiner:: 835 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 836 // Replace all uses. If any nodes become isomorphic to other nodes and 837 // are deleted, make sure to remove them from our worklist. 838 WorklistRemover DeadNodes(*this); 839 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 840 841 // Push the new node and any (possibly new) users onto the worklist. 842 AddToWorklist(TLO.New.getNode()); 843 AddUsersToWorklist(TLO.New.getNode()); 844 845 // Finally, if the node is now dead, remove it from the graph. The node 846 // may not be dead if the replacement process recursively simplified to 847 // something else needing this node. 848 if (TLO.Old.getNode()->use_empty()) 849 deleteAndRecombine(TLO.Old.getNode()); 850 } 851 852 /// Check the specified integer node value to see if it can be simplified or if 853 /// things it uses can be simplified by bit propagation. If so, return true. 854 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 855 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 856 APInt KnownZero, KnownOne; 857 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 858 return false; 859 860 // Revisit the node. 861 AddToWorklist(Op.getNode()); 862 863 // Replace the old value with the new one. 864 ++NodesCombined; 865 DEBUG(dbgs() << "\nReplacing.2 "; 866 TLO.Old.getNode()->dump(&DAG); 867 dbgs() << "\nWith: "; 868 TLO.New.getNode()->dump(&DAG); 869 dbgs() << '\n'); 870 871 CommitTargetLoweringOpt(TLO); 872 return true; 873 } 874 875 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 876 SDLoc dl(Load); 877 EVT VT = Load->getValueType(0); 878 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 879 880 DEBUG(dbgs() << "\nReplacing.9 "; 881 Load->dump(&DAG); 882 dbgs() << "\nWith: "; 883 Trunc.getNode()->dump(&DAG); 884 dbgs() << '\n'); 885 WorklistRemover DeadNodes(*this); 886 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 887 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 888 deleteAndRecombine(Load); 889 AddToWorklist(Trunc.getNode()); 890 } 891 892 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 893 Replace = false; 894 SDLoc dl(Op); 895 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 896 EVT MemVT = LD->getMemoryVT(); 897 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 898 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 899 : ISD::EXTLOAD) 900 : LD->getExtensionType(); 901 Replace = true; 902 return DAG.getExtLoad(ExtType, dl, PVT, 903 LD->getChain(), LD->getBasePtr(), 904 MemVT, LD->getMemOperand()); 905 } 906 907 unsigned Opc = Op.getOpcode(); 908 switch (Opc) { 909 default: break; 910 case ISD::AssertSext: 911 return DAG.getNode(ISD::AssertSext, dl, PVT, 912 SExtPromoteOperand(Op.getOperand(0), PVT), 913 Op.getOperand(1)); 914 case ISD::AssertZext: 915 return DAG.getNode(ISD::AssertZext, dl, PVT, 916 ZExtPromoteOperand(Op.getOperand(0), PVT), 917 Op.getOperand(1)); 918 case ISD::Constant: { 919 unsigned ExtOpc = 920 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 921 return DAG.getNode(ExtOpc, dl, PVT, Op); 922 } 923 } 924 925 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 926 return SDValue(); 927 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 928 } 929 930 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 931 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 932 return SDValue(); 933 EVT OldVT = Op.getValueType(); 934 SDLoc dl(Op); 935 bool Replace = false; 936 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 937 if (!NewOp.getNode()) 938 return SDValue(); 939 AddToWorklist(NewOp.getNode()); 940 941 if (Replace) 942 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 943 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 944 DAG.getValueType(OldVT)); 945 } 946 947 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 948 EVT OldVT = Op.getValueType(); 949 SDLoc dl(Op); 950 bool Replace = false; 951 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 952 if (!NewOp.getNode()) 953 return SDValue(); 954 AddToWorklist(NewOp.getNode()); 955 956 if (Replace) 957 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 958 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 959 } 960 961 /// Promote the specified integer binary operation if the target indicates it is 962 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 963 /// i32 since i16 instructions are longer. 964 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 965 if (!LegalOperations) 966 return SDValue(); 967 968 EVT VT = Op.getValueType(); 969 if (VT.isVector() || !VT.isInteger()) 970 return SDValue(); 971 972 // If operation type is 'undesirable', e.g. i16 on x86, consider 973 // promoting it. 974 unsigned Opc = Op.getOpcode(); 975 if (TLI.isTypeDesirableForOp(Opc, VT)) 976 return SDValue(); 977 978 EVT PVT = VT; 979 // Consult target whether it is a good idea to promote this operation and 980 // what's the right type to promote it to. 981 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 982 assert(PVT != VT && "Don't know what type to promote to!"); 983 984 bool Replace0 = false; 985 SDValue N0 = Op.getOperand(0); 986 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 987 if (!NN0.getNode()) 988 return SDValue(); 989 990 bool Replace1 = false; 991 SDValue N1 = Op.getOperand(1); 992 SDValue NN1; 993 if (N0 == N1) 994 NN1 = NN0; 995 else { 996 NN1 = PromoteOperand(N1, PVT, Replace1); 997 if (!NN1.getNode()) 998 return SDValue(); 999 } 1000 1001 AddToWorklist(NN0.getNode()); 1002 if (NN1.getNode()) 1003 AddToWorklist(NN1.getNode()); 1004 1005 if (Replace0) 1006 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1007 if (Replace1) 1008 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1009 1010 DEBUG(dbgs() << "\nPromoting "; 1011 Op.getNode()->dump(&DAG)); 1012 SDLoc dl(Op); 1013 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1014 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1015 } 1016 return SDValue(); 1017 } 1018 1019 /// Promote the specified integer shift operation if the target indicates it is 1020 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1021 /// i32 since i16 instructions are longer. 1022 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1023 if (!LegalOperations) 1024 return SDValue(); 1025 1026 EVT VT = Op.getValueType(); 1027 if (VT.isVector() || !VT.isInteger()) 1028 return SDValue(); 1029 1030 // If operation type is 'undesirable', e.g. i16 on x86, consider 1031 // promoting it. 1032 unsigned Opc = Op.getOpcode(); 1033 if (TLI.isTypeDesirableForOp(Opc, VT)) 1034 return SDValue(); 1035 1036 EVT PVT = VT; 1037 // Consult target whether it is a good idea to promote this operation and 1038 // what's the right type to promote it to. 1039 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1040 assert(PVT != VT && "Don't know what type to promote to!"); 1041 1042 bool Replace = false; 1043 SDValue N0 = Op.getOperand(0); 1044 if (Opc == ISD::SRA) 1045 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1046 else if (Opc == ISD::SRL) 1047 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1048 else 1049 N0 = PromoteOperand(N0, PVT, Replace); 1050 if (!N0.getNode()) 1051 return SDValue(); 1052 1053 AddToWorklist(N0.getNode()); 1054 if (Replace) 1055 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1056 1057 DEBUG(dbgs() << "\nPromoting "; 1058 Op.getNode()->dump(&DAG)); 1059 SDLoc dl(Op); 1060 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1061 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1062 } 1063 return SDValue(); 1064 } 1065 1066 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1067 if (!LegalOperations) 1068 return SDValue(); 1069 1070 EVT VT = Op.getValueType(); 1071 if (VT.isVector() || !VT.isInteger()) 1072 return SDValue(); 1073 1074 // If operation type is 'undesirable', e.g. i16 on x86, consider 1075 // promoting it. 1076 unsigned Opc = Op.getOpcode(); 1077 if (TLI.isTypeDesirableForOp(Opc, VT)) 1078 return SDValue(); 1079 1080 EVT PVT = VT; 1081 // Consult target whether it is a good idea to promote this operation and 1082 // what's the right type to promote it to. 1083 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1084 assert(PVT != VT && "Don't know what type to promote to!"); 1085 // fold (aext (aext x)) -> (aext x) 1086 // fold (aext (zext x)) -> (zext x) 1087 // fold (aext (sext x)) -> (sext x) 1088 DEBUG(dbgs() << "\nPromoting "; 1089 Op.getNode()->dump(&DAG)); 1090 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1091 } 1092 return SDValue(); 1093 } 1094 1095 bool DAGCombiner::PromoteLoad(SDValue Op) { 1096 if (!LegalOperations) 1097 return false; 1098 1099 EVT VT = Op.getValueType(); 1100 if (VT.isVector() || !VT.isInteger()) 1101 return false; 1102 1103 // If operation type is 'undesirable', e.g. i16 on x86, consider 1104 // promoting it. 1105 unsigned Opc = Op.getOpcode(); 1106 if (TLI.isTypeDesirableForOp(Opc, VT)) 1107 return false; 1108 1109 EVT PVT = VT; 1110 // Consult target whether it is a good idea to promote this operation and 1111 // what's the right type to promote it to. 1112 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1113 assert(PVT != VT && "Don't know what type to promote to!"); 1114 1115 SDLoc dl(Op); 1116 SDNode *N = Op.getNode(); 1117 LoadSDNode *LD = cast<LoadSDNode>(N); 1118 EVT MemVT = LD->getMemoryVT(); 1119 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1120 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1121 : ISD::EXTLOAD) 1122 : LD->getExtensionType(); 1123 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1124 LD->getChain(), LD->getBasePtr(), 1125 MemVT, LD->getMemOperand()); 1126 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1127 1128 DEBUG(dbgs() << "\nPromoting "; 1129 N->dump(&DAG); 1130 dbgs() << "\nTo: "; 1131 Result.getNode()->dump(&DAG); 1132 dbgs() << '\n'); 1133 WorklistRemover DeadNodes(*this); 1134 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1135 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1136 deleteAndRecombine(N); 1137 AddToWorklist(Result.getNode()); 1138 return true; 1139 } 1140 return false; 1141 } 1142 1143 /// \brief Recursively delete a node which has no uses and any operands for 1144 /// which it is the only use. 1145 /// 1146 /// Note that this both deletes the nodes and removes them from the worklist. 1147 /// It also adds any nodes who have had a user deleted to the worklist as they 1148 /// may now have only one use and subject to other combines. 1149 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1150 if (!N->use_empty()) 1151 return false; 1152 1153 SmallSetVector<SDNode *, 16> Nodes; 1154 Nodes.insert(N); 1155 do { 1156 N = Nodes.pop_back_val(); 1157 if (!N) 1158 continue; 1159 1160 if (N->use_empty()) { 1161 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1162 Nodes.insert(N->getOperand(i).getNode()); 1163 1164 removeFromWorklist(N); 1165 DAG.DeleteNode(N); 1166 } else { 1167 AddToWorklist(N); 1168 } 1169 } while (!Nodes.empty()); 1170 return true; 1171 } 1172 1173 //===----------------------------------------------------------------------===// 1174 // Main DAG Combiner implementation 1175 //===----------------------------------------------------------------------===// 1176 1177 void DAGCombiner::Run(CombineLevel AtLevel) { 1178 // set the instance variables, so that the various visit routines may use it. 1179 Level = AtLevel; 1180 LegalOperations = Level >= AfterLegalizeVectorOps; 1181 LegalTypes = Level >= AfterLegalizeTypes; 1182 1183 // Early exit if this basic block is in an optnone function. 1184 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 1185 Attribute::OptimizeNone)) 1186 return; 1187 1188 // Add all the dag nodes to the worklist. 1189 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1190 E = DAG.allnodes_end(); I != E; ++I) 1191 AddToWorklist(I); 1192 1193 // Create a dummy node (which is not added to allnodes), that adds a reference 1194 // to the root node, preventing it from being deleted, and tracking any 1195 // changes of the root. 1196 HandleSDNode Dummy(DAG.getRoot()); 1197 1198 // while the worklist isn't empty, find a node and 1199 // try and combine it. 1200 while (!WorklistMap.empty()) { 1201 SDNode *N; 1202 // The Worklist holds the SDNodes in order, but it may contain null entries. 1203 do { 1204 N = Worklist.pop_back_val(); 1205 } while (!N); 1206 1207 bool GoodWorklistEntry = WorklistMap.erase(N); 1208 (void)GoodWorklistEntry; 1209 assert(GoodWorklistEntry && 1210 "Found a worklist entry without a corresponding map entry!"); 1211 1212 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1213 // N is deleted from the DAG, since they too may now be dead or may have a 1214 // reduced number of uses, allowing other xforms. 1215 if (recursivelyDeleteUnusedNodes(N)) 1216 continue; 1217 1218 WorklistRemover DeadNodes(*this); 1219 1220 // If this combine is running after legalizing the DAG, re-legalize any 1221 // nodes pulled off the worklist. 1222 if (Level == AfterLegalizeDAG) { 1223 SmallSetVector<SDNode *, 16> UpdatedNodes; 1224 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1225 1226 for (SDNode *LN : UpdatedNodes) { 1227 AddToWorklist(LN); 1228 AddUsersToWorklist(LN); 1229 } 1230 if (!NIsValid) 1231 continue; 1232 } 1233 1234 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1235 1236 // Add any operands of the new node which have not yet been combined to the 1237 // worklist as well. Because the worklist uniques things already, this 1238 // won't repeatedly process the same operand. 1239 CombinedNodes.insert(N); 1240 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1241 if (!CombinedNodes.count(N->getOperand(i).getNode())) 1242 AddToWorklist(N->getOperand(i).getNode()); 1243 1244 SDValue RV = combine(N); 1245 1246 if (!RV.getNode()) 1247 continue; 1248 1249 ++NodesCombined; 1250 1251 // If we get back the same node we passed in, rather than a new node or 1252 // zero, we know that the node must have defined multiple values and 1253 // CombineTo was used. Since CombineTo takes care of the worklist 1254 // mechanics for us, we have no work to do in this case. 1255 if (RV.getNode() == N) 1256 continue; 1257 1258 assert(N->getOpcode() != ISD::DELETED_NODE && 1259 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1260 "Node was deleted but visit returned new node!"); 1261 1262 DEBUG(dbgs() << " ... into: "; 1263 RV.getNode()->dump(&DAG)); 1264 1265 // Transfer debug value. 1266 DAG.TransferDbgValues(SDValue(N, 0), RV); 1267 if (N->getNumValues() == RV.getNode()->getNumValues()) 1268 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1269 else { 1270 assert(N->getValueType(0) == RV.getValueType() && 1271 N->getNumValues() == 1 && "Type mismatch"); 1272 SDValue OpV = RV; 1273 DAG.ReplaceAllUsesWith(N, &OpV); 1274 } 1275 1276 // Push the new node and any users onto the worklist 1277 AddToWorklist(RV.getNode()); 1278 AddUsersToWorklist(RV.getNode()); 1279 1280 // Finally, if the node is now dead, remove it from the graph. The node 1281 // may not be dead if the replacement process recursively simplified to 1282 // something else needing this node. This will also take care of adding any 1283 // operands which have lost a user to the worklist. 1284 recursivelyDeleteUnusedNodes(N); 1285 } 1286 1287 // If the root changed (e.g. it was a dead load, update the root). 1288 DAG.setRoot(Dummy.getValue()); 1289 DAG.RemoveDeadNodes(); 1290 } 1291 1292 SDValue DAGCombiner::visit(SDNode *N) { 1293 switch (N->getOpcode()) { 1294 default: break; 1295 case ISD::TokenFactor: return visitTokenFactor(N); 1296 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1297 case ISD::ADD: return visitADD(N); 1298 case ISD::SUB: return visitSUB(N); 1299 case ISD::ADDC: return visitADDC(N); 1300 case ISD::SUBC: return visitSUBC(N); 1301 case ISD::ADDE: return visitADDE(N); 1302 case ISD::SUBE: return visitSUBE(N); 1303 case ISD::MUL: return visitMUL(N); 1304 case ISD::SDIV: return visitSDIV(N); 1305 case ISD::UDIV: return visitUDIV(N); 1306 case ISD::SREM: return visitSREM(N); 1307 case ISD::UREM: return visitUREM(N); 1308 case ISD::MULHU: return visitMULHU(N); 1309 case ISD::MULHS: return visitMULHS(N); 1310 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1311 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1312 case ISD::SMULO: return visitSMULO(N); 1313 case ISD::UMULO: return visitUMULO(N); 1314 case ISD::SDIVREM: return visitSDIVREM(N); 1315 case ISD::UDIVREM: return visitUDIVREM(N); 1316 case ISD::AND: return visitAND(N); 1317 case ISD::OR: return visitOR(N); 1318 case ISD::XOR: return visitXOR(N); 1319 case ISD::SHL: return visitSHL(N); 1320 case ISD::SRA: return visitSRA(N); 1321 case ISD::SRL: return visitSRL(N); 1322 case ISD::ROTR: 1323 case ISD::ROTL: return visitRotate(N); 1324 case ISD::CTLZ: return visitCTLZ(N); 1325 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1326 case ISD::CTTZ: return visitCTTZ(N); 1327 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1328 case ISD::CTPOP: return visitCTPOP(N); 1329 case ISD::SELECT: return visitSELECT(N); 1330 case ISD::VSELECT: return visitVSELECT(N); 1331 case ISD::SELECT_CC: return visitSELECT_CC(N); 1332 case ISD::SETCC: return visitSETCC(N); 1333 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1334 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1335 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1336 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1337 case ISD::TRUNCATE: return visitTRUNCATE(N); 1338 case ISD::BITCAST: return visitBITCAST(N); 1339 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1340 case ISD::FADD: return visitFADD(N); 1341 case ISD::FSUB: return visitFSUB(N); 1342 case ISD::FMUL: return visitFMUL(N); 1343 case ISD::FMA: return visitFMA(N); 1344 case ISD::FDIV: return visitFDIV(N); 1345 case ISD::FREM: return visitFREM(N); 1346 case ISD::FSQRT: return visitFSQRT(N); 1347 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1348 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1349 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1350 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1351 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1352 case ISD::FP_ROUND: return visitFP_ROUND(N); 1353 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1354 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1355 case ISD::FNEG: return visitFNEG(N); 1356 case ISD::FABS: return visitFABS(N); 1357 case ISD::FFLOOR: return visitFFLOOR(N); 1358 case ISD::FMINNUM: return visitFMINNUM(N); 1359 case ISD::FMAXNUM: return visitFMAXNUM(N); 1360 case ISD::FCEIL: return visitFCEIL(N); 1361 case ISD::FTRUNC: return visitFTRUNC(N); 1362 case ISD::BRCOND: return visitBRCOND(N); 1363 case ISD::BR_CC: return visitBR_CC(N); 1364 case ISD::LOAD: return visitLOAD(N); 1365 case ISD::STORE: return visitSTORE(N); 1366 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1367 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1368 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1369 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1370 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1371 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1372 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1373 case ISD::MLOAD: return visitMLOAD(N); 1374 case ISD::MSTORE: return visitMSTORE(N); 1375 } 1376 return SDValue(); 1377 } 1378 1379 SDValue DAGCombiner::combine(SDNode *N) { 1380 SDValue RV = visit(N); 1381 1382 // If nothing happened, try a target-specific DAG combine. 1383 if (!RV.getNode()) { 1384 assert(N->getOpcode() != ISD::DELETED_NODE && 1385 "Node was deleted but visit returned NULL!"); 1386 1387 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1388 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1389 1390 // Expose the DAG combiner to the target combiner impls. 1391 TargetLowering::DAGCombinerInfo 1392 DagCombineInfo(DAG, Level, false, this); 1393 1394 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1395 } 1396 } 1397 1398 // If nothing happened still, try promoting the operation. 1399 if (!RV.getNode()) { 1400 switch (N->getOpcode()) { 1401 default: break; 1402 case ISD::ADD: 1403 case ISD::SUB: 1404 case ISD::MUL: 1405 case ISD::AND: 1406 case ISD::OR: 1407 case ISD::XOR: 1408 RV = PromoteIntBinOp(SDValue(N, 0)); 1409 break; 1410 case ISD::SHL: 1411 case ISD::SRA: 1412 case ISD::SRL: 1413 RV = PromoteIntShiftOp(SDValue(N, 0)); 1414 break; 1415 case ISD::SIGN_EXTEND: 1416 case ISD::ZERO_EXTEND: 1417 case ISD::ANY_EXTEND: 1418 RV = PromoteExtend(SDValue(N, 0)); 1419 break; 1420 case ISD::LOAD: 1421 if (PromoteLoad(SDValue(N, 0))) 1422 RV = SDValue(N, 0); 1423 break; 1424 } 1425 } 1426 1427 // If N is a commutative binary node, try commuting it to enable more 1428 // sdisel CSE. 1429 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1430 N->getNumValues() == 1) { 1431 SDValue N0 = N->getOperand(0); 1432 SDValue N1 = N->getOperand(1); 1433 1434 // Constant operands are canonicalized to RHS. 1435 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1436 SDValue Ops[] = {N1, N0}; 1437 SDNode *CSENode; 1438 if (const BinaryWithFlagsSDNode *BinNode = 1439 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1440 CSENode = DAG.getNodeIfExists( 1441 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(), 1442 BinNode->hasNoSignedWrap(), BinNode->isExact()); 1443 } else { 1444 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1445 } 1446 if (CSENode) 1447 return SDValue(CSENode, 0); 1448 } 1449 } 1450 1451 return RV; 1452 } 1453 1454 /// Given a node, return its input chain if it has one, otherwise return a null 1455 /// sd operand. 1456 static SDValue getInputChainForNode(SDNode *N) { 1457 if (unsigned NumOps = N->getNumOperands()) { 1458 if (N->getOperand(0).getValueType() == MVT::Other) 1459 return N->getOperand(0); 1460 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1461 return N->getOperand(NumOps-1); 1462 for (unsigned i = 1; i < NumOps-1; ++i) 1463 if (N->getOperand(i).getValueType() == MVT::Other) 1464 return N->getOperand(i); 1465 } 1466 return SDValue(); 1467 } 1468 1469 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1470 // If N has two operands, where one has an input chain equal to the other, 1471 // the 'other' chain is redundant. 1472 if (N->getNumOperands() == 2) { 1473 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1474 return N->getOperand(0); 1475 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1476 return N->getOperand(1); 1477 } 1478 1479 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1480 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1481 SmallPtrSet<SDNode*, 16> SeenOps; 1482 bool Changed = false; // If we should replace this token factor. 1483 1484 // Start out with this token factor. 1485 TFs.push_back(N); 1486 1487 // Iterate through token factors. The TFs grows when new token factors are 1488 // encountered. 1489 for (unsigned i = 0; i < TFs.size(); ++i) { 1490 SDNode *TF = TFs[i]; 1491 1492 // Check each of the operands. 1493 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1494 SDValue Op = TF->getOperand(i); 1495 1496 switch (Op.getOpcode()) { 1497 case ISD::EntryToken: 1498 // Entry tokens don't need to be added to the list. They are 1499 // redundant. 1500 Changed = true; 1501 break; 1502 1503 case ISD::TokenFactor: 1504 if (Op.hasOneUse() && 1505 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1506 // Queue up for processing. 1507 TFs.push_back(Op.getNode()); 1508 // Clean up in case the token factor is removed. 1509 AddToWorklist(Op.getNode()); 1510 Changed = true; 1511 break; 1512 } 1513 // Fall thru 1514 1515 default: 1516 // Only add if it isn't already in the list. 1517 if (SeenOps.insert(Op.getNode()).second) 1518 Ops.push_back(Op); 1519 else 1520 Changed = true; 1521 break; 1522 } 1523 } 1524 } 1525 1526 SDValue Result; 1527 1528 // If we've changed things around then replace token factor. 1529 if (Changed) { 1530 if (Ops.empty()) { 1531 // The entry token is the only possible outcome. 1532 Result = DAG.getEntryNode(); 1533 } else { 1534 // New and improved token factor. 1535 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1536 } 1537 1538 // Add users to worklist if AA is enabled, since it may introduce 1539 // a lot of new chained token factors while removing memory deps. 1540 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1541 : DAG.getSubtarget().useAA(); 1542 return CombineTo(N, Result, UseAA /*add to worklist*/); 1543 } 1544 1545 return Result; 1546 } 1547 1548 /// MERGE_VALUES can always be eliminated. 1549 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1550 WorklistRemover DeadNodes(*this); 1551 // Replacing results may cause a different MERGE_VALUES to suddenly 1552 // be CSE'd with N, and carry its uses with it. Iterate until no 1553 // uses remain, to ensure that the node can be safely deleted. 1554 // First add the users of this node to the work list so that they 1555 // can be tried again once they have new operands. 1556 AddUsersToWorklist(N); 1557 do { 1558 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1559 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1560 } while (!N->use_empty()); 1561 deleteAndRecombine(N); 1562 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1563 } 1564 1565 SDValue DAGCombiner::visitADD(SDNode *N) { 1566 SDValue N0 = N->getOperand(0); 1567 SDValue N1 = N->getOperand(1); 1568 EVT VT = N0.getValueType(); 1569 1570 // fold vector ops 1571 if (VT.isVector()) { 1572 SDValue FoldedVOp = SimplifyVBinOp(N); 1573 if (FoldedVOp.getNode()) return FoldedVOp; 1574 1575 // fold (add x, 0) -> x, vector edition 1576 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1577 return N0; 1578 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1579 return N1; 1580 } 1581 1582 // fold (add x, undef) -> undef 1583 if (N0.getOpcode() == ISD::UNDEF) 1584 return N0; 1585 if (N1.getOpcode() == ISD::UNDEF) 1586 return N1; 1587 // fold (add c1, c2) -> c1+c2 1588 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1589 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1590 if (N0C && N1C) 1591 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1592 // canonicalize constant to RHS 1593 if (N0C && !N1C) 1594 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1595 // fold (add x, 0) -> x 1596 if (N1C && N1C->isNullValue()) 1597 return N0; 1598 // fold (add Sym, c) -> Sym+c 1599 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1600 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1601 GA->getOpcode() == ISD::GlobalAddress) 1602 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1603 GA->getOffset() + 1604 (uint64_t)N1C->getSExtValue()); 1605 // fold ((c1-A)+c2) -> (c1+c2)-A 1606 if (N1C && N0.getOpcode() == ISD::SUB) 1607 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1608 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1609 DAG.getConstant(N1C->getAPIntValue()+ 1610 N0C->getAPIntValue(), VT), 1611 N0.getOperand(1)); 1612 // reassociate add 1613 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1614 if (RADD.getNode()) 1615 return RADD; 1616 // fold ((0-A) + B) -> B-A 1617 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1618 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1619 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1620 // fold (A + (0-B)) -> A-B 1621 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1622 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1623 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1624 // fold (A+(B-A)) -> B 1625 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1626 return N1.getOperand(0); 1627 // fold ((B-A)+A) -> B 1628 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1629 return N0.getOperand(0); 1630 // fold (A+(B-(A+C))) to (B-C) 1631 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1632 N0 == N1.getOperand(1).getOperand(0)) 1633 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1634 N1.getOperand(1).getOperand(1)); 1635 // fold (A+(B-(C+A))) to (B-C) 1636 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1637 N0 == N1.getOperand(1).getOperand(1)) 1638 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1639 N1.getOperand(1).getOperand(0)); 1640 // fold (A+((B-A)+or-C)) to (B+or-C) 1641 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1642 N1.getOperand(0).getOpcode() == ISD::SUB && 1643 N0 == N1.getOperand(0).getOperand(1)) 1644 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1645 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1646 1647 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1648 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1649 SDValue N00 = N0.getOperand(0); 1650 SDValue N01 = N0.getOperand(1); 1651 SDValue N10 = N1.getOperand(0); 1652 SDValue N11 = N1.getOperand(1); 1653 1654 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1655 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1656 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1657 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1658 } 1659 1660 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1661 return SDValue(N, 0); 1662 1663 // fold (a+b) -> (a|b) iff a and b share no bits. 1664 if (VT.isInteger() && !VT.isVector()) { 1665 APInt LHSZero, LHSOne; 1666 APInt RHSZero, RHSOne; 1667 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1668 1669 if (LHSZero.getBoolValue()) { 1670 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1671 1672 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1673 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1674 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1675 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1676 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1677 } 1678 } 1679 } 1680 1681 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1682 if (N1.getOpcode() == ISD::SHL && 1683 N1.getOperand(0).getOpcode() == ISD::SUB) 1684 if (ConstantSDNode *C = 1685 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1686 if (C->getAPIntValue() == 0) 1687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1688 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1689 N1.getOperand(0).getOperand(1), 1690 N1.getOperand(1))); 1691 if (N0.getOpcode() == ISD::SHL && 1692 N0.getOperand(0).getOpcode() == ISD::SUB) 1693 if (ConstantSDNode *C = 1694 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1695 if (C->getAPIntValue() == 0) 1696 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1697 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1698 N0.getOperand(0).getOperand(1), 1699 N0.getOperand(1))); 1700 1701 if (N1.getOpcode() == ISD::AND) { 1702 SDValue AndOp0 = N1.getOperand(0); 1703 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1704 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1705 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1706 1707 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1708 // and similar xforms where the inner op is either ~0 or 0. 1709 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1710 SDLoc DL(N); 1711 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1712 } 1713 } 1714 1715 // add (sext i1), X -> sub X, (zext i1) 1716 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1717 N0.getOperand(0).getValueType() == MVT::i1 && 1718 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1719 SDLoc DL(N); 1720 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1721 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1722 } 1723 1724 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1725 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1726 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1727 if (TN->getVT() == MVT::i1) { 1728 SDLoc DL(N); 1729 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1730 DAG.getConstant(1, VT)); 1731 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1732 } 1733 } 1734 1735 return SDValue(); 1736 } 1737 1738 SDValue DAGCombiner::visitADDC(SDNode *N) { 1739 SDValue N0 = N->getOperand(0); 1740 SDValue N1 = N->getOperand(1); 1741 EVT VT = N0.getValueType(); 1742 1743 // If the flag result is dead, turn this into an ADD. 1744 if (!N->hasAnyUseOfValue(1)) 1745 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1746 DAG.getNode(ISD::CARRY_FALSE, 1747 SDLoc(N), MVT::Glue)); 1748 1749 // canonicalize constant to RHS. 1750 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1751 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1752 if (N0C && !N1C) 1753 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1754 1755 // fold (addc x, 0) -> x + no carry out 1756 if (N1C && N1C->isNullValue()) 1757 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1758 SDLoc(N), MVT::Glue)); 1759 1760 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1761 APInt LHSZero, LHSOne; 1762 APInt RHSZero, RHSOne; 1763 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1764 1765 if (LHSZero.getBoolValue()) { 1766 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1767 1768 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1769 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1770 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1771 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1772 DAG.getNode(ISD::CARRY_FALSE, 1773 SDLoc(N), MVT::Glue)); 1774 } 1775 1776 return SDValue(); 1777 } 1778 1779 SDValue DAGCombiner::visitADDE(SDNode *N) { 1780 SDValue N0 = N->getOperand(0); 1781 SDValue N1 = N->getOperand(1); 1782 SDValue CarryIn = N->getOperand(2); 1783 1784 // canonicalize constant to RHS 1785 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1786 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1787 if (N0C && !N1C) 1788 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1789 N1, N0, CarryIn); 1790 1791 // fold (adde x, y, false) -> (addc x, y) 1792 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1793 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1794 1795 return SDValue(); 1796 } 1797 1798 // Since it may not be valid to emit a fold to zero for vector initializers 1799 // check if we can before folding. 1800 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1801 SelectionDAG &DAG, 1802 bool LegalOperations, bool LegalTypes) { 1803 if (!VT.isVector()) 1804 return DAG.getConstant(0, VT); 1805 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1806 return DAG.getConstant(0, VT); 1807 return SDValue(); 1808 } 1809 1810 SDValue DAGCombiner::visitSUB(SDNode *N) { 1811 SDValue N0 = N->getOperand(0); 1812 SDValue N1 = N->getOperand(1); 1813 EVT VT = N0.getValueType(); 1814 1815 // fold vector ops 1816 if (VT.isVector()) { 1817 SDValue FoldedVOp = SimplifyVBinOp(N); 1818 if (FoldedVOp.getNode()) return FoldedVOp; 1819 1820 // fold (sub x, 0) -> x, vector edition 1821 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1822 return N0; 1823 } 1824 1825 // fold (sub x, x) -> 0 1826 // FIXME: Refactor this and xor and other similar operations together. 1827 if (N0 == N1) 1828 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1829 // fold (sub c1, c2) -> c1-c2 1830 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1831 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1832 if (N0C && N1C) 1833 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1834 // fold (sub x, c) -> (add x, -c) 1835 if (N1C) 1836 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1837 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1838 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1839 if (N0C && N0C->isAllOnesValue()) 1840 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1841 // fold A-(A-B) -> B 1842 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1843 return N1.getOperand(1); 1844 // fold (A+B)-A -> B 1845 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1846 return N0.getOperand(1); 1847 // fold (A+B)-B -> A 1848 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1849 return N0.getOperand(0); 1850 // fold C2-(A+C1) -> (C2-C1)-A 1851 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1852 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1853 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1854 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1855 VT); 1856 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1857 N1.getOperand(0)); 1858 } 1859 // fold ((A+(B+or-C))-B) -> A+or-C 1860 if (N0.getOpcode() == ISD::ADD && 1861 (N0.getOperand(1).getOpcode() == ISD::SUB || 1862 N0.getOperand(1).getOpcode() == ISD::ADD) && 1863 N0.getOperand(1).getOperand(0) == N1) 1864 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1865 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1866 // fold ((A+(C+B))-B) -> A+C 1867 if (N0.getOpcode() == ISD::ADD && 1868 N0.getOperand(1).getOpcode() == ISD::ADD && 1869 N0.getOperand(1).getOperand(1) == N1) 1870 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1871 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1872 // fold ((A-(B-C))-C) -> A-B 1873 if (N0.getOpcode() == ISD::SUB && 1874 N0.getOperand(1).getOpcode() == ISD::SUB && 1875 N0.getOperand(1).getOperand(1) == N1) 1876 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1877 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1878 1879 // If either operand of a sub is undef, the result is undef 1880 if (N0.getOpcode() == ISD::UNDEF) 1881 return N0; 1882 if (N1.getOpcode() == ISD::UNDEF) 1883 return N1; 1884 1885 // If the relocation model supports it, consider symbol offsets. 1886 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1887 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1888 // fold (sub Sym, c) -> Sym-c 1889 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1890 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1891 GA->getOffset() - 1892 (uint64_t)N1C->getSExtValue()); 1893 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1894 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1895 if (GA->getGlobal() == GB->getGlobal()) 1896 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1897 VT); 1898 } 1899 1900 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1901 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1902 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1903 if (TN->getVT() == MVT::i1) { 1904 SDLoc DL(N); 1905 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1906 DAG.getConstant(1, VT)); 1907 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1908 } 1909 } 1910 1911 return SDValue(); 1912 } 1913 1914 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1915 SDValue N0 = N->getOperand(0); 1916 SDValue N1 = N->getOperand(1); 1917 EVT VT = N0.getValueType(); 1918 1919 // If the flag result is dead, turn this into an SUB. 1920 if (!N->hasAnyUseOfValue(1)) 1921 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1922 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1923 MVT::Glue)); 1924 1925 // fold (subc x, x) -> 0 + no borrow 1926 if (N0 == N1) 1927 return CombineTo(N, DAG.getConstant(0, VT), 1928 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1929 MVT::Glue)); 1930 1931 // fold (subc x, 0) -> x + no borrow 1932 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1933 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1934 if (N1C && N1C->isNullValue()) 1935 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1936 MVT::Glue)); 1937 1938 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1939 if (N0C && N0C->isAllOnesValue()) 1940 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1941 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1942 MVT::Glue)); 1943 1944 return SDValue(); 1945 } 1946 1947 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1948 SDValue N0 = N->getOperand(0); 1949 SDValue N1 = N->getOperand(1); 1950 SDValue CarryIn = N->getOperand(2); 1951 1952 // fold (sube x, y, false) -> (subc x, y) 1953 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1954 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1955 1956 return SDValue(); 1957 } 1958 1959 SDValue DAGCombiner::visitMUL(SDNode *N) { 1960 SDValue N0 = N->getOperand(0); 1961 SDValue N1 = N->getOperand(1); 1962 EVT VT = N0.getValueType(); 1963 1964 // fold (mul x, undef) -> 0 1965 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1966 return DAG.getConstant(0, VT); 1967 1968 bool N0IsConst = false; 1969 bool N1IsConst = false; 1970 APInt ConstValue0, ConstValue1; 1971 // fold vector ops 1972 if (VT.isVector()) { 1973 SDValue FoldedVOp = SimplifyVBinOp(N); 1974 if (FoldedVOp.getNode()) return FoldedVOp; 1975 1976 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1977 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1978 } else { 1979 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr; 1980 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1981 : APInt(); 1982 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr; 1983 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1984 : APInt(); 1985 } 1986 1987 // fold (mul c1, c2) -> c1*c2 1988 if (N0IsConst && N1IsConst) 1989 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1990 1991 // canonicalize constant to RHS 1992 if (N0IsConst && !N1IsConst) 1993 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1994 // fold (mul x, 0) -> 0 1995 if (N1IsConst && ConstValue1 == 0) 1996 return N1; 1997 // We require a splat of the entire scalar bit width for non-contiguous 1998 // bit patterns. 1999 bool IsFullSplat = 2000 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2001 // fold (mul x, 1) -> x 2002 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2003 return N0; 2004 // fold (mul x, -1) -> 0-x 2005 if (N1IsConst && ConstValue1.isAllOnesValue()) 2006 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2007 DAG.getConstant(0, VT), N0); 2008 // fold (mul x, (1 << c)) -> x << c 2009 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 2010 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2011 DAG.getConstant(ConstValue1.logBase2(), 2012 getShiftAmountTy(N0.getValueType()))); 2013 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2014 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 2015 unsigned Log2Val = (-ConstValue1).logBase2(); 2016 // FIXME: If the input is something that is easily negated (e.g. a 2017 // single-use add), we should put the negate there. 2018 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2019 DAG.getConstant(0, VT), 2020 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2021 DAG.getConstant(Log2Val, 2022 getShiftAmountTy(N0.getValueType())))); 2023 } 2024 2025 APInt Val; 2026 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2027 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2028 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2029 isa<ConstantSDNode>(N0.getOperand(1)))) { 2030 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2031 N1, N0.getOperand(1)); 2032 AddToWorklist(C3.getNode()); 2033 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2034 N0.getOperand(0), C3); 2035 } 2036 2037 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2038 // use. 2039 { 2040 SDValue Sh(nullptr,0), Y(nullptr,0); 2041 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2042 if (N0.getOpcode() == ISD::SHL && 2043 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2044 isa<ConstantSDNode>(N0.getOperand(1))) && 2045 N0.getNode()->hasOneUse()) { 2046 Sh = N0; Y = N1; 2047 } else if (N1.getOpcode() == ISD::SHL && 2048 isa<ConstantSDNode>(N1.getOperand(1)) && 2049 N1.getNode()->hasOneUse()) { 2050 Sh = N1; Y = N0; 2051 } 2052 2053 if (Sh.getNode()) { 2054 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2055 Sh.getOperand(0), Y); 2056 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2057 Mul, Sh.getOperand(1)); 2058 } 2059 } 2060 2061 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2062 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2063 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2064 isa<ConstantSDNode>(N0.getOperand(1)))) 2065 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2066 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2067 N0.getOperand(0), N1), 2068 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2069 N0.getOperand(1), N1)); 2070 2071 // reassociate mul 2072 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 2073 if (RMUL.getNode()) 2074 return RMUL; 2075 2076 return SDValue(); 2077 } 2078 2079 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2080 SDValue N0 = N->getOperand(0); 2081 SDValue N1 = N->getOperand(1); 2082 EVT VT = N->getValueType(0); 2083 2084 // fold vector ops 2085 if (VT.isVector()) { 2086 SDValue FoldedVOp = SimplifyVBinOp(N); 2087 if (FoldedVOp.getNode()) return FoldedVOp; 2088 } 2089 2090 // fold (sdiv c1, c2) -> c1/c2 2091 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2092 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2093 if (N0C && N1C && !N1C->isNullValue()) 2094 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 2095 // fold (sdiv X, 1) -> X 2096 if (N1C && N1C->getAPIntValue() == 1LL) 2097 return N0; 2098 // fold (sdiv X, -1) -> 0-X 2099 if (N1C && N1C->isAllOnesValue()) 2100 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2101 DAG.getConstant(0, VT), N0); 2102 // If we know the sign bits of both operands are zero, strength reduce to a 2103 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2104 if (!VT.isVector()) { 2105 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2106 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2107 N0, N1); 2108 } 2109 2110 // fold (sdiv X, pow2) -> simple ops after legalize 2111 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2112 (-N1C->getAPIntValue()).isPowerOf2())) { 2113 // If dividing by powers of two is cheap, then don't perform the following 2114 // fold. 2115 if (TLI.isPow2SDivCheap()) 2116 return SDValue(); 2117 2118 // Target-specific implementation of sdiv x, pow2. 2119 SDValue Res = BuildSDIVPow2(N); 2120 if (Res.getNode()) 2121 return Res; 2122 2123 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2124 2125 // Splat the sign bit into the register 2126 SDValue SGN = 2127 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2128 DAG.getConstant(VT.getScalarSizeInBits() - 1, 2129 getShiftAmountTy(N0.getValueType()))); 2130 AddToWorklist(SGN.getNode()); 2131 2132 // Add (N0 < 0) ? abs2 - 1 : 0; 2133 SDValue SRL = 2134 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2135 DAG.getConstant(VT.getScalarSizeInBits() - lg2, 2136 getShiftAmountTy(SGN.getValueType()))); 2137 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2138 AddToWorklist(SRL.getNode()); 2139 AddToWorklist(ADD.getNode()); // Divide by pow2 2140 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2141 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2142 2143 // If we're dividing by a positive value, we're done. Otherwise, we must 2144 // negate the result. 2145 if (N1C->getAPIntValue().isNonNegative()) 2146 return SRA; 2147 2148 AddToWorklist(SRA.getNode()); 2149 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA); 2150 } 2151 2152 // if integer divide is expensive and we satisfy the requirements, emit an 2153 // alternate sequence. 2154 if (N1C && !TLI.isIntDivCheap()) { 2155 SDValue Op = BuildSDIV(N); 2156 if (Op.getNode()) return Op; 2157 } 2158 2159 // undef / X -> 0 2160 if (N0.getOpcode() == ISD::UNDEF) 2161 return DAG.getConstant(0, VT); 2162 // X / undef -> undef 2163 if (N1.getOpcode() == ISD::UNDEF) 2164 return N1; 2165 2166 return SDValue(); 2167 } 2168 2169 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2170 SDValue N0 = N->getOperand(0); 2171 SDValue N1 = N->getOperand(1); 2172 EVT VT = N->getValueType(0); 2173 2174 // fold vector ops 2175 if (VT.isVector()) { 2176 SDValue FoldedVOp = SimplifyVBinOp(N); 2177 if (FoldedVOp.getNode()) return FoldedVOp; 2178 } 2179 2180 // fold (udiv c1, c2) -> c1/c2 2181 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2182 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2183 if (N0C && N1C && !N1C->isNullValue()) 2184 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2185 // fold (udiv x, (1 << c)) -> x >>u c 2186 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2187 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2188 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2189 getShiftAmountTy(N0.getValueType()))); 2190 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2191 if (N1.getOpcode() == ISD::SHL) { 2192 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2193 if (SHC->getAPIntValue().isPowerOf2()) { 2194 EVT ADDVT = N1.getOperand(1).getValueType(); 2195 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2196 N1.getOperand(1), 2197 DAG.getConstant(SHC->getAPIntValue() 2198 .logBase2(), 2199 ADDVT)); 2200 AddToWorklist(Add.getNode()); 2201 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2202 } 2203 } 2204 } 2205 // fold (udiv x, c) -> alternate 2206 if (N1C && !TLI.isIntDivCheap()) { 2207 SDValue Op = BuildUDIV(N); 2208 if (Op.getNode()) return Op; 2209 } 2210 2211 // undef / X -> 0 2212 if (N0.getOpcode() == ISD::UNDEF) 2213 return DAG.getConstant(0, VT); 2214 // X / undef -> undef 2215 if (N1.getOpcode() == ISD::UNDEF) 2216 return N1; 2217 2218 return SDValue(); 2219 } 2220 2221 SDValue DAGCombiner::visitSREM(SDNode *N) { 2222 SDValue N0 = N->getOperand(0); 2223 SDValue N1 = N->getOperand(1); 2224 EVT VT = N->getValueType(0); 2225 2226 // fold (srem c1, c2) -> c1%c2 2227 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2228 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2229 if (N0C && N1C && !N1C->isNullValue()) 2230 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2231 // If we know the sign bits of both operands are zero, strength reduce to a 2232 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2233 if (!VT.isVector()) { 2234 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2235 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2236 } 2237 2238 // If X/C can be simplified by the division-by-constant logic, lower 2239 // X%C to the equivalent of X-X/C*C. 2240 if (N1C && !N1C->isNullValue()) { 2241 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2242 AddToWorklist(Div.getNode()); 2243 SDValue OptimizedDiv = combine(Div.getNode()); 2244 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2245 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2246 OptimizedDiv, N1); 2247 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2248 AddToWorklist(Mul.getNode()); 2249 return Sub; 2250 } 2251 } 2252 2253 // undef % X -> 0 2254 if (N0.getOpcode() == ISD::UNDEF) 2255 return DAG.getConstant(0, VT); 2256 // X % undef -> undef 2257 if (N1.getOpcode() == ISD::UNDEF) 2258 return N1; 2259 2260 return SDValue(); 2261 } 2262 2263 SDValue DAGCombiner::visitUREM(SDNode *N) { 2264 SDValue N0 = N->getOperand(0); 2265 SDValue N1 = N->getOperand(1); 2266 EVT VT = N->getValueType(0); 2267 2268 // fold (urem c1, c2) -> c1%c2 2269 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2270 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2271 if (N0C && N1C && !N1C->isNullValue()) 2272 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2273 // fold (urem x, pow2) -> (and x, pow2-1) 2274 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2275 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2276 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2277 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2278 if (N1.getOpcode() == ISD::SHL) { 2279 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2280 if (SHC->getAPIntValue().isPowerOf2()) { 2281 SDValue Add = 2282 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2283 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2284 VT)); 2285 AddToWorklist(Add.getNode()); 2286 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2287 } 2288 } 2289 } 2290 2291 // If X/C can be simplified by the division-by-constant logic, lower 2292 // X%C to the equivalent of X-X/C*C. 2293 if (N1C && !N1C->isNullValue()) { 2294 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2295 AddToWorklist(Div.getNode()); 2296 SDValue OptimizedDiv = combine(Div.getNode()); 2297 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2298 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2299 OptimizedDiv, N1); 2300 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2301 AddToWorklist(Mul.getNode()); 2302 return Sub; 2303 } 2304 } 2305 2306 // undef % X -> 0 2307 if (N0.getOpcode() == ISD::UNDEF) 2308 return DAG.getConstant(0, VT); 2309 // X % undef -> undef 2310 if (N1.getOpcode() == ISD::UNDEF) 2311 return N1; 2312 2313 return SDValue(); 2314 } 2315 2316 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2317 SDValue N0 = N->getOperand(0); 2318 SDValue N1 = N->getOperand(1); 2319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2320 EVT VT = N->getValueType(0); 2321 SDLoc DL(N); 2322 2323 // fold (mulhs x, 0) -> 0 2324 if (N1C && N1C->isNullValue()) 2325 return N1; 2326 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2327 if (N1C && N1C->getAPIntValue() == 1) 2328 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2329 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2330 getShiftAmountTy(N0.getValueType()))); 2331 // fold (mulhs x, undef) -> 0 2332 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2333 return DAG.getConstant(0, VT); 2334 2335 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2336 // plus a shift. 2337 if (VT.isSimple() && !VT.isVector()) { 2338 MVT Simple = VT.getSimpleVT(); 2339 unsigned SimpleSize = Simple.getSizeInBits(); 2340 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2341 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2342 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2343 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2344 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2345 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2346 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2347 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2348 } 2349 } 2350 2351 return SDValue(); 2352 } 2353 2354 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2355 SDValue N0 = N->getOperand(0); 2356 SDValue N1 = N->getOperand(1); 2357 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2358 EVT VT = N->getValueType(0); 2359 SDLoc DL(N); 2360 2361 // fold (mulhu x, 0) -> 0 2362 if (N1C && N1C->isNullValue()) 2363 return N1; 2364 // fold (mulhu x, 1) -> 0 2365 if (N1C && N1C->getAPIntValue() == 1) 2366 return DAG.getConstant(0, N0.getValueType()); 2367 // fold (mulhu x, undef) -> 0 2368 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2369 return DAG.getConstant(0, VT); 2370 2371 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2372 // plus a shift. 2373 if (VT.isSimple() && !VT.isVector()) { 2374 MVT Simple = VT.getSimpleVT(); 2375 unsigned SimpleSize = Simple.getSizeInBits(); 2376 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2377 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2378 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2379 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2380 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2381 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2382 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2383 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2384 } 2385 } 2386 2387 return SDValue(); 2388 } 2389 2390 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2391 /// give the opcodes for the two computations that are being performed. Return 2392 /// true if a simplification was made. 2393 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2394 unsigned HiOp) { 2395 // If the high half is not needed, just compute the low half. 2396 bool HiExists = N->hasAnyUseOfValue(1); 2397 if (!HiExists && 2398 (!LegalOperations || 2399 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2400 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2401 return CombineTo(N, Res, Res); 2402 } 2403 2404 // If the low half is not needed, just compute the high half. 2405 bool LoExists = N->hasAnyUseOfValue(0); 2406 if (!LoExists && 2407 (!LegalOperations || 2408 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2409 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2410 return CombineTo(N, Res, Res); 2411 } 2412 2413 // If both halves are used, return as it is. 2414 if (LoExists && HiExists) 2415 return SDValue(); 2416 2417 // If the two computed results can be simplified separately, separate them. 2418 if (LoExists) { 2419 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2420 AddToWorklist(Lo.getNode()); 2421 SDValue LoOpt = combine(Lo.getNode()); 2422 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2423 (!LegalOperations || 2424 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2425 return CombineTo(N, LoOpt, LoOpt); 2426 } 2427 2428 if (HiExists) { 2429 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2430 AddToWorklist(Hi.getNode()); 2431 SDValue HiOpt = combine(Hi.getNode()); 2432 if (HiOpt.getNode() && HiOpt != Hi && 2433 (!LegalOperations || 2434 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2435 return CombineTo(N, HiOpt, HiOpt); 2436 } 2437 2438 return SDValue(); 2439 } 2440 2441 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2442 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2443 if (Res.getNode()) return Res; 2444 2445 EVT VT = N->getValueType(0); 2446 SDLoc DL(N); 2447 2448 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2449 // plus a shift. 2450 if (VT.isSimple() && !VT.isVector()) { 2451 MVT Simple = VT.getSimpleVT(); 2452 unsigned SimpleSize = Simple.getSizeInBits(); 2453 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2454 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2455 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2456 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2457 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2458 // Compute the high part as N1. 2459 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2460 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2461 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2462 // Compute the low part as N0. 2463 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2464 return CombineTo(N, Lo, Hi); 2465 } 2466 } 2467 2468 return SDValue(); 2469 } 2470 2471 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2472 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2473 if (Res.getNode()) return Res; 2474 2475 EVT VT = N->getValueType(0); 2476 SDLoc DL(N); 2477 2478 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2479 // plus a shift. 2480 if (VT.isSimple() && !VT.isVector()) { 2481 MVT Simple = VT.getSimpleVT(); 2482 unsigned SimpleSize = Simple.getSizeInBits(); 2483 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2484 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2485 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2486 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2487 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2488 // Compute the high part as N1. 2489 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2490 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2491 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2492 // Compute the low part as N0. 2493 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2494 return CombineTo(N, Lo, Hi); 2495 } 2496 } 2497 2498 return SDValue(); 2499 } 2500 2501 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2502 // (smulo x, 2) -> (saddo x, x) 2503 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2504 if (C2->getAPIntValue() == 2) 2505 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2506 N->getOperand(0), N->getOperand(0)); 2507 2508 return SDValue(); 2509 } 2510 2511 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2512 // (umulo x, 2) -> (uaddo x, x) 2513 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2514 if (C2->getAPIntValue() == 2) 2515 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2516 N->getOperand(0), N->getOperand(0)); 2517 2518 return SDValue(); 2519 } 2520 2521 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2522 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2523 if (Res.getNode()) return Res; 2524 2525 return SDValue(); 2526 } 2527 2528 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2529 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2530 if (Res.getNode()) return Res; 2531 2532 return SDValue(); 2533 } 2534 2535 /// If this is a binary operator with two operands of the same opcode, try to 2536 /// simplify it. 2537 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2538 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2539 EVT VT = N0.getValueType(); 2540 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2541 2542 // Bail early if none of these transforms apply. 2543 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2544 2545 // For each of OP in AND/OR/XOR: 2546 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2547 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2548 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2549 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2550 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2551 // 2552 // do not sink logical op inside of a vector extend, since it may combine 2553 // into a vsetcc. 2554 EVT Op0VT = N0.getOperand(0).getValueType(); 2555 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2556 N0.getOpcode() == ISD::SIGN_EXTEND || 2557 N0.getOpcode() == ISD::BSWAP || 2558 // Avoid infinite looping with PromoteIntBinOp. 2559 (N0.getOpcode() == ISD::ANY_EXTEND && 2560 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2561 (N0.getOpcode() == ISD::TRUNCATE && 2562 (!TLI.isZExtFree(VT, Op0VT) || 2563 !TLI.isTruncateFree(Op0VT, VT)) && 2564 TLI.isTypeLegal(Op0VT))) && 2565 !VT.isVector() && 2566 Op0VT == N1.getOperand(0).getValueType() && 2567 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2568 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2569 N0.getOperand(0).getValueType(), 2570 N0.getOperand(0), N1.getOperand(0)); 2571 AddToWorklist(ORNode.getNode()); 2572 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2573 } 2574 2575 // For each of OP in SHL/SRL/SRA/AND... 2576 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2577 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2578 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2579 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2580 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2581 N0.getOperand(1) == N1.getOperand(1)) { 2582 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2583 N0.getOperand(0).getValueType(), 2584 N0.getOperand(0), N1.getOperand(0)); 2585 AddToWorklist(ORNode.getNode()); 2586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2587 ORNode, N0.getOperand(1)); 2588 } 2589 2590 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2591 // Only perform this optimization after type legalization and before 2592 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2593 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2594 // we don't want to undo this promotion. 2595 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2596 // on scalars. 2597 if ((N0.getOpcode() == ISD::BITCAST || 2598 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2599 Level == AfterLegalizeTypes) { 2600 SDValue In0 = N0.getOperand(0); 2601 SDValue In1 = N1.getOperand(0); 2602 EVT In0Ty = In0.getValueType(); 2603 EVT In1Ty = In1.getValueType(); 2604 SDLoc DL(N); 2605 // If both incoming values are integers, and the original types are the 2606 // same. 2607 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2608 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2609 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2610 AddToWorklist(Op.getNode()); 2611 return BC; 2612 } 2613 } 2614 2615 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2616 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2617 // If both shuffles use the same mask, and both shuffle within a single 2618 // vector, then it is worthwhile to move the swizzle after the operation. 2619 // The type-legalizer generates this pattern when loading illegal 2620 // vector types from memory. In many cases this allows additional shuffle 2621 // optimizations. 2622 // There are other cases where moving the shuffle after the xor/and/or 2623 // is profitable even if shuffles don't perform a swizzle. 2624 // If both shuffles use the same mask, and both shuffles have the same first 2625 // or second operand, then it might still be profitable to move the shuffle 2626 // after the xor/and/or operation. 2627 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2628 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2629 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2630 2631 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2632 "Inputs to shuffles are not the same type"); 2633 2634 // Check that both shuffles use the same mask. The masks are known to be of 2635 // the same length because the result vector type is the same. 2636 // Check also that shuffles have only one use to avoid introducing extra 2637 // instructions. 2638 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2639 SVN0->getMask().equals(SVN1->getMask())) { 2640 SDValue ShOp = N0->getOperand(1); 2641 2642 // Don't try to fold this node if it requires introducing a 2643 // build vector of all zeros that might be illegal at this stage. 2644 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2645 if (!LegalTypes) 2646 ShOp = DAG.getConstant(0, VT); 2647 else 2648 ShOp = SDValue(); 2649 } 2650 2651 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2652 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2653 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2654 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2655 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2656 N0->getOperand(0), N1->getOperand(0)); 2657 AddToWorklist(NewNode.getNode()); 2658 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2659 &SVN0->getMask()[0]); 2660 } 2661 2662 // Don't try to fold this node if it requires introducing a 2663 // build vector of all zeros that might be illegal at this stage. 2664 ShOp = N0->getOperand(0); 2665 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2666 if (!LegalTypes) 2667 ShOp = DAG.getConstant(0, VT); 2668 else 2669 ShOp = SDValue(); 2670 } 2671 2672 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2673 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2674 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2675 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2676 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2677 N0->getOperand(1), N1->getOperand(1)); 2678 AddToWorklist(NewNode.getNode()); 2679 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2680 &SVN0->getMask()[0]); 2681 } 2682 } 2683 } 2684 2685 return SDValue(); 2686 } 2687 2688 SDValue DAGCombiner::visitAND(SDNode *N) { 2689 SDValue N0 = N->getOperand(0); 2690 SDValue N1 = N->getOperand(1); 2691 EVT VT = N1.getValueType(); 2692 2693 // fold vector ops 2694 if (VT.isVector()) { 2695 SDValue FoldedVOp = SimplifyVBinOp(N); 2696 if (FoldedVOp.getNode()) return FoldedVOp; 2697 2698 // fold (and x, 0) -> 0, vector edition 2699 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2700 // do not return N0, because undef node may exist in N0 2701 return DAG.getConstant( 2702 APInt::getNullValue( 2703 N0.getValueType().getScalarType().getSizeInBits()), 2704 N0.getValueType()); 2705 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2706 // do not return N1, because undef node may exist in N1 2707 return DAG.getConstant( 2708 APInt::getNullValue( 2709 N1.getValueType().getScalarType().getSizeInBits()), 2710 N1.getValueType()); 2711 2712 // fold (and x, -1) -> x, vector edition 2713 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2714 return N1; 2715 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2716 return N0; 2717 } 2718 2719 // fold (and x, undef) -> 0 2720 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2721 return DAG.getConstant(0, VT); 2722 // fold (and c1, c2) -> c1&c2 2723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2724 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2725 if (N0C && N1C) 2726 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2727 // canonicalize constant to RHS 2728 if (N0C && !N1C) 2729 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2730 // fold (and x, -1) -> x 2731 if (N1C && N1C->isAllOnesValue()) 2732 return N0; 2733 // if (and x, c) is known to be zero, return 0 2734 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2735 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2736 APInt::getAllOnesValue(BitWidth))) 2737 return DAG.getConstant(0, VT); 2738 // reassociate and 2739 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2740 if (RAND.getNode()) 2741 return RAND; 2742 // fold (and (or x, C), D) -> D if (C & D) == D 2743 if (N1C && N0.getOpcode() == ISD::OR) 2744 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2745 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2746 return N1; 2747 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2748 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2749 SDValue N0Op0 = N0.getOperand(0); 2750 APInt Mask = ~N1C->getAPIntValue(); 2751 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2752 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2753 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2754 N0.getValueType(), N0Op0); 2755 2756 // Replace uses of the AND with uses of the Zero extend node. 2757 CombineTo(N, Zext); 2758 2759 // We actually want to replace all uses of the any_extend with the 2760 // zero_extend, to avoid duplicating things. This will later cause this 2761 // AND to be folded. 2762 CombineTo(N0.getNode(), Zext); 2763 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2764 } 2765 } 2766 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2767 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2768 // already be zero by virtue of the width of the base type of the load. 2769 // 2770 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2771 // more cases. 2772 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2773 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2774 N0.getOpcode() == ISD::LOAD) { 2775 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2776 N0 : N0.getOperand(0) ); 2777 2778 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2779 // This can be a pure constant or a vector splat, in which case we treat the 2780 // vector as a scalar and use the splat value. 2781 APInt Constant = APInt::getNullValue(1); 2782 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2783 Constant = C->getAPIntValue(); 2784 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2785 APInt SplatValue, SplatUndef; 2786 unsigned SplatBitSize; 2787 bool HasAnyUndefs; 2788 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2789 SplatBitSize, HasAnyUndefs); 2790 if (IsSplat) { 2791 // Undef bits can contribute to a possible optimisation if set, so 2792 // set them. 2793 SplatValue |= SplatUndef; 2794 2795 // The splat value may be something like "0x00FFFFFF", which means 0 for 2796 // the first vector value and FF for the rest, repeating. We need a mask 2797 // that will apply equally to all members of the vector, so AND all the 2798 // lanes of the constant together. 2799 EVT VT = Vector->getValueType(0); 2800 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2801 2802 // If the splat value has been compressed to a bitlength lower 2803 // than the size of the vector lane, we need to re-expand it to 2804 // the lane size. 2805 if (BitWidth > SplatBitSize) 2806 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2807 SplatBitSize < BitWidth; 2808 SplatBitSize = SplatBitSize * 2) 2809 SplatValue |= SplatValue.shl(SplatBitSize); 2810 2811 Constant = APInt::getAllOnesValue(BitWidth); 2812 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2813 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2814 } 2815 } 2816 2817 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2818 // actually legal and isn't going to get expanded, else this is a false 2819 // optimisation. 2820 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2821 Load->getValueType(0), 2822 Load->getMemoryVT()); 2823 2824 // Resize the constant to the same size as the original memory access before 2825 // extension. If it is still the AllOnesValue then this AND is completely 2826 // unneeded. 2827 Constant = 2828 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2829 2830 bool B; 2831 switch (Load->getExtensionType()) { 2832 default: B = false; break; 2833 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2834 case ISD::ZEXTLOAD: 2835 case ISD::NON_EXTLOAD: B = true; break; 2836 } 2837 2838 if (B && Constant.isAllOnesValue()) { 2839 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2840 // preserve semantics once we get rid of the AND. 2841 SDValue NewLoad(Load, 0); 2842 if (Load->getExtensionType() == ISD::EXTLOAD) { 2843 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2844 Load->getValueType(0), SDLoc(Load), 2845 Load->getChain(), Load->getBasePtr(), 2846 Load->getOffset(), Load->getMemoryVT(), 2847 Load->getMemOperand()); 2848 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2849 if (Load->getNumValues() == 3) { 2850 // PRE/POST_INC loads have 3 values. 2851 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2852 NewLoad.getValue(2) }; 2853 CombineTo(Load, To, 3, true); 2854 } else { 2855 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2856 } 2857 } 2858 2859 // Fold the AND away, taking care not to fold to the old load node if we 2860 // replaced it. 2861 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2862 2863 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2864 } 2865 } 2866 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2867 SDValue LL, LR, RL, RR, CC0, CC1; 2868 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2869 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2870 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2871 2872 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2873 LL.getValueType().isInteger()) { 2874 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2875 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2876 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2877 LR.getValueType(), LL, RL); 2878 AddToWorklist(ORNode.getNode()); 2879 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2880 } 2881 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2882 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2883 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2884 LR.getValueType(), LL, RL); 2885 AddToWorklist(ANDNode.getNode()); 2886 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2887 } 2888 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2889 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2890 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2891 LR.getValueType(), LL, RL); 2892 AddToWorklist(ORNode.getNode()); 2893 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2894 } 2895 } 2896 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2897 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2898 Op0 == Op1 && LL.getValueType().isInteger() && 2899 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2900 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2901 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2902 cast<ConstantSDNode>(RR)->isNullValue()))) { 2903 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2904 LL, DAG.getConstant(1, LL.getValueType())); 2905 AddToWorklist(ADDNode.getNode()); 2906 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2907 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2908 } 2909 // canonicalize equivalent to ll == rl 2910 if (LL == RR && LR == RL) { 2911 Op1 = ISD::getSetCCSwappedOperands(Op1); 2912 std::swap(RL, RR); 2913 } 2914 if (LL == RL && LR == RR) { 2915 bool isInteger = LL.getValueType().isInteger(); 2916 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2917 if (Result != ISD::SETCC_INVALID && 2918 (!LegalOperations || 2919 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2920 TLI.isOperationLegal(ISD::SETCC, 2921 getSetCCResultType(N0.getSimpleValueType()))))) 2922 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2923 LL, LR, Result); 2924 } 2925 } 2926 2927 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2928 if (N0.getOpcode() == N1.getOpcode()) { 2929 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2930 if (Tmp.getNode()) return Tmp; 2931 } 2932 2933 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2934 // fold (and (sra)) -> (and (srl)) when possible. 2935 if (!VT.isVector() && 2936 SimplifyDemandedBits(SDValue(N, 0))) 2937 return SDValue(N, 0); 2938 2939 // fold (zext_inreg (extload x)) -> (zextload x) 2940 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2941 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2942 EVT MemVT = LN0->getMemoryVT(); 2943 // If we zero all the possible extended bits, then we can turn this into 2944 // a zextload if we are running before legalize or the operation is legal. 2945 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2946 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2947 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2948 ((!LegalOperations && !LN0->isVolatile()) || 2949 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 2950 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2951 LN0->getChain(), LN0->getBasePtr(), 2952 MemVT, LN0->getMemOperand()); 2953 AddToWorklist(N); 2954 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2955 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2956 } 2957 } 2958 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2959 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2960 N0.hasOneUse()) { 2961 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2962 EVT MemVT = LN0->getMemoryVT(); 2963 // If we zero all the possible extended bits, then we can turn this into 2964 // a zextload if we are running before legalize or the operation is legal. 2965 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2966 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2967 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2968 ((!LegalOperations && !LN0->isVolatile()) || 2969 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 2970 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2971 LN0->getChain(), LN0->getBasePtr(), 2972 MemVT, LN0->getMemOperand()); 2973 AddToWorklist(N); 2974 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2975 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2976 } 2977 } 2978 2979 // fold (and (load x), 255) -> (zextload x, i8) 2980 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2981 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2982 if (N1C && (N0.getOpcode() == ISD::LOAD || 2983 (N0.getOpcode() == ISD::ANY_EXTEND && 2984 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2985 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2986 LoadSDNode *LN0 = HasAnyExt 2987 ? cast<LoadSDNode>(N0.getOperand(0)) 2988 : cast<LoadSDNode>(N0); 2989 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2990 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2991 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2992 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2993 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2994 EVT LoadedVT = LN0->getMemoryVT(); 2995 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2996 2997 if (ExtVT == LoadedVT && 2998 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 2999 ExtVT))) { 3000 3001 SDValue NewLoad = 3002 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3003 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3004 LN0->getMemOperand()); 3005 AddToWorklist(N); 3006 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3007 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3008 } 3009 3010 // Do not change the width of a volatile load. 3011 // Do not generate loads of non-round integer types since these can 3012 // be expensive (and would be wrong if the type is not byte sized). 3013 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3014 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3015 ExtVT))) { 3016 EVT PtrType = LN0->getOperand(1).getValueType(); 3017 3018 unsigned Alignment = LN0->getAlignment(); 3019 SDValue NewPtr = LN0->getBasePtr(); 3020 3021 // For big endian targets, we need to add an offset to the pointer 3022 // to load the correct bytes. For little endian systems, we merely 3023 // need to read fewer bytes from the same pointer. 3024 if (TLI.isBigEndian()) { 3025 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3026 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3027 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3028 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 3029 NewPtr, DAG.getConstant(PtrOff, PtrType)); 3030 Alignment = MinAlign(Alignment, PtrOff); 3031 } 3032 3033 AddToWorklist(NewPtr.getNode()); 3034 3035 SDValue Load = 3036 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3037 LN0->getChain(), NewPtr, 3038 LN0->getPointerInfo(), 3039 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3040 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3041 AddToWorklist(N); 3042 CombineTo(LN0, Load, Load.getValue(1)); 3043 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3044 } 3045 } 3046 } 3047 } 3048 3049 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3050 VT.getSizeInBits() <= 64) { 3051 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3052 APInt ADDC = ADDI->getAPIntValue(); 3053 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3054 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3055 // immediate for an add, but it is legal if its top c2 bits are set, 3056 // transform the ADD so the immediate doesn't need to be materialized 3057 // in a register. 3058 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3059 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3060 SRLI->getZExtValue()); 3061 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3062 ADDC |= Mask; 3063 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3064 SDValue NewAdd = 3065 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 3066 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 3067 CombineTo(N0.getNode(), NewAdd); 3068 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3069 } 3070 } 3071 } 3072 } 3073 } 3074 } 3075 3076 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3077 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3078 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3079 N0.getOperand(1), false); 3080 if (BSwap.getNode()) 3081 return BSwap; 3082 } 3083 3084 return SDValue(); 3085 } 3086 3087 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3088 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3089 bool DemandHighBits) { 3090 if (!LegalOperations) 3091 return SDValue(); 3092 3093 EVT VT = N->getValueType(0); 3094 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3095 return SDValue(); 3096 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3097 return SDValue(); 3098 3099 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3100 bool LookPassAnd0 = false; 3101 bool LookPassAnd1 = false; 3102 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3103 std::swap(N0, N1); 3104 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3105 std::swap(N0, N1); 3106 if (N0.getOpcode() == ISD::AND) { 3107 if (!N0.getNode()->hasOneUse()) 3108 return SDValue(); 3109 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3110 if (!N01C || N01C->getZExtValue() != 0xFF00) 3111 return SDValue(); 3112 N0 = N0.getOperand(0); 3113 LookPassAnd0 = true; 3114 } 3115 3116 if (N1.getOpcode() == ISD::AND) { 3117 if (!N1.getNode()->hasOneUse()) 3118 return SDValue(); 3119 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3120 if (!N11C || N11C->getZExtValue() != 0xFF) 3121 return SDValue(); 3122 N1 = N1.getOperand(0); 3123 LookPassAnd1 = true; 3124 } 3125 3126 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3127 std::swap(N0, N1); 3128 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3129 return SDValue(); 3130 if (!N0.getNode()->hasOneUse() || 3131 !N1.getNode()->hasOneUse()) 3132 return SDValue(); 3133 3134 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3135 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3136 if (!N01C || !N11C) 3137 return SDValue(); 3138 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3139 return SDValue(); 3140 3141 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3142 SDValue N00 = N0->getOperand(0); 3143 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3144 if (!N00.getNode()->hasOneUse()) 3145 return SDValue(); 3146 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3147 if (!N001C || N001C->getZExtValue() != 0xFF) 3148 return SDValue(); 3149 N00 = N00.getOperand(0); 3150 LookPassAnd0 = true; 3151 } 3152 3153 SDValue N10 = N1->getOperand(0); 3154 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3155 if (!N10.getNode()->hasOneUse()) 3156 return SDValue(); 3157 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3158 if (!N101C || N101C->getZExtValue() != 0xFF00) 3159 return SDValue(); 3160 N10 = N10.getOperand(0); 3161 LookPassAnd1 = true; 3162 } 3163 3164 if (N00 != N10) 3165 return SDValue(); 3166 3167 // Make sure everything beyond the low halfword gets set to zero since the SRL 3168 // 16 will clear the top bits. 3169 unsigned OpSizeInBits = VT.getSizeInBits(); 3170 if (DemandHighBits && OpSizeInBits > 16) { 3171 // If the left-shift isn't masked out then the only way this is a bswap is 3172 // if all bits beyond the low 8 are 0. In that case the entire pattern 3173 // reduces to a left shift anyway: leave it for other parts of the combiner. 3174 if (!LookPassAnd0) 3175 return SDValue(); 3176 3177 // However, if the right shift isn't masked out then it might be because 3178 // it's not needed. See if we can spot that too. 3179 if (!LookPassAnd1 && 3180 !DAG.MaskedValueIsZero( 3181 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3182 return SDValue(); 3183 } 3184 3185 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3186 if (OpSizeInBits > 16) 3187 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3188 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3189 return Res; 3190 } 3191 3192 /// Return true if the specified node is an element that makes up a 32-bit 3193 /// packed halfword byteswap. 3194 /// ((x & 0x000000ff) << 8) | 3195 /// ((x & 0x0000ff00) >> 8) | 3196 /// ((x & 0x00ff0000) << 8) | 3197 /// ((x & 0xff000000) >> 8) 3198 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3199 if (!N.getNode()->hasOneUse()) 3200 return false; 3201 3202 unsigned Opc = N.getOpcode(); 3203 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3204 return false; 3205 3206 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3207 if (!N1C) 3208 return false; 3209 3210 unsigned Num; 3211 switch (N1C->getZExtValue()) { 3212 default: 3213 return false; 3214 case 0xFF: Num = 0; break; 3215 case 0xFF00: Num = 1; break; 3216 case 0xFF0000: Num = 2; break; 3217 case 0xFF000000: Num = 3; break; 3218 } 3219 3220 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3221 SDValue N0 = N.getOperand(0); 3222 if (Opc == ISD::AND) { 3223 if (Num == 0 || Num == 2) { 3224 // (x >> 8) & 0xff 3225 // (x >> 8) & 0xff0000 3226 if (N0.getOpcode() != ISD::SRL) 3227 return false; 3228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3229 if (!C || C->getZExtValue() != 8) 3230 return false; 3231 } else { 3232 // (x << 8) & 0xff00 3233 // (x << 8) & 0xff000000 3234 if (N0.getOpcode() != ISD::SHL) 3235 return false; 3236 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3237 if (!C || C->getZExtValue() != 8) 3238 return false; 3239 } 3240 } else if (Opc == ISD::SHL) { 3241 // (x & 0xff) << 8 3242 // (x & 0xff0000) << 8 3243 if (Num != 0 && Num != 2) 3244 return false; 3245 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3246 if (!C || C->getZExtValue() != 8) 3247 return false; 3248 } else { // Opc == ISD::SRL 3249 // (x & 0xff00) >> 8 3250 // (x & 0xff000000) >> 8 3251 if (Num != 1 && Num != 3) 3252 return false; 3253 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3254 if (!C || C->getZExtValue() != 8) 3255 return false; 3256 } 3257 3258 if (Parts[Num]) 3259 return false; 3260 3261 Parts[Num] = N0.getOperand(0).getNode(); 3262 return true; 3263 } 3264 3265 /// Match a 32-bit packed halfword bswap. That is 3266 /// ((x & 0x000000ff) << 8) | 3267 /// ((x & 0x0000ff00) >> 8) | 3268 /// ((x & 0x00ff0000) << 8) | 3269 /// ((x & 0xff000000) >> 8) 3270 /// => (rotl (bswap x), 16) 3271 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3272 if (!LegalOperations) 3273 return SDValue(); 3274 3275 EVT VT = N->getValueType(0); 3276 if (VT != MVT::i32) 3277 return SDValue(); 3278 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3279 return SDValue(); 3280 3281 // Look for either 3282 // (or (or (and), (and)), (or (and), (and))) 3283 // (or (or (or (and), (and)), (and)), (and)) 3284 if (N0.getOpcode() != ISD::OR) 3285 return SDValue(); 3286 SDValue N00 = N0.getOperand(0); 3287 SDValue N01 = N0.getOperand(1); 3288 SDNode *Parts[4] = {}; 3289 3290 if (N1.getOpcode() == ISD::OR && 3291 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3292 // (or (or (and), (and)), (or (and), (and))) 3293 SDValue N000 = N00.getOperand(0); 3294 if (!isBSwapHWordElement(N000, Parts)) 3295 return SDValue(); 3296 3297 SDValue N001 = N00.getOperand(1); 3298 if (!isBSwapHWordElement(N001, Parts)) 3299 return SDValue(); 3300 SDValue N010 = N01.getOperand(0); 3301 if (!isBSwapHWordElement(N010, Parts)) 3302 return SDValue(); 3303 SDValue N011 = N01.getOperand(1); 3304 if (!isBSwapHWordElement(N011, Parts)) 3305 return SDValue(); 3306 } else { 3307 // (or (or (or (and), (and)), (and)), (and)) 3308 if (!isBSwapHWordElement(N1, Parts)) 3309 return SDValue(); 3310 if (!isBSwapHWordElement(N01, Parts)) 3311 return SDValue(); 3312 if (N00.getOpcode() != ISD::OR) 3313 return SDValue(); 3314 SDValue N000 = N00.getOperand(0); 3315 if (!isBSwapHWordElement(N000, Parts)) 3316 return SDValue(); 3317 SDValue N001 = N00.getOperand(1); 3318 if (!isBSwapHWordElement(N001, Parts)) 3319 return SDValue(); 3320 } 3321 3322 // Make sure the parts are all coming from the same node. 3323 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3324 return SDValue(); 3325 3326 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3327 SDValue(Parts[0],0)); 3328 3329 // Result of the bswap should be rotated by 16. If it's not legal, then 3330 // do (x << 16) | (x >> 16). 3331 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3332 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3333 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3334 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3335 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3336 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3337 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3338 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3339 } 3340 3341 SDValue DAGCombiner::visitOR(SDNode *N) { 3342 SDValue N0 = N->getOperand(0); 3343 SDValue N1 = N->getOperand(1); 3344 EVT VT = N1.getValueType(); 3345 3346 // fold vector ops 3347 if (VT.isVector()) { 3348 SDValue FoldedVOp = SimplifyVBinOp(N); 3349 if (FoldedVOp.getNode()) return FoldedVOp; 3350 3351 // fold (or x, 0) -> x, vector edition 3352 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3353 return N1; 3354 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3355 return N0; 3356 3357 // fold (or x, -1) -> -1, vector edition 3358 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3359 // do not return N0, because undef node may exist in N0 3360 return DAG.getConstant( 3361 APInt::getAllOnesValue( 3362 N0.getValueType().getScalarType().getSizeInBits()), 3363 N0.getValueType()); 3364 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3365 // do not return N1, because undef node may exist in N1 3366 return DAG.getConstant( 3367 APInt::getAllOnesValue( 3368 N1.getValueType().getScalarType().getSizeInBits()), 3369 N1.getValueType()); 3370 3371 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3372 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3373 // Do this only if the resulting shuffle is legal. 3374 if (isa<ShuffleVectorSDNode>(N0) && 3375 isa<ShuffleVectorSDNode>(N1) && 3376 // Avoid folding a node with illegal type. 3377 TLI.isTypeLegal(VT) && 3378 N0->getOperand(1) == N1->getOperand(1) && 3379 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3380 bool CanFold = true; 3381 unsigned NumElts = VT.getVectorNumElements(); 3382 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3383 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3384 // We construct two shuffle masks: 3385 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3386 // and N1 as the second operand. 3387 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3388 // and N0 as the second operand. 3389 // We do this because OR is commutable and therefore there might be 3390 // two ways to fold this node into a shuffle. 3391 SmallVector<int,4> Mask1; 3392 SmallVector<int,4> Mask2; 3393 3394 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3395 int M0 = SV0->getMaskElt(i); 3396 int M1 = SV1->getMaskElt(i); 3397 3398 // Both shuffle indexes are undef. Propagate Undef. 3399 if (M0 < 0 && M1 < 0) { 3400 Mask1.push_back(M0); 3401 Mask2.push_back(M0); 3402 continue; 3403 } 3404 3405 if (M0 < 0 || M1 < 0 || 3406 (M0 < (int)NumElts && M1 < (int)NumElts) || 3407 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3408 CanFold = false; 3409 break; 3410 } 3411 3412 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3413 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3414 } 3415 3416 if (CanFold) { 3417 // Fold this sequence only if the resulting shuffle is 'legal'. 3418 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3419 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3420 N1->getOperand(0), &Mask1[0]); 3421 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3422 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3423 N0->getOperand(0), &Mask2[0]); 3424 } 3425 } 3426 } 3427 3428 // fold (or x, undef) -> -1 3429 if (!LegalOperations && 3430 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3431 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3432 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3433 } 3434 // fold (or c1, c2) -> c1|c2 3435 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3436 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3437 if (N0C && N1C) 3438 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3439 // canonicalize constant to RHS 3440 if (N0C && !N1C) 3441 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3442 // fold (or x, 0) -> x 3443 if (N1C && N1C->isNullValue()) 3444 return N0; 3445 // fold (or x, -1) -> -1 3446 if (N1C && N1C->isAllOnesValue()) 3447 return N1; 3448 // fold (or x, c) -> c iff (x & ~c) == 0 3449 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3450 return N1; 3451 3452 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3453 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3454 if (BSwap.getNode()) 3455 return BSwap; 3456 BSwap = MatchBSwapHWordLow(N, N0, N1); 3457 if (BSwap.getNode()) 3458 return BSwap; 3459 3460 // reassociate or 3461 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3462 if (ROR.getNode()) 3463 return ROR; 3464 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3465 // iff (c1 & c2) == 0. 3466 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3467 isa<ConstantSDNode>(N0.getOperand(1))) { 3468 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3469 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3470 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)) 3471 return DAG.getNode( 3472 ISD::AND, SDLoc(N), VT, 3473 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3474 return SDValue(); 3475 } 3476 } 3477 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3478 SDValue LL, LR, RL, RR, CC0, CC1; 3479 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3480 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3481 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3482 3483 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3484 LL.getValueType().isInteger()) { 3485 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3486 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3487 if (cast<ConstantSDNode>(LR)->isNullValue() && 3488 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3489 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3490 LR.getValueType(), LL, RL); 3491 AddToWorklist(ORNode.getNode()); 3492 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3493 } 3494 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3495 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3496 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3497 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3498 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3499 LR.getValueType(), LL, RL); 3500 AddToWorklist(ANDNode.getNode()); 3501 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3502 } 3503 } 3504 // canonicalize equivalent to ll == rl 3505 if (LL == RR && LR == RL) { 3506 Op1 = ISD::getSetCCSwappedOperands(Op1); 3507 std::swap(RL, RR); 3508 } 3509 if (LL == RL && LR == RR) { 3510 bool isInteger = LL.getValueType().isInteger(); 3511 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3512 if (Result != ISD::SETCC_INVALID && 3513 (!LegalOperations || 3514 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3515 TLI.isOperationLegal(ISD::SETCC, 3516 getSetCCResultType(N0.getValueType()))))) 3517 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3518 LL, LR, Result); 3519 } 3520 } 3521 3522 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3523 if (N0.getOpcode() == N1.getOpcode()) { 3524 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3525 if (Tmp.getNode()) return Tmp; 3526 } 3527 3528 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3529 if (N0.getOpcode() == ISD::AND && 3530 N1.getOpcode() == ISD::AND && 3531 N0.getOperand(1).getOpcode() == ISD::Constant && 3532 N1.getOperand(1).getOpcode() == ISD::Constant && 3533 // Don't increase # computations. 3534 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3535 // We can only do this xform if we know that bits from X that are set in C2 3536 // but not in C1 are already zero. Likewise for Y. 3537 const APInt &LHSMask = 3538 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3539 const APInt &RHSMask = 3540 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3541 3542 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3543 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3544 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3545 N0.getOperand(0), N1.getOperand(0)); 3546 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3547 DAG.getConstant(LHSMask | RHSMask, VT)); 3548 } 3549 } 3550 3551 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3552 if (N0.getOpcode() == ISD::AND && 3553 N1.getOpcode() == ISD::AND && 3554 N0.getOperand(0) == N1.getOperand(0) && 3555 // Don't increase # computations. 3556 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3557 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3558 N0.getOperand(1), N1.getOperand(1)); 3559 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X); 3560 } 3561 3562 // See if this is some rotate idiom. 3563 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3564 return SDValue(Rot, 0); 3565 3566 // Simplify the operands using demanded-bits information. 3567 if (!VT.isVector() && 3568 SimplifyDemandedBits(SDValue(N, 0))) 3569 return SDValue(N, 0); 3570 3571 return SDValue(); 3572 } 3573 3574 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3575 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3576 if (Op.getOpcode() == ISD::AND) { 3577 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3578 Mask = Op.getOperand(1); 3579 Op = Op.getOperand(0); 3580 } else { 3581 return false; 3582 } 3583 } 3584 3585 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3586 Shift = Op; 3587 return true; 3588 } 3589 3590 return false; 3591 } 3592 3593 // Return true if we can prove that, whenever Neg and Pos are both in the 3594 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3595 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3596 // 3597 // (or (shift1 X, Neg), (shift2 X, Pos)) 3598 // 3599 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3600 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3601 // to consider shift amounts with defined behavior. 3602 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3603 // If OpSize is a power of 2 then: 3604 // 3605 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3606 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3607 // 3608 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3609 // for the stronger condition: 3610 // 3611 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3612 // 3613 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3614 // we can just replace Neg with Neg' for the rest of the function. 3615 // 3616 // In other cases we check for the even stronger condition: 3617 // 3618 // Neg == OpSize - Pos [B] 3619 // 3620 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3621 // behavior if Pos == 0 (and consequently Neg == OpSize). 3622 // 3623 // We could actually use [A] whenever OpSize is a power of 2, but the 3624 // only extra cases that it would match are those uninteresting ones 3625 // where Neg and Pos are never in range at the same time. E.g. for 3626 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3627 // as well as (sub 32, Pos), but: 3628 // 3629 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3630 // 3631 // always invokes undefined behavior for 32-bit X. 3632 // 3633 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3634 unsigned MaskLoBits = 0; 3635 if (Neg.getOpcode() == ISD::AND && 3636 isPowerOf2_64(OpSize) && 3637 Neg.getOperand(1).getOpcode() == ISD::Constant && 3638 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3639 Neg = Neg.getOperand(0); 3640 MaskLoBits = Log2_64(OpSize); 3641 } 3642 3643 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3644 if (Neg.getOpcode() != ISD::SUB) 3645 return 0; 3646 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3647 if (!NegC) 3648 return 0; 3649 SDValue NegOp1 = Neg.getOperand(1); 3650 3651 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3652 // Pos'. The truncation is redundant for the purpose of the equality. 3653 if (MaskLoBits && 3654 Pos.getOpcode() == ISD::AND && 3655 Pos.getOperand(1).getOpcode() == ISD::Constant && 3656 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3657 Pos = Pos.getOperand(0); 3658 3659 // The condition we need is now: 3660 // 3661 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3662 // 3663 // If NegOp1 == Pos then we need: 3664 // 3665 // OpSize & Mask == NegC & Mask 3666 // 3667 // (because "x & Mask" is a truncation and distributes through subtraction). 3668 APInt Width; 3669 if (Pos == NegOp1) 3670 Width = NegC->getAPIntValue(); 3671 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3672 // Then the condition we want to prove becomes: 3673 // 3674 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3675 // 3676 // which, again because "x & Mask" is a truncation, becomes: 3677 // 3678 // NegC & Mask == (OpSize - PosC) & Mask 3679 // OpSize & Mask == (NegC + PosC) & Mask 3680 else if (Pos.getOpcode() == ISD::ADD && 3681 Pos.getOperand(0) == NegOp1 && 3682 Pos.getOperand(1).getOpcode() == ISD::Constant) 3683 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3684 NegC->getAPIntValue()); 3685 else 3686 return false; 3687 3688 // Now we just need to check that OpSize & Mask == Width & Mask. 3689 if (MaskLoBits) 3690 // Opsize & Mask is 0 since Mask is Opsize - 1. 3691 return Width.getLoBits(MaskLoBits) == 0; 3692 return Width == OpSize; 3693 } 3694 3695 // A subroutine of MatchRotate used once we have found an OR of two opposite 3696 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3697 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3698 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3699 // Neg with outer conversions stripped away. 3700 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3701 SDValue Neg, SDValue InnerPos, 3702 SDValue InnerNeg, unsigned PosOpcode, 3703 unsigned NegOpcode, SDLoc DL) { 3704 // fold (or (shl x, (*ext y)), 3705 // (srl x, (*ext (sub 32, y)))) -> 3706 // (rotl x, y) or (rotr x, (sub 32, y)) 3707 // 3708 // fold (or (shl x, (*ext (sub 32, y))), 3709 // (srl x, (*ext y))) -> 3710 // (rotr x, y) or (rotl x, (sub 32, y)) 3711 EVT VT = Shifted.getValueType(); 3712 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3713 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3714 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3715 HasPos ? Pos : Neg).getNode(); 3716 } 3717 3718 return nullptr; 3719 } 3720 3721 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3722 // idioms for rotate, and if the target supports rotation instructions, generate 3723 // a rot[lr]. 3724 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3725 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3726 EVT VT = LHS.getValueType(); 3727 if (!TLI.isTypeLegal(VT)) return nullptr; 3728 3729 // The target must have at least one rotate flavor. 3730 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3731 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3732 if (!HasROTL && !HasROTR) return nullptr; 3733 3734 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3735 SDValue LHSShift; // The shift. 3736 SDValue LHSMask; // AND value if any. 3737 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3738 return nullptr; // Not part of a rotate. 3739 3740 SDValue RHSShift; // The shift. 3741 SDValue RHSMask; // AND value if any. 3742 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3743 return nullptr; // Not part of a rotate. 3744 3745 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3746 return nullptr; // Not shifting the same value. 3747 3748 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3749 return nullptr; // Shifts must disagree. 3750 3751 // Canonicalize shl to left side in a shl/srl pair. 3752 if (RHSShift.getOpcode() == ISD::SHL) { 3753 std::swap(LHS, RHS); 3754 std::swap(LHSShift, RHSShift); 3755 std::swap(LHSMask , RHSMask ); 3756 } 3757 3758 unsigned OpSizeInBits = VT.getSizeInBits(); 3759 SDValue LHSShiftArg = LHSShift.getOperand(0); 3760 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3761 SDValue RHSShiftArg = RHSShift.getOperand(0); 3762 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3763 3764 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3765 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3766 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3767 RHSShiftAmt.getOpcode() == ISD::Constant) { 3768 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3769 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3770 if ((LShVal + RShVal) != OpSizeInBits) 3771 return nullptr; 3772 3773 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3774 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3775 3776 // If there is an AND of either shifted operand, apply it to the result. 3777 if (LHSMask.getNode() || RHSMask.getNode()) { 3778 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3779 3780 if (LHSMask.getNode()) { 3781 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3782 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3783 } 3784 if (RHSMask.getNode()) { 3785 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3786 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3787 } 3788 3789 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3790 } 3791 3792 return Rot.getNode(); 3793 } 3794 3795 // If there is a mask here, and we have a variable shift, we can't be sure 3796 // that we're masking out the right stuff. 3797 if (LHSMask.getNode() || RHSMask.getNode()) 3798 return nullptr; 3799 3800 // If the shift amount is sign/zext/any-extended just peel it off. 3801 SDValue LExtOp0 = LHSShiftAmt; 3802 SDValue RExtOp0 = RHSShiftAmt; 3803 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3804 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3805 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3806 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3807 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3808 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3809 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3810 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3811 LExtOp0 = LHSShiftAmt.getOperand(0); 3812 RExtOp0 = RHSShiftAmt.getOperand(0); 3813 } 3814 3815 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3816 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3817 if (TryL) 3818 return TryL; 3819 3820 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3821 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3822 if (TryR) 3823 return TryR; 3824 3825 return nullptr; 3826 } 3827 3828 SDValue DAGCombiner::visitXOR(SDNode *N) { 3829 SDValue N0 = N->getOperand(0); 3830 SDValue N1 = N->getOperand(1); 3831 EVT VT = N0.getValueType(); 3832 3833 // fold vector ops 3834 if (VT.isVector()) { 3835 SDValue FoldedVOp = SimplifyVBinOp(N); 3836 if (FoldedVOp.getNode()) return FoldedVOp; 3837 3838 // fold (xor x, 0) -> x, vector edition 3839 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3840 return N1; 3841 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3842 return N0; 3843 } 3844 3845 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3846 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3847 return DAG.getConstant(0, VT); 3848 // fold (xor x, undef) -> undef 3849 if (N0.getOpcode() == ISD::UNDEF) 3850 return N0; 3851 if (N1.getOpcode() == ISD::UNDEF) 3852 return N1; 3853 // fold (xor c1, c2) -> c1^c2 3854 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3855 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3856 if (N0C && N1C) 3857 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3858 // canonicalize constant to RHS 3859 if (N0C && !N1C) 3860 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3861 // fold (xor x, 0) -> x 3862 if (N1C && N1C->isNullValue()) 3863 return N0; 3864 // reassociate xor 3865 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3866 if (RXOR.getNode()) 3867 return RXOR; 3868 3869 // fold !(x cc y) -> (x !cc y) 3870 SDValue LHS, RHS, CC; 3871 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3872 bool isInt = LHS.getValueType().isInteger(); 3873 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3874 isInt); 3875 3876 if (!LegalOperations || 3877 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3878 switch (N0.getOpcode()) { 3879 default: 3880 llvm_unreachable("Unhandled SetCC Equivalent!"); 3881 case ISD::SETCC: 3882 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3883 case ISD::SELECT_CC: 3884 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3885 N0.getOperand(3), NotCC); 3886 } 3887 } 3888 } 3889 3890 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3891 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3892 N0.getNode()->hasOneUse() && 3893 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3894 SDValue V = N0.getOperand(0); 3895 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3896 DAG.getConstant(1, V.getValueType())); 3897 AddToWorklist(V.getNode()); 3898 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3899 } 3900 3901 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3902 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3903 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3904 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3905 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3906 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3907 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3908 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3909 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3910 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3911 } 3912 } 3913 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3914 if (N1C && N1C->isAllOnesValue() && 3915 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3916 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3917 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3918 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3919 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3920 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3921 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3922 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3923 } 3924 } 3925 // fold (xor (and x, y), y) -> (and (not x), y) 3926 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3927 N0->getOperand(1) == N1) { 3928 SDValue X = N0->getOperand(0); 3929 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3930 AddToWorklist(NotX.getNode()); 3931 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3932 } 3933 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3934 if (N1C && N0.getOpcode() == ISD::XOR) { 3935 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3936 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3937 if (N00C) 3938 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3939 DAG.getConstant(N1C->getAPIntValue() ^ 3940 N00C->getAPIntValue(), VT)); 3941 if (N01C) 3942 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3943 DAG.getConstant(N1C->getAPIntValue() ^ 3944 N01C->getAPIntValue(), VT)); 3945 } 3946 // fold (xor x, x) -> 0 3947 if (N0 == N1) 3948 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3949 3950 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3951 if (N0.getOpcode() == N1.getOpcode()) { 3952 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3953 if (Tmp.getNode()) return Tmp; 3954 } 3955 3956 // Simplify the expression using non-local knowledge. 3957 if (!VT.isVector() && 3958 SimplifyDemandedBits(SDValue(N, 0))) 3959 return SDValue(N, 0); 3960 3961 return SDValue(); 3962 } 3963 3964 /// Handle transforms common to the three shifts, when the shift amount is a 3965 /// constant. 3966 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 3967 // We can't and shouldn't fold opaque constants. 3968 if (Amt->isOpaque()) 3969 return SDValue(); 3970 3971 SDNode *LHS = N->getOperand(0).getNode(); 3972 if (!LHS->hasOneUse()) return SDValue(); 3973 3974 // We want to pull some binops through shifts, so that we have (and (shift)) 3975 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3976 // thing happens with address calculations, so it's important to canonicalize 3977 // it. 3978 bool HighBitSet = false; // Can we transform this if the high bit is set? 3979 3980 switch (LHS->getOpcode()) { 3981 default: return SDValue(); 3982 case ISD::OR: 3983 case ISD::XOR: 3984 HighBitSet = false; // We can only transform sra if the high bit is clear. 3985 break; 3986 case ISD::AND: 3987 HighBitSet = true; // We can only transform sra if the high bit is set. 3988 break; 3989 case ISD::ADD: 3990 if (N->getOpcode() != ISD::SHL) 3991 return SDValue(); // only shl(add) not sr[al](add). 3992 HighBitSet = false; // We can only transform sra if the high bit is clear. 3993 break; 3994 } 3995 3996 // We require the RHS of the binop to be a constant and not opaque as well. 3997 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3998 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 3999 4000 // FIXME: disable this unless the input to the binop is a shift by a constant. 4001 // If it is not a shift, it pessimizes some common cases like: 4002 // 4003 // void foo(int *X, int i) { X[i & 1235] = 1; } 4004 // int bar(int *X, int i) { return X[i & 255]; } 4005 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4006 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4007 BinOpLHSVal->getOpcode() != ISD::SRA && 4008 BinOpLHSVal->getOpcode() != ISD::SRL) || 4009 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4010 return SDValue(); 4011 4012 EVT VT = N->getValueType(0); 4013 4014 // If this is a signed shift right, and the high bit is modified by the 4015 // logical operation, do not perform the transformation. The highBitSet 4016 // boolean indicates the value of the high bit of the constant which would 4017 // cause it to be modified for this operation. 4018 if (N->getOpcode() == ISD::SRA) { 4019 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4020 if (BinOpRHSSignSet != HighBitSet) 4021 return SDValue(); 4022 } 4023 4024 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4025 return SDValue(); 4026 4027 // Fold the constants, shifting the binop RHS by the shift amount. 4028 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4029 N->getValueType(0), 4030 LHS->getOperand(1), N->getOperand(1)); 4031 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4032 4033 // Create the new shift. 4034 SDValue NewShift = DAG.getNode(N->getOpcode(), 4035 SDLoc(LHS->getOperand(0)), 4036 VT, LHS->getOperand(0), N->getOperand(1)); 4037 4038 // Create the new binop. 4039 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4040 } 4041 4042 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4043 assert(N->getOpcode() == ISD::TRUNCATE); 4044 assert(N->getOperand(0).getOpcode() == ISD::AND); 4045 4046 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4047 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4048 SDValue N01 = N->getOperand(0).getOperand(1); 4049 4050 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4051 EVT TruncVT = N->getValueType(0); 4052 SDValue N00 = N->getOperand(0).getOperand(0); 4053 APInt TruncC = N01C->getAPIntValue(); 4054 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4055 4056 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 4057 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00), 4058 DAG.getConstant(TruncC, TruncVT)); 4059 } 4060 } 4061 4062 return SDValue(); 4063 } 4064 4065 SDValue DAGCombiner::visitRotate(SDNode *N) { 4066 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4067 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4068 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4069 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4070 if (NewOp1.getNode()) 4071 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4072 N->getOperand(0), NewOp1); 4073 } 4074 return SDValue(); 4075 } 4076 4077 SDValue DAGCombiner::visitSHL(SDNode *N) { 4078 SDValue N0 = N->getOperand(0); 4079 SDValue N1 = N->getOperand(1); 4080 EVT VT = N0.getValueType(); 4081 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4082 4083 // fold vector ops 4084 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4085 if (VT.isVector()) { 4086 SDValue FoldedVOp = SimplifyVBinOp(N); 4087 if (FoldedVOp.getNode()) return FoldedVOp; 4088 4089 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4090 // If setcc produces all-one true value then: 4091 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4092 if (N1CV && N1CV->isConstant()) { 4093 if (N0.getOpcode() == ISD::AND) { 4094 SDValue N00 = N0->getOperand(0); 4095 SDValue N01 = N0->getOperand(1); 4096 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4097 4098 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4099 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4100 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4101 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV)) 4102 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4103 } 4104 } else { 4105 N1C = isConstOrConstSplat(N1); 4106 } 4107 } 4108 } 4109 4110 // fold (shl c1, c2) -> c1<<c2 4111 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4112 if (N0C && N1C) 4113 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 4114 // fold (shl 0, x) -> 0 4115 if (N0C && N0C->isNullValue()) 4116 return N0; 4117 // fold (shl x, c >= size(x)) -> undef 4118 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4119 return DAG.getUNDEF(VT); 4120 // fold (shl x, 0) -> x 4121 if (N1C && N1C->isNullValue()) 4122 return N0; 4123 // fold (shl undef, x) -> 0 4124 if (N0.getOpcode() == ISD::UNDEF) 4125 return DAG.getConstant(0, VT); 4126 // if (shl x, c) is known to be zero, return 0 4127 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4128 APInt::getAllOnesValue(OpSizeInBits))) 4129 return DAG.getConstant(0, VT); 4130 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4131 if (N1.getOpcode() == ISD::TRUNCATE && 4132 N1.getOperand(0).getOpcode() == ISD::AND) { 4133 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4134 if (NewOp1.getNode()) 4135 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4136 } 4137 4138 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4139 return SDValue(N, 0); 4140 4141 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4142 if (N1C && N0.getOpcode() == ISD::SHL) { 4143 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4144 uint64_t c1 = N0C1->getZExtValue(); 4145 uint64_t c2 = N1C->getZExtValue(); 4146 if (c1 + c2 >= OpSizeInBits) 4147 return DAG.getConstant(0, VT); 4148 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4149 DAG.getConstant(c1 + c2, N1.getValueType())); 4150 } 4151 } 4152 4153 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4154 // For this to be valid, the second form must not preserve any of the bits 4155 // that are shifted out by the inner shift in the first form. This means 4156 // the outer shift size must be >= the number of bits added by the ext. 4157 // As a corollary, we don't care what kind of ext it is. 4158 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4159 N0.getOpcode() == ISD::ANY_EXTEND || 4160 N0.getOpcode() == ISD::SIGN_EXTEND) && 4161 N0.getOperand(0).getOpcode() == ISD::SHL) { 4162 SDValue N0Op0 = N0.getOperand(0); 4163 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4164 uint64_t c1 = N0Op0C1->getZExtValue(); 4165 uint64_t c2 = N1C->getZExtValue(); 4166 EVT InnerShiftVT = N0Op0.getValueType(); 4167 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4168 if (c2 >= OpSizeInBits - InnerShiftSize) { 4169 if (c1 + c2 >= OpSizeInBits) 4170 return DAG.getConstant(0, VT); 4171 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 4172 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 4173 N0Op0->getOperand(0)), 4174 DAG.getConstant(c1 + c2, N1.getValueType())); 4175 } 4176 } 4177 } 4178 4179 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4180 // Only fold this if the inner zext has no other uses to avoid increasing 4181 // the total number of instructions. 4182 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4183 N0.getOperand(0).getOpcode() == ISD::SRL) { 4184 SDValue N0Op0 = N0.getOperand(0); 4185 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4186 uint64_t c1 = N0Op0C1->getZExtValue(); 4187 if (c1 < VT.getScalarSizeInBits()) { 4188 uint64_t c2 = N1C->getZExtValue(); 4189 if (c1 == c2) { 4190 SDValue NewOp0 = N0.getOperand(0); 4191 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4192 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 4193 NewOp0, DAG.getConstant(c2, CountVT)); 4194 AddToWorklist(NewSHL.getNode()); 4195 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4196 } 4197 } 4198 } 4199 } 4200 4201 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4202 // (and (srl x, (sub c1, c2), MASK) 4203 // Only fold this if the inner shift has no other uses -- if it does, folding 4204 // this will increase the total number of instructions. 4205 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4206 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4207 uint64_t c1 = N0C1->getZExtValue(); 4208 if (c1 < OpSizeInBits) { 4209 uint64_t c2 = N1C->getZExtValue(); 4210 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4211 SDValue Shift; 4212 if (c2 > c1) { 4213 Mask = Mask.shl(c2 - c1); 4214 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4215 DAG.getConstant(c2 - c1, N1.getValueType())); 4216 } else { 4217 Mask = Mask.lshr(c1 - c2); 4218 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4219 DAG.getConstant(c1 - c2, N1.getValueType())); 4220 } 4221 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 4222 DAG.getConstant(Mask, VT)); 4223 } 4224 } 4225 } 4226 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4227 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4228 unsigned BitSize = VT.getScalarSizeInBits(); 4229 SDValue HiBitsMask = 4230 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4231 BitSize - N1C->getZExtValue()), VT); 4232 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4233 HiBitsMask); 4234 } 4235 4236 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4237 // Variant of version done on multiply, except mul by a power of 2 is turned 4238 // into a shift. 4239 APInt Val; 4240 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4241 (isa<ConstantSDNode>(N0.getOperand(1)) || 4242 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4243 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4244 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4245 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4246 } 4247 4248 if (N1C) { 4249 SDValue NewSHL = visitShiftByConstant(N, N1C); 4250 if (NewSHL.getNode()) 4251 return NewSHL; 4252 } 4253 4254 return SDValue(); 4255 } 4256 4257 SDValue DAGCombiner::visitSRA(SDNode *N) { 4258 SDValue N0 = N->getOperand(0); 4259 SDValue N1 = N->getOperand(1); 4260 EVT VT = N0.getValueType(); 4261 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4262 4263 // fold vector ops 4264 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4265 if (VT.isVector()) { 4266 SDValue FoldedVOp = SimplifyVBinOp(N); 4267 if (FoldedVOp.getNode()) return FoldedVOp; 4268 4269 N1C = isConstOrConstSplat(N1); 4270 } 4271 4272 // fold (sra c1, c2) -> (sra c1, c2) 4273 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4274 if (N0C && N1C) 4275 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4276 // fold (sra 0, x) -> 0 4277 if (N0C && N0C->isNullValue()) 4278 return N0; 4279 // fold (sra -1, x) -> -1 4280 if (N0C && N0C->isAllOnesValue()) 4281 return N0; 4282 // fold (sra x, (setge c, size(x))) -> undef 4283 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4284 return DAG.getUNDEF(VT); 4285 // fold (sra x, 0) -> x 4286 if (N1C && N1C->isNullValue()) 4287 return N0; 4288 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4289 // sext_inreg. 4290 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4291 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4292 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4293 if (VT.isVector()) 4294 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4295 ExtVT, VT.getVectorNumElements()); 4296 if ((!LegalOperations || 4297 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4298 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4299 N0.getOperand(0), DAG.getValueType(ExtVT)); 4300 } 4301 4302 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4303 if (N1C && N0.getOpcode() == ISD::SRA) { 4304 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4305 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4306 if (Sum >= OpSizeInBits) 4307 Sum = OpSizeInBits - 1; 4308 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4309 DAG.getConstant(Sum, N1.getValueType())); 4310 } 4311 } 4312 4313 // fold (sra (shl X, m), (sub result_size, n)) 4314 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4315 // result_size - n != m. 4316 // If truncate is free for the target sext(shl) is likely to result in better 4317 // code. 4318 if (N0.getOpcode() == ISD::SHL && N1C) { 4319 // Get the two constanst of the shifts, CN0 = m, CN = n. 4320 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4321 if (N01C) { 4322 LLVMContext &Ctx = *DAG.getContext(); 4323 // Determine what the truncate's result bitsize and type would be. 4324 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4325 4326 if (VT.isVector()) 4327 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4328 4329 // Determine the residual right-shift amount. 4330 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4331 4332 // If the shift is not a no-op (in which case this should be just a sign 4333 // extend already), the truncated to type is legal, sign_extend is legal 4334 // on that type, and the truncate to that type is both legal and free, 4335 // perform the transform. 4336 if ((ShiftAmt > 0) && 4337 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4338 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4339 TLI.isTruncateFree(VT, TruncVT)) { 4340 4341 SDValue Amt = DAG.getConstant(ShiftAmt, 4342 getShiftAmountTy(N0.getOperand(0).getValueType())); 4343 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4344 N0.getOperand(0), Amt); 4345 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4346 Shift); 4347 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4348 N->getValueType(0), Trunc); 4349 } 4350 } 4351 } 4352 4353 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4354 if (N1.getOpcode() == ISD::TRUNCATE && 4355 N1.getOperand(0).getOpcode() == ISD::AND) { 4356 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4357 if (NewOp1.getNode()) 4358 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4359 } 4360 4361 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4362 // if c1 is equal to the number of bits the trunc removes 4363 if (N0.getOpcode() == ISD::TRUNCATE && 4364 (N0.getOperand(0).getOpcode() == ISD::SRL || 4365 N0.getOperand(0).getOpcode() == ISD::SRA) && 4366 N0.getOperand(0).hasOneUse() && 4367 N0.getOperand(0).getOperand(1).hasOneUse() && 4368 N1C) { 4369 SDValue N0Op0 = N0.getOperand(0); 4370 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4371 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4372 EVT LargeVT = N0Op0.getValueType(); 4373 4374 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4375 SDValue Amt = 4376 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), 4377 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4378 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4379 N0Op0.getOperand(0), Amt); 4380 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4381 } 4382 } 4383 } 4384 4385 // Simplify, based on bits shifted out of the LHS. 4386 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4387 return SDValue(N, 0); 4388 4389 4390 // If the sign bit is known to be zero, switch this to a SRL. 4391 if (DAG.SignBitIsZero(N0)) 4392 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4393 4394 if (N1C) { 4395 SDValue NewSRA = visitShiftByConstant(N, N1C); 4396 if (NewSRA.getNode()) 4397 return NewSRA; 4398 } 4399 4400 return SDValue(); 4401 } 4402 4403 SDValue DAGCombiner::visitSRL(SDNode *N) { 4404 SDValue N0 = N->getOperand(0); 4405 SDValue N1 = N->getOperand(1); 4406 EVT VT = N0.getValueType(); 4407 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4408 4409 // fold vector ops 4410 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4411 if (VT.isVector()) { 4412 SDValue FoldedVOp = SimplifyVBinOp(N); 4413 if (FoldedVOp.getNode()) return FoldedVOp; 4414 4415 N1C = isConstOrConstSplat(N1); 4416 } 4417 4418 // fold (srl c1, c2) -> c1 >>u c2 4419 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4420 if (N0C && N1C) 4421 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4422 // fold (srl 0, x) -> 0 4423 if (N0C && N0C->isNullValue()) 4424 return N0; 4425 // fold (srl x, c >= size(x)) -> undef 4426 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4427 return DAG.getUNDEF(VT); 4428 // fold (srl x, 0) -> x 4429 if (N1C && N1C->isNullValue()) 4430 return N0; 4431 // if (srl x, c) is known to be zero, return 0 4432 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4433 APInt::getAllOnesValue(OpSizeInBits))) 4434 return DAG.getConstant(0, VT); 4435 4436 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4437 if (N1C && N0.getOpcode() == ISD::SRL) { 4438 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4439 uint64_t c1 = N01C->getZExtValue(); 4440 uint64_t c2 = N1C->getZExtValue(); 4441 if (c1 + c2 >= OpSizeInBits) 4442 return DAG.getConstant(0, VT); 4443 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4444 DAG.getConstant(c1 + c2, N1.getValueType())); 4445 } 4446 } 4447 4448 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4449 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4450 N0.getOperand(0).getOpcode() == ISD::SRL && 4451 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4452 uint64_t c1 = 4453 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4454 uint64_t c2 = N1C->getZExtValue(); 4455 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4456 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4457 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4458 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4459 if (c1 + OpSizeInBits == InnerShiftSize) { 4460 if (c1 + c2 >= InnerShiftSize) 4461 return DAG.getConstant(0, VT); 4462 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4463 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4464 N0.getOperand(0)->getOperand(0), 4465 DAG.getConstant(c1 + c2, ShiftCountVT))); 4466 } 4467 } 4468 4469 // fold (srl (shl x, c), c) -> (and x, cst2) 4470 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4471 unsigned BitSize = N0.getScalarValueSizeInBits(); 4472 if (BitSize <= 64) { 4473 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4474 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4475 DAG.getConstant(~0ULL >> ShAmt, VT)); 4476 } 4477 } 4478 4479 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4480 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4481 // Shifting in all undef bits? 4482 EVT SmallVT = N0.getOperand(0).getValueType(); 4483 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4484 if (N1C->getZExtValue() >= BitSize) 4485 return DAG.getUNDEF(VT); 4486 4487 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4488 uint64_t ShiftAmt = N1C->getZExtValue(); 4489 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4490 N0.getOperand(0), 4491 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4492 AddToWorklist(SmallShift.getNode()); 4493 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4494 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4495 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4496 DAG.getConstant(Mask, VT)); 4497 } 4498 } 4499 4500 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4501 // bit, which is unmodified by sra. 4502 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4503 if (N0.getOpcode() == ISD::SRA) 4504 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4505 } 4506 4507 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4508 if (N1C && N0.getOpcode() == ISD::CTLZ && 4509 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4510 APInt KnownZero, KnownOne; 4511 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4512 4513 // If any of the input bits are KnownOne, then the input couldn't be all 4514 // zeros, thus the result of the srl will always be zero. 4515 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4516 4517 // If all of the bits input the to ctlz node are known to be zero, then 4518 // the result of the ctlz is "32" and the result of the shift is one. 4519 APInt UnknownBits = ~KnownZero; 4520 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4521 4522 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4523 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4524 // Okay, we know that only that the single bit specified by UnknownBits 4525 // could be set on input to the CTLZ node. If this bit is set, the SRL 4526 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4527 // to an SRL/XOR pair, which is likely to simplify more. 4528 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4529 SDValue Op = N0.getOperand(0); 4530 4531 if (ShAmt) { 4532 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4533 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4534 AddToWorklist(Op.getNode()); 4535 } 4536 4537 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4538 Op, DAG.getConstant(1, VT)); 4539 } 4540 } 4541 4542 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4543 if (N1.getOpcode() == ISD::TRUNCATE && 4544 N1.getOperand(0).getOpcode() == ISD::AND) { 4545 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4546 if (NewOp1.getNode()) 4547 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4548 } 4549 4550 // fold operands of srl based on knowledge that the low bits are not 4551 // demanded. 4552 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4553 return SDValue(N, 0); 4554 4555 if (N1C) { 4556 SDValue NewSRL = visitShiftByConstant(N, N1C); 4557 if (NewSRL.getNode()) 4558 return NewSRL; 4559 } 4560 4561 // Attempt to convert a srl of a load into a narrower zero-extending load. 4562 SDValue NarrowLoad = ReduceLoadWidth(N); 4563 if (NarrowLoad.getNode()) 4564 return NarrowLoad; 4565 4566 // Here is a common situation. We want to optimize: 4567 // 4568 // %a = ... 4569 // %b = and i32 %a, 2 4570 // %c = srl i32 %b, 1 4571 // brcond i32 %c ... 4572 // 4573 // into 4574 // 4575 // %a = ... 4576 // %b = and %a, 2 4577 // %c = setcc eq %b, 0 4578 // brcond %c ... 4579 // 4580 // However when after the source operand of SRL is optimized into AND, the SRL 4581 // itself may not be optimized further. Look for it and add the BRCOND into 4582 // the worklist. 4583 if (N->hasOneUse()) { 4584 SDNode *Use = *N->use_begin(); 4585 if (Use->getOpcode() == ISD::BRCOND) 4586 AddToWorklist(Use); 4587 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4588 // Also look pass the truncate. 4589 Use = *Use->use_begin(); 4590 if (Use->getOpcode() == ISD::BRCOND) 4591 AddToWorklist(Use); 4592 } 4593 } 4594 4595 return SDValue(); 4596 } 4597 4598 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4599 SDValue N0 = N->getOperand(0); 4600 EVT VT = N->getValueType(0); 4601 4602 // fold (ctlz c1) -> c2 4603 if (isa<ConstantSDNode>(N0)) 4604 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4605 return SDValue(); 4606 } 4607 4608 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4609 SDValue N0 = N->getOperand(0); 4610 EVT VT = N->getValueType(0); 4611 4612 // fold (ctlz_zero_undef c1) -> c2 4613 if (isa<ConstantSDNode>(N0)) 4614 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4615 return SDValue(); 4616 } 4617 4618 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4619 SDValue N0 = N->getOperand(0); 4620 EVT VT = N->getValueType(0); 4621 4622 // fold (cttz c1) -> c2 4623 if (isa<ConstantSDNode>(N0)) 4624 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4625 return SDValue(); 4626 } 4627 4628 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4629 SDValue N0 = N->getOperand(0); 4630 EVT VT = N->getValueType(0); 4631 4632 // fold (cttz_zero_undef c1) -> c2 4633 if (isa<ConstantSDNode>(N0)) 4634 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4635 return SDValue(); 4636 } 4637 4638 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4639 SDValue N0 = N->getOperand(0); 4640 EVT VT = N->getValueType(0); 4641 4642 // fold (ctpop c1) -> c2 4643 if (isa<ConstantSDNode>(N0)) 4644 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4645 return SDValue(); 4646 } 4647 4648 4649 /// \brief Generate Min/Max node 4650 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4651 SDValue True, SDValue False, 4652 ISD::CondCode CC, const TargetLowering &TLI, 4653 SelectionDAG &DAG) { 4654 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4655 return SDValue(); 4656 4657 switch (CC) { 4658 case ISD::SETOLT: 4659 case ISD::SETOLE: 4660 case ISD::SETLT: 4661 case ISD::SETLE: 4662 case ISD::SETULT: 4663 case ISD::SETULE: { 4664 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4665 if (TLI.isOperationLegal(Opcode, VT)) 4666 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4667 return SDValue(); 4668 } 4669 case ISD::SETOGT: 4670 case ISD::SETOGE: 4671 case ISD::SETGT: 4672 case ISD::SETGE: 4673 case ISD::SETUGT: 4674 case ISD::SETUGE: { 4675 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4676 if (TLI.isOperationLegal(Opcode, VT)) 4677 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4678 return SDValue(); 4679 } 4680 default: 4681 return SDValue(); 4682 } 4683 } 4684 4685 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4686 SDValue N0 = N->getOperand(0); 4687 SDValue N1 = N->getOperand(1); 4688 SDValue N2 = N->getOperand(2); 4689 EVT VT = N->getValueType(0); 4690 EVT VT0 = N0.getValueType(); 4691 4692 // fold (select C, X, X) -> X 4693 if (N1 == N2) 4694 return N1; 4695 // fold (select true, X, Y) -> X 4696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4697 if (N0C && !N0C->isNullValue()) 4698 return N1; 4699 // fold (select false, X, Y) -> Y 4700 if (N0C && N0C->isNullValue()) 4701 return N2; 4702 // fold (select C, 1, X) -> (or C, X) 4703 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4704 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4705 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4706 // fold (select C, 0, 1) -> (xor C, 1) 4707 // We can't do this reliably if integer based booleans have different contents 4708 // to floating point based booleans. This is because we can't tell whether we 4709 // have an integer-based boolean or a floating-point-based boolean unless we 4710 // can find the SETCC that produced it and inspect its operands. This is 4711 // fairly easy if C is the SETCC node, but it can potentially be 4712 // undiscoverable (or not reasonably discoverable). For example, it could be 4713 // in another basic block or it could require searching a complicated 4714 // expression. 4715 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4716 if (VT.isInteger() && 4717 (VT0 == MVT::i1 || (VT0.isInteger() && 4718 TLI.getBooleanContents(false, false) == 4719 TLI.getBooleanContents(false, true) && 4720 TLI.getBooleanContents(false, false) == 4721 TargetLowering::ZeroOrOneBooleanContent)) && 4722 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4723 SDValue XORNode; 4724 if (VT == VT0) 4725 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4726 N0, DAG.getConstant(1, VT0)); 4727 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4728 N0, DAG.getConstant(1, VT0)); 4729 AddToWorklist(XORNode.getNode()); 4730 if (VT.bitsGT(VT0)) 4731 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4732 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4733 } 4734 // fold (select C, 0, X) -> (and (not C), X) 4735 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4736 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4737 AddToWorklist(NOTNode.getNode()); 4738 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4739 } 4740 // fold (select C, X, 1) -> (or (not C), X) 4741 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4742 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4743 AddToWorklist(NOTNode.getNode()); 4744 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4745 } 4746 // fold (select C, X, 0) -> (and C, X) 4747 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4748 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4749 // fold (select X, X, Y) -> (or X, Y) 4750 // fold (select X, 1, Y) -> (or X, Y) 4751 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4752 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4753 // fold (select X, Y, X) -> (and X, Y) 4754 // fold (select X, Y, 0) -> (and X, Y) 4755 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4756 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4757 4758 // If we can fold this based on the true/false value, do so. 4759 if (SimplifySelectOps(N, N1, N2)) 4760 return SDValue(N, 0); // Don't revisit N. 4761 4762 // fold selects based on a setcc into other things, such as min/max/abs 4763 if (N0.getOpcode() == ISD::SETCC) { 4764 // select x, y (fcmp lt x, y) -> fminnum x, y 4765 // select x, y (fcmp gt x, y) -> fmaxnum x, y 4766 // 4767 // This is OK if we don't care about what happens if either operand is a 4768 // NaN. 4769 // 4770 4771 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 4772 // no signed zeros as well as no nans. 4773 const TargetOptions &Options = DAG.getTarget().Options; 4774 if (Options.UnsafeFPMath && 4775 VT.isFloatingPoint() && N0.hasOneUse() && 4776 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 4777 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4778 4779 SDValue FMinMax = 4780 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1), 4781 N1, N2, CC, TLI, DAG); 4782 if (FMinMax) 4783 return FMinMax; 4784 } 4785 4786 if ((!LegalOperations && 4787 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4788 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4789 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4790 N0.getOperand(0), N0.getOperand(1), 4791 N1, N2, N0.getOperand(2)); 4792 return SimplifySelect(SDLoc(N), N0, N1, N2); 4793 } 4794 4795 return SDValue(); 4796 } 4797 4798 static 4799 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4800 SDLoc DL(N); 4801 EVT LoVT, HiVT; 4802 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4803 4804 // Split the inputs. 4805 SDValue Lo, Hi, LL, LH, RL, RH; 4806 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4807 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4808 4809 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4810 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4811 4812 return std::make_pair(Lo, Hi); 4813 } 4814 4815 // This function assumes all the vselect's arguments are CONCAT_VECTOR 4816 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 4817 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 4818 SDLoc dl(N); 4819 SDValue Cond = N->getOperand(0); 4820 SDValue LHS = N->getOperand(1); 4821 SDValue RHS = N->getOperand(2); 4822 EVT VT = N->getValueType(0); 4823 int NumElems = VT.getVectorNumElements(); 4824 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 4825 RHS.getOpcode() == ISD::CONCAT_VECTORS && 4826 Cond.getOpcode() == ISD::BUILD_VECTOR); 4827 4828 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 4829 // binary ones here. 4830 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 4831 return SDValue(); 4832 4833 // We're sure we have an even number of elements due to the 4834 // concat_vectors we have as arguments to vselect. 4835 // Skip BV elements until we find one that's not an UNDEF 4836 // After we find an UNDEF element, keep looping until we get to half the 4837 // length of the BV and see if all the non-undef nodes are the same. 4838 ConstantSDNode *BottomHalf = nullptr; 4839 for (int i = 0; i < NumElems / 2; ++i) { 4840 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4841 continue; 4842 4843 if (BottomHalf == nullptr) 4844 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4845 else if (Cond->getOperand(i).getNode() != BottomHalf) 4846 return SDValue(); 4847 } 4848 4849 // Do the same for the second half of the BuildVector 4850 ConstantSDNode *TopHalf = nullptr; 4851 for (int i = NumElems / 2; i < NumElems; ++i) { 4852 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4853 continue; 4854 4855 if (TopHalf == nullptr) 4856 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4857 else if (Cond->getOperand(i).getNode() != TopHalf) 4858 return SDValue(); 4859 } 4860 4861 assert(TopHalf && BottomHalf && 4862 "One half of the selector was all UNDEFs and the other was all the " 4863 "same value. This should have been addressed before this function."); 4864 return DAG.getNode( 4865 ISD::CONCAT_VECTORS, dl, VT, 4866 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 4867 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 4868 } 4869 4870 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 4871 4872 if (Level >= AfterLegalizeTypes) 4873 return SDValue(); 4874 4875 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 4876 SDValue Mask = MST->getMask(); 4877 SDValue Data = MST->getValue(); 4878 SDLoc DL(N); 4879 4880 // If the MSTORE data type requires splitting and the mask is provided by a 4881 // SETCC, then split both nodes and its operands before legalization. This 4882 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4883 // and enables future optimizations (e.g. min/max pattern matching on X86). 4884 if (Mask.getOpcode() == ISD::SETCC) { 4885 4886 // Check if any splitting is required. 4887 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 4888 TargetLowering::TypeSplitVector) 4889 return SDValue(); 4890 4891 SDValue MaskLo, MaskHi, Lo, Hi; 4892 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 4893 4894 EVT LoVT, HiVT; 4895 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 4896 4897 SDValue Chain = MST->getChain(); 4898 SDValue Ptr = MST->getBasePtr(); 4899 4900 EVT MemoryVT = MST->getMemoryVT(); 4901 unsigned Alignment = MST->getOriginalAlignment(); 4902 4903 // if Alignment is equal to the vector size, 4904 // take the half of it for the second part 4905 unsigned SecondHalfAlignment = 4906 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 4907 Alignment/2 : Alignment; 4908 4909 EVT LoMemVT, HiMemVT; 4910 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 4911 4912 SDValue DataLo, DataHi; 4913 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 4914 4915 MachineMemOperand *MMO = DAG.getMachineFunction(). 4916 getMachineMemOperand(MST->getPointerInfo(), 4917 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 4918 Alignment, MST->getAAInfo(), MST->getRanges()); 4919 4920 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 4921 MST->isTruncatingStore()); 4922 4923 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 4924 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 4925 DAG.getConstant(IncrementSize, Ptr.getValueType())); 4926 4927 MMO = DAG.getMachineFunction(). 4928 getMachineMemOperand(MST->getPointerInfo(), 4929 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 4930 SecondHalfAlignment, MST->getAAInfo(), 4931 MST->getRanges()); 4932 4933 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 4934 MST->isTruncatingStore()); 4935 4936 AddToWorklist(Lo.getNode()); 4937 AddToWorklist(Hi.getNode()); 4938 4939 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 4940 } 4941 return SDValue(); 4942 } 4943 4944 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 4945 4946 if (Level >= AfterLegalizeTypes) 4947 return SDValue(); 4948 4949 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 4950 SDValue Mask = MLD->getMask(); 4951 SDLoc DL(N); 4952 4953 // If the MLOAD result requires splitting and the mask is provided by a 4954 // SETCC, then split both nodes and its operands before legalization. This 4955 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4956 // and enables future optimizations (e.g. min/max pattern matching on X86). 4957 4958 if (Mask.getOpcode() == ISD::SETCC) { 4959 EVT VT = N->getValueType(0); 4960 4961 // Check if any splitting is required. 4962 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4963 TargetLowering::TypeSplitVector) 4964 return SDValue(); 4965 4966 SDValue MaskLo, MaskHi, Lo, Hi; 4967 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 4968 4969 SDValue Src0 = MLD->getSrc0(); 4970 SDValue Src0Lo, Src0Hi; 4971 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 4972 4973 EVT LoVT, HiVT; 4974 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 4975 4976 SDValue Chain = MLD->getChain(); 4977 SDValue Ptr = MLD->getBasePtr(); 4978 EVT MemoryVT = MLD->getMemoryVT(); 4979 unsigned Alignment = MLD->getOriginalAlignment(); 4980 4981 // if Alignment is equal to the vector size, 4982 // take the half of it for the second part 4983 unsigned SecondHalfAlignment = 4984 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 4985 Alignment/2 : Alignment; 4986 4987 EVT LoMemVT, HiMemVT; 4988 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 4989 4990 MachineMemOperand *MMO = DAG.getMachineFunction(). 4991 getMachineMemOperand(MLD->getPointerInfo(), 4992 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 4993 Alignment, MLD->getAAInfo(), MLD->getRanges()); 4994 4995 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 4996 ISD::NON_EXTLOAD); 4997 4998 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 4999 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5000 DAG.getConstant(IncrementSize, Ptr.getValueType())); 5001 5002 MMO = DAG.getMachineFunction(). 5003 getMachineMemOperand(MLD->getPointerInfo(), 5004 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5005 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5006 5007 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5008 ISD::NON_EXTLOAD); 5009 5010 AddToWorklist(Lo.getNode()); 5011 AddToWorklist(Hi.getNode()); 5012 5013 // Build a factor node to remember that this load is independent of the 5014 // other one. 5015 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5016 Hi.getValue(1)); 5017 5018 // Legalized the chain result - switch anything that used the old chain to 5019 // use the new one. 5020 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5021 5022 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5023 5024 SDValue RetOps[] = { LoadRes, Chain }; 5025 return DAG.getMergeValues(RetOps, DL); 5026 } 5027 return SDValue(); 5028 } 5029 5030 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5031 SDValue N0 = N->getOperand(0); 5032 SDValue N1 = N->getOperand(1); 5033 SDValue N2 = N->getOperand(2); 5034 SDLoc DL(N); 5035 5036 // Canonicalize integer abs. 5037 // vselect (setg[te] X, 0), X, -X -> 5038 // vselect (setgt X, -1), X, -X -> 5039 // vselect (setl[te] X, 0), -X, X -> 5040 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5041 if (N0.getOpcode() == ISD::SETCC) { 5042 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5043 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5044 bool isAbs = false; 5045 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5046 5047 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5048 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5049 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5050 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5051 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5052 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5053 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5054 5055 if (isAbs) { 5056 EVT VT = LHS.getValueType(); 5057 SDValue Shift = DAG.getNode( 5058 ISD::SRA, DL, VT, LHS, 5059 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 5060 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5061 AddToWorklist(Shift.getNode()); 5062 AddToWorklist(Add.getNode()); 5063 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5064 } 5065 } 5066 5067 // If the VSELECT result requires splitting and the mask is provided by a 5068 // SETCC, then split both nodes and its operands before legalization. This 5069 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5070 // and enables future optimizations (e.g. min/max pattern matching on X86). 5071 if (N0.getOpcode() == ISD::SETCC) { 5072 EVT VT = N->getValueType(0); 5073 5074 // Check if any splitting is required. 5075 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5076 TargetLowering::TypeSplitVector) 5077 return SDValue(); 5078 5079 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5080 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5081 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5082 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5083 5084 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5085 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5086 5087 // Add the new VSELECT nodes to the work list in case they need to be split 5088 // again. 5089 AddToWorklist(Lo.getNode()); 5090 AddToWorklist(Hi.getNode()); 5091 5092 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5093 } 5094 5095 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5096 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5097 return N1; 5098 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5099 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5100 return N2; 5101 5102 // The ConvertSelectToConcatVector function is assuming both the above 5103 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5104 // and addressed. 5105 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5106 N2.getOpcode() == ISD::CONCAT_VECTORS && 5107 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5108 SDValue CV = ConvertSelectToConcatVector(N, DAG); 5109 if (CV.getNode()) 5110 return CV; 5111 } 5112 5113 return SDValue(); 5114 } 5115 5116 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5117 SDValue N0 = N->getOperand(0); 5118 SDValue N1 = N->getOperand(1); 5119 SDValue N2 = N->getOperand(2); 5120 SDValue N3 = N->getOperand(3); 5121 SDValue N4 = N->getOperand(4); 5122 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5123 5124 // fold select_cc lhs, rhs, x, x, cc -> x 5125 if (N2 == N3) 5126 return N2; 5127 5128 // Determine if the condition we're dealing with is constant 5129 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5130 N0, N1, CC, SDLoc(N), false); 5131 if (SCC.getNode()) { 5132 AddToWorklist(SCC.getNode()); 5133 5134 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5135 if (!SCCC->isNullValue()) 5136 return N2; // cond always true -> true val 5137 else 5138 return N3; // cond always false -> false val 5139 } else if (SCC->getOpcode() == ISD::UNDEF) { 5140 // When the condition is UNDEF, just return the first operand. This is 5141 // coherent the DAG creation, no setcc node is created in this case 5142 return N2; 5143 } else if (SCC.getOpcode() == ISD::SETCC) { 5144 // Fold to a simpler select_cc 5145 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5146 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5147 SCC.getOperand(2)); 5148 } 5149 } 5150 5151 // If we can fold this based on the true/false value, do so. 5152 if (SimplifySelectOps(N, N2, N3)) 5153 return SDValue(N, 0); // Don't revisit N. 5154 5155 // fold select_cc into other things, such as min/max/abs 5156 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5157 } 5158 5159 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5160 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5161 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5162 SDLoc(N)); 5163 } 5164 5165 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 5166 // dag node into a ConstantSDNode or a build_vector of constants. 5167 // This function is called by the DAGCombiner when visiting sext/zext/aext 5168 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5169 // Vector extends are not folded if operations are legal; this is to 5170 // avoid introducing illegal build_vector dag nodes. 5171 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5172 SelectionDAG &DAG, bool LegalTypes, 5173 bool LegalOperations) { 5174 unsigned Opcode = N->getOpcode(); 5175 SDValue N0 = N->getOperand(0); 5176 EVT VT = N->getValueType(0); 5177 5178 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5179 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 5180 5181 // fold (sext c1) -> c1 5182 // fold (zext c1) -> c1 5183 // fold (aext c1) -> c1 5184 if (isa<ConstantSDNode>(N0)) 5185 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5186 5187 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5188 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5189 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5190 EVT SVT = VT.getScalarType(); 5191 if (!(VT.isVector() && 5192 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5193 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5194 return nullptr; 5195 5196 // We can fold this node into a build_vector. 5197 unsigned VTBits = SVT.getSizeInBits(); 5198 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5199 unsigned ShAmt = VTBits - EVTBits; 5200 SmallVector<SDValue, 8> Elts; 5201 unsigned NumElts = N0->getNumOperands(); 5202 SDLoc DL(N); 5203 5204 for (unsigned i=0; i != NumElts; ++i) { 5205 SDValue Op = N0->getOperand(i); 5206 if (Op->getOpcode() == ISD::UNDEF) { 5207 Elts.push_back(DAG.getUNDEF(SVT)); 5208 continue; 5209 } 5210 5211 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5212 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5213 if (Opcode == ISD::SIGN_EXTEND) 5214 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5215 SVT)); 5216 else 5217 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 5218 SVT)); 5219 } 5220 5221 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5222 } 5223 5224 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5225 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5226 // transformation. Returns true if extension are possible and the above 5227 // mentioned transformation is profitable. 5228 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5229 unsigned ExtOpc, 5230 SmallVectorImpl<SDNode *> &ExtendNodes, 5231 const TargetLowering &TLI) { 5232 bool HasCopyToRegUses = false; 5233 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5234 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5235 UE = N0.getNode()->use_end(); 5236 UI != UE; ++UI) { 5237 SDNode *User = *UI; 5238 if (User == N) 5239 continue; 5240 if (UI.getUse().getResNo() != N0.getResNo()) 5241 continue; 5242 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5243 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5244 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5245 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5246 // Sign bits will be lost after a zext. 5247 return false; 5248 bool Add = false; 5249 for (unsigned i = 0; i != 2; ++i) { 5250 SDValue UseOp = User->getOperand(i); 5251 if (UseOp == N0) 5252 continue; 5253 if (!isa<ConstantSDNode>(UseOp)) 5254 return false; 5255 Add = true; 5256 } 5257 if (Add) 5258 ExtendNodes.push_back(User); 5259 continue; 5260 } 5261 // If truncates aren't free and there are users we can't 5262 // extend, it isn't worthwhile. 5263 if (!isTruncFree) 5264 return false; 5265 // Remember if this value is live-out. 5266 if (User->getOpcode() == ISD::CopyToReg) 5267 HasCopyToRegUses = true; 5268 } 5269 5270 if (HasCopyToRegUses) { 5271 bool BothLiveOut = false; 5272 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5273 UI != UE; ++UI) { 5274 SDUse &Use = UI.getUse(); 5275 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5276 BothLiveOut = true; 5277 break; 5278 } 5279 } 5280 if (BothLiveOut) 5281 // Both unextended and extended values are live out. There had better be 5282 // a good reason for the transformation. 5283 return ExtendNodes.size(); 5284 } 5285 return true; 5286 } 5287 5288 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5289 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5290 ISD::NodeType ExtType) { 5291 // Extend SetCC uses if necessary. 5292 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5293 SDNode *SetCC = SetCCs[i]; 5294 SmallVector<SDValue, 4> Ops; 5295 5296 for (unsigned j = 0; j != 2; ++j) { 5297 SDValue SOp = SetCC->getOperand(j); 5298 if (SOp == Trunc) 5299 Ops.push_back(ExtLoad); 5300 else 5301 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5302 } 5303 5304 Ops.push_back(SetCC->getOperand(2)); 5305 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5306 } 5307 } 5308 5309 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5310 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5311 SDValue N0 = N->getOperand(0); 5312 EVT DstVT = N->getValueType(0); 5313 EVT SrcVT = N0.getValueType(); 5314 5315 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5316 N->getOpcode() == ISD::ZERO_EXTEND) && 5317 "Unexpected node type (not an extend)!"); 5318 5319 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5320 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5321 // (v8i32 (sext (v8i16 (load x)))) 5322 // into: 5323 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5324 // (v4i32 (sextload (x + 16))))) 5325 // Where uses of the original load, i.e.: 5326 // (v8i16 (load x)) 5327 // are replaced with: 5328 // (v8i16 (truncate 5329 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5330 // (v4i32 (sextload (x + 16))))))) 5331 // 5332 // This combine is only applicable to illegal, but splittable, vectors. 5333 // All legal types, and illegal non-vector types, are handled elsewhere. 5334 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5335 // 5336 if (N0->getOpcode() != ISD::LOAD) 5337 return SDValue(); 5338 5339 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5340 5341 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5342 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5343 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5344 return SDValue(); 5345 5346 SmallVector<SDNode *, 4> SetCCs; 5347 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5348 return SDValue(); 5349 5350 ISD::LoadExtType ExtType = 5351 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5352 5353 // Try to split the vector types to get down to legal types. 5354 EVT SplitSrcVT = SrcVT; 5355 EVT SplitDstVT = DstVT; 5356 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5357 SplitSrcVT.getVectorNumElements() > 1) { 5358 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5359 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5360 } 5361 5362 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5363 return SDValue(); 5364 5365 SDLoc DL(N); 5366 const unsigned NumSplits = 5367 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5368 const unsigned Stride = SplitSrcVT.getStoreSize(); 5369 SmallVector<SDValue, 4> Loads; 5370 SmallVector<SDValue, 4> Chains; 5371 5372 SDValue BasePtr = LN0->getBasePtr(); 5373 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5374 const unsigned Offset = Idx * Stride; 5375 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5376 5377 SDValue SplitLoad = DAG.getExtLoad( 5378 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5379 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5380 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5381 Align, LN0->getAAInfo()); 5382 5383 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5384 DAG.getConstant(Stride, BasePtr.getValueType())); 5385 5386 Loads.push_back(SplitLoad.getValue(0)); 5387 Chains.push_back(SplitLoad.getValue(1)); 5388 } 5389 5390 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5391 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5392 5393 CombineTo(N, NewValue); 5394 5395 // Replace uses of the original load (before extension) 5396 // with a truncate of the concatenated sextloaded vectors. 5397 SDValue Trunc = 5398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5399 CombineTo(N0.getNode(), Trunc, NewChain); 5400 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5401 (ISD::NodeType)N->getOpcode()); 5402 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5403 } 5404 5405 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5406 SDValue N0 = N->getOperand(0); 5407 EVT VT = N->getValueType(0); 5408 5409 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5410 LegalOperations)) 5411 return SDValue(Res, 0); 5412 5413 // fold (sext (sext x)) -> (sext x) 5414 // fold (sext (aext x)) -> (sext x) 5415 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5416 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5417 N0.getOperand(0)); 5418 5419 if (N0.getOpcode() == ISD::TRUNCATE) { 5420 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5421 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5422 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5423 if (NarrowLoad.getNode()) { 5424 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5425 if (NarrowLoad.getNode() != N0.getNode()) { 5426 CombineTo(N0.getNode(), NarrowLoad); 5427 // CombineTo deleted the truncate, if needed, but not what's under it. 5428 AddToWorklist(oye); 5429 } 5430 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5431 } 5432 5433 // See if the value being truncated is already sign extended. If so, just 5434 // eliminate the trunc/sext pair. 5435 SDValue Op = N0.getOperand(0); 5436 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5437 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5438 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5439 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5440 5441 if (OpBits == DestBits) { 5442 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5443 // bits, it is already ready. 5444 if (NumSignBits > DestBits-MidBits) 5445 return Op; 5446 } else if (OpBits < DestBits) { 5447 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5448 // bits, just sext from i32. 5449 if (NumSignBits > OpBits-MidBits) 5450 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5451 } else { 5452 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5453 // bits, just truncate to i32. 5454 if (NumSignBits > OpBits-MidBits) 5455 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5456 } 5457 5458 // fold (sext (truncate x)) -> (sextinreg x). 5459 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5460 N0.getValueType())) { 5461 if (OpBits < DestBits) 5462 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5463 else if (OpBits > DestBits) 5464 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5465 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5466 DAG.getValueType(N0.getValueType())); 5467 } 5468 } 5469 5470 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5471 // Only generate vector extloads when 1) they're legal, and 2) they are 5472 // deemed desirable by the target. 5473 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5474 ((!LegalOperations && !VT.isVector() && 5475 !cast<LoadSDNode>(N0)->isVolatile()) || 5476 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5477 bool DoXform = true; 5478 SmallVector<SDNode*, 4> SetCCs; 5479 if (!N0.hasOneUse()) 5480 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5481 if (VT.isVector()) 5482 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5483 if (DoXform) { 5484 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5485 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5486 LN0->getChain(), 5487 LN0->getBasePtr(), N0.getValueType(), 5488 LN0->getMemOperand()); 5489 CombineTo(N, ExtLoad); 5490 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5491 N0.getValueType(), ExtLoad); 5492 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5493 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5494 ISD::SIGN_EXTEND); 5495 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5496 } 5497 } 5498 5499 // fold (sext (load x)) to multiple smaller sextloads. 5500 // Only on illegal but splittable vectors. 5501 if (SDValue ExtLoad = CombineExtLoad(N)) 5502 return ExtLoad; 5503 5504 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5505 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5506 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5507 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5508 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5509 EVT MemVT = LN0->getMemoryVT(); 5510 if ((!LegalOperations && !LN0->isVolatile()) || 5511 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5512 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5513 LN0->getChain(), 5514 LN0->getBasePtr(), MemVT, 5515 LN0->getMemOperand()); 5516 CombineTo(N, ExtLoad); 5517 CombineTo(N0.getNode(), 5518 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5519 N0.getValueType(), ExtLoad), 5520 ExtLoad.getValue(1)); 5521 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5522 } 5523 } 5524 5525 // fold (sext (and/or/xor (load x), cst)) -> 5526 // (and/or/xor (sextload x), (sext cst)) 5527 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5528 N0.getOpcode() == ISD::XOR) && 5529 isa<LoadSDNode>(N0.getOperand(0)) && 5530 N0.getOperand(1).getOpcode() == ISD::Constant && 5531 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5532 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5533 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5534 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5535 bool DoXform = true; 5536 SmallVector<SDNode*, 4> SetCCs; 5537 if (!N0.hasOneUse()) 5538 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5539 SetCCs, TLI); 5540 if (DoXform) { 5541 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5542 LN0->getChain(), LN0->getBasePtr(), 5543 LN0->getMemoryVT(), 5544 LN0->getMemOperand()); 5545 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5546 Mask = Mask.sext(VT.getSizeInBits()); 5547 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5548 ExtLoad, DAG.getConstant(Mask, VT)); 5549 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5550 SDLoc(N0.getOperand(0)), 5551 N0.getOperand(0).getValueType(), ExtLoad); 5552 CombineTo(N, And); 5553 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5554 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5555 ISD::SIGN_EXTEND); 5556 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5557 } 5558 } 5559 } 5560 5561 if (N0.getOpcode() == ISD::SETCC) { 5562 EVT N0VT = N0.getOperand(0).getValueType(); 5563 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5564 // Only do this before legalize for now. 5565 if (VT.isVector() && !LegalOperations && 5566 TLI.getBooleanContents(N0VT) == 5567 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5568 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5569 // of the same size as the compared operands. Only optimize sext(setcc()) 5570 // if this is the case. 5571 EVT SVT = getSetCCResultType(N0VT); 5572 5573 // We know that the # elements of the results is the same as the 5574 // # elements of the compare (and the # elements of the compare result 5575 // for that matter). Check to see that they are the same size. If so, 5576 // we know that the element size of the sext'd result matches the 5577 // element size of the compare operands. 5578 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5579 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5580 N0.getOperand(1), 5581 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5582 5583 // If the desired elements are smaller or larger than the source 5584 // elements we can use a matching integer vector type and then 5585 // truncate/sign extend 5586 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5587 if (SVT == MatchingVectorType) { 5588 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5589 N0.getOperand(0), N0.getOperand(1), 5590 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5591 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5592 } 5593 } 5594 5595 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5596 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5597 SDValue NegOne = 5598 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 5599 SDValue SCC = 5600 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5601 NegOne, DAG.getConstant(0, VT), 5602 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5603 if (SCC.getNode()) return SCC; 5604 5605 if (!VT.isVector()) { 5606 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5607 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5608 SDLoc DL(N); 5609 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5610 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 5611 N0.getOperand(0), N0.getOperand(1), CC); 5612 return DAG.getSelect(DL, VT, SetCC, 5613 NegOne, DAG.getConstant(0, VT)); 5614 } 5615 } 5616 } 5617 5618 // fold (sext x) -> (zext x) if the sign bit is known zero. 5619 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5620 DAG.SignBitIsZero(N0)) 5621 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5622 5623 return SDValue(); 5624 } 5625 5626 // isTruncateOf - If N is a truncate of some other value, return true, record 5627 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5628 // This function computes KnownZero to avoid a duplicated call to 5629 // computeKnownBits in the caller. 5630 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5631 APInt &KnownZero) { 5632 APInt KnownOne; 5633 if (N->getOpcode() == ISD::TRUNCATE) { 5634 Op = N->getOperand(0); 5635 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5636 return true; 5637 } 5638 5639 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5640 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5641 return false; 5642 5643 SDValue Op0 = N->getOperand(0); 5644 SDValue Op1 = N->getOperand(1); 5645 assert(Op0.getValueType() == Op1.getValueType()); 5646 5647 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 5648 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 5649 if (COp0 && COp0->isNullValue()) 5650 Op = Op1; 5651 else if (COp1 && COp1->isNullValue()) 5652 Op = Op0; 5653 else 5654 return false; 5655 5656 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5657 5658 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5659 return false; 5660 5661 return true; 5662 } 5663 5664 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5665 SDValue N0 = N->getOperand(0); 5666 EVT VT = N->getValueType(0); 5667 5668 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5669 LegalOperations)) 5670 return SDValue(Res, 0); 5671 5672 // fold (zext (zext x)) -> (zext x) 5673 // fold (zext (aext x)) -> (zext x) 5674 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5675 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5676 N0.getOperand(0)); 5677 5678 // fold (zext (truncate x)) -> (zext x) or 5679 // (zext (truncate x)) -> (truncate x) 5680 // This is valid when the truncated bits of x are already zero. 5681 // FIXME: We should extend this to work for vectors too. 5682 SDValue Op; 5683 APInt KnownZero; 5684 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5685 APInt TruncatedBits = 5686 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5687 APInt(Op.getValueSizeInBits(), 0) : 5688 APInt::getBitsSet(Op.getValueSizeInBits(), 5689 N0.getValueSizeInBits(), 5690 std::min(Op.getValueSizeInBits(), 5691 VT.getSizeInBits())); 5692 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5693 if (VT.bitsGT(Op.getValueType())) 5694 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5695 if (VT.bitsLT(Op.getValueType())) 5696 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5697 5698 return Op; 5699 } 5700 } 5701 5702 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5703 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5704 if (N0.getOpcode() == ISD::TRUNCATE) { 5705 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5706 if (NarrowLoad.getNode()) { 5707 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5708 if (NarrowLoad.getNode() != N0.getNode()) { 5709 CombineTo(N0.getNode(), NarrowLoad); 5710 // CombineTo deleted the truncate, if needed, but not what's under it. 5711 AddToWorklist(oye); 5712 } 5713 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5714 } 5715 } 5716 5717 // fold (zext (truncate x)) -> (and x, mask) 5718 if (N0.getOpcode() == ISD::TRUNCATE && 5719 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5720 5721 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5722 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5723 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5724 if (NarrowLoad.getNode()) { 5725 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5726 if (NarrowLoad.getNode() != N0.getNode()) { 5727 CombineTo(N0.getNode(), NarrowLoad); 5728 // CombineTo deleted the truncate, if needed, but not what's under it. 5729 AddToWorklist(oye); 5730 } 5731 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5732 } 5733 5734 SDValue Op = N0.getOperand(0); 5735 if (Op.getValueType().bitsLT(VT)) { 5736 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5737 AddToWorklist(Op.getNode()); 5738 } else if (Op.getValueType().bitsGT(VT)) { 5739 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5740 AddToWorklist(Op.getNode()); 5741 } 5742 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5743 N0.getValueType().getScalarType()); 5744 } 5745 5746 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5747 // if either of the casts is not free. 5748 if (N0.getOpcode() == ISD::AND && 5749 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5750 N0.getOperand(1).getOpcode() == ISD::Constant && 5751 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5752 N0.getValueType()) || 5753 !TLI.isZExtFree(N0.getValueType(), VT))) { 5754 SDValue X = N0.getOperand(0).getOperand(0); 5755 if (X.getValueType().bitsLT(VT)) { 5756 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5757 } else if (X.getValueType().bitsGT(VT)) { 5758 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5759 } 5760 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5761 Mask = Mask.zext(VT.getSizeInBits()); 5762 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5763 X, DAG.getConstant(Mask, VT)); 5764 } 5765 5766 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5767 // Only generate vector extloads when 1) they're legal, and 2) they are 5768 // deemed desirable by the target. 5769 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5770 ((!LegalOperations && !VT.isVector() && 5771 !cast<LoadSDNode>(N0)->isVolatile()) || 5772 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 5773 bool DoXform = true; 5774 SmallVector<SDNode*, 4> SetCCs; 5775 if (!N0.hasOneUse()) 5776 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5777 if (VT.isVector()) 5778 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5779 if (DoXform) { 5780 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5781 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5782 LN0->getChain(), 5783 LN0->getBasePtr(), N0.getValueType(), 5784 LN0->getMemOperand()); 5785 CombineTo(N, ExtLoad); 5786 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5787 N0.getValueType(), ExtLoad); 5788 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5789 5790 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5791 ISD::ZERO_EXTEND); 5792 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5793 } 5794 } 5795 5796 // fold (zext (load x)) to multiple smaller zextloads. 5797 // Only on illegal but splittable vectors. 5798 if (SDValue ExtLoad = CombineExtLoad(N)) 5799 return ExtLoad; 5800 5801 // fold (zext (and/or/xor (load x), cst)) -> 5802 // (and/or/xor (zextload x), (zext cst)) 5803 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5804 N0.getOpcode() == ISD::XOR) && 5805 isa<LoadSDNode>(N0.getOperand(0)) && 5806 N0.getOperand(1).getOpcode() == ISD::Constant && 5807 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 5808 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5809 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5810 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 5811 bool DoXform = true; 5812 SmallVector<SDNode*, 4> SetCCs; 5813 if (!N0.hasOneUse()) 5814 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5815 SetCCs, TLI); 5816 if (DoXform) { 5817 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5818 LN0->getChain(), LN0->getBasePtr(), 5819 LN0->getMemoryVT(), 5820 LN0->getMemOperand()); 5821 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5822 Mask = Mask.zext(VT.getSizeInBits()); 5823 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5824 ExtLoad, DAG.getConstant(Mask, VT)); 5825 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5826 SDLoc(N0.getOperand(0)), 5827 N0.getOperand(0).getValueType(), ExtLoad); 5828 CombineTo(N, And); 5829 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5830 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5831 ISD::ZERO_EXTEND); 5832 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5833 } 5834 } 5835 } 5836 5837 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5838 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5839 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5840 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5841 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5842 EVT MemVT = LN0->getMemoryVT(); 5843 if ((!LegalOperations && !LN0->isVolatile()) || 5844 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 5845 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5846 LN0->getChain(), 5847 LN0->getBasePtr(), MemVT, 5848 LN0->getMemOperand()); 5849 CombineTo(N, ExtLoad); 5850 CombineTo(N0.getNode(), 5851 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5852 ExtLoad), 5853 ExtLoad.getValue(1)); 5854 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5855 } 5856 } 5857 5858 if (N0.getOpcode() == ISD::SETCC) { 5859 if (!LegalOperations && VT.isVector() && 5860 N0.getValueType().getVectorElementType() == MVT::i1) { 5861 EVT N0VT = N0.getOperand(0).getValueType(); 5862 if (getSetCCResultType(N0VT) == N0.getValueType()) 5863 return SDValue(); 5864 5865 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5866 // Only do this before legalize for now. 5867 EVT EltVT = VT.getVectorElementType(); 5868 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5869 DAG.getConstant(1, EltVT)); 5870 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5871 // We know that the # elements of the results is the same as the 5872 // # elements of the compare (and the # elements of the compare result 5873 // for that matter). Check to see that they are the same size. If so, 5874 // we know that the element size of the sext'd result matches the 5875 // element size of the compare operands. 5876 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5877 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5878 N0.getOperand(1), 5879 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5880 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5881 OneOps)); 5882 5883 // If the desired elements are smaller or larger than the source 5884 // elements we can use a matching integer vector type and then 5885 // truncate/sign extend 5886 EVT MatchingElementType = 5887 EVT::getIntegerVT(*DAG.getContext(), 5888 N0VT.getScalarType().getSizeInBits()); 5889 EVT MatchingVectorType = 5890 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5891 N0VT.getVectorNumElements()); 5892 SDValue VsetCC = 5893 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5894 N0.getOperand(1), 5895 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5896 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5897 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5898 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps)); 5899 } 5900 5901 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5902 SDValue SCC = 5903 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5904 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5905 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5906 if (SCC.getNode()) return SCC; 5907 } 5908 5909 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5910 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5911 isa<ConstantSDNode>(N0.getOperand(1)) && 5912 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5913 N0.hasOneUse()) { 5914 SDValue ShAmt = N0.getOperand(1); 5915 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5916 if (N0.getOpcode() == ISD::SHL) { 5917 SDValue InnerZExt = N0.getOperand(0); 5918 // If the original shl may be shifting out bits, do not perform this 5919 // transformation. 5920 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5921 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5922 if (ShAmtVal > KnownZeroBits) 5923 return SDValue(); 5924 } 5925 5926 SDLoc DL(N); 5927 5928 // Ensure that the shift amount is wide enough for the shifted value. 5929 if (VT.getSizeInBits() >= 256) 5930 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5931 5932 return DAG.getNode(N0.getOpcode(), DL, VT, 5933 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5934 ShAmt); 5935 } 5936 5937 return SDValue(); 5938 } 5939 5940 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5941 SDValue N0 = N->getOperand(0); 5942 EVT VT = N->getValueType(0); 5943 5944 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5945 LegalOperations)) 5946 return SDValue(Res, 0); 5947 5948 // fold (aext (aext x)) -> (aext x) 5949 // fold (aext (zext x)) -> (zext x) 5950 // fold (aext (sext x)) -> (sext x) 5951 if (N0.getOpcode() == ISD::ANY_EXTEND || 5952 N0.getOpcode() == ISD::ZERO_EXTEND || 5953 N0.getOpcode() == ISD::SIGN_EXTEND) 5954 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5955 5956 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5957 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5958 if (N0.getOpcode() == ISD::TRUNCATE) { 5959 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5960 if (NarrowLoad.getNode()) { 5961 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5962 if (NarrowLoad.getNode() != N0.getNode()) { 5963 CombineTo(N0.getNode(), NarrowLoad); 5964 // CombineTo deleted the truncate, if needed, but not what's under it. 5965 AddToWorklist(oye); 5966 } 5967 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5968 } 5969 } 5970 5971 // fold (aext (truncate x)) 5972 if (N0.getOpcode() == ISD::TRUNCATE) { 5973 SDValue TruncOp = N0.getOperand(0); 5974 if (TruncOp.getValueType() == VT) 5975 return TruncOp; // x iff x size == zext size. 5976 if (TruncOp.getValueType().bitsGT(VT)) 5977 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5978 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5979 } 5980 5981 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5982 // if the trunc is not free. 5983 if (N0.getOpcode() == ISD::AND && 5984 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5985 N0.getOperand(1).getOpcode() == ISD::Constant && 5986 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5987 N0.getValueType())) { 5988 SDValue X = N0.getOperand(0).getOperand(0); 5989 if (X.getValueType().bitsLT(VT)) { 5990 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5991 } else if (X.getValueType().bitsGT(VT)) { 5992 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5993 } 5994 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5995 Mask = Mask.zext(VT.getSizeInBits()); 5996 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5997 X, DAG.getConstant(Mask, VT)); 5998 } 5999 6000 // fold (aext (load x)) -> (aext (truncate (extload x))) 6001 // None of the supported targets knows how to perform load and any_ext 6002 // on vectors in one instruction. We only perform this transformation on 6003 // scalars. 6004 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6005 ISD::isUNINDEXEDLoad(N0.getNode()) && 6006 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6007 bool DoXform = true; 6008 SmallVector<SDNode*, 4> SetCCs; 6009 if (!N0.hasOneUse()) 6010 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6011 if (DoXform) { 6012 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6013 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6014 LN0->getChain(), 6015 LN0->getBasePtr(), N0.getValueType(), 6016 LN0->getMemOperand()); 6017 CombineTo(N, ExtLoad); 6018 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6019 N0.getValueType(), ExtLoad); 6020 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6021 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6022 ISD::ANY_EXTEND); 6023 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6024 } 6025 } 6026 6027 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6028 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6029 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6030 if (N0.getOpcode() == ISD::LOAD && 6031 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6032 N0.hasOneUse()) { 6033 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6034 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6035 EVT MemVT = LN0->getMemoryVT(); 6036 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6037 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6038 VT, LN0->getChain(), LN0->getBasePtr(), 6039 MemVT, LN0->getMemOperand()); 6040 CombineTo(N, ExtLoad); 6041 CombineTo(N0.getNode(), 6042 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6043 N0.getValueType(), ExtLoad), 6044 ExtLoad.getValue(1)); 6045 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6046 } 6047 } 6048 6049 if (N0.getOpcode() == ISD::SETCC) { 6050 // For vectors: 6051 // aext(setcc) -> vsetcc 6052 // aext(setcc) -> truncate(vsetcc) 6053 // aext(setcc) -> aext(vsetcc) 6054 // Only do this before legalize for now. 6055 if (VT.isVector() && !LegalOperations) { 6056 EVT N0VT = N0.getOperand(0).getValueType(); 6057 // We know that the # elements of the results is the same as the 6058 // # elements of the compare (and the # elements of the compare result 6059 // for that matter). Check to see that they are the same size. If so, 6060 // we know that the element size of the sext'd result matches the 6061 // element size of the compare operands. 6062 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6063 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6064 N0.getOperand(1), 6065 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6066 // If the desired elements are smaller or larger than the source 6067 // elements we can use a matching integer vector type and then 6068 // truncate/any extend 6069 else { 6070 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6071 SDValue VsetCC = 6072 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6073 N0.getOperand(1), 6074 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6075 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6076 } 6077 } 6078 6079 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6080 SDValue SCC = 6081 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 6082 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 6083 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6084 if (SCC.getNode()) 6085 return SCC; 6086 } 6087 6088 return SDValue(); 6089 } 6090 6091 /// See if the specified operand can be simplified with the knowledge that only 6092 /// the bits specified by Mask are used. If so, return the simpler operand, 6093 /// otherwise return a null SDValue. 6094 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6095 switch (V.getOpcode()) { 6096 default: break; 6097 case ISD::Constant: { 6098 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6099 assert(CV && "Const value should be ConstSDNode."); 6100 const APInt &CVal = CV->getAPIntValue(); 6101 APInt NewVal = CVal & Mask; 6102 if (NewVal != CVal) 6103 return DAG.getConstant(NewVal, V.getValueType()); 6104 break; 6105 } 6106 case ISD::OR: 6107 case ISD::XOR: 6108 // If the LHS or RHS don't contribute bits to the or, drop them. 6109 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6110 return V.getOperand(1); 6111 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6112 return V.getOperand(0); 6113 break; 6114 case ISD::SRL: 6115 // Only look at single-use SRLs. 6116 if (!V.getNode()->hasOneUse()) 6117 break; 6118 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 6119 // See if we can recursively simplify the LHS. 6120 unsigned Amt = RHSC->getZExtValue(); 6121 6122 // Watch out for shift count overflow though. 6123 if (Amt >= Mask.getBitWidth()) break; 6124 APInt NewMask = Mask << Amt; 6125 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 6126 if (SimplifyLHS.getNode()) 6127 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6128 SimplifyLHS, V.getOperand(1)); 6129 } 6130 } 6131 return SDValue(); 6132 } 6133 6134 /// If the result of a wider load is shifted to right of N bits and then 6135 /// truncated to a narrower type and where N is a multiple of number of bits of 6136 /// the narrower type, transform it to a narrower load from address + N / num of 6137 /// bits of new type. If the result is to be extended, also fold the extension 6138 /// to form a extending load. 6139 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6140 unsigned Opc = N->getOpcode(); 6141 6142 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6143 SDValue N0 = N->getOperand(0); 6144 EVT VT = N->getValueType(0); 6145 EVT ExtVT = VT; 6146 6147 // This transformation isn't valid for vector loads. 6148 if (VT.isVector()) 6149 return SDValue(); 6150 6151 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6152 // extended to VT. 6153 if (Opc == ISD::SIGN_EXTEND_INREG) { 6154 ExtType = ISD::SEXTLOAD; 6155 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6156 } else if (Opc == ISD::SRL) { 6157 // Another special-case: SRL is basically zero-extending a narrower value. 6158 ExtType = ISD::ZEXTLOAD; 6159 N0 = SDValue(N, 0); 6160 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6161 if (!N01) return SDValue(); 6162 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6163 VT.getSizeInBits() - N01->getZExtValue()); 6164 } 6165 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6166 return SDValue(); 6167 6168 unsigned EVTBits = ExtVT.getSizeInBits(); 6169 6170 // Do not generate loads of non-round integer types since these can 6171 // be expensive (and would be wrong if the type is not byte sized). 6172 if (!ExtVT.isRound()) 6173 return SDValue(); 6174 6175 unsigned ShAmt = 0; 6176 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6177 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6178 ShAmt = N01->getZExtValue(); 6179 // Is the shift amount a multiple of size of VT? 6180 if ((ShAmt & (EVTBits-1)) == 0) { 6181 N0 = N0.getOperand(0); 6182 // Is the load width a multiple of size of VT? 6183 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6184 return SDValue(); 6185 } 6186 6187 // At this point, we must have a load or else we can't do the transform. 6188 if (!isa<LoadSDNode>(N0)) return SDValue(); 6189 6190 // Because a SRL must be assumed to *need* to zero-extend the high bits 6191 // (as opposed to anyext the high bits), we can't combine the zextload 6192 // lowering of SRL and an sextload. 6193 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6194 return SDValue(); 6195 6196 // If the shift amount is larger than the input type then we're not 6197 // accessing any of the loaded bytes. If the load was a zextload/extload 6198 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6199 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6200 return SDValue(); 6201 } 6202 } 6203 6204 // If the load is shifted left (and the result isn't shifted back right), 6205 // we can fold the truncate through the shift. 6206 unsigned ShLeftAmt = 0; 6207 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6208 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6209 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6210 ShLeftAmt = N01->getZExtValue(); 6211 N0 = N0.getOperand(0); 6212 } 6213 } 6214 6215 // If we haven't found a load, we can't narrow it. Don't transform one with 6216 // multiple uses, this would require adding a new load. 6217 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6218 return SDValue(); 6219 6220 // Don't change the width of a volatile load. 6221 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6222 if (LN0->isVolatile()) 6223 return SDValue(); 6224 6225 // Verify that we are actually reducing a load width here. 6226 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6227 return SDValue(); 6228 6229 // For the transform to be legal, the load must produce only two values 6230 // (the value loaded and the chain). Don't transform a pre-increment 6231 // load, for example, which produces an extra value. Otherwise the 6232 // transformation is not equivalent, and the downstream logic to replace 6233 // uses gets things wrong. 6234 if (LN0->getNumValues() > 2) 6235 return SDValue(); 6236 6237 // If the load that we're shrinking is an extload and we're not just 6238 // discarding the extension we can't simply shrink the load. Bail. 6239 // TODO: It would be possible to merge the extensions in some cases. 6240 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6241 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6242 return SDValue(); 6243 6244 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6245 return SDValue(); 6246 6247 EVT PtrType = N0.getOperand(1).getValueType(); 6248 6249 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6250 // It's not possible to generate a constant of extended or untyped type. 6251 return SDValue(); 6252 6253 // For big endian targets, we need to adjust the offset to the pointer to 6254 // load the correct bytes. 6255 if (TLI.isBigEndian()) { 6256 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6257 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6258 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6259 } 6260 6261 uint64_t PtrOff = ShAmt / 8; 6262 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6263 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 6264 PtrType, LN0->getBasePtr(), 6265 DAG.getConstant(PtrOff, PtrType)); 6266 AddToWorklist(NewPtr.getNode()); 6267 6268 SDValue Load; 6269 if (ExtType == ISD::NON_EXTLOAD) 6270 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6271 LN0->getPointerInfo().getWithOffset(PtrOff), 6272 LN0->isVolatile(), LN0->isNonTemporal(), 6273 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6274 else 6275 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6276 LN0->getPointerInfo().getWithOffset(PtrOff), 6277 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6278 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6279 6280 // Replace the old load's chain with the new load's chain. 6281 WorklistRemover DeadNodes(*this); 6282 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6283 6284 // Shift the result left, if we've swallowed a left shift. 6285 SDValue Result = Load; 6286 if (ShLeftAmt != 0) { 6287 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6288 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6289 ShImmTy = VT; 6290 // If the shift amount is as large as the result size (but, presumably, 6291 // no larger than the source) then the useful bits of the result are 6292 // zero; we can't simply return the shortened shift, because the result 6293 // of that operation is undefined. 6294 if (ShLeftAmt >= VT.getSizeInBits()) 6295 Result = DAG.getConstant(0, VT); 6296 else 6297 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 6298 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 6299 } 6300 6301 // Return the new loaded value. 6302 return Result; 6303 } 6304 6305 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6306 SDValue N0 = N->getOperand(0); 6307 SDValue N1 = N->getOperand(1); 6308 EVT VT = N->getValueType(0); 6309 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6310 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6311 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6312 6313 // fold (sext_in_reg c1) -> c1 6314 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6315 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6316 6317 // If the input is already sign extended, just drop the extension. 6318 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6319 return N0; 6320 6321 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6322 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6323 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6324 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6325 N0.getOperand(0), N1); 6326 6327 // fold (sext_in_reg (sext x)) -> (sext x) 6328 // fold (sext_in_reg (aext x)) -> (sext x) 6329 // if x is small enough. 6330 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6331 SDValue N00 = N0.getOperand(0); 6332 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6333 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6334 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6335 } 6336 6337 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6338 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6339 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6340 6341 // fold operands of sext_in_reg based on knowledge that the top bits are not 6342 // demanded. 6343 if (SimplifyDemandedBits(SDValue(N, 0))) 6344 return SDValue(N, 0); 6345 6346 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6347 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6348 SDValue NarrowLoad = ReduceLoadWidth(N); 6349 if (NarrowLoad.getNode()) 6350 return NarrowLoad; 6351 6352 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6353 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6354 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6355 if (N0.getOpcode() == ISD::SRL) { 6356 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6357 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6358 // We can turn this into an SRA iff the input to the SRL is already sign 6359 // extended enough. 6360 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6361 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6362 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6363 N0.getOperand(0), N0.getOperand(1)); 6364 } 6365 } 6366 6367 // fold (sext_inreg (extload x)) -> (sextload x) 6368 if (ISD::isEXTLoad(N0.getNode()) && 6369 ISD::isUNINDEXEDLoad(N0.getNode()) && 6370 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6371 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6372 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6373 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6374 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6375 LN0->getChain(), 6376 LN0->getBasePtr(), EVT, 6377 LN0->getMemOperand()); 6378 CombineTo(N, ExtLoad); 6379 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6380 AddToWorklist(ExtLoad.getNode()); 6381 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6382 } 6383 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6384 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6385 N0.hasOneUse() && 6386 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6387 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6388 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6389 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6390 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6391 LN0->getChain(), 6392 LN0->getBasePtr(), EVT, 6393 LN0->getMemOperand()); 6394 CombineTo(N, ExtLoad); 6395 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6396 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6397 } 6398 6399 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6400 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6401 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6402 N0.getOperand(1), false); 6403 if (BSwap.getNode()) 6404 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6405 BSwap, N1); 6406 } 6407 6408 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6409 // into a build_vector. 6410 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6411 SmallVector<SDValue, 8> Elts; 6412 unsigned NumElts = N0->getNumOperands(); 6413 unsigned ShAmt = VTBits - EVTBits; 6414 6415 for (unsigned i = 0; i != NumElts; ++i) { 6416 SDValue Op = N0->getOperand(i); 6417 if (Op->getOpcode() == ISD::UNDEF) { 6418 Elts.push_back(Op); 6419 continue; 6420 } 6421 6422 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6423 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6424 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6425 Op.getValueType())); 6426 } 6427 6428 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6429 } 6430 6431 return SDValue(); 6432 } 6433 6434 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6435 SDValue N0 = N->getOperand(0); 6436 EVT VT = N->getValueType(0); 6437 bool isLE = TLI.isLittleEndian(); 6438 6439 // noop truncate 6440 if (N0.getValueType() == N->getValueType(0)) 6441 return N0; 6442 // fold (truncate c1) -> c1 6443 if (isa<ConstantSDNode>(N0)) 6444 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6445 // fold (truncate (truncate x)) -> (truncate x) 6446 if (N0.getOpcode() == ISD::TRUNCATE) 6447 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6448 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6449 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6450 N0.getOpcode() == ISD::SIGN_EXTEND || 6451 N0.getOpcode() == ISD::ANY_EXTEND) { 6452 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6453 // if the source is smaller than the dest, we still need an extend 6454 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6455 N0.getOperand(0)); 6456 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6457 // if the source is larger than the dest, than we just need the truncate 6458 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6459 // if the source and dest are the same type, we can drop both the extend 6460 // and the truncate. 6461 return N0.getOperand(0); 6462 } 6463 6464 // Fold extract-and-trunc into a narrow extract. For example: 6465 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6466 // i32 y = TRUNCATE(i64 x) 6467 // -- becomes -- 6468 // v16i8 b = BITCAST (v2i64 val) 6469 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6470 // 6471 // Note: We only run this optimization after type legalization (which often 6472 // creates this pattern) and before operation legalization after which 6473 // we need to be more careful about the vector instructions that we generate. 6474 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6475 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6476 6477 EVT VecTy = N0.getOperand(0).getValueType(); 6478 EVT ExTy = N0.getValueType(); 6479 EVT TrTy = N->getValueType(0); 6480 6481 unsigned NumElem = VecTy.getVectorNumElements(); 6482 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6483 6484 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6485 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6486 6487 SDValue EltNo = N0->getOperand(1); 6488 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6489 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6490 EVT IndexTy = TLI.getVectorIdxTy(); 6491 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6492 6493 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6494 NVT, N0.getOperand(0)); 6495 6496 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6497 SDLoc(N), TrTy, V, 6498 DAG.getConstant(Index, IndexTy)); 6499 } 6500 } 6501 6502 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6503 if (N0.getOpcode() == ISD::SELECT) { 6504 EVT SrcVT = N0.getValueType(); 6505 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6506 TLI.isTruncateFree(SrcVT, VT)) { 6507 SDLoc SL(N0); 6508 SDValue Cond = N0.getOperand(0); 6509 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6510 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6511 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6512 } 6513 } 6514 6515 // Fold a series of buildvector, bitcast, and truncate if possible. 6516 // For example fold 6517 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6518 // (2xi32 (buildvector x, y)). 6519 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6520 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6521 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6522 N0.getOperand(0).hasOneUse()) { 6523 6524 SDValue BuildVect = N0.getOperand(0); 6525 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6526 EVT TruncVecEltTy = VT.getVectorElementType(); 6527 6528 // Check that the element types match. 6529 if (BuildVectEltTy == TruncVecEltTy) { 6530 // Now we only need to compute the offset of the truncated elements. 6531 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6532 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6533 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6534 6535 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6536 "Invalid number of elements"); 6537 6538 SmallVector<SDValue, 8> Opnds; 6539 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6540 Opnds.push_back(BuildVect.getOperand(i)); 6541 6542 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6543 } 6544 } 6545 6546 // See if we can simplify the input to this truncate through knowledge that 6547 // only the low bits are being used. 6548 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6549 // Currently we only perform this optimization on scalars because vectors 6550 // may have different active low bits. 6551 if (!VT.isVector()) { 6552 SDValue Shorter = 6553 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6554 VT.getSizeInBits())); 6555 if (Shorter.getNode()) 6556 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6557 } 6558 // fold (truncate (load x)) -> (smaller load x) 6559 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6560 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6561 SDValue Reduced = ReduceLoadWidth(N); 6562 if (Reduced.getNode()) 6563 return Reduced; 6564 // Handle the case where the load remains an extending load even 6565 // after truncation. 6566 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6567 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6568 if (!LN0->isVolatile() && 6569 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6570 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6571 VT, LN0->getChain(), LN0->getBasePtr(), 6572 LN0->getMemoryVT(), 6573 LN0->getMemOperand()); 6574 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6575 return NewLoad; 6576 } 6577 } 6578 } 6579 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6580 // where ... are all 'undef'. 6581 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6582 SmallVector<EVT, 8> VTs; 6583 SDValue V; 6584 unsigned Idx = 0; 6585 unsigned NumDefs = 0; 6586 6587 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6588 SDValue X = N0.getOperand(i); 6589 if (X.getOpcode() != ISD::UNDEF) { 6590 V = X; 6591 Idx = i; 6592 NumDefs++; 6593 } 6594 // Stop if more than one members are non-undef. 6595 if (NumDefs > 1) 6596 break; 6597 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6598 VT.getVectorElementType(), 6599 X.getValueType().getVectorNumElements())); 6600 } 6601 6602 if (NumDefs == 0) 6603 return DAG.getUNDEF(VT); 6604 6605 if (NumDefs == 1) { 6606 assert(V.getNode() && "The single defined operand is empty!"); 6607 SmallVector<SDValue, 8> Opnds; 6608 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6609 if (i != Idx) { 6610 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6611 continue; 6612 } 6613 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6614 AddToWorklist(NV.getNode()); 6615 Opnds.push_back(NV); 6616 } 6617 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6618 } 6619 } 6620 6621 // Simplify the operands using demanded-bits information. 6622 if (!VT.isVector() && 6623 SimplifyDemandedBits(SDValue(N, 0))) 6624 return SDValue(N, 0); 6625 6626 return SDValue(); 6627 } 6628 6629 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6630 SDValue Elt = N->getOperand(i); 6631 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6632 return Elt.getNode(); 6633 return Elt.getOperand(Elt.getResNo()).getNode(); 6634 } 6635 6636 /// build_pair (load, load) -> load 6637 /// if load locations are consecutive. 6638 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6639 assert(N->getOpcode() == ISD::BUILD_PAIR); 6640 6641 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6642 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6643 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6644 LD1->getAddressSpace() != LD2->getAddressSpace()) 6645 return SDValue(); 6646 EVT LD1VT = LD1->getValueType(0); 6647 6648 if (ISD::isNON_EXTLoad(LD2) && 6649 LD2->hasOneUse() && 6650 // If both are volatile this would reduce the number of volatile loads. 6651 // If one is volatile it might be ok, but play conservative and bail out. 6652 !LD1->isVolatile() && 6653 !LD2->isVolatile() && 6654 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 6655 unsigned Align = LD1->getAlignment(); 6656 unsigned NewAlign = TLI.getDataLayout()-> 6657 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6658 6659 if (NewAlign <= Align && 6660 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 6661 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 6662 LD1->getBasePtr(), LD1->getPointerInfo(), 6663 false, false, false, Align); 6664 } 6665 6666 return SDValue(); 6667 } 6668 6669 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 6670 SDValue N0 = N->getOperand(0); 6671 EVT VT = N->getValueType(0); 6672 6673 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 6674 // Only do this before legalize, since afterward the target may be depending 6675 // on the bitconvert. 6676 // First check to see if this is all constant. 6677 if (!LegalTypes && 6678 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6679 VT.isVector()) { 6680 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6681 6682 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6683 assert(!DestEltVT.isVector() && 6684 "Element type of vector ValueType must not be vector!"); 6685 if (isSimple) 6686 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6687 } 6688 6689 // If the input is a constant, let getNode fold it. 6690 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6691 // If we can't allow illegal operations, we need to check that this is just 6692 // a fp -> int or int -> conversion and that the resulting operation will 6693 // be legal. 6694 if (!LegalOperations || 6695 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 6696 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 6697 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 6698 TLI.isOperationLegal(ISD::Constant, VT))) 6699 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6700 } 6701 6702 // (conv (conv x, t1), t2) -> (conv x, t2) 6703 if (N0.getOpcode() == ISD::BITCAST) 6704 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6705 N0.getOperand(0)); 6706 6707 // fold (conv (load x)) -> (load (conv*)x) 6708 // If the resultant load doesn't need a higher alignment than the original! 6709 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6710 // Do not change the width of a volatile load. 6711 !cast<LoadSDNode>(N0)->isVolatile() && 6712 // Do not remove the cast if the types differ in endian layout. 6713 TLI.hasBigEndianPartOrdering(N0.getValueType()) == 6714 TLI.hasBigEndianPartOrdering(VT) && 6715 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6716 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6717 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6718 unsigned Align = TLI.getDataLayout()-> 6719 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6720 unsigned OrigAlign = LN0->getAlignment(); 6721 6722 if (Align <= OrigAlign) { 6723 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6724 LN0->getBasePtr(), LN0->getPointerInfo(), 6725 LN0->isVolatile(), LN0->isNonTemporal(), 6726 LN0->isInvariant(), OrigAlign, 6727 LN0->getAAInfo()); 6728 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6729 return Load; 6730 } 6731 } 6732 6733 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6734 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6735 // This often reduces constant pool loads. 6736 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6737 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6738 N0.getNode()->hasOneUse() && VT.isInteger() && 6739 !VT.isVector() && !N0.getValueType().isVector()) { 6740 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6741 N0.getOperand(0)); 6742 AddToWorklist(NewConv.getNode()); 6743 6744 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6745 if (N0.getOpcode() == ISD::FNEG) 6746 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6747 NewConv, DAG.getConstant(SignBit, VT)); 6748 assert(N0.getOpcode() == ISD::FABS); 6749 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6750 NewConv, DAG.getConstant(~SignBit, VT)); 6751 } 6752 6753 // fold (bitconvert (fcopysign cst, x)) -> 6754 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6755 // Note that we don't handle (copysign x, cst) because this can always be 6756 // folded to an fneg or fabs. 6757 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6758 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6759 VT.isInteger() && !VT.isVector()) { 6760 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6761 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6762 if (isTypeLegal(IntXVT)) { 6763 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6764 IntXVT, N0.getOperand(1)); 6765 AddToWorklist(X.getNode()); 6766 6767 // If X has a different width than the result/lhs, sext it or truncate it. 6768 unsigned VTWidth = VT.getSizeInBits(); 6769 if (OrigXWidth < VTWidth) { 6770 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6771 AddToWorklist(X.getNode()); 6772 } else if (OrigXWidth > VTWidth) { 6773 // To get the sign bit in the right place, we have to shift it right 6774 // before truncating. 6775 X = DAG.getNode(ISD::SRL, SDLoc(X), 6776 X.getValueType(), X, 6777 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6778 AddToWorklist(X.getNode()); 6779 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6780 AddToWorklist(X.getNode()); 6781 } 6782 6783 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6784 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6785 X, DAG.getConstant(SignBit, VT)); 6786 AddToWorklist(X.getNode()); 6787 6788 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6789 VT, N0.getOperand(0)); 6790 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6791 Cst, DAG.getConstant(~SignBit, VT)); 6792 AddToWorklist(Cst.getNode()); 6793 6794 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6795 } 6796 } 6797 6798 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6799 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6800 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6801 if (CombineLD.getNode()) 6802 return CombineLD; 6803 } 6804 6805 return SDValue(); 6806 } 6807 6808 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6809 EVT VT = N->getValueType(0); 6810 return CombineConsecutiveLoads(N, VT); 6811 } 6812 6813 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 6814 /// operands. DstEltVT indicates the destination element value type. 6815 SDValue DAGCombiner:: 6816 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6817 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6818 6819 // If this is already the right type, we're done. 6820 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6821 6822 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6823 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6824 6825 // If this is a conversion of N elements of one type to N elements of another 6826 // type, convert each element. This handles FP<->INT cases. 6827 if (SrcBitSize == DstBitSize) { 6828 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6829 BV->getValueType(0).getVectorNumElements()); 6830 6831 // Due to the FP element handling below calling this routine recursively, 6832 // we can end up with a scalar-to-vector node here. 6833 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6834 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6835 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6836 DstEltVT, BV->getOperand(0))); 6837 6838 SmallVector<SDValue, 8> Ops; 6839 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6840 SDValue Op = BV->getOperand(i); 6841 // If the vector element type is not legal, the BUILD_VECTOR operands 6842 // are promoted and implicitly truncated. Make that explicit here. 6843 if (Op.getValueType() != SrcEltVT) 6844 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6845 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6846 DstEltVT, Op)); 6847 AddToWorklist(Ops.back().getNode()); 6848 } 6849 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6850 } 6851 6852 // Otherwise, we're growing or shrinking the elements. To avoid having to 6853 // handle annoying details of growing/shrinking FP values, we convert them to 6854 // int first. 6855 if (SrcEltVT.isFloatingPoint()) { 6856 // Convert the input float vector to a int vector where the elements are the 6857 // same sizes. 6858 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6859 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6860 SrcEltVT = IntVT; 6861 } 6862 6863 // Now we know the input is an integer vector. If the output is a FP type, 6864 // convert to integer first, then to FP of the right size. 6865 if (DstEltVT.isFloatingPoint()) { 6866 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6867 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6868 6869 // Next, convert to FP elements of the same size. 6870 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6871 } 6872 6873 // Okay, we know the src/dst types are both integers of differing types. 6874 // Handling growing first. 6875 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 6876 if (SrcBitSize < DstBitSize) { 6877 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 6878 6879 SmallVector<SDValue, 8> Ops; 6880 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 6881 i += NumInputsPerOutput) { 6882 bool isLE = TLI.isLittleEndian(); 6883 APInt NewBits = APInt(DstBitSize, 0); 6884 bool EltIsUndef = true; 6885 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 6886 // Shift the previously computed bits over. 6887 NewBits <<= SrcBitSize; 6888 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 6889 if (Op.getOpcode() == ISD::UNDEF) continue; 6890 EltIsUndef = false; 6891 6892 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 6893 zextOrTrunc(SrcBitSize).zext(DstBitSize); 6894 } 6895 6896 if (EltIsUndef) 6897 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6898 else 6899 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 6900 } 6901 6902 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 6903 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6904 } 6905 6906 // Finally, this must be the case where we are shrinking elements: each input 6907 // turns into multiple outputs. 6908 bool isS2V = ISD::isScalarToVector(BV); 6909 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 6910 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6911 NumOutputsPerInput*BV->getNumOperands()); 6912 SmallVector<SDValue, 8> Ops; 6913 6914 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6915 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6916 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 6917 continue; 6918 } 6919 6920 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6921 getAPIntValue().zextOrTrunc(SrcBitSize); 6922 6923 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6924 APInt ThisVal = OpVal.trunc(DstBitSize); 6925 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6926 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6927 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6928 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6929 Ops[0]); 6930 OpVal = OpVal.lshr(DstBitSize); 6931 } 6932 6933 // For big endian targets, swap the order of the pieces of each element. 6934 if (TLI.isBigEndian()) 6935 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6936 } 6937 6938 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6939 } 6940 6941 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad 6942 static SDValue performFaddFmulCombines(unsigned FusedOpcode, 6943 bool Aggressive, 6944 SDNode *N, 6945 const TargetLowering &TLI, 6946 SelectionDAG &DAG) { 6947 SDValue N0 = N->getOperand(0); 6948 SDValue N1 = N->getOperand(1); 6949 EVT VT = N->getValueType(0); 6950 6951 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6952 if (N0.getOpcode() == ISD::FMUL && 6953 (Aggressive || N0->hasOneUse())) { 6954 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 6955 N0.getOperand(0), N0.getOperand(1), N1); 6956 } 6957 6958 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6959 // Note: Commutes FADD operands. 6960 if (N1.getOpcode() == ISD::FMUL && 6961 (Aggressive || N1->hasOneUse())) { 6962 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 6963 N1.getOperand(0), N1.getOperand(1), N0); 6964 } 6965 6966 // More folding opportunities when target permits. 6967 if (Aggressive) { 6968 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 6969 if (N0.getOpcode() == ISD::FMA && 6970 N0.getOperand(2).getOpcode() == ISD::FMUL) { 6971 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 6972 N0.getOperand(0), N0.getOperand(1), 6973 DAG.getNode(FusedOpcode, SDLoc(N), VT, 6974 N0.getOperand(2).getOperand(0), 6975 N0.getOperand(2).getOperand(1), 6976 N1)); 6977 } 6978 6979 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 6980 if (N1->getOpcode() == ISD::FMA && 6981 N1.getOperand(2).getOpcode() == ISD::FMUL) { 6982 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 6983 N1.getOperand(0), N1.getOperand(1), 6984 DAG.getNode(FusedOpcode, SDLoc(N), VT, 6985 N1.getOperand(2).getOperand(0), 6986 N1.getOperand(2).getOperand(1), 6987 N0)); 6988 } 6989 } 6990 6991 return SDValue(); 6992 } 6993 6994 static SDValue performFsubFmulCombines(unsigned FusedOpcode, 6995 bool Aggressive, 6996 SDNode *N, 6997 const TargetLowering &TLI, 6998 SelectionDAG &DAG) { 6999 SDValue N0 = N->getOperand(0); 7000 SDValue N1 = N->getOperand(1); 7001 EVT VT = N->getValueType(0); 7002 7003 SDLoc SL(N); 7004 7005 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7006 if (N0.getOpcode() == ISD::FMUL && 7007 (Aggressive || N0->hasOneUse())) { 7008 return DAG.getNode(FusedOpcode, SL, VT, 7009 N0.getOperand(0), N0.getOperand(1), 7010 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7011 } 7012 7013 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7014 // Note: Commutes FSUB operands. 7015 if (N1.getOpcode() == ISD::FMUL && 7016 (Aggressive || N1->hasOneUse())) 7017 return DAG.getNode(FusedOpcode, SL, VT, 7018 DAG.getNode(ISD::FNEG, SL, VT, 7019 N1.getOperand(0)), 7020 N1.getOperand(1), N0); 7021 7022 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7023 if (N0.getOpcode() == ISD::FNEG && 7024 N0.getOperand(0).getOpcode() == ISD::FMUL && 7025 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7026 SDValue N00 = N0.getOperand(0).getOperand(0); 7027 SDValue N01 = N0.getOperand(0).getOperand(1); 7028 return DAG.getNode(FusedOpcode, SL, VT, 7029 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7030 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7031 } 7032 7033 // More folding opportunities when target permits. 7034 if (Aggressive) { 7035 // fold (fsub (fma x, y, (fmul u, v)), z) 7036 // -> (fma x, y (fma u, v, (fneg z))) 7037 if (N0.getOpcode() == FusedOpcode && 7038 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7039 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7040 N0.getOperand(0), N0.getOperand(1), 7041 DAG.getNode(FusedOpcode, SDLoc(N), VT, 7042 N0.getOperand(2).getOperand(0), 7043 N0.getOperand(2).getOperand(1), 7044 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7045 N1))); 7046 } 7047 7048 // fold (fsub x, (fma y, z, (fmul u, v))) 7049 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7050 if (N1.getOpcode() == FusedOpcode && 7051 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7052 SDValue N20 = N1.getOperand(2).getOperand(0); 7053 SDValue N21 = N1.getOperand(2).getOperand(1); 7054 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7055 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7056 N1.getOperand(0)), 7057 N1.getOperand(1), 7058 DAG.getNode(FusedOpcode, SDLoc(N), VT, 7059 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7060 N20), 7061 N21, N0)); 7062 } 7063 } 7064 7065 return SDValue(); 7066 } 7067 7068 SDValue DAGCombiner::visitFADD(SDNode *N) { 7069 SDValue N0 = N->getOperand(0); 7070 SDValue N1 = N->getOperand(1); 7071 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7072 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7073 EVT VT = N->getValueType(0); 7074 const TargetOptions &Options = DAG.getTarget().Options; 7075 7076 // fold vector ops 7077 if (VT.isVector()) { 7078 SDValue FoldedVOp = SimplifyVBinOp(N); 7079 if (FoldedVOp.getNode()) return FoldedVOp; 7080 } 7081 7082 // fold (fadd c1, c2) -> c1 + c2 7083 if (N0CFP && N1CFP) 7084 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 7085 7086 // canonicalize constant to RHS 7087 if (N0CFP && !N1CFP) 7088 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 7089 7090 // fold (fadd A, (fneg B)) -> (fsub A, B) 7091 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7092 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 7093 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 7094 GetNegatedExpression(N1, DAG, LegalOperations)); 7095 7096 // fold (fadd (fneg A), B) -> (fsub B, A) 7097 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7098 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 7099 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 7100 GetNegatedExpression(N0, DAG, LegalOperations)); 7101 7102 // If 'unsafe math' is enabled, fold lots of things. 7103 if (Options.UnsafeFPMath) { 7104 // No FP constant should be created after legalization as Instruction 7105 // Selection pass has a hard time dealing with FP constants. 7106 bool AllowNewConst = (Level < AfterLegalizeDAG); 7107 7108 // fold (fadd A, 0) -> A 7109 if (N1CFP && N1CFP->getValueAPF().isZero()) 7110 return N0; 7111 7112 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 7113 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 7114 isa<ConstantFPSDNode>(N0.getOperand(1))) 7115 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 7116 DAG.getNode(ISD::FADD, SDLoc(N), VT, 7117 N0.getOperand(1), N1)); 7118 7119 // If allowed, fold (fadd (fneg x), x) -> 0.0 7120 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 7121 return DAG.getConstantFP(0.0, VT); 7122 7123 // If allowed, fold (fadd x, (fneg x)) -> 0.0 7124 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 7125 return DAG.getConstantFP(0.0, VT); 7126 7127 // We can fold chains of FADD's of the same value into multiplications. 7128 // This transform is not safe in general because we are reducing the number 7129 // of rounding steps. 7130 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 7131 if (N0.getOpcode() == ISD::FMUL) { 7132 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7133 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7134 7135 // (fadd (fmul x, c), x) -> (fmul x, c+1) 7136 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 7137 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7138 SDValue(CFP01, 0), 7139 DAG.getConstantFP(1.0, VT)); 7140 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP); 7141 } 7142 7143 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 7144 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 7145 N1.getOperand(0) == N1.getOperand(1) && 7146 N0.getOperand(0) == N1.getOperand(0)) { 7147 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7148 SDValue(CFP01, 0), 7149 DAG.getConstantFP(2.0, VT)); 7150 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7151 N0.getOperand(0), NewCFP); 7152 } 7153 } 7154 7155 if (N1.getOpcode() == ISD::FMUL) { 7156 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7157 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 7158 7159 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 7160 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 7161 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7162 SDValue(CFP11, 0), 7163 DAG.getConstantFP(1.0, VT)); 7164 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP); 7165 } 7166 7167 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 7168 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 7169 N0.getOperand(0) == N0.getOperand(1) && 7170 N1.getOperand(0) == N0.getOperand(0)) { 7171 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7172 SDValue(CFP11, 0), 7173 DAG.getConstantFP(2.0, VT)); 7174 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP); 7175 } 7176 } 7177 7178 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 7179 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7180 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 7181 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 7182 (N0.getOperand(0) == N1)) 7183 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7184 N1, DAG.getConstantFP(3.0, VT)); 7185 } 7186 7187 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 7188 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7189 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 7190 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 7191 N1.getOperand(0) == N0) 7192 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7193 N0, DAG.getConstantFP(3.0, VT)); 7194 } 7195 7196 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 7197 if (AllowNewConst && 7198 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 7199 N0.getOperand(0) == N0.getOperand(1) && 7200 N1.getOperand(0) == N1.getOperand(1) && 7201 N0.getOperand(0) == N1.getOperand(0)) 7202 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7203 N0.getOperand(0), DAG.getConstantFP(4.0, VT)); 7204 } 7205 } // enable-unsafe-fp-math 7206 7207 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) { 7208 // Assume if there is an fmad instruction that it should be aggressively 7209 // used. 7210 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG)) 7211 return Fused; 7212 } 7213 7214 // FADD -> FMA combines: 7215 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 7216 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7217 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 7218 7219 if (!TLI.isOperationLegal(ISD::FMAD, VT)) { 7220 // Don't form FMA if we are preferring FMAD. 7221 if (SDValue Fused 7222 = performFaddFmulCombines(ISD::FMA, 7223 TLI.enableAggressiveFMAFusion(VT), 7224 N, TLI, DAG)) { 7225 return Fused; 7226 } 7227 } 7228 7229 // When FP_EXTEND nodes are free on the target, and there is an opportunity 7230 // to combine into FMA, arrange such nodes accordingly. 7231 if (TLI.isFPExtFree(VT)) { 7232 7233 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7234 if (N0.getOpcode() == ISD::FP_EXTEND) { 7235 SDValue N00 = N0.getOperand(0); 7236 if (N00.getOpcode() == ISD::FMUL) 7237 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7238 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7239 N00.getOperand(0)), 7240 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7241 N00.getOperand(1)), N1); 7242 } 7243 7244 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x) 7245 // Note: Commutes FADD operands. 7246 if (N1.getOpcode() == ISD::FP_EXTEND) { 7247 SDValue N10 = N1.getOperand(0); 7248 if (N10.getOpcode() == ISD::FMUL) 7249 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7250 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7251 N10.getOperand(0)), 7252 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7253 N10.getOperand(1)), N0); 7254 } 7255 } 7256 } 7257 7258 return SDValue(); 7259 } 7260 7261 SDValue DAGCombiner::visitFSUB(SDNode *N) { 7262 SDValue N0 = N->getOperand(0); 7263 SDValue N1 = N->getOperand(1); 7264 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7265 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7266 EVT VT = N->getValueType(0); 7267 SDLoc dl(N); 7268 const TargetOptions &Options = DAG.getTarget().Options; 7269 7270 // fold vector ops 7271 if (VT.isVector()) { 7272 SDValue FoldedVOp = SimplifyVBinOp(N); 7273 if (FoldedVOp.getNode()) return FoldedVOp; 7274 } 7275 7276 // fold (fsub c1, c2) -> c1-c2 7277 if (N0CFP && N1CFP) 7278 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 7279 7280 // fold (fsub A, (fneg B)) -> (fadd A, B) 7281 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7282 return DAG.getNode(ISD::FADD, dl, VT, N0, 7283 GetNegatedExpression(N1, DAG, LegalOperations)); 7284 7285 // If 'unsafe math' is enabled, fold lots of things. 7286 if (Options.UnsafeFPMath) { 7287 // (fsub A, 0) -> A 7288 if (N1CFP && N1CFP->getValueAPF().isZero()) 7289 return N0; 7290 7291 // (fsub 0, B) -> -B 7292 if (N0CFP && N0CFP->getValueAPF().isZero()) { 7293 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7294 return GetNegatedExpression(N1, DAG, LegalOperations); 7295 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7296 return DAG.getNode(ISD::FNEG, dl, VT, N1); 7297 } 7298 7299 // (fsub x, x) -> 0.0 7300 if (N0 == N1) 7301 return DAG.getConstantFP(0.0f, VT); 7302 7303 // (fsub x, (fadd x, y)) -> (fneg y) 7304 // (fsub x, (fadd y, x)) -> (fneg y) 7305 if (N1.getOpcode() == ISD::FADD) { 7306 SDValue N10 = N1->getOperand(0); 7307 SDValue N11 = N1->getOperand(1); 7308 7309 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 7310 return GetNegatedExpression(N11, DAG, LegalOperations); 7311 7312 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 7313 return GetNegatedExpression(N10, DAG, LegalOperations); 7314 } 7315 } 7316 7317 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) { 7318 // Assume if there is an fmad instruction that it should be aggressively 7319 // used. 7320 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG)) 7321 return Fused; 7322 } 7323 7324 // FSUB -> FMA combines: 7325 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 7326 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7327 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 7328 7329 if (!TLI.isOperationLegal(ISD::FMAD, VT)) { 7330 // Don't form FMA if we are preferring FMAD. 7331 7332 if (SDValue Fused 7333 = performFsubFmulCombines(ISD::FMA, 7334 TLI.enableAggressiveFMAFusion(VT), 7335 N, TLI, DAG)) { 7336 return Fused; 7337 } 7338 } 7339 7340 // When FP_EXTEND nodes are free on the target, and there is an opportunity 7341 // to combine into FMA, arrange such nodes accordingly. 7342 if (TLI.isFPExtFree(VT)) { 7343 // fold (fsub (fpext (fmul x, y)), z) 7344 // -> (fma (fpext x), (fpext y), (fneg z)) 7345 if (N0.getOpcode() == ISD::FP_EXTEND) { 7346 SDValue N00 = N0.getOperand(0); 7347 if (N00.getOpcode() == ISD::FMUL) 7348 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7349 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7350 N00.getOperand(0)), 7351 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7352 N00.getOperand(1)), 7353 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1)); 7354 } 7355 7356 // fold (fsub x, (fpext (fmul y, z))) 7357 // -> (fma (fneg (fpext y)), (fpext z), x) 7358 // Note: Commutes FSUB operands. 7359 if (N1.getOpcode() == ISD::FP_EXTEND) { 7360 SDValue N10 = N1.getOperand(0); 7361 if (N10.getOpcode() == ISD::FMUL) 7362 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7363 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7364 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7365 VT, N10.getOperand(0))), 7366 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7367 N10.getOperand(1)), 7368 N0); 7369 } 7370 7371 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7372 // -> (fma (fneg (fpext x)), (fpext y), (fneg z)) 7373 if (N0.getOpcode() == ISD::FP_EXTEND) { 7374 SDValue N00 = N0.getOperand(0); 7375 if (N00.getOpcode() == ISD::FNEG) { 7376 SDValue N000 = N00.getOperand(0); 7377 if (N000.getOpcode() == ISD::FMUL) { 7378 return DAG.getNode(ISD::FMA, dl, VT, 7379 DAG.getNode(ISD::FNEG, dl, VT, 7380 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7381 VT, N000.getOperand(0))), 7382 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7383 N000.getOperand(1)), 7384 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7385 } 7386 } 7387 } 7388 7389 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7390 // -> (fma (fneg (fpext x)), (fpext y), (fneg z)) 7391 if (N0.getOpcode() == ISD::FNEG) { 7392 SDValue N00 = N0.getOperand(0); 7393 if (N00.getOpcode() == ISD::FP_EXTEND) { 7394 SDValue N000 = N00.getOperand(0); 7395 if (N000.getOpcode() == ISD::FMUL) { 7396 return DAG.getNode(ISD::FMA, dl, VT, 7397 DAG.getNode(ISD::FNEG, dl, VT, 7398 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7399 VT, N000.getOperand(0))), 7400 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7401 N000.getOperand(1)), 7402 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7403 } 7404 } 7405 } 7406 } 7407 } 7408 7409 return SDValue(); 7410 } 7411 7412 SDValue DAGCombiner::visitFMUL(SDNode *N) { 7413 SDValue N0 = N->getOperand(0); 7414 SDValue N1 = N->getOperand(1); 7415 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7416 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7417 EVT VT = N->getValueType(0); 7418 const TargetOptions &Options = DAG.getTarget().Options; 7419 7420 // fold vector ops 7421 if (VT.isVector()) { 7422 // This just handles C1 * C2 for vectors. Other vector folds are below. 7423 SDValue FoldedVOp = SimplifyVBinOp(N); 7424 if (FoldedVOp.getNode()) 7425 return FoldedVOp; 7426 // Canonicalize vector constant to RHS. 7427 if (N0.getOpcode() == ISD::BUILD_VECTOR && 7428 N1.getOpcode() != ISD::BUILD_VECTOR) 7429 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0)) 7430 if (BV0->isConstant()) 7431 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 7432 } 7433 7434 // fold (fmul c1, c2) -> c1*c2 7435 if (N0CFP && N1CFP) 7436 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 7437 7438 // canonicalize constant to RHS 7439 if (N0CFP && !N1CFP) 7440 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 7441 7442 // fold (fmul A, 1.0) -> A 7443 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7444 return N0; 7445 7446 if (Options.UnsafeFPMath) { 7447 // fold (fmul A, 0) -> 0 7448 if (N1CFP && N1CFP->getValueAPF().isZero()) 7449 return N1; 7450 7451 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 7452 if (N0.getOpcode() == ISD::FMUL) { 7453 // Fold scalars or any vector constants (not just splats). 7454 // This fold is done in general by InstCombine, but extra fmul insts 7455 // may have been generated during lowering. 7456 SDValue N00 = N0.getOperand(0); 7457 SDValue N01 = N0.getOperand(1); 7458 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 7459 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 7460 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 7461 7462 // Check 1: Make sure that the first operand of the inner multiply is NOT 7463 // a constant. Otherwise, we may induce infinite looping. 7464 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 7465 // Check 2: Make sure that the second operand of the inner multiply and 7466 // the second operand of the outer multiply are constants. 7467 if ((N1CFP && isConstOrConstSplatFP(N01)) || 7468 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 7469 SDLoc SL(N); 7470 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1); 7471 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts); 7472 } 7473 } 7474 } 7475 7476 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 7477 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 7478 // during an early run of DAGCombiner can prevent folding with fmuls 7479 // inserted during lowering. 7480 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) { 7481 SDLoc SL(N); 7482 const SDValue Two = DAG.getConstantFP(2.0, VT); 7483 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1); 7484 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts); 7485 } 7486 } 7487 7488 // fold (fmul X, 2.0) -> (fadd X, X) 7489 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 7490 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 7491 7492 // fold (fmul X, -1.0) -> (fneg X) 7493 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 7494 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7495 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 7496 7497 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 7498 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7499 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7500 // Both can be negated for free, check to see if at least one is cheaper 7501 // negated. 7502 if (LHSNeg == 2 || RHSNeg == 2) 7503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7504 GetNegatedExpression(N0, DAG, LegalOperations), 7505 GetNegatedExpression(N1, DAG, LegalOperations)); 7506 } 7507 } 7508 7509 return SDValue(); 7510 } 7511 7512 SDValue DAGCombiner::visitFMA(SDNode *N) { 7513 SDValue N0 = N->getOperand(0); 7514 SDValue N1 = N->getOperand(1); 7515 SDValue N2 = N->getOperand(2); 7516 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7517 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7518 EVT VT = N->getValueType(0); 7519 SDLoc dl(N); 7520 const TargetOptions &Options = DAG.getTarget().Options; 7521 7522 // Constant fold FMA. 7523 if (isa<ConstantFPSDNode>(N0) && 7524 isa<ConstantFPSDNode>(N1) && 7525 isa<ConstantFPSDNode>(N2)) { 7526 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 7527 } 7528 7529 if (Options.UnsafeFPMath) { 7530 if (N0CFP && N0CFP->isZero()) 7531 return N2; 7532 if (N1CFP && N1CFP->isZero()) 7533 return N2; 7534 } 7535 if (N0CFP && N0CFP->isExactlyValue(1.0)) 7536 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 7537 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7538 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 7539 7540 // Canonicalize (fma c, x, y) -> (fma x, c, y) 7541 if (N0CFP && !N1CFP) 7542 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 7543 7544 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 7545 if (Options.UnsafeFPMath && N1CFP && 7546 N2.getOpcode() == ISD::FMUL && 7547 N0 == N2.getOperand(0) && 7548 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 7549 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7550 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 7551 } 7552 7553 7554 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 7555 if (Options.UnsafeFPMath && 7556 N0.getOpcode() == ISD::FMUL && N1CFP && 7557 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 7558 return DAG.getNode(ISD::FMA, dl, VT, 7559 N0.getOperand(0), 7560 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 7561 N2); 7562 } 7563 7564 // (fma x, 1, y) -> (fadd x, y) 7565 // (fma x, -1, y) -> (fadd (fneg x), y) 7566 if (N1CFP) { 7567 if (N1CFP->isExactlyValue(1.0)) 7568 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 7569 7570 if (N1CFP->isExactlyValue(-1.0) && 7571 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 7572 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 7573 AddToWorklist(RHSNeg.getNode()); 7574 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 7575 } 7576 } 7577 7578 // (fma x, c, x) -> (fmul x, (c+1)) 7579 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 7580 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7581 DAG.getNode(ISD::FADD, dl, VT, 7582 N1, DAG.getConstantFP(1.0, VT))); 7583 7584 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 7585 if (Options.UnsafeFPMath && N1CFP && 7586 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 7587 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7588 DAG.getNode(ISD::FADD, dl, VT, 7589 N1, DAG.getConstantFP(-1.0, VT))); 7590 7591 7592 return SDValue(); 7593 } 7594 7595 SDValue DAGCombiner::visitFDIV(SDNode *N) { 7596 SDValue N0 = N->getOperand(0); 7597 SDValue N1 = N->getOperand(1); 7598 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7599 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7600 EVT VT = N->getValueType(0); 7601 SDLoc DL(N); 7602 const TargetOptions &Options = DAG.getTarget().Options; 7603 7604 // fold vector ops 7605 if (VT.isVector()) { 7606 SDValue FoldedVOp = SimplifyVBinOp(N); 7607 if (FoldedVOp.getNode()) return FoldedVOp; 7608 } 7609 7610 // fold (fdiv c1, c2) -> c1/c2 7611 if (N0CFP && N1CFP) 7612 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 7613 7614 if (Options.UnsafeFPMath) { 7615 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 7616 if (N1CFP) { 7617 // Compute the reciprocal 1.0 / c2. 7618 APFloat N1APF = N1CFP->getValueAPF(); 7619 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 7620 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 7621 // Only do the transform if the reciprocal is a legal fp immediate that 7622 // isn't too nasty (eg NaN, denormal, ...). 7623 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 7624 (!LegalOperations || 7625 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 7626 // backend)... we should handle this gracefully after Legalize. 7627 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 7628 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 7629 TLI.isFPImmLegal(Recip, VT))) 7630 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 7631 DAG.getConstantFP(Recip, VT)); 7632 } 7633 7634 // If this FDIV is part of a reciprocal square root, it may be folded 7635 // into a target-specific square root estimate instruction. 7636 if (N1.getOpcode() == ISD::FSQRT) { 7637 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) { 7638 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7639 } 7640 } else if (N1.getOpcode() == ISD::FP_EXTEND && 7641 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7642 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7643 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 7644 AddToWorklist(RV.getNode()); 7645 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7646 } 7647 } else if (N1.getOpcode() == ISD::FP_ROUND && 7648 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7649 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7650 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 7651 AddToWorklist(RV.getNode()); 7652 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7653 } 7654 } else if (N1.getOpcode() == ISD::FMUL) { 7655 // Look through an FMUL. Even though this won't remove the FDIV directly, 7656 // it's still worthwhile to get rid of the FSQRT if possible. 7657 SDValue SqrtOp; 7658 SDValue OtherOp; 7659 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7660 SqrtOp = N1.getOperand(0); 7661 OtherOp = N1.getOperand(1); 7662 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 7663 SqrtOp = N1.getOperand(1); 7664 OtherOp = N1.getOperand(0); 7665 } 7666 if (SqrtOp.getNode()) { 7667 // We found a FSQRT, so try to make this fold: 7668 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 7669 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) { 7670 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp); 7671 AddToWorklist(RV.getNode()); 7672 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7673 } 7674 } 7675 } 7676 7677 // Fold into a reciprocal estimate and multiply instead of a real divide. 7678 if (SDValue RV = BuildReciprocalEstimate(N1)) { 7679 AddToWorklist(RV.getNode()); 7680 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7681 } 7682 } 7683 7684 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 7685 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7686 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7687 // Both can be negated for free, check to see if at least one is cheaper 7688 // negated. 7689 if (LHSNeg == 2 || RHSNeg == 2) 7690 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 7691 GetNegatedExpression(N0, DAG, LegalOperations), 7692 GetNegatedExpression(N1, DAG, LegalOperations)); 7693 } 7694 } 7695 7696 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 7697 // reciprocal. 7698 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 7699 // Notice that this is not always beneficial. One reason is different target 7700 // may have different costs for FDIV and FMUL, so sometimes the cost of two 7701 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 7702 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 7703 if (Options.UnsafeFPMath) { 7704 // Skip if current node is a reciprocal. 7705 if (N0CFP && N0CFP->isExactlyValue(1.0)) 7706 return SDValue(); 7707 7708 SmallVector<SDNode *, 4> Users; 7709 // Find all FDIV users of the same divisor. 7710 for (SDNode::use_iterator UI = N1.getNode()->use_begin(), 7711 UE = N1.getNode()->use_end(); 7712 UI != UE; ++UI) { 7713 SDNode *User = UI.getUse().getUser(); 7714 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1) 7715 Users.push_back(User); 7716 } 7717 7718 if (TLI.combineRepeatedFPDivisors(Users.size())) { 7719 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0 7720 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1); 7721 7722 // Dividend / Divisor -> Dividend * Reciprocal 7723 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) { 7724 if ((*I)->getOperand(0) != FPOne) { 7725 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT, 7726 (*I)->getOperand(0), Reciprocal); 7727 DAG.ReplaceAllUsesWith(*I, NewNode.getNode()); 7728 } 7729 } 7730 return SDValue(); 7731 } 7732 } 7733 7734 return SDValue(); 7735 } 7736 7737 SDValue DAGCombiner::visitFREM(SDNode *N) { 7738 SDValue N0 = N->getOperand(0); 7739 SDValue N1 = N->getOperand(1); 7740 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7741 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7742 EVT VT = N->getValueType(0); 7743 7744 // fold (frem c1, c2) -> fmod(c1,c2) 7745 if (N0CFP && N1CFP) 7746 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 7747 7748 return SDValue(); 7749 } 7750 7751 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 7752 if (DAG.getTarget().Options.UnsafeFPMath && 7753 !TLI.isFsqrtCheap()) { 7754 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 7755 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) { 7756 EVT VT = RV.getValueType(); 7757 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV); 7758 AddToWorklist(RV.getNode()); 7759 7760 // Unfortunately, RV is now NaN if the input was exactly 0. 7761 // Select out this case and force the answer to 0. 7762 SDValue Zero = DAG.getConstantFP(0.0, VT); 7763 SDValue ZeroCmp = 7764 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT), 7765 N->getOperand(0), Zero, ISD::SETEQ); 7766 AddToWorklist(ZeroCmp.getNode()); 7767 AddToWorklist(RV.getNode()); 7768 7769 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, 7770 SDLoc(N), VT, ZeroCmp, Zero, RV); 7771 return RV; 7772 } 7773 } 7774 return SDValue(); 7775 } 7776 7777 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 7778 SDValue N0 = N->getOperand(0); 7779 SDValue N1 = N->getOperand(1); 7780 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7781 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7782 EVT VT = N->getValueType(0); 7783 7784 if (N0CFP && N1CFP) // Constant fold 7785 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 7786 7787 if (N1CFP) { 7788 const APFloat& V = N1CFP->getValueAPF(); 7789 // copysign(x, c1) -> fabs(x) iff ispos(c1) 7790 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 7791 if (!V.isNegative()) { 7792 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 7793 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7794 } else { 7795 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7796 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7797 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 7798 } 7799 } 7800 7801 // copysign(fabs(x), y) -> copysign(x, y) 7802 // copysign(fneg(x), y) -> copysign(x, y) 7803 // copysign(copysign(x,z), y) -> copysign(x, y) 7804 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 7805 N0.getOpcode() == ISD::FCOPYSIGN) 7806 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7807 N0.getOperand(0), N1); 7808 7809 // copysign(x, abs(y)) -> abs(x) 7810 if (N1.getOpcode() == ISD::FABS) 7811 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7812 7813 // copysign(x, copysign(y,z)) -> copysign(x, z) 7814 if (N1.getOpcode() == ISD::FCOPYSIGN) 7815 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7816 N0, N1.getOperand(1)); 7817 7818 // copysign(x, fp_extend(y)) -> copysign(x, y) 7819 // copysign(x, fp_round(y)) -> copysign(x, y) 7820 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 7821 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7822 N0, N1.getOperand(0)); 7823 7824 return SDValue(); 7825 } 7826 7827 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 7828 SDValue N0 = N->getOperand(0); 7829 EVT VT = N->getValueType(0); 7830 EVT OpVT = N0.getValueType(); 7831 7832 // fold (sint_to_fp c1) -> c1fp 7833 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7834 if (N0C && 7835 // ...but only if the target supports immediate floating-point values 7836 (!LegalOperations || 7837 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7838 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7839 7840 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 7841 // but UINT_TO_FP is legal on this target, try to convert. 7842 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 7843 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 7844 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 7845 if (DAG.SignBitIsZero(N0)) 7846 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7847 } 7848 7849 // The next optimizations are desirable only if SELECT_CC can be lowered. 7850 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7851 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7852 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 7853 !VT.isVector() && 7854 (!LegalOperations || 7855 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7856 SDValue Ops[] = 7857 { N0.getOperand(0), N0.getOperand(1), 7858 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 7859 N0.getOperand(2) }; 7860 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7861 } 7862 7863 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 7864 // (select_cc x, y, 1.0, 0.0,, cc) 7865 if (N0.getOpcode() == ISD::ZERO_EXTEND && 7866 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 7867 (!LegalOperations || 7868 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7869 SDValue Ops[] = 7870 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 7871 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 7872 N0.getOperand(0).getOperand(2) }; 7873 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7874 } 7875 } 7876 7877 return SDValue(); 7878 } 7879 7880 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 7881 SDValue N0 = N->getOperand(0); 7882 EVT VT = N->getValueType(0); 7883 EVT OpVT = N0.getValueType(); 7884 7885 // fold (uint_to_fp c1) -> c1fp 7886 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7887 if (N0C && 7888 // ...but only if the target supports immediate floating-point values 7889 (!LegalOperations || 7890 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7891 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7892 7893 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 7894 // but SINT_TO_FP is legal on this target, try to convert. 7895 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 7896 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 7897 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 7898 if (DAG.SignBitIsZero(N0)) 7899 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7900 } 7901 7902 // The next optimizations are desirable only if SELECT_CC can be lowered. 7903 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7904 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7905 7906 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 7907 (!LegalOperations || 7908 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7909 SDValue Ops[] = 7910 { N0.getOperand(0), N0.getOperand(1), 7911 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 7912 N0.getOperand(2) }; 7913 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7914 } 7915 } 7916 7917 return SDValue(); 7918 } 7919 7920 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 7921 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 7922 SDValue N0 = N->getOperand(0); 7923 EVT VT = N->getValueType(0); 7924 7925 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 7926 return SDValue(); 7927 7928 SDValue Src = N0.getOperand(0); 7929 EVT SrcVT = Src.getValueType(); 7930 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 7931 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 7932 7933 // We can safely assume the conversion won't overflow the output range, 7934 // because (for example) (uint8_t)18293.f is undefined behavior. 7935 7936 // Since we can assume the conversion won't overflow, our decision as to 7937 // whether the input will fit in the float should depend on the minimum 7938 // of the input range and output range. 7939 7940 // This means this is also safe for a signed input and unsigned output, since 7941 // a negative input would lead to undefined behavior. 7942 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 7943 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 7944 unsigned ActualSize = std::min(InputSize, OutputSize); 7945 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 7946 7947 // We can only fold away the float conversion if the input range can be 7948 // represented exactly in the float range. 7949 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 7950 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 7951 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 7952 : ISD::ZERO_EXTEND; 7953 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 7954 } 7955 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 7956 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 7957 if (SrcVT == VT) 7958 return Src; 7959 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 7960 } 7961 return SDValue(); 7962 } 7963 7964 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 7965 SDValue N0 = N->getOperand(0); 7966 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7967 EVT VT = N->getValueType(0); 7968 7969 // fold (fp_to_sint c1fp) -> c1 7970 if (N0CFP) 7971 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 7972 7973 return FoldIntToFPToInt(N, DAG); 7974 } 7975 7976 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 7977 SDValue N0 = N->getOperand(0); 7978 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7979 EVT VT = N->getValueType(0); 7980 7981 // fold (fp_to_uint c1fp) -> c1 7982 if (N0CFP) 7983 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 7984 7985 return FoldIntToFPToInt(N, DAG); 7986 } 7987 7988 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 7989 SDValue N0 = N->getOperand(0); 7990 SDValue N1 = N->getOperand(1); 7991 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7992 EVT VT = N->getValueType(0); 7993 7994 // fold (fp_round c1fp) -> c1fp 7995 if (N0CFP) 7996 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 7997 7998 // fold (fp_round (fp_extend x)) -> x 7999 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8000 return N0.getOperand(0); 8001 8002 // fold (fp_round (fp_round x)) -> (fp_round x) 8003 if (N0.getOpcode() == ISD::FP_ROUND) { 8004 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8005 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8006 // If the first fp_round isn't a value preserving truncation, it might 8007 // introduce a tie in the second fp_round, that wouldn't occur in the 8008 // single-step fp_round we want to fold to. 8009 // In other words, double rounding isn't the same as rounding. 8010 // Also, this is a value preserving truncation iff both fp_round's are. 8011 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) 8012 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 8013 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc)); 8014 } 8015 8016 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8017 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8018 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8019 N0.getOperand(0), N1); 8020 AddToWorklist(Tmp.getNode()); 8021 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8022 Tmp, N0.getOperand(1)); 8023 } 8024 8025 return SDValue(); 8026 } 8027 8028 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8029 SDValue N0 = N->getOperand(0); 8030 EVT VT = N->getValueType(0); 8031 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8032 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8033 8034 // fold (fp_round_inreg c1fp) -> c1fp 8035 if (N0CFP && isTypeLegal(EVT)) { 8036 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 8037 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 8038 } 8039 8040 return SDValue(); 8041 } 8042 8043 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8044 SDValue N0 = N->getOperand(0); 8045 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8046 EVT VT = N->getValueType(0); 8047 8048 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8049 if (N->hasOneUse() && 8050 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8051 return SDValue(); 8052 8053 // fold (fp_extend c1fp) -> c1fp 8054 if (N0CFP) 8055 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8056 8057 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8058 // value of X. 8059 if (N0.getOpcode() == ISD::FP_ROUND 8060 && N0.getNode()->getConstantOperandVal(1) == 1) { 8061 SDValue In = N0.getOperand(0); 8062 if (In.getValueType() == VT) return In; 8063 if (VT.bitsLT(In.getValueType())) 8064 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8065 In, N0.getOperand(1)); 8066 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8067 } 8068 8069 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8070 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8071 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8072 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8073 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8074 LN0->getChain(), 8075 LN0->getBasePtr(), N0.getValueType(), 8076 LN0->getMemOperand()); 8077 CombineTo(N, ExtLoad); 8078 CombineTo(N0.getNode(), 8079 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8080 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 8081 ExtLoad.getValue(1)); 8082 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8083 } 8084 8085 return SDValue(); 8086 } 8087 8088 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8089 SDValue N0 = N->getOperand(0); 8090 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8091 EVT VT = N->getValueType(0); 8092 8093 // fold (fceil c1) -> fceil(c1) 8094 if (N0CFP) 8095 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8096 8097 return SDValue(); 8098 } 8099 8100 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8101 SDValue N0 = N->getOperand(0); 8102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8103 EVT VT = N->getValueType(0); 8104 8105 // fold (ftrunc c1) -> ftrunc(c1) 8106 if (N0CFP) 8107 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8108 8109 return SDValue(); 8110 } 8111 8112 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8113 SDValue N0 = N->getOperand(0); 8114 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8115 EVT VT = N->getValueType(0); 8116 8117 // fold (ffloor c1) -> ffloor(c1) 8118 if (N0CFP) 8119 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8120 8121 return SDValue(); 8122 } 8123 8124 // FIXME: FNEG and FABS have a lot in common; refactor. 8125 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8126 SDValue N0 = N->getOperand(0); 8127 EVT VT = N->getValueType(0); 8128 8129 if (VT.isVector()) { 8130 SDValue FoldedVOp = SimplifyVUnaryOp(N); 8131 if (FoldedVOp.getNode()) return FoldedVOp; 8132 } 8133 8134 // Constant fold FNEG. 8135 if (isa<ConstantFPSDNode>(N0)) 8136 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0)); 8137 8138 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8139 &DAG.getTarget().Options)) 8140 return GetNegatedExpression(N0, DAG, LegalOperations); 8141 8142 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8143 // constant pool values. 8144 if (!TLI.isFNegFree(VT) && 8145 N0.getOpcode() == ISD::BITCAST && 8146 N0.getNode()->hasOneUse()) { 8147 SDValue Int = N0.getOperand(0); 8148 EVT IntVT = Int.getValueType(); 8149 if (IntVT.isInteger() && !IntVT.isVector()) { 8150 APInt SignMask; 8151 if (N0.getValueType().isVector()) { 8152 // For a vector, get a mask such as 0x80... per scalar element 8153 // and splat it. 8154 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8155 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8156 } else { 8157 // For a scalar, just generate 0x80... 8158 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 8159 } 8160 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 8161 DAG.getConstant(SignMask, IntVT)); 8162 AddToWorklist(Int.getNode()); 8163 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 8164 } 8165 } 8166 8167 // (fneg (fmul c, x)) -> (fmul -c, x) 8168 if (N0.getOpcode() == ISD::FMUL) { 8169 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8170 if (CFP1) { 8171 APFloat CVal = CFP1->getValueAPF(); 8172 CVal.changeSign(); 8173 if (Level >= AfterLegalizeDAG && 8174 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 8175 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 8176 return DAG.getNode( 8177 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 8178 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 8179 } 8180 } 8181 8182 return SDValue(); 8183 } 8184 8185 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 8186 SDValue N0 = N->getOperand(0); 8187 SDValue N1 = N->getOperand(1); 8188 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8189 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8190 8191 if (N0CFP && N1CFP) { 8192 const APFloat &C0 = N0CFP->getValueAPF(); 8193 const APFloat &C1 = N1CFP->getValueAPF(); 8194 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0)); 8195 } 8196 8197 if (N0CFP) { 8198 EVT VT = N->getValueType(0); 8199 // Canonicalize to constant on RHS. 8200 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 8201 } 8202 8203 return SDValue(); 8204 } 8205 8206 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 8207 SDValue N0 = N->getOperand(0); 8208 SDValue N1 = N->getOperand(1); 8209 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8210 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8211 8212 if (N0CFP && N1CFP) { 8213 const APFloat &C0 = N0CFP->getValueAPF(); 8214 const APFloat &C1 = N1CFP->getValueAPF(); 8215 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0)); 8216 } 8217 8218 if (N0CFP) { 8219 EVT VT = N->getValueType(0); 8220 // Canonicalize to constant on RHS. 8221 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 8222 } 8223 8224 return SDValue(); 8225 } 8226 8227 SDValue DAGCombiner::visitFABS(SDNode *N) { 8228 SDValue N0 = N->getOperand(0); 8229 EVT VT = N->getValueType(0); 8230 8231 if (VT.isVector()) { 8232 SDValue FoldedVOp = SimplifyVUnaryOp(N); 8233 if (FoldedVOp.getNode()) return FoldedVOp; 8234 } 8235 8236 // fold (fabs c1) -> fabs(c1) 8237 if (isa<ConstantFPSDNode>(N0)) 8238 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8239 8240 // fold (fabs (fabs x)) -> (fabs x) 8241 if (N0.getOpcode() == ISD::FABS) 8242 return N->getOperand(0); 8243 8244 // fold (fabs (fneg x)) -> (fabs x) 8245 // fold (fabs (fcopysign x, y)) -> (fabs x) 8246 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 8247 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 8248 8249 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 8250 // constant pool values. 8251 if (!TLI.isFAbsFree(VT) && 8252 N0.getOpcode() == ISD::BITCAST && 8253 N0.getNode()->hasOneUse()) { 8254 SDValue Int = N0.getOperand(0); 8255 EVT IntVT = Int.getValueType(); 8256 if (IntVT.isInteger() && !IntVT.isVector()) { 8257 APInt SignMask; 8258 if (N0.getValueType().isVector()) { 8259 // For a vector, get a mask such as 0x7f... per scalar element 8260 // and splat it. 8261 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8262 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8263 } else { 8264 // For a scalar, just generate 0x7f... 8265 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 8266 } 8267 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 8268 DAG.getConstant(SignMask, IntVT)); 8269 AddToWorklist(Int.getNode()); 8270 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 8271 } 8272 } 8273 8274 return SDValue(); 8275 } 8276 8277 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 8278 SDValue Chain = N->getOperand(0); 8279 SDValue N1 = N->getOperand(1); 8280 SDValue N2 = N->getOperand(2); 8281 8282 // If N is a constant we could fold this into a fallthrough or unconditional 8283 // branch. However that doesn't happen very often in normal code, because 8284 // Instcombine/SimplifyCFG should have handled the available opportunities. 8285 // If we did this folding here, it would be necessary to update the 8286 // MachineBasicBlock CFG, which is awkward. 8287 8288 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 8289 // on the target. 8290 if (N1.getOpcode() == ISD::SETCC && 8291 TLI.isOperationLegalOrCustom(ISD::BR_CC, 8292 N1.getOperand(0).getValueType())) { 8293 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8294 Chain, N1.getOperand(2), 8295 N1.getOperand(0), N1.getOperand(1), N2); 8296 } 8297 8298 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 8299 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 8300 (N1.getOperand(0).hasOneUse() && 8301 N1.getOperand(0).getOpcode() == ISD::SRL))) { 8302 SDNode *Trunc = nullptr; 8303 if (N1.getOpcode() == ISD::TRUNCATE) { 8304 // Look pass the truncate. 8305 Trunc = N1.getNode(); 8306 N1 = N1.getOperand(0); 8307 } 8308 8309 // Match this pattern so that we can generate simpler code: 8310 // 8311 // %a = ... 8312 // %b = and i32 %a, 2 8313 // %c = srl i32 %b, 1 8314 // brcond i32 %c ... 8315 // 8316 // into 8317 // 8318 // %a = ... 8319 // %b = and i32 %a, 2 8320 // %c = setcc eq %b, 0 8321 // brcond %c ... 8322 // 8323 // This applies only when the AND constant value has one bit set and the 8324 // SRL constant is equal to the log2 of the AND constant. The back-end is 8325 // smart enough to convert the result into a TEST/JMP sequence. 8326 SDValue Op0 = N1.getOperand(0); 8327 SDValue Op1 = N1.getOperand(1); 8328 8329 if (Op0.getOpcode() == ISD::AND && 8330 Op1.getOpcode() == ISD::Constant) { 8331 SDValue AndOp1 = Op0.getOperand(1); 8332 8333 if (AndOp1.getOpcode() == ISD::Constant) { 8334 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 8335 8336 if (AndConst.isPowerOf2() && 8337 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 8338 SDValue SetCC = 8339 DAG.getSetCC(SDLoc(N), 8340 getSetCCResultType(Op0.getValueType()), 8341 Op0, DAG.getConstant(0, Op0.getValueType()), 8342 ISD::SETNE); 8343 8344 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 8345 MVT::Other, Chain, SetCC, N2); 8346 // Don't add the new BRCond into the worklist or else SimplifySelectCC 8347 // will convert it back to (X & C1) >> C2. 8348 CombineTo(N, NewBRCond, false); 8349 // Truncate is dead. 8350 if (Trunc) 8351 deleteAndRecombine(Trunc); 8352 // Replace the uses of SRL with SETCC 8353 WorklistRemover DeadNodes(*this); 8354 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8355 deleteAndRecombine(N1.getNode()); 8356 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8357 } 8358 } 8359 } 8360 8361 if (Trunc) 8362 // Restore N1 if the above transformation doesn't match. 8363 N1 = N->getOperand(1); 8364 } 8365 8366 // Transform br(xor(x, y)) -> br(x != y) 8367 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 8368 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 8369 SDNode *TheXor = N1.getNode(); 8370 SDValue Op0 = TheXor->getOperand(0); 8371 SDValue Op1 = TheXor->getOperand(1); 8372 if (Op0.getOpcode() == Op1.getOpcode()) { 8373 // Avoid missing important xor optimizations. 8374 SDValue Tmp = visitXOR(TheXor); 8375 if (Tmp.getNode()) { 8376 if (Tmp.getNode() != TheXor) { 8377 DEBUG(dbgs() << "\nReplacing.8 "; 8378 TheXor->dump(&DAG); 8379 dbgs() << "\nWith: "; 8380 Tmp.getNode()->dump(&DAG); 8381 dbgs() << '\n'); 8382 WorklistRemover DeadNodes(*this); 8383 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 8384 deleteAndRecombine(TheXor); 8385 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8386 MVT::Other, Chain, Tmp, N2); 8387 } 8388 8389 // visitXOR has changed XOR's operands or replaced the XOR completely, 8390 // bail out. 8391 return SDValue(N, 0); 8392 } 8393 } 8394 8395 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 8396 bool Equal = false; 8397 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 8398 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 8399 Op0.getOpcode() == ISD::XOR) { 8400 TheXor = Op0.getNode(); 8401 Equal = true; 8402 } 8403 8404 EVT SetCCVT = N1.getValueType(); 8405 if (LegalTypes) 8406 SetCCVT = getSetCCResultType(SetCCVT); 8407 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 8408 SetCCVT, 8409 Op0, Op1, 8410 Equal ? ISD::SETEQ : ISD::SETNE); 8411 // Replace the uses of XOR with SETCC 8412 WorklistRemover DeadNodes(*this); 8413 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8414 deleteAndRecombine(N1.getNode()); 8415 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8416 MVT::Other, Chain, SetCC, N2); 8417 } 8418 } 8419 8420 return SDValue(); 8421 } 8422 8423 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 8424 // 8425 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 8426 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 8427 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 8428 8429 // If N is a constant we could fold this into a fallthrough or unconditional 8430 // branch. However that doesn't happen very often in normal code, because 8431 // Instcombine/SimplifyCFG should have handled the available opportunities. 8432 // If we did this folding here, it would be necessary to update the 8433 // MachineBasicBlock CFG, which is awkward. 8434 8435 // Use SimplifySetCC to simplify SETCC's. 8436 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 8437 CondLHS, CondRHS, CC->get(), SDLoc(N), 8438 false); 8439 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 8440 8441 // fold to a simpler setcc 8442 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 8443 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8444 N->getOperand(0), Simp.getOperand(2), 8445 Simp.getOperand(0), Simp.getOperand(1), 8446 N->getOperand(4)); 8447 8448 return SDValue(); 8449 } 8450 8451 /// Return true if 'Use' is a load or a store that uses N as its base pointer 8452 /// and that N may be folded in the load / store addressing mode. 8453 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 8454 SelectionDAG &DAG, 8455 const TargetLowering &TLI) { 8456 EVT VT; 8457 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 8458 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 8459 return false; 8460 VT = Use->getValueType(0); 8461 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 8462 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 8463 return false; 8464 VT = ST->getValue().getValueType(); 8465 } else 8466 return false; 8467 8468 TargetLowering::AddrMode AM; 8469 if (N->getOpcode() == ISD::ADD) { 8470 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8471 if (Offset) 8472 // [reg +/- imm] 8473 AM.BaseOffs = Offset->getSExtValue(); 8474 else 8475 // [reg +/- reg] 8476 AM.Scale = 1; 8477 } else if (N->getOpcode() == ISD::SUB) { 8478 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8479 if (Offset) 8480 // [reg +/- imm] 8481 AM.BaseOffs = -Offset->getSExtValue(); 8482 else 8483 // [reg +/- reg] 8484 AM.Scale = 1; 8485 } else 8486 return false; 8487 8488 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 8489 } 8490 8491 /// Try turning a load/store into a pre-indexed load/store when the base 8492 /// pointer is an add or subtract and it has other uses besides the load/store. 8493 /// After the transformation, the new indexed load/store has effectively folded 8494 /// the add/subtract in and all of its other uses are redirected to the 8495 /// new load/store. 8496 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 8497 if (Level < AfterLegalizeDAG) 8498 return false; 8499 8500 bool isLoad = true; 8501 SDValue Ptr; 8502 EVT VT; 8503 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8504 if (LD->isIndexed()) 8505 return false; 8506 VT = LD->getMemoryVT(); 8507 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 8508 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 8509 return false; 8510 Ptr = LD->getBasePtr(); 8511 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 8512 if (ST->isIndexed()) 8513 return false; 8514 VT = ST->getMemoryVT(); 8515 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 8516 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 8517 return false; 8518 Ptr = ST->getBasePtr(); 8519 isLoad = false; 8520 } else { 8521 return false; 8522 } 8523 8524 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 8525 // out. There is no reason to make this a preinc/predec. 8526 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 8527 Ptr.getNode()->hasOneUse()) 8528 return false; 8529 8530 // Ask the target to do addressing mode selection. 8531 SDValue BasePtr; 8532 SDValue Offset; 8533 ISD::MemIndexedMode AM = ISD::UNINDEXED; 8534 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 8535 return false; 8536 8537 // Backends without true r+i pre-indexed forms may need to pass a 8538 // constant base with a variable offset so that constant coercion 8539 // will work with the patterns in canonical form. 8540 bool Swapped = false; 8541 if (isa<ConstantSDNode>(BasePtr)) { 8542 std::swap(BasePtr, Offset); 8543 Swapped = true; 8544 } 8545 8546 // Don't create a indexed load / store with zero offset. 8547 if (isa<ConstantSDNode>(Offset) && 8548 cast<ConstantSDNode>(Offset)->isNullValue()) 8549 return false; 8550 8551 // Try turning it into a pre-indexed load / store except when: 8552 // 1) The new base ptr is a frame index. 8553 // 2) If N is a store and the new base ptr is either the same as or is a 8554 // predecessor of the value being stored. 8555 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 8556 // that would create a cycle. 8557 // 4) All uses are load / store ops that use it as old base ptr. 8558 8559 // Check #1. Preinc'ing a frame index would require copying the stack pointer 8560 // (plus the implicit offset) to a register to preinc anyway. 8561 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 8562 return false; 8563 8564 // Check #2. 8565 if (!isLoad) { 8566 SDValue Val = cast<StoreSDNode>(N)->getValue(); 8567 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 8568 return false; 8569 } 8570 8571 // If the offset is a constant, there may be other adds of constants that 8572 // can be folded with this one. We should do this to avoid having to keep 8573 // a copy of the original base pointer. 8574 SmallVector<SDNode *, 16> OtherUses; 8575 if (isa<ConstantSDNode>(Offset)) 8576 for (SDNode *Use : BasePtr.getNode()->uses()) { 8577 if (Use == Ptr.getNode()) 8578 continue; 8579 8580 if (Use->isPredecessorOf(N)) 8581 continue; 8582 8583 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 8584 OtherUses.clear(); 8585 break; 8586 } 8587 8588 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 8589 if (Op1.getNode() == BasePtr.getNode()) 8590 std::swap(Op0, Op1); 8591 assert(Op0.getNode() == BasePtr.getNode() && 8592 "Use of ADD/SUB but not an operand"); 8593 8594 if (!isa<ConstantSDNode>(Op1)) { 8595 OtherUses.clear(); 8596 break; 8597 } 8598 8599 // FIXME: In some cases, we can be smarter about this. 8600 if (Op1.getValueType() != Offset.getValueType()) { 8601 OtherUses.clear(); 8602 break; 8603 } 8604 8605 OtherUses.push_back(Use); 8606 } 8607 8608 if (Swapped) 8609 std::swap(BasePtr, Offset); 8610 8611 // Now check for #3 and #4. 8612 bool RealUse = false; 8613 8614 // Caches for hasPredecessorHelper 8615 SmallPtrSet<const SDNode *, 32> Visited; 8616 SmallVector<const SDNode *, 16> Worklist; 8617 8618 for (SDNode *Use : Ptr.getNode()->uses()) { 8619 if (Use == N) 8620 continue; 8621 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 8622 return false; 8623 8624 // If Ptr may be folded in addressing mode of other use, then it's 8625 // not profitable to do this transformation. 8626 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 8627 RealUse = true; 8628 } 8629 8630 if (!RealUse) 8631 return false; 8632 8633 SDValue Result; 8634 if (isLoad) 8635 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 8636 BasePtr, Offset, AM); 8637 else 8638 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 8639 BasePtr, Offset, AM); 8640 ++PreIndexedNodes; 8641 ++NodesCombined; 8642 DEBUG(dbgs() << "\nReplacing.4 "; 8643 N->dump(&DAG); 8644 dbgs() << "\nWith: "; 8645 Result.getNode()->dump(&DAG); 8646 dbgs() << '\n'); 8647 WorklistRemover DeadNodes(*this); 8648 if (isLoad) { 8649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 8650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 8651 } else { 8652 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 8653 } 8654 8655 // Finally, since the node is now dead, remove it from the graph. 8656 deleteAndRecombine(N); 8657 8658 if (Swapped) 8659 std::swap(BasePtr, Offset); 8660 8661 // Replace other uses of BasePtr that can be updated to use Ptr 8662 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 8663 unsigned OffsetIdx = 1; 8664 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 8665 OffsetIdx = 0; 8666 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 8667 BasePtr.getNode() && "Expected BasePtr operand"); 8668 8669 // We need to replace ptr0 in the following expression: 8670 // x0 * offset0 + y0 * ptr0 = t0 8671 // knowing that 8672 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 8673 // 8674 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 8675 // indexed load/store and the expresion that needs to be re-written. 8676 // 8677 // Therefore, we have: 8678 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 8679 8680 ConstantSDNode *CN = 8681 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 8682 int X0, X1, Y0, Y1; 8683 APInt Offset0 = CN->getAPIntValue(); 8684 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 8685 8686 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 8687 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 8688 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 8689 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 8690 8691 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 8692 8693 APInt CNV = Offset0; 8694 if (X0 < 0) CNV = -CNV; 8695 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 8696 else CNV = CNV - Offset1; 8697 8698 // We can now generate the new expression. 8699 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 8700 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 8701 8702 SDValue NewUse = DAG.getNode(Opcode, 8703 SDLoc(OtherUses[i]), 8704 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 8705 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 8706 deleteAndRecombine(OtherUses[i]); 8707 } 8708 8709 // Replace the uses of Ptr with uses of the updated base value. 8710 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 8711 deleteAndRecombine(Ptr.getNode()); 8712 8713 return true; 8714 } 8715 8716 /// Try to combine a load/store with a add/sub of the base pointer node into a 8717 /// post-indexed load/store. The transformation folded the add/subtract into the 8718 /// new indexed load/store effectively and all of its uses are redirected to the 8719 /// new load/store. 8720 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 8721 if (Level < AfterLegalizeDAG) 8722 return false; 8723 8724 bool isLoad = true; 8725 SDValue Ptr; 8726 EVT VT; 8727 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8728 if (LD->isIndexed()) 8729 return false; 8730 VT = LD->getMemoryVT(); 8731 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 8732 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 8733 return false; 8734 Ptr = LD->getBasePtr(); 8735 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 8736 if (ST->isIndexed()) 8737 return false; 8738 VT = ST->getMemoryVT(); 8739 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 8740 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 8741 return false; 8742 Ptr = ST->getBasePtr(); 8743 isLoad = false; 8744 } else { 8745 return false; 8746 } 8747 8748 if (Ptr.getNode()->hasOneUse()) 8749 return false; 8750 8751 for (SDNode *Op : Ptr.getNode()->uses()) { 8752 if (Op == N || 8753 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 8754 continue; 8755 8756 SDValue BasePtr; 8757 SDValue Offset; 8758 ISD::MemIndexedMode AM = ISD::UNINDEXED; 8759 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 8760 // Don't create a indexed load / store with zero offset. 8761 if (isa<ConstantSDNode>(Offset) && 8762 cast<ConstantSDNode>(Offset)->isNullValue()) 8763 continue; 8764 8765 // Try turning it into a post-indexed load / store except when 8766 // 1) All uses are load / store ops that use it as base ptr (and 8767 // it may be folded as addressing mmode). 8768 // 2) Op must be independent of N, i.e. Op is neither a predecessor 8769 // nor a successor of N. Otherwise, if Op is folded that would 8770 // create a cycle. 8771 8772 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 8773 continue; 8774 8775 // Check for #1. 8776 bool TryNext = false; 8777 for (SDNode *Use : BasePtr.getNode()->uses()) { 8778 if (Use == Ptr.getNode()) 8779 continue; 8780 8781 // If all the uses are load / store addresses, then don't do the 8782 // transformation. 8783 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 8784 bool RealUse = false; 8785 for (SDNode *UseUse : Use->uses()) { 8786 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 8787 RealUse = true; 8788 } 8789 8790 if (!RealUse) { 8791 TryNext = true; 8792 break; 8793 } 8794 } 8795 } 8796 8797 if (TryNext) 8798 continue; 8799 8800 // Check for #2 8801 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 8802 SDValue Result = isLoad 8803 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 8804 BasePtr, Offset, AM) 8805 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 8806 BasePtr, Offset, AM); 8807 ++PostIndexedNodes; 8808 ++NodesCombined; 8809 DEBUG(dbgs() << "\nReplacing.5 "; 8810 N->dump(&DAG); 8811 dbgs() << "\nWith: "; 8812 Result.getNode()->dump(&DAG); 8813 dbgs() << '\n'); 8814 WorklistRemover DeadNodes(*this); 8815 if (isLoad) { 8816 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 8817 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 8818 } else { 8819 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 8820 } 8821 8822 // Finally, since the node is now dead, remove it from the graph. 8823 deleteAndRecombine(N); 8824 8825 // Replace the uses of Use with uses of the updated base value. 8826 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 8827 Result.getValue(isLoad ? 1 : 0)); 8828 deleteAndRecombine(Op); 8829 return true; 8830 } 8831 } 8832 } 8833 8834 return false; 8835 } 8836 8837 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 8838 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 8839 ISD::MemIndexedMode AM = LD->getAddressingMode(); 8840 assert(AM != ISD::UNINDEXED); 8841 SDValue BP = LD->getOperand(1); 8842 SDValue Inc = LD->getOperand(2); 8843 8844 // Some backends use TargetConstants for load offsets, but don't expect 8845 // TargetConstants in general ADD nodes. We can convert these constants into 8846 // regular Constants (if the constant is not opaque). 8847 assert((Inc.getOpcode() != ISD::TargetConstant || 8848 !cast<ConstantSDNode>(Inc)->isOpaque()) && 8849 "Cannot split out indexing using opaque target constants"); 8850 if (Inc.getOpcode() == ISD::TargetConstant) { 8851 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 8852 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), 8853 ConstInc->getValueType(0)); 8854 } 8855 8856 unsigned Opc = 8857 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 8858 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 8859 } 8860 8861 SDValue DAGCombiner::visitLOAD(SDNode *N) { 8862 LoadSDNode *LD = cast<LoadSDNode>(N); 8863 SDValue Chain = LD->getChain(); 8864 SDValue Ptr = LD->getBasePtr(); 8865 8866 // If load is not volatile and there are no uses of the loaded value (and 8867 // the updated indexed value in case of indexed loads), change uses of the 8868 // chain value into uses of the chain input (i.e. delete the dead load). 8869 if (!LD->isVolatile()) { 8870 if (N->getValueType(1) == MVT::Other) { 8871 // Unindexed loads. 8872 if (!N->hasAnyUseOfValue(0)) { 8873 // It's not safe to use the two value CombineTo variant here. e.g. 8874 // v1, chain2 = load chain1, loc 8875 // v2, chain3 = load chain2, loc 8876 // v3 = add v2, c 8877 // Now we replace use of chain2 with chain1. This makes the second load 8878 // isomorphic to the one we are deleting, and thus makes this load live. 8879 DEBUG(dbgs() << "\nReplacing.6 "; 8880 N->dump(&DAG); 8881 dbgs() << "\nWith chain: "; 8882 Chain.getNode()->dump(&DAG); 8883 dbgs() << "\n"); 8884 WorklistRemover DeadNodes(*this); 8885 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8886 8887 if (N->use_empty()) 8888 deleteAndRecombine(N); 8889 8890 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8891 } 8892 } else { 8893 // Indexed loads. 8894 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 8895 8896 // If this load has an opaque TargetConstant offset, then we cannot split 8897 // the indexing into an add/sub directly (that TargetConstant may not be 8898 // valid for a different type of node, and we cannot convert an opaque 8899 // target constant into a regular constant). 8900 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 8901 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 8902 8903 if (!N->hasAnyUseOfValue(0) && 8904 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 8905 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 8906 SDValue Index; 8907 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 8908 Index = SplitIndexingFromLoad(LD); 8909 // Try to fold the base pointer arithmetic into subsequent loads and 8910 // stores. 8911 AddUsersToWorklist(N); 8912 } else 8913 Index = DAG.getUNDEF(N->getValueType(1)); 8914 DEBUG(dbgs() << "\nReplacing.7 "; 8915 N->dump(&DAG); 8916 dbgs() << "\nWith: "; 8917 Undef.getNode()->dump(&DAG); 8918 dbgs() << " and 2 other values\n"); 8919 WorklistRemover DeadNodes(*this); 8920 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 8921 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 8922 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 8923 deleteAndRecombine(N); 8924 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8925 } 8926 } 8927 } 8928 8929 // If this load is directly stored, replace the load value with the stored 8930 // value. 8931 // TODO: Handle store large -> read small portion. 8932 // TODO: Handle TRUNCSTORE/LOADEXT 8933 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 8934 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 8935 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 8936 if (PrevST->getBasePtr() == Ptr && 8937 PrevST->getValue().getValueType() == N->getValueType(0)) 8938 return CombineTo(N, Chain.getOperand(1), Chain); 8939 } 8940 } 8941 8942 // Try to infer better alignment information than the load already has. 8943 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 8944 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 8945 if (Align > LD->getMemOperand()->getBaseAlignment()) { 8946 SDValue NewLoad = 8947 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 8948 LD->getValueType(0), 8949 Chain, Ptr, LD->getPointerInfo(), 8950 LD->getMemoryVT(), 8951 LD->isVolatile(), LD->isNonTemporal(), 8952 LD->isInvariant(), Align, LD->getAAInfo()); 8953 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 8954 } 8955 } 8956 } 8957 8958 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 8959 : DAG.getSubtarget().useAA(); 8960 #ifndef NDEBUG 8961 if (CombinerAAOnlyFunc.getNumOccurrences() && 8962 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 8963 UseAA = false; 8964 #endif 8965 if (UseAA && LD->isUnindexed()) { 8966 // Walk up chain skipping non-aliasing memory nodes. 8967 SDValue BetterChain = FindBetterChain(N, Chain); 8968 8969 // If there is a better chain. 8970 if (Chain != BetterChain) { 8971 SDValue ReplLoad; 8972 8973 // Replace the chain to void dependency. 8974 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 8975 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 8976 BetterChain, Ptr, LD->getMemOperand()); 8977 } else { 8978 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 8979 LD->getValueType(0), 8980 BetterChain, Ptr, LD->getMemoryVT(), 8981 LD->getMemOperand()); 8982 } 8983 8984 // Create token factor to keep old chain connected. 8985 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 8986 MVT::Other, Chain, ReplLoad.getValue(1)); 8987 8988 // Make sure the new and old chains are cleaned up. 8989 AddToWorklist(Token.getNode()); 8990 8991 // Replace uses with load result and token factor. Don't add users 8992 // to work list. 8993 return CombineTo(N, ReplLoad.getValue(0), Token, false); 8994 } 8995 } 8996 8997 // Try transforming N to an indexed load. 8998 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 8999 return SDValue(N, 0); 9000 9001 // Try to slice up N to more direct loads if the slices are mapped to 9002 // different register banks or pairing can take place. 9003 if (SliceUpLoad(N)) 9004 return SDValue(N, 0); 9005 9006 return SDValue(); 9007 } 9008 9009 namespace { 9010 /// \brief Helper structure used to slice a load in smaller loads. 9011 /// Basically a slice is obtained from the following sequence: 9012 /// Origin = load Ty1, Base 9013 /// Shift = srl Ty1 Origin, CstTy Amount 9014 /// Inst = trunc Shift to Ty2 9015 /// 9016 /// Then, it will be rewriten into: 9017 /// Slice = load SliceTy, Base + SliceOffset 9018 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9019 /// 9020 /// SliceTy is deduced from the number of bits that are actually used to 9021 /// build Inst. 9022 struct LoadedSlice { 9023 /// \brief Helper structure used to compute the cost of a slice. 9024 struct Cost { 9025 /// Are we optimizing for code size. 9026 bool ForCodeSize; 9027 /// Various cost. 9028 unsigned Loads; 9029 unsigned Truncates; 9030 unsigned CrossRegisterBanksCopies; 9031 unsigned ZExts; 9032 unsigned Shift; 9033 9034 Cost(bool ForCodeSize = false) 9035 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9036 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9037 9038 /// \brief Get the cost of one isolated slice. 9039 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9040 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9041 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9042 EVT TruncType = LS.Inst->getValueType(0); 9043 EVT LoadedType = LS.getLoadedType(); 9044 if (TruncType != LoadedType && 9045 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9046 ZExts = 1; 9047 } 9048 9049 /// \brief Account for slicing gain in the current cost. 9050 /// Slicing provide a few gains like removing a shift or a 9051 /// truncate. This method allows to grow the cost of the original 9052 /// load with the gain from this slice. 9053 void addSliceGain(const LoadedSlice &LS) { 9054 // Each slice saves a truncate. 9055 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9056 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 9057 LS.Inst->getOperand(0).getValueType())) 9058 ++Truncates; 9059 // If there is a shift amount, this slice gets rid of it. 9060 if (LS.Shift) 9061 ++Shift; 9062 // If this slice can merge a cross register bank copy, account for it. 9063 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9064 ++CrossRegisterBanksCopies; 9065 } 9066 9067 Cost &operator+=(const Cost &RHS) { 9068 Loads += RHS.Loads; 9069 Truncates += RHS.Truncates; 9070 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9071 ZExts += RHS.ZExts; 9072 Shift += RHS.Shift; 9073 return *this; 9074 } 9075 9076 bool operator==(const Cost &RHS) const { 9077 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9078 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9079 ZExts == RHS.ZExts && Shift == RHS.Shift; 9080 } 9081 9082 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9083 9084 bool operator<(const Cost &RHS) const { 9085 // Assume cross register banks copies are as expensive as loads. 9086 // FIXME: Do we want some more target hooks? 9087 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9088 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9089 // Unless we are optimizing for code size, consider the 9090 // expensive operation first. 9091 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9092 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9093 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9094 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9095 } 9096 9097 bool operator>(const Cost &RHS) const { return RHS < *this; } 9098 9099 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9100 9101 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9102 }; 9103 // The last instruction that represent the slice. This should be a 9104 // truncate instruction. 9105 SDNode *Inst; 9106 // The original load instruction. 9107 LoadSDNode *Origin; 9108 // The right shift amount in bits from the original load. 9109 unsigned Shift; 9110 // The DAG from which Origin came from. 9111 // This is used to get some contextual information about legal types, etc. 9112 SelectionDAG *DAG; 9113 9114 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9115 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9116 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9117 9118 LoadedSlice(const LoadedSlice &LS) 9119 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 9120 9121 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9122 /// \return Result is \p BitWidth and has used bits set to 1 and 9123 /// not used bits set to 0. 9124 APInt getUsedBits() const { 9125 // Reproduce the trunc(lshr) sequence: 9126 // - Start from the truncated value. 9127 // - Zero extend to the desired bit width. 9128 // - Shift left. 9129 assert(Origin && "No original load to compare against."); 9130 unsigned BitWidth = Origin->getValueSizeInBits(0); 9131 assert(Inst && "This slice is not bound to an instruction"); 9132 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9133 "Extracted slice is bigger than the whole type!"); 9134 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9135 UsedBits.setAllBits(); 9136 UsedBits = UsedBits.zext(BitWidth); 9137 UsedBits <<= Shift; 9138 return UsedBits; 9139 } 9140 9141 /// \brief Get the size of the slice to be loaded in bytes. 9142 unsigned getLoadedSize() const { 9143 unsigned SliceSize = getUsedBits().countPopulation(); 9144 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 9145 return SliceSize / 8; 9146 } 9147 9148 /// \brief Get the type that will be loaded for this slice. 9149 /// Note: This may not be the final type for the slice. 9150 EVT getLoadedType() const { 9151 assert(DAG && "Missing context"); 9152 LLVMContext &Ctxt = *DAG->getContext(); 9153 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 9154 } 9155 9156 /// \brief Get the alignment of the load used for this slice. 9157 unsigned getAlignment() const { 9158 unsigned Alignment = Origin->getAlignment(); 9159 unsigned Offset = getOffsetFromBase(); 9160 if (Offset != 0) 9161 Alignment = MinAlign(Alignment, Alignment + Offset); 9162 return Alignment; 9163 } 9164 9165 /// \brief Check if this slice can be rewritten with legal operations. 9166 bool isLegal() const { 9167 // An invalid slice is not legal. 9168 if (!Origin || !Inst || !DAG) 9169 return false; 9170 9171 // Offsets are for indexed load only, we do not handle that. 9172 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 9173 return false; 9174 9175 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9176 9177 // Check that the type is legal. 9178 EVT SliceType = getLoadedType(); 9179 if (!TLI.isTypeLegal(SliceType)) 9180 return false; 9181 9182 // Check that the load is legal for this type. 9183 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 9184 return false; 9185 9186 // Check that the offset can be computed. 9187 // 1. Check its type. 9188 EVT PtrType = Origin->getBasePtr().getValueType(); 9189 if (PtrType == MVT::Untyped || PtrType.isExtended()) 9190 return false; 9191 9192 // 2. Check that it fits in the immediate. 9193 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 9194 return false; 9195 9196 // 3. Check that the computation is legal. 9197 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 9198 return false; 9199 9200 // Check that the zext is legal if it needs one. 9201 EVT TruncateType = Inst->getValueType(0); 9202 if (TruncateType != SliceType && 9203 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 9204 return false; 9205 9206 return true; 9207 } 9208 9209 /// \brief Get the offset in bytes of this slice in the original chunk of 9210 /// bits. 9211 /// \pre DAG != nullptr. 9212 uint64_t getOffsetFromBase() const { 9213 assert(DAG && "Missing context."); 9214 bool IsBigEndian = 9215 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 9216 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 9217 uint64_t Offset = Shift / 8; 9218 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 9219 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 9220 "The size of the original loaded type is not a multiple of a" 9221 " byte."); 9222 // If Offset is bigger than TySizeInBytes, it means we are loading all 9223 // zeros. This should have been optimized before in the process. 9224 assert(TySizeInBytes > Offset && 9225 "Invalid shift amount for given loaded size"); 9226 if (IsBigEndian) 9227 Offset = TySizeInBytes - Offset - getLoadedSize(); 9228 return Offset; 9229 } 9230 9231 /// \brief Generate the sequence of instructions to load the slice 9232 /// represented by this object and redirect the uses of this slice to 9233 /// this new sequence of instructions. 9234 /// \pre this->Inst && this->Origin are valid Instructions and this 9235 /// object passed the legal check: LoadedSlice::isLegal returned true. 9236 /// \return The last instruction of the sequence used to load the slice. 9237 SDValue loadSlice() const { 9238 assert(Inst && Origin && "Unable to replace a non-existing slice."); 9239 const SDValue &OldBaseAddr = Origin->getBasePtr(); 9240 SDValue BaseAddr = OldBaseAddr; 9241 // Get the offset in that chunk of bytes w.r.t. the endianess. 9242 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 9243 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 9244 if (Offset) { 9245 // BaseAddr = BaseAddr + Offset. 9246 EVT ArithType = BaseAddr.getValueType(); 9247 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 9248 DAG->getConstant(Offset, ArithType)); 9249 } 9250 9251 // Create the type of the loaded slice according to its size. 9252 EVT SliceType = getLoadedType(); 9253 9254 // Create the load for the slice. 9255 SDValue LastInst = DAG->getLoad( 9256 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 9257 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 9258 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 9259 // If the final type is not the same as the loaded type, this means that 9260 // we have to pad with zero. Create a zero extend for that. 9261 EVT FinalType = Inst->getValueType(0); 9262 if (SliceType != FinalType) 9263 LastInst = 9264 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 9265 return LastInst; 9266 } 9267 9268 /// \brief Check if this slice can be merged with an expensive cross register 9269 /// bank copy. E.g., 9270 /// i = load i32 9271 /// f = bitcast i32 i to float 9272 bool canMergeExpensiveCrossRegisterBankCopy() const { 9273 if (!Inst || !Inst->hasOneUse()) 9274 return false; 9275 SDNode *Use = *Inst->use_begin(); 9276 if (Use->getOpcode() != ISD::BITCAST) 9277 return false; 9278 assert(DAG && "Missing context"); 9279 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9280 EVT ResVT = Use->getValueType(0); 9281 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 9282 const TargetRegisterClass *ArgRC = 9283 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 9284 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 9285 return false; 9286 9287 // At this point, we know that we perform a cross-register-bank copy. 9288 // Check if it is expensive. 9289 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 9290 // Assume bitcasts are cheap, unless both register classes do not 9291 // explicitly share a common sub class. 9292 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 9293 return false; 9294 9295 // Check if it will be merged with the load. 9296 // 1. Check the alignment constraint. 9297 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 9298 ResVT.getTypeForEVT(*DAG->getContext())); 9299 9300 if (RequiredAlignment > getAlignment()) 9301 return false; 9302 9303 // 2. Check that the load is a legal operation for that type. 9304 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 9305 return false; 9306 9307 // 3. Check that we do not have a zext in the way. 9308 if (Inst->getValueType(0) != getLoadedType()) 9309 return false; 9310 9311 return true; 9312 } 9313 }; 9314 } 9315 9316 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 9317 /// \p UsedBits looks like 0..0 1..1 0..0. 9318 static bool areUsedBitsDense(const APInt &UsedBits) { 9319 // If all the bits are one, this is dense! 9320 if (UsedBits.isAllOnesValue()) 9321 return true; 9322 9323 // Get rid of the unused bits on the right. 9324 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 9325 // Get rid of the unused bits on the left. 9326 if (NarrowedUsedBits.countLeadingZeros()) 9327 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 9328 // Check that the chunk of bits is completely used. 9329 return NarrowedUsedBits.isAllOnesValue(); 9330 } 9331 9332 /// \brief Check whether or not \p First and \p Second are next to each other 9333 /// in memory. This means that there is no hole between the bits loaded 9334 /// by \p First and the bits loaded by \p Second. 9335 static bool areSlicesNextToEachOther(const LoadedSlice &First, 9336 const LoadedSlice &Second) { 9337 assert(First.Origin == Second.Origin && First.Origin && 9338 "Unable to match different memory origins."); 9339 APInt UsedBits = First.getUsedBits(); 9340 assert((UsedBits & Second.getUsedBits()) == 0 && 9341 "Slices are not supposed to overlap."); 9342 UsedBits |= Second.getUsedBits(); 9343 return areUsedBitsDense(UsedBits); 9344 } 9345 9346 /// \brief Adjust the \p GlobalLSCost according to the target 9347 /// paring capabilities and the layout of the slices. 9348 /// \pre \p GlobalLSCost should account for at least as many loads as 9349 /// there is in the slices in \p LoadedSlices. 9350 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9351 LoadedSlice::Cost &GlobalLSCost) { 9352 unsigned NumberOfSlices = LoadedSlices.size(); 9353 // If there is less than 2 elements, no pairing is possible. 9354 if (NumberOfSlices < 2) 9355 return; 9356 9357 // Sort the slices so that elements that are likely to be next to each 9358 // other in memory are next to each other in the list. 9359 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 9360 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 9361 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 9362 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 9363 }); 9364 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 9365 // First (resp. Second) is the first (resp. Second) potentially candidate 9366 // to be placed in a paired load. 9367 const LoadedSlice *First = nullptr; 9368 const LoadedSlice *Second = nullptr; 9369 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 9370 // Set the beginning of the pair. 9371 First = Second) { 9372 9373 Second = &LoadedSlices[CurrSlice]; 9374 9375 // If First is NULL, it means we start a new pair. 9376 // Get to the next slice. 9377 if (!First) 9378 continue; 9379 9380 EVT LoadedType = First->getLoadedType(); 9381 9382 // If the types of the slices are different, we cannot pair them. 9383 if (LoadedType != Second->getLoadedType()) 9384 continue; 9385 9386 // Check if the target supplies paired loads for this type. 9387 unsigned RequiredAlignment = 0; 9388 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 9389 // move to the next pair, this type is hopeless. 9390 Second = nullptr; 9391 continue; 9392 } 9393 // Check if we meet the alignment requirement. 9394 if (RequiredAlignment > First->getAlignment()) 9395 continue; 9396 9397 // Check that both loads are next to each other in memory. 9398 if (!areSlicesNextToEachOther(*First, *Second)) 9399 continue; 9400 9401 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 9402 --GlobalLSCost.Loads; 9403 // Move to the next pair. 9404 Second = nullptr; 9405 } 9406 } 9407 9408 /// \brief Check the profitability of all involved LoadedSlice. 9409 /// Currently, it is considered profitable if there is exactly two 9410 /// involved slices (1) which are (2) next to each other in memory, and 9411 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 9412 /// 9413 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 9414 /// the elements themselves. 9415 /// 9416 /// FIXME: When the cost model will be mature enough, we can relax 9417 /// constraints (1) and (2). 9418 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9419 const APInt &UsedBits, bool ForCodeSize) { 9420 unsigned NumberOfSlices = LoadedSlices.size(); 9421 if (StressLoadSlicing) 9422 return NumberOfSlices > 1; 9423 9424 // Check (1). 9425 if (NumberOfSlices != 2) 9426 return false; 9427 9428 // Check (2). 9429 if (!areUsedBitsDense(UsedBits)) 9430 return false; 9431 9432 // Check (3). 9433 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 9434 // The original code has one big load. 9435 OrigCost.Loads = 1; 9436 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 9437 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 9438 // Accumulate the cost of all the slices. 9439 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 9440 GlobalSlicingCost += SliceCost; 9441 9442 // Account as cost in the original configuration the gain obtained 9443 // with the current slices. 9444 OrigCost.addSliceGain(LS); 9445 } 9446 9447 // If the target supports paired load, adjust the cost accordingly. 9448 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 9449 return OrigCost > GlobalSlicingCost; 9450 } 9451 9452 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 9453 /// operations, split it in the various pieces being extracted. 9454 /// 9455 /// This sort of thing is introduced by SROA. 9456 /// This slicing takes care not to insert overlapping loads. 9457 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 9458 bool DAGCombiner::SliceUpLoad(SDNode *N) { 9459 if (Level < AfterLegalizeDAG) 9460 return false; 9461 9462 LoadSDNode *LD = cast<LoadSDNode>(N); 9463 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 9464 !LD->getValueType(0).isInteger()) 9465 return false; 9466 9467 // Keep track of already used bits to detect overlapping values. 9468 // In that case, we will just abort the transformation. 9469 APInt UsedBits(LD->getValueSizeInBits(0), 0); 9470 9471 SmallVector<LoadedSlice, 4> LoadedSlices; 9472 9473 // Check if this load is used as several smaller chunks of bits. 9474 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 9475 // of computation for each trunc. 9476 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 9477 UI != UIEnd; ++UI) { 9478 // Skip the uses of the chain. 9479 if (UI.getUse().getResNo() != 0) 9480 continue; 9481 9482 SDNode *User = *UI; 9483 unsigned Shift = 0; 9484 9485 // Check if this is a trunc(lshr). 9486 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 9487 isa<ConstantSDNode>(User->getOperand(1))) { 9488 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 9489 User = *User->use_begin(); 9490 } 9491 9492 // At this point, User is a Truncate, iff we encountered, trunc or 9493 // trunc(lshr). 9494 if (User->getOpcode() != ISD::TRUNCATE) 9495 return false; 9496 9497 // The width of the type must be a power of 2 and greater than 8-bits. 9498 // Otherwise the load cannot be represented in LLVM IR. 9499 // Moreover, if we shifted with a non-8-bits multiple, the slice 9500 // will be across several bytes. We do not support that. 9501 unsigned Width = User->getValueSizeInBits(0); 9502 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 9503 return 0; 9504 9505 // Build the slice for this chain of computations. 9506 LoadedSlice LS(User, LD, Shift, &DAG); 9507 APInt CurrentUsedBits = LS.getUsedBits(); 9508 9509 // Check if this slice overlaps with another. 9510 if ((CurrentUsedBits & UsedBits) != 0) 9511 return false; 9512 // Update the bits used globally. 9513 UsedBits |= CurrentUsedBits; 9514 9515 // Check if the new slice would be legal. 9516 if (!LS.isLegal()) 9517 return false; 9518 9519 // Record the slice. 9520 LoadedSlices.push_back(LS); 9521 } 9522 9523 // Abort slicing if it does not seem to be profitable. 9524 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 9525 return false; 9526 9527 ++SlicedLoads; 9528 9529 // Rewrite each chain to use an independent load. 9530 // By construction, each chain can be represented by a unique load. 9531 9532 // Prepare the argument for the new token factor for all the slices. 9533 SmallVector<SDValue, 8> ArgChains; 9534 for (SmallVectorImpl<LoadedSlice>::const_iterator 9535 LSIt = LoadedSlices.begin(), 9536 LSItEnd = LoadedSlices.end(); 9537 LSIt != LSItEnd; ++LSIt) { 9538 SDValue SliceInst = LSIt->loadSlice(); 9539 CombineTo(LSIt->Inst, SliceInst, true); 9540 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 9541 SliceInst = SliceInst.getOperand(0); 9542 assert(SliceInst->getOpcode() == ISD::LOAD && 9543 "It takes more than a zext to get to the loaded slice!!"); 9544 ArgChains.push_back(SliceInst.getValue(1)); 9545 } 9546 9547 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 9548 ArgChains); 9549 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9550 return true; 9551 } 9552 9553 /// Check to see if V is (and load (ptr), imm), where the load is having 9554 /// specific bytes cleared out. If so, return the byte size being masked out 9555 /// and the shift amount. 9556 static std::pair<unsigned, unsigned> 9557 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 9558 std::pair<unsigned, unsigned> Result(0, 0); 9559 9560 // Check for the structure we're looking for. 9561 if (V->getOpcode() != ISD::AND || 9562 !isa<ConstantSDNode>(V->getOperand(1)) || 9563 !ISD::isNormalLoad(V->getOperand(0).getNode())) 9564 return Result; 9565 9566 // Check the chain and pointer. 9567 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 9568 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 9569 9570 // The store should be chained directly to the load or be an operand of a 9571 // tokenfactor. 9572 if (LD == Chain.getNode()) 9573 ; // ok. 9574 else if (Chain->getOpcode() != ISD::TokenFactor) 9575 return Result; // Fail. 9576 else { 9577 bool isOk = false; 9578 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 9579 if (Chain->getOperand(i).getNode() == LD) { 9580 isOk = true; 9581 break; 9582 } 9583 if (!isOk) return Result; 9584 } 9585 9586 // This only handles simple types. 9587 if (V.getValueType() != MVT::i16 && 9588 V.getValueType() != MVT::i32 && 9589 V.getValueType() != MVT::i64) 9590 return Result; 9591 9592 // Check the constant mask. Invert it so that the bits being masked out are 9593 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 9594 // follow the sign bit for uniformity. 9595 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 9596 unsigned NotMaskLZ = countLeadingZeros(NotMask); 9597 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 9598 unsigned NotMaskTZ = countTrailingZeros(NotMask); 9599 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 9600 if (NotMaskLZ == 64) return Result; // All zero mask. 9601 9602 // See if we have a continuous run of bits. If so, we have 0*1+0* 9603 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 9604 return Result; 9605 9606 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 9607 if (V.getValueType() != MVT::i64 && NotMaskLZ) 9608 NotMaskLZ -= 64-V.getValueSizeInBits(); 9609 9610 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 9611 switch (MaskedBytes) { 9612 case 1: 9613 case 2: 9614 case 4: break; 9615 default: return Result; // All one mask, or 5-byte mask. 9616 } 9617 9618 // Verify that the first bit starts at a multiple of mask so that the access 9619 // is aligned the same as the access width. 9620 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 9621 9622 Result.first = MaskedBytes; 9623 Result.second = NotMaskTZ/8; 9624 return Result; 9625 } 9626 9627 9628 /// Check to see if IVal is something that provides a value as specified by 9629 /// MaskInfo. If so, replace the specified store with a narrower store of 9630 /// truncated IVal. 9631 static SDNode * 9632 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 9633 SDValue IVal, StoreSDNode *St, 9634 DAGCombiner *DC) { 9635 unsigned NumBytes = MaskInfo.first; 9636 unsigned ByteShift = MaskInfo.second; 9637 SelectionDAG &DAG = DC->getDAG(); 9638 9639 // Check to see if IVal is all zeros in the part being masked in by the 'or' 9640 // that uses this. If not, this is not a replacement. 9641 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 9642 ByteShift*8, (ByteShift+NumBytes)*8); 9643 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 9644 9645 // Check that it is legal on the target to do this. It is legal if the new 9646 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 9647 // legalization. 9648 MVT VT = MVT::getIntegerVT(NumBytes*8); 9649 if (!DC->isTypeLegal(VT)) 9650 return nullptr; 9651 9652 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 9653 // shifted by ByteShift and truncated down to NumBytes. 9654 if (ByteShift) 9655 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 9656 DAG.getConstant(ByteShift*8, 9657 DC->getShiftAmountTy(IVal.getValueType()))); 9658 9659 // Figure out the offset for the store and the alignment of the access. 9660 unsigned StOffset; 9661 unsigned NewAlign = St->getAlignment(); 9662 9663 if (DAG.getTargetLoweringInfo().isLittleEndian()) 9664 StOffset = ByteShift; 9665 else 9666 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 9667 9668 SDValue Ptr = St->getBasePtr(); 9669 if (StOffset) { 9670 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 9671 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 9672 NewAlign = MinAlign(NewAlign, StOffset); 9673 } 9674 9675 // Truncate down to the new size. 9676 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 9677 9678 ++OpsNarrowed; 9679 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 9680 St->getPointerInfo().getWithOffset(StOffset), 9681 false, false, NewAlign).getNode(); 9682 } 9683 9684 9685 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 9686 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 9687 /// narrowing the load and store if it would end up being a win for performance 9688 /// or code size. 9689 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 9690 StoreSDNode *ST = cast<StoreSDNode>(N); 9691 if (ST->isVolatile()) 9692 return SDValue(); 9693 9694 SDValue Chain = ST->getChain(); 9695 SDValue Value = ST->getValue(); 9696 SDValue Ptr = ST->getBasePtr(); 9697 EVT VT = Value.getValueType(); 9698 9699 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 9700 return SDValue(); 9701 9702 unsigned Opc = Value.getOpcode(); 9703 9704 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 9705 // is a byte mask indicating a consecutive number of bytes, check to see if 9706 // Y is known to provide just those bytes. If so, we try to replace the 9707 // load + replace + store sequence with a single (narrower) store, which makes 9708 // the load dead. 9709 if (Opc == ISD::OR) { 9710 std::pair<unsigned, unsigned> MaskedLoad; 9711 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 9712 if (MaskedLoad.first) 9713 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 9714 Value.getOperand(1), ST,this)) 9715 return SDValue(NewST, 0); 9716 9717 // Or is commutative, so try swapping X and Y. 9718 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 9719 if (MaskedLoad.first) 9720 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 9721 Value.getOperand(0), ST,this)) 9722 return SDValue(NewST, 0); 9723 } 9724 9725 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 9726 Value.getOperand(1).getOpcode() != ISD::Constant) 9727 return SDValue(); 9728 9729 SDValue N0 = Value.getOperand(0); 9730 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9731 Chain == SDValue(N0.getNode(), 1)) { 9732 LoadSDNode *LD = cast<LoadSDNode>(N0); 9733 if (LD->getBasePtr() != Ptr || 9734 LD->getPointerInfo().getAddrSpace() != 9735 ST->getPointerInfo().getAddrSpace()) 9736 return SDValue(); 9737 9738 // Find the type to narrow it the load / op / store to. 9739 SDValue N1 = Value.getOperand(1); 9740 unsigned BitWidth = N1.getValueSizeInBits(); 9741 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 9742 if (Opc == ISD::AND) 9743 Imm ^= APInt::getAllOnesValue(BitWidth); 9744 if (Imm == 0 || Imm.isAllOnesValue()) 9745 return SDValue(); 9746 unsigned ShAmt = Imm.countTrailingZeros(); 9747 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 9748 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 9749 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 9750 // The narrowing should be profitable, the load/store operation should be 9751 // legal (or custom) and the store size should be equal to the NewVT width. 9752 while (NewBW < BitWidth && 9753 (NewVT.getStoreSizeInBits() != NewBW || 9754 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 9755 !TLI.isNarrowingProfitable(VT, NewVT))) { 9756 NewBW = NextPowerOf2(NewBW); 9757 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 9758 } 9759 if (NewBW >= BitWidth) 9760 return SDValue(); 9761 9762 // If the lsb changed does not start at the type bitwidth boundary, 9763 // start at the previous one. 9764 if (ShAmt % NewBW) 9765 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 9766 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 9767 std::min(BitWidth, ShAmt + NewBW)); 9768 if ((Imm & Mask) == Imm) { 9769 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 9770 if (Opc == ISD::AND) 9771 NewImm ^= APInt::getAllOnesValue(NewBW); 9772 uint64_t PtrOff = ShAmt / 8; 9773 // For big endian targets, we need to adjust the offset to the pointer to 9774 // load the correct bytes. 9775 if (TLI.isBigEndian()) 9776 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 9777 9778 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 9779 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 9780 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 9781 return SDValue(); 9782 9783 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 9784 Ptr.getValueType(), Ptr, 9785 DAG.getConstant(PtrOff, Ptr.getValueType())); 9786 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 9787 LD->getChain(), NewPtr, 9788 LD->getPointerInfo().getWithOffset(PtrOff), 9789 LD->isVolatile(), LD->isNonTemporal(), 9790 LD->isInvariant(), NewAlign, 9791 LD->getAAInfo()); 9792 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 9793 DAG.getConstant(NewImm, NewVT)); 9794 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 9795 NewVal, NewPtr, 9796 ST->getPointerInfo().getWithOffset(PtrOff), 9797 false, false, NewAlign); 9798 9799 AddToWorklist(NewPtr.getNode()); 9800 AddToWorklist(NewLD.getNode()); 9801 AddToWorklist(NewVal.getNode()); 9802 WorklistRemover DeadNodes(*this); 9803 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 9804 ++OpsNarrowed; 9805 return NewST; 9806 } 9807 } 9808 9809 return SDValue(); 9810 } 9811 9812 /// For a given floating point load / store pair, if the load value isn't used 9813 /// by any other operations, then consider transforming the pair to integer 9814 /// load / store operations if the target deems the transformation profitable. 9815 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 9816 StoreSDNode *ST = cast<StoreSDNode>(N); 9817 SDValue Chain = ST->getChain(); 9818 SDValue Value = ST->getValue(); 9819 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 9820 Value.hasOneUse() && 9821 Chain == SDValue(Value.getNode(), 1)) { 9822 LoadSDNode *LD = cast<LoadSDNode>(Value); 9823 EVT VT = LD->getMemoryVT(); 9824 if (!VT.isFloatingPoint() || 9825 VT != ST->getMemoryVT() || 9826 LD->isNonTemporal() || 9827 ST->isNonTemporal() || 9828 LD->getPointerInfo().getAddrSpace() != 0 || 9829 ST->getPointerInfo().getAddrSpace() != 0) 9830 return SDValue(); 9831 9832 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 9833 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 9834 !TLI.isOperationLegal(ISD::STORE, IntVT) || 9835 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 9836 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 9837 return SDValue(); 9838 9839 unsigned LDAlign = LD->getAlignment(); 9840 unsigned STAlign = ST->getAlignment(); 9841 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 9842 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 9843 if (LDAlign < ABIAlign || STAlign < ABIAlign) 9844 return SDValue(); 9845 9846 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 9847 LD->getChain(), LD->getBasePtr(), 9848 LD->getPointerInfo(), 9849 false, false, false, LDAlign); 9850 9851 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 9852 NewLD, ST->getBasePtr(), 9853 ST->getPointerInfo(), 9854 false, false, STAlign); 9855 9856 AddToWorklist(NewLD.getNode()); 9857 AddToWorklist(NewST.getNode()); 9858 WorklistRemover DeadNodes(*this); 9859 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 9860 ++LdStFP2Int; 9861 return NewST; 9862 } 9863 9864 return SDValue(); 9865 } 9866 9867 /// Helper struct to parse and store a memory address as base + index + offset. 9868 /// We ignore sign extensions when it is safe to do so. 9869 /// The following two expressions are not equivalent. To differentiate we need 9870 /// to store whether there was a sign extension involved in the index 9871 /// computation. 9872 /// (load (i64 add (i64 copyfromreg %c) 9873 /// (i64 signextend (add (i8 load %index) 9874 /// (i8 1)))) 9875 /// vs 9876 /// 9877 /// (load (i64 add (i64 copyfromreg %c) 9878 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 9879 /// (i32 1))))) 9880 struct BaseIndexOffset { 9881 SDValue Base; 9882 SDValue Index; 9883 int64_t Offset; 9884 bool IsIndexSignExt; 9885 9886 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 9887 9888 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 9889 bool IsIndexSignExt) : 9890 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 9891 9892 bool equalBaseIndex(const BaseIndexOffset &Other) { 9893 return Other.Base == Base && Other.Index == Index && 9894 Other.IsIndexSignExt == IsIndexSignExt; 9895 } 9896 9897 /// Parses tree in Ptr for base, index, offset addresses. 9898 static BaseIndexOffset match(SDValue Ptr) { 9899 bool IsIndexSignExt = false; 9900 9901 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 9902 // instruction, then it could be just the BASE or everything else we don't 9903 // know how to handle. Just use Ptr as BASE and give up. 9904 if (Ptr->getOpcode() != ISD::ADD) 9905 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9906 9907 // We know that we have at least an ADD instruction. Try to pattern match 9908 // the simple case of BASE + OFFSET. 9909 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 9910 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 9911 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 9912 IsIndexSignExt); 9913 } 9914 9915 // Inside a loop the current BASE pointer is calculated using an ADD and a 9916 // MUL instruction. In this case Ptr is the actual BASE pointer. 9917 // (i64 add (i64 %array_ptr) 9918 // (i64 mul (i64 %induction_var) 9919 // (i64 %element_size))) 9920 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 9921 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9922 9923 // Look at Base + Index + Offset cases. 9924 SDValue Base = Ptr->getOperand(0); 9925 SDValue IndexOffset = Ptr->getOperand(1); 9926 9927 // Skip signextends. 9928 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 9929 IndexOffset = IndexOffset->getOperand(0); 9930 IsIndexSignExt = true; 9931 } 9932 9933 // Either the case of Base + Index (no offset) or something else. 9934 if (IndexOffset->getOpcode() != ISD::ADD) 9935 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 9936 9937 // Now we have the case of Base + Index + offset. 9938 SDValue Index = IndexOffset->getOperand(0); 9939 SDValue Offset = IndexOffset->getOperand(1); 9940 9941 if (!isa<ConstantSDNode>(Offset)) 9942 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9943 9944 // Ignore signextends. 9945 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 9946 Index = Index->getOperand(0); 9947 IsIndexSignExt = true; 9948 } else IsIndexSignExt = false; 9949 9950 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 9951 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 9952 } 9953 }; 9954 9955 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 9956 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 9957 unsigned NumElem, bool IsConstantSrc, bool UseVector) { 9958 // Make sure we have something to merge. 9959 if (NumElem < 2) 9960 return false; 9961 9962 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 9963 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 9964 unsigned EarliestNodeUsed = 0; 9965 9966 for (unsigned i=0; i < NumElem; ++i) { 9967 // Find a chain for the new wide-store operand. Notice that some 9968 // of the store nodes that we found may not be selected for inclusion 9969 // in the wide store. The chain we use needs to be the chain of the 9970 // earliest store node which is *used* and replaced by the wide store. 9971 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9972 EarliestNodeUsed = i; 9973 } 9974 9975 // The earliest Node in the DAG. 9976 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9977 SDLoc DL(StoreNodes[0].MemNode); 9978 9979 SDValue StoredVal; 9980 if (UseVector) { 9981 // Find a legal type for the vector store. 9982 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9983 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 9984 if (IsConstantSrc) { 9985 // A vector store with a constant source implies that the constant is 9986 // zero; we only handle merging stores of constant zeros because the zero 9987 // can be materialized without a load. 9988 // It may be beneficial to loosen this restriction to allow non-zero 9989 // store merging. 9990 StoredVal = DAG.getConstant(0, Ty); 9991 } else { 9992 SmallVector<SDValue, 8> Ops; 9993 for (unsigned i = 0; i < NumElem ; ++i) { 9994 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9995 SDValue Val = St->getValue(); 9996 // All of the operands of a BUILD_VECTOR must have the same type. 9997 if (Val.getValueType() != MemVT) 9998 return false; 9999 Ops.push_back(Val); 10000 } 10001 10002 // Build the extracted vector elements back into a vector. 10003 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops); 10004 } 10005 } else { 10006 // We should always use a vector store when merging extracted vector 10007 // elements, so this path implies a store of constants. 10008 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10009 10010 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10011 APInt StoreInt(StoreBW, 0); 10012 10013 // Construct a single integer constant which is made of the smaller 10014 // constant inputs. 10015 bool IsLE = TLI.isLittleEndian(); 10016 for (unsigned i = 0; i < NumElem ; ++i) { 10017 unsigned Idx = IsLE ? (NumElem - 1 - i) : i; 10018 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10019 SDValue Val = St->getValue(); 10020 StoreInt <<= ElementSizeBytes*8; 10021 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10022 StoreInt |= C->getAPIntValue().zext(StoreBW); 10023 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10024 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 10025 } else { 10026 llvm_unreachable("Invalid constant element type"); 10027 } 10028 } 10029 10030 // Create the new Load and Store operations. 10031 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10032 StoredVal = DAG.getConstant(StoreInt, StoreTy); 10033 } 10034 10035 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 10036 FirstInChain->getBasePtr(), 10037 FirstInChain->getPointerInfo(), 10038 false, false, 10039 FirstInChain->getAlignment()); 10040 10041 // Replace the first store with the new store 10042 CombineTo(EarliestOp, NewStore); 10043 // Erase all other stores. 10044 for (unsigned i = 0; i < NumElem ; ++i) { 10045 if (StoreNodes[i].MemNode == EarliestOp) 10046 continue; 10047 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10048 // ReplaceAllUsesWith will replace all uses that existed when it was 10049 // called, but graph optimizations may cause new ones to appear. For 10050 // example, the case in pr14333 looks like 10051 // 10052 // St's chain -> St -> another store -> X 10053 // 10054 // And the only difference from St to the other store is the chain. 10055 // When we change it's chain to be St's chain they become identical, 10056 // get CSEed and the net result is that X is now a use of St. 10057 // Since we know that St is redundant, just iterate. 10058 while (!St->use_empty()) 10059 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10060 deleteAndRecombine(St); 10061 } 10062 10063 return true; 10064 } 10065 10066 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 10067 if (OptLevel == CodeGenOpt::None) 10068 return false; 10069 10070 EVT MemVT = St->getMemoryVT(); 10071 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 10072 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 10073 Attribute::NoImplicitFloat); 10074 10075 // Don't merge vectors into wider inputs. 10076 if (MemVT.isVector() || !MemVT.isSimple()) 10077 return false; 10078 10079 // Perform an early exit check. Do not bother looking at stored values that 10080 // are not constants, loads, or extracted vector elements. 10081 SDValue StoredVal = St->getValue(); 10082 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 10083 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 10084 isa<ConstantFPSDNode>(StoredVal); 10085 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 10086 10087 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 10088 return false; 10089 10090 // Only look at ends of store sequences. 10091 SDValue Chain = SDValue(St, 0); 10092 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 10093 return false; 10094 10095 // This holds the base pointer, index, and the offset in bytes from the base 10096 // pointer. 10097 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10098 10099 // We must have a base and an offset. 10100 if (!BasePtr.Base.getNode()) 10101 return false; 10102 10103 // Do not handle stores to undef base pointers. 10104 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10105 return false; 10106 10107 // Save the LoadSDNodes that we find in the chain. 10108 // We need to make sure that these nodes do not interfere with 10109 // any of the store nodes. 10110 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 10111 10112 // Save the StoreSDNodes that we find in the chain. 10113 SmallVector<MemOpLink, 8> StoreNodes; 10114 10115 // Walk up the chain and look for nodes with offsets from the same 10116 // base pointer. Stop when reaching an instruction with a different kind 10117 // or instruction which has a different base pointer. 10118 unsigned Seq = 0; 10119 StoreSDNode *Index = St; 10120 while (Index) { 10121 // If the chain has more than one use, then we can't reorder the mem ops. 10122 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10123 break; 10124 10125 // Find the base pointer and offset for this memory node. 10126 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 10127 10128 // Check that the base pointer is the same as the original one. 10129 if (!Ptr.equalBaseIndex(BasePtr)) 10130 break; 10131 10132 // Check that the alignment is the same. 10133 if (Index->getAlignment() != St->getAlignment()) 10134 break; 10135 10136 // The memory operands must not be volatile. 10137 if (Index->isVolatile() || Index->isIndexed()) 10138 break; 10139 10140 // No truncation. 10141 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 10142 if (St->isTruncatingStore()) 10143 break; 10144 10145 // The stored memory type must be the same. 10146 if (Index->getMemoryVT() != MemVT) 10147 break; 10148 10149 // We do not allow unaligned stores because we want to prevent overriding 10150 // stores. 10151 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 10152 break; 10153 10154 // We found a potential memory operand to merge. 10155 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 10156 10157 // Find the next memory operand in the chain. If the next operand in the 10158 // chain is a store then move up and continue the scan with the next 10159 // memory operand. If the next operand is a load save it and use alias 10160 // information to check if it interferes with anything. 10161 SDNode *NextInChain = Index->getChain().getNode(); 10162 while (1) { 10163 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 10164 // We found a store node. Use it for the next iteration. 10165 Index = STn; 10166 break; 10167 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 10168 if (Ldn->isVolatile()) { 10169 Index = nullptr; 10170 break; 10171 } 10172 10173 // Save the load node for later. Continue the scan. 10174 AliasLoadNodes.push_back(Ldn); 10175 NextInChain = Ldn->getChain().getNode(); 10176 continue; 10177 } else { 10178 Index = nullptr; 10179 break; 10180 } 10181 } 10182 } 10183 10184 // Check if there is anything to merge. 10185 if (StoreNodes.size() < 2) 10186 return false; 10187 10188 // Sort the memory operands according to their distance from the base pointer. 10189 std::sort(StoreNodes.begin(), StoreNodes.end(), 10190 [](MemOpLink LHS, MemOpLink RHS) { 10191 return LHS.OffsetFromBase < RHS.OffsetFromBase || 10192 (LHS.OffsetFromBase == RHS.OffsetFromBase && 10193 LHS.SequenceNum > RHS.SequenceNum); 10194 }); 10195 10196 // Scan the memory operations on the chain and find the first non-consecutive 10197 // store memory address. 10198 unsigned LastConsecutiveStore = 0; 10199 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 10200 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 10201 10202 // Check that the addresses are consecutive starting from the second 10203 // element in the list of stores. 10204 if (i > 0) { 10205 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 10206 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10207 break; 10208 } 10209 10210 bool Alias = false; 10211 // Check if this store interferes with any of the loads that we found. 10212 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 10213 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 10214 Alias = true; 10215 break; 10216 } 10217 // We found a load that alias with this store. Stop the sequence. 10218 if (Alias) 10219 break; 10220 10221 // Mark this node as useful. 10222 LastConsecutiveStore = i; 10223 } 10224 10225 // The node with the lowest store address. 10226 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10227 10228 // Store the constants into memory as one consecutive store. 10229 if (IsConstantSrc) { 10230 unsigned LastLegalType = 0; 10231 unsigned LastLegalVectorType = 0; 10232 bool NonZero = false; 10233 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10234 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10235 SDValue StoredVal = St->getValue(); 10236 10237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 10238 NonZero |= !C->isNullValue(); 10239 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 10240 NonZero |= !C->getConstantFPValue()->isNullValue(); 10241 } else { 10242 // Non-constant. 10243 break; 10244 } 10245 10246 // Find a legal type for the constant store. 10247 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10248 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10249 if (TLI.isTypeLegal(StoreTy)) 10250 LastLegalType = i+1; 10251 // Or check whether a truncstore is legal. 10252 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10253 TargetLowering::TypePromoteInteger) { 10254 EVT LegalizedStoredValueTy = 10255 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 10256 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 10257 LastLegalType = i+1; 10258 } 10259 10260 // Find a legal type for the vector store. 10261 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10262 if (TLI.isTypeLegal(Ty)) 10263 LastLegalVectorType = i + 1; 10264 } 10265 10266 // We only use vectors if the constant is known to be zero and the 10267 // function is not marked with the noimplicitfloat attribute. 10268 if (NonZero || NoVectors) 10269 LastLegalVectorType = 0; 10270 10271 // Check if we found a legal integer type to store. 10272 if (LastLegalType == 0 && LastLegalVectorType == 0) 10273 return false; 10274 10275 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 10276 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 10277 10278 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10279 true, UseVector); 10280 } 10281 10282 // When extracting multiple vector elements, try to store them 10283 // in one vector store rather than a sequence of scalar stores. 10284 if (IsExtractVecEltSrc) { 10285 unsigned NumElem = 0; 10286 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 10287 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10288 SDValue StoredVal = St->getValue(); 10289 // This restriction could be loosened. 10290 // Bail out if any stored values are not elements extracted from a vector. 10291 // It should be possible to handle mixed sources, but load sources need 10292 // more careful handling (see the block of code below that handles 10293 // consecutive loads). 10294 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10295 return false; 10296 10297 // Find a legal type for the vector store. 10298 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10299 if (TLI.isTypeLegal(Ty)) 10300 NumElem = i + 1; 10301 } 10302 10303 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10304 false, true); 10305 } 10306 10307 // Below we handle the case of multiple consecutive stores that 10308 // come from multiple consecutive loads. We merge them into a single 10309 // wide load and a single wide store. 10310 10311 // Look for load nodes which are used by the stored values. 10312 SmallVector<MemOpLink, 8> LoadNodes; 10313 10314 // Find acceptable loads. Loads need to have the same chain (token factor), 10315 // must not be zext, volatile, indexed, and they must be consecutive. 10316 BaseIndexOffset LdBasePtr; 10317 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10318 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10319 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 10320 if (!Ld) break; 10321 10322 // Loads must only have one use. 10323 if (!Ld->hasNUsesOfValue(1, 0)) 10324 break; 10325 10326 // Check that the alignment is the same as the stores. 10327 if (Ld->getAlignment() != St->getAlignment()) 10328 break; 10329 10330 // The memory operands must not be volatile. 10331 if (Ld->isVolatile() || Ld->isIndexed()) 10332 break; 10333 10334 // We do not accept ext loads. 10335 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 10336 break; 10337 10338 // The stored memory type must be the same. 10339 if (Ld->getMemoryVT() != MemVT) 10340 break; 10341 10342 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 10343 // If this is not the first ptr that we check. 10344 if (LdBasePtr.Base.getNode()) { 10345 // The base ptr must be the same. 10346 if (!LdPtr.equalBaseIndex(LdBasePtr)) 10347 break; 10348 } else { 10349 // Check that all other base pointers are the same as this one. 10350 LdBasePtr = LdPtr; 10351 } 10352 10353 // We found a potential memory operand to merge. 10354 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 10355 } 10356 10357 if (LoadNodes.size() < 2) 10358 return false; 10359 10360 // If we have load/store pair instructions and we only have two values, 10361 // don't bother. 10362 unsigned RequiredAlignment; 10363 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 10364 St->getAlignment() >= RequiredAlignment) 10365 return false; 10366 10367 // Scan the memory operations on the chain and find the first non-consecutive 10368 // load memory address. These variables hold the index in the store node 10369 // array. 10370 unsigned LastConsecutiveLoad = 0; 10371 // This variable refers to the size and not index in the array. 10372 unsigned LastLegalVectorType = 0; 10373 unsigned LastLegalIntegerType = 0; 10374 StartAddress = LoadNodes[0].OffsetFromBase; 10375 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 10376 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 10377 // All loads much share the same chain. 10378 if (LoadNodes[i].MemNode->getChain() != FirstChain) 10379 break; 10380 10381 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 10382 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10383 break; 10384 LastConsecutiveLoad = i; 10385 10386 // Find a legal type for the vector store. 10387 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10388 if (TLI.isTypeLegal(StoreTy)) 10389 LastLegalVectorType = i + 1; 10390 10391 // Find a legal type for the integer store. 10392 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10393 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10394 if (TLI.isTypeLegal(StoreTy)) 10395 LastLegalIntegerType = i + 1; 10396 // Or check whether a truncstore and extload is legal. 10397 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10398 TargetLowering::TypePromoteInteger) { 10399 EVT LegalizedStoredValueTy = 10400 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 10401 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10402 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10403 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10404 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy)) 10405 LastLegalIntegerType = i+1; 10406 } 10407 } 10408 10409 // Only use vector types if the vector type is larger than the integer type. 10410 // If they are the same, use integers. 10411 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 10412 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 10413 10414 // We add +1 here because the LastXXX variables refer to location while 10415 // the NumElem refers to array/index size. 10416 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 10417 NumElem = std::min(LastLegalType, NumElem); 10418 10419 if (NumElem < 2) 10420 return false; 10421 10422 // The earliest Node in the DAG. 10423 unsigned EarliestNodeUsed = 0; 10424 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 10425 for (unsigned i=1; i<NumElem; ++i) { 10426 // Find a chain for the new wide-store operand. Notice that some 10427 // of the store nodes that we found may not be selected for inclusion 10428 // in the wide store. The chain we use needs to be the chain of the 10429 // earliest store node which is *used* and replaced by the wide store. 10430 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 10431 EarliestNodeUsed = i; 10432 } 10433 10434 // Find if it is better to use vectors or integers to load and store 10435 // to memory. 10436 EVT JointMemOpVT; 10437 if (UseVectorTy) { 10438 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10439 } else { 10440 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10441 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10442 } 10443 10444 SDLoc LoadDL(LoadNodes[0].MemNode); 10445 SDLoc StoreDL(StoreNodes[0].MemNode); 10446 10447 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 10448 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 10449 FirstLoad->getChain(), 10450 FirstLoad->getBasePtr(), 10451 FirstLoad->getPointerInfo(), 10452 false, false, false, 10453 FirstLoad->getAlignment()); 10454 10455 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 10456 FirstInChain->getBasePtr(), 10457 FirstInChain->getPointerInfo(), false, false, 10458 FirstInChain->getAlignment()); 10459 10460 // Replace one of the loads with the new load. 10461 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 10462 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 10463 SDValue(NewLoad.getNode(), 1)); 10464 10465 // Remove the rest of the load chains. 10466 for (unsigned i = 1; i < NumElem ; ++i) { 10467 // Replace all chain users of the old load nodes with the chain of the new 10468 // load node. 10469 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 10470 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 10471 } 10472 10473 // Replace the first store with the new store. 10474 CombineTo(EarliestOp, NewStore); 10475 // Erase all other stores. 10476 for (unsigned i = 0; i < NumElem ; ++i) { 10477 // Remove all Store nodes. 10478 if (StoreNodes[i].MemNode == EarliestOp) 10479 continue; 10480 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10481 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 10482 deleteAndRecombine(St); 10483 } 10484 10485 return true; 10486 } 10487 10488 SDValue DAGCombiner::visitSTORE(SDNode *N) { 10489 StoreSDNode *ST = cast<StoreSDNode>(N); 10490 SDValue Chain = ST->getChain(); 10491 SDValue Value = ST->getValue(); 10492 SDValue Ptr = ST->getBasePtr(); 10493 10494 // If this is a store of a bit convert, store the input value if the 10495 // resultant store does not need a higher alignment than the original. 10496 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 10497 ST->isUnindexed()) { 10498 unsigned OrigAlign = ST->getAlignment(); 10499 EVT SVT = Value.getOperand(0).getValueType(); 10500 unsigned Align = TLI.getDataLayout()-> 10501 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 10502 if (Align <= OrigAlign && 10503 ((!LegalOperations && !ST->isVolatile()) || 10504 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 10505 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 10506 Ptr, ST->getPointerInfo(), ST->isVolatile(), 10507 ST->isNonTemporal(), OrigAlign, 10508 ST->getAAInfo()); 10509 } 10510 10511 // Turn 'store undef, Ptr' -> nothing. 10512 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 10513 return Chain; 10514 10515 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 10516 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 10517 // NOTE: If the original store is volatile, this transform must not increase 10518 // the number of stores. For example, on x86-32 an f64 can be stored in one 10519 // processor operation but an i64 (which is not legal) requires two. So the 10520 // transform should not be done in this case. 10521 if (Value.getOpcode() != ISD::TargetConstantFP) { 10522 SDValue Tmp; 10523 switch (CFP->getSimpleValueType(0).SimpleTy) { 10524 default: llvm_unreachable("Unknown FP type"); 10525 case MVT::f16: // We don't do this for these yet. 10526 case MVT::f80: 10527 case MVT::f128: 10528 case MVT::ppcf128: 10529 break; 10530 case MVT::f32: 10531 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 10532 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10533 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 10534 bitcastToAPInt().getZExtValue(), MVT::i32); 10535 return DAG.getStore(Chain, SDLoc(N), Tmp, 10536 Ptr, ST->getMemOperand()); 10537 } 10538 break; 10539 case MVT::f64: 10540 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 10541 !ST->isVolatile()) || 10542 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 10543 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 10544 getZExtValue(), MVT::i64); 10545 return DAG.getStore(Chain, SDLoc(N), Tmp, 10546 Ptr, ST->getMemOperand()); 10547 } 10548 10549 if (!ST->isVolatile() && 10550 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10551 // Many FP stores are not made apparent until after legalize, e.g. for 10552 // argument passing. Since this is so common, custom legalize the 10553 // 64-bit integer store into two 32-bit stores. 10554 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 10555 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 10556 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 10557 if (TLI.isBigEndian()) std::swap(Lo, Hi); 10558 10559 unsigned Alignment = ST->getAlignment(); 10560 bool isVolatile = ST->isVolatile(); 10561 bool isNonTemporal = ST->isNonTemporal(); 10562 AAMDNodes AAInfo = ST->getAAInfo(); 10563 10564 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 10565 Ptr, ST->getPointerInfo(), 10566 isVolatile, isNonTemporal, 10567 ST->getAlignment(), AAInfo); 10568 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 10569 DAG.getConstant(4, Ptr.getValueType())); 10570 Alignment = MinAlign(Alignment, 4U); 10571 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 10572 Ptr, ST->getPointerInfo().getWithOffset(4), 10573 isVolatile, isNonTemporal, 10574 Alignment, AAInfo); 10575 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 10576 St0, St1); 10577 } 10578 10579 break; 10580 } 10581 } 10582 } 10583 10584 // Try to infer better alignment information than the store already has. 10585 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 10586 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10587 if (Align > ST->getAlignment()) 10588 return DAG.getTruncStore(Chain, SDLoc(N), Value, 10589 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 10590 ST->isVolatile(), ST->isNonTemporal(), Align, 10591 ST->getAAInfo()); 10592 } 10593 } 10594 10595 // Try transforming a pair floating point load / store ops to integer 10596 // load / store ops. 10597 SDValue NewST = TransformFPLoadStorePair(N); 10598 if (NewST.getNode()) 10599 return NewST; 10600 10601 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10602 : DAG.getSubtarget().useAA(); 10603 #ifndef NDEBUG 10604 if (CombinerAAOnlyFunc.getNumOccurrences() && 10605 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10606 UseAA = false; 10607 #endif 10608 if (UseAA && ST->isUnindexed()) { 10609 // Walk up chain skipping non-aliasing memory nodes. 10610 SDValue BetterChain = FindBetterChain(N, Chain); 10611 10612 // If there is a better chain. 10613 if (Chain != BetterChain) { 10614 SDValue ReplStore; 10615 10616 // Replace the chain to avoid dependency. 10617 if (ST->isTruncatingStore()) { 10618 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 10619 ST->getMemoryVT(), ST->getMemOperand()); 10620 } else { 10621 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 10622 ST->getMemOperand()); 10623 } 10624 10625 // Create token to keep both nodes around. 10626 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10627 MVT::Other, Chain, ReplStore); 10628 10629 // Make sure the new and old chains are cleaned up. 10630 AddToWorklist(Token.getNode()); 10631 10632 // Don't add users to work list. 10633 return CombineTo(N, Token, false); 10634 } 10635 } 10636 10637 // Try transforming N to an indexed store. 10638 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10639 return SDValue(N, 0); 10640 10641 // FIXME: is there such a thing as a truncating indexed store? 10642 if (ST->isTruncatingStore() && ST->isUnindexed() && 10643 Value.getValueType().isInteger()) { 10644 // See if we can simplify the input to this truncstore with knowledge that 10645 // only the low bits are being used. For example: 10646 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 10647 SDValue Shorter = 10648 GetDemandedBits(Value, 10649 APInt::getLowBitsSet( 10650 Value.getValueType().getScalarType().getSizeInBits(), 10651 ST->getMemoryVT().getScalarType().getSizeInBits())); 10652 AddToWorklist(Value.getNode()); 10653 if (Shorter.getNode()) 10654 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 10655 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 10656 10657 // Otherwise, see if we can simplify the operation with 10658 // SimplifyDemandedBits, which only works if the value has a single use. 10659 if (SimplifyDemandedBits(Value, 10660 APInt::getLowBitsSet( 10661 Value.getValueType().getScalarType().getSizeInBits(), 10662 ST->getMemoryVT().getScalarType().getSizeInBits()))) 10663 return SDValue(N, 0); 10664 } 10665 10666 // If this is a load followed by a store to the same location, then the store 10667 // is dead/noop. 10668 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 10669 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 10670 ST->isUnindexed() && !ST->isVolatile() && 10671 // There can't be any side effects between the load and store, such as 10672 // a call or store. 10673 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 10674 // The store is dead, remove it. 10675 return Chain; 10676 } 10677 } 10678 10679 // If this is a store followed by a store with the same value to the same 10680 // location, then the store is dead/noop. 10681 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 10682 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 10683 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 10684 ST1->isUnindexed() && !ST1->isVolatile()) { 10685 // The store is dead, remove it. 10686 return Chain; 10687 } 10688 } 10689 10690 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 10691 // truncating store. We can do this even if this is already a truncstore. 10692 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 10693 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 10694 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 10695 ST->getMemoryVT())) { 10696 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 10697 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 10698 } 10699 10700 // Only perform this optimization before the types are legal, because we 10701 // don't want to perform this optimization on every DAGCombine invocation. 10702 if (!LegalTypes) { 10703 bool EverChanged = false; 10704 10705 do { 10706 // There can be multiple store sequences on the same chain. 10707 // Keep trying to merge store sequences until we are unable to do so 10708 // or until we merge the last store on the chain. 10709 bool Changed = MergeConsecutiveStores(ST); 10710 EverChanged |= Changed; 10711 if (!Changed) break; 10712 } while (ST->getOpcode() != ISD::DELETED_NODE); 10713 10714 if (EverChanged) 10715 return SDValue(N, 0); 10716 } 10717 10718 return ReduceLoadOpStoreWidth(N); 10719 } 10720 10721 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 10722 SDValue InVec = N->getOperand(0); 10723 SDValue InVal = N->getOperand(1); 10724 SDValue EltNo = N->getOperand(2); 10725 SDLoc dl(N); 10726 10727 // If the inserted element is an UNDEF, just use the input vector. 10728 if (InVal.getOpcode() == ISD::UNDEF) 10729 return InVec; 10730 10731 EVT VT = InVec.getValueType(); 10732 10733 // If we can't generate a legal BUILD_VECTOR, exit 10734 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 10735 return SDValue(); 10736 10737 // Check that we know which element is being inserted 10738 if (!isa<ConstantSDNode>(EltNo)) 10739 return SDValue(); 10740 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10741 10742 // Canonicalize insert_vector_elt dag nodes. 10743 // Example: 10744 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 10745 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 10746 // 10747 // Do this only if the child insert_vector node has one use; also 10748 // do this only if indices are both constants and Idx1 < Idx0. 10749 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 10750 && isa<ConstantSDNode>(InVec.getOperand(2))) { 10751 unsigned OtherElt = 10752 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 10753 if (Elt < OtherElt) { 10754 // Swap nodes. 10755 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 10756 InVec.getOperand(0), InVal, EltNo); 10757 AddToWorklist(NewOp.getNode()); 10758 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 10759 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 10760 } 10761 } 10762 10763 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 10764 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 10765 // vector elements. 10766 SmallVector<SDValue, 8> Ops; 10767 // Do not combine these two vectors if the output vector will not replace 10768 // the input vector. 10769 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 10770 Ops.append(InVec.getNode()->op_begin(), 10771 InVec.getNode()->op_end()); 10772 } else if (InVec.getOpcode() == ISD::UNDEF) { 10773 unsigned NElts = VT.getVectorNumElements(); 10774 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 10775 } else { 10776 return SDValue(); 10777 } 10778 10779 // Insert the element 10780 if (Elt < Ops.size()) { 10781 // All the operands of BUILD_VECTOR must have the same type; 10782 // we enforce that here. 10783 EVT OpVT = Ops[0].getValueType(); 10784 if (InVal.getValueType() != OpVT) 10785 InVal = OpVT.bitsGT(InVal.getValueType()) ? 10786 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 10787 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 10788 Ops[Elt] = InVal; 10789 } 10790 10791 // Return the new vector 10792 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 10793 } 10794 10795 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 10796 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 10797 EVT ResultVT = EVE->getValueType(0); 10798 EVT VecEltVT = InVecVT.getVectorElementType(); 10799 unsigned Align = OriginalLoad->getAlignment(); 10800 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 10801 VecEltVT.getTypeForEVT(*DAG.getContext())); 10802 10803 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 10804 return SDValue(); 10805 10806 Align = NewAlign; 10807 10808 SDValue NewPtr = OriginalLoad->getBasePtr(); 10809 SDValue Offset; 10810 EVT PtrType = NewPtr.getValueType(); 10811 MachinePointerInfo MPI; 10812 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 10813 int Elt = ConstEltNo->getZExtValue(); 10814 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 10815 if (TLI.isBigEndian()) 10816 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff; 10817 Offset = DAG.getConstant(PtrOff, PtrType); 10818 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 10819 } else { 10820 Offset = DAG.getNode( 10821 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo, 10822 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType())); 10823 if (TLI.isBigEndian()) 10824 Offset = DAG.getNode( 10825 ISD::SUB, SDLoc(EVE), EltNo.getValueType(), 10826 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset); 10827 MPI = OriginalLoad->getPointerInfo(); 10828 } 10829 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset); 10830 10831 // The replacement we need to do here is a little tricky: we need to 10832 // replace an extractelement of a load with a load. 10833 // Use ReplaceAllUsesOfValuesWith to do the replacement. 10834 // Note that this replacement assumes that the extractvalue is the only 10835 // use of the load; that's okay because we don't want to perform this 10836 // transformation in other cases anyway. 10837 SDValue Load; 10838 SDValue Chain; 10839 if (ResultVT.bitsGT(VecEltVT)) { 10840 // If the result type of vextract is wider than the load, then issue an 10841 // extending load instead. 10842 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 10843 VecEltVT) 10844 ? ISD::ZEXTLOAD 10845 : ISD::EXTLOAD; 10846 Load = DAG.getExtLoad( 10847 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 10848 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 10849 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 10850 Chain = Load.getValue(1); 10851 } else { 10852 Load = DAG.getLoad( 10853 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 10854 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 10855 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 10856 Chain = Load.getValue(1); 10857 if (ResultVT.bitsLT(VecEltVT)) 10858 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 10859 else 10860 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 10861 } 10862 WorklistRemover DeadNodes(*this); 10863 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 10864 SDValue To[] = { Load, Chain }; 10865 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10866 // Since we're explicitly calling ReplaceAllUses, add the new node to the 10867 // worklist explicitly as well. 10868 AddToWorklist(Load.getNode()); 10869 AddUsersToWorklist(Load.getNode()); // Add users too 10870 // Make sure to revisit this node to clean it up; it will usually be dead. 10871 AddToWorklist(EVE); 10872 ++OpsNarrowed; 10873 return SDValue(EVE, 0); 10874 } 10875 10876 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 10877 // (vextract (scalar_to_vector val, 0) -> val 10878 SDValue InVec = N->getOperand(0); 10879 EVT VT = InVec.getValueType(); 10880 EVT NVT = N->getValueType(0); 10881 10882 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 10883 // Check if the result type doesn't match the inserted element type. A 10884 // SCALAR_TO_VECTOR may truncate the inserted element and the 10885 // EXTRACT_VECTOR_ELT may widen the extracted vector. 10886 SDValue InOp = InVec.getOperand(0); 10887 if (InOp.getValueType() != NVT) { 10888 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 10889 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 10890 } 10891 return InOp; 10892 } 10893 10894 SDValue EltNo = N->getOperand(1); 10895 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 10896 10897 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 10898 // We only perform this optimization before the op legalization phase because 10899 // we may introduce new vector instructions which are not backed by TD 10900 // patterns. For example on AVX, extracting elements from a wide vector 10901 // without using extract_subvector. However, if we can find an underlying 10902 // scalar value, then we can always use that. 10903 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 10904 && ConstEltNo) { 10905 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10906 int NumElem = VT.getVectorNumElements(); 10907 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 10908 // Find the new index to extract from. 10909 int OrigElt = SVOp->getMaskElt(Elt); 10910 10911 // Extracting an undef index is undef. 10912 if (OrigElt == -1) 10913 return DAG.getUNDEF(NVT); 10914 10915 // Select the right vector half to extract from. 10916 SDValue SVInVec; 10917 if (OrigElt < NumElem) { 10918 SVInVec = InVec->getOperand(0); 10919 } else { 10920 SVInVec = InVec->getOperand(1); 10921 OrigElt -= NumElem; 10922 } 10923 10924 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 10925 SDValue InOp = SVInVec.getOperand(OrigElt); 10926 if (InOp.getValueType() != NVT) { 10927 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 10928 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 10929 } 10930 10931 return InOp; 10932 } 10933 10934 // FIXME: We should handle recursing on other vector shuffles and 10935 // scalar_to_vector here as well. 10936 10937 if (!LegalOperations) { 10938 EVT IndexTy = TLI.getVectorIdxTy(); 10939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 10940 SVInVec, DAG.getConstant(OrigElt, IndexTy)); 10941 } 10942 } 10943 10944 bool BCNumEltsChanged = false; 10945 EVT ExtVT = VT.getVectorElementType(); 10946 EVT LVT = ExtVT; 10947 10948 // If the result of load has to be truncated, then it's not necessarily 10949 // profitable. 10950 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 10951 return SDValue(); 10952 10953 if (InVec.getOpcode() == ISD::BITCAST) { 10954 // Don't duplicate a load with other uses. 10955 if (!InVec.hasOneUse()) 10956 return SDValue(); 10957 10958 EVT BCVT = InVec.getOperand(0).getValueType(); 10959 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 10960 return SDValue(); 10961 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 10962 BCNumEltsChanged = true; 10963 InVec = InVec.getOperand(0); 10964 ExtVT = BCVT.getVectorElementType(); 10965 } 10966 10967 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 10968 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 10969 ISD::isNormalLoad(InVec.getNode()) && 10970 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 10971 SDValue Index = N->getOperand(1); 10972 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 10973 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 10974 OrigLoad); 10975 } 10976 10977 // Perform only after legalization to ensure build_vector / vector_shuffle 10978 // optimizations have already been done. 10979 if (!LegalOperations) return SDValue(); 10980 10981 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 10982 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 10983 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 10984 10985 if (ConstEltNo) { 10986 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10987 10988 LoadSDNode *LN0 = nullptr; 10989 const ShuffleVectorSDNode *SVN = nullptr; 10990 if (ISD::isNormalLoad(InVec.getNode())) { 10991 LN0 = cast<LoadSDNode>(InVec); 10992 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 10993 InVec.getOperand(0).getValueType() == ExtVT && 10994 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 10995 // Don't duplicate a load with other uses. 10996 if (!InVec.hasOneUse()) 10997 return SDValue(); 10998 10999 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11000 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11001 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11002 // => 11003 // (load $addr+1*size) 11004 11005 // Don't duplicate a load with other uses. 11006 if (!InVec.hasOneUse()) 11007 return SDValue(); 11008 11009 // If the bit convert changed the number of elements, it is unsafe 11010 // to examine the mask. 11011 if (BCNumEltsChanged) 11012 return SDValue(); 11013 11014 // Select the input vector, guarding against out of range extract vector. 11015 unsigned NumElems = VT.getVectorNumElements(); 11016 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 11017 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 11018 11019 if (InVec.getOpcode() == ISD::BITCAST) { 11020 // Don't duplicate a load with other uses. 11021 if (!InVec.hasOneUse()) 11022 return SDValue(); 11023 11024 InVec = InVec.getOperand(0); 11025 } 11026 if (ISD::isNormalLoad(InVec.getNode())) { 11027 LN0 = cast<LoadSDNode>(InVec); 11028 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 11029 EltNo = DAG.getConstant(Elt, EltNo.getValueType()); 11030 } 11031 } 11032 11033 // Make sure we found a non-volatile load and the extractelement is 11034 // the only use. 11035 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 11036 return SDValue(); 11037 11038 // If Idx was -1 above, Elt is going to be -1, so just return undef. 11039 if (Elt == -1) 11040 return DAG.getUNDEF(LVT); 11041 11042 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 11043 } 11044 11045 return SDValue(); 11046 } 11047 11048 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 11049 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 11050 // We perform this optimization post type-legalization because 11051 // the type-legalizer often scalarizes integer-promoted vectors. 11052 // Performing this optimization before may create bit-casts which 11053 // will be type-legalized to complex code sequences. 11054 // We perform this optimization only before the operation legalizer because we 11055 // may introduce illegal operations. 11056 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 11057 return SDValue(); 11058 11059 unsigned NumInScalars = N->getNumOperands(); 11060 SDLoc dl(N); 11061 EVT VT = N->getValueType(0); 11062 11063 // Check to see if this is a BUILD_VECTOR of a bunch of values 11064 // which come from any_extend or zero_extend nodes. If so, we can create 11065 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 11066 // optimizations. We do not handle sign-extend because we can't fill the sign 11067 // using shuffles. 11068 EVT SourceType = MVT::Other; 11069 bool AllAnyExt = true; 11070 11071 for (unsigned i = 0; i != NumInScalars; ++i) { 11072 SDValue In = N->getOperand(i); 11073 // Ignore undef inputs. 11074 if (In.getOpcode() == ISD::UNDEF) continue; 11075 11076 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 11077 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 11078 11079 // Abort if the element is not an extension. 11080 if (!ZeroExt && !AnyExt) { 11081 SourceType = MVT::Other; 11082 break; 11083 } 11084 11085 // The input is a ZeroExt or AnyExt. Check the original type. 11086 EVT InTy = In.getOperand(0).getValueType(); 11087 11088 // Check that all of the widened source types are the same. 11089 if (SourceType == MVT::Other) 11090 // First time. 11091 SourceType = InTy; 11092 else if (InTy != SourceType) { 11093 // Multiple income types. Abort. 11094 SourceType = MVT::Other; 11095 break; 11096 } 11097 11098 // Check if all of the extends are ANY_EXTENDs. 11099 AllAnyExt &= AnyExt; 11100 } 11101 11102 // In order to have valid types, all of the inputs must be extended from the 11103 // same source type and all of the inputs must be any or zero extend. 11104 // Scalar sizes must be a power of two. 11105 EVT OutScalarTy = VT.getScalarType(); 11106 bool ValidTypes = SourceType != MVT::Other && 11107 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 11108 isPowerOf2_32(SourceType.getSizeInBits()); 11109 11110 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 11111 // turn into a single shuffle instruction. 11112 if (!ValidTypes) 11113 return SDValue(); 11114 11115 bool isLE = TLI.isLittleEndian(); 11116 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 11117 assert(ElemRatio > 1 && "Invalid element size ratio"); 11118 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 11119 DAG.getConstant(0, SourceType); 11120 11121 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 11122 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 11123 11124 // Populate the new build_vector 11125 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11126 SDValue Cast = N->getOperand(i); 11127 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 11128 Cast.getOpcode() == ISD::ZERO_EXTEND || 11129 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 11130 SDValue In; 11131 if (Cast.getOpcode() == ISD::UNDEF) 11132 In = DAG.getUNDEF(SourceType); 11133 else 11134 In = Cast->getOperand(0); 11135 unsigned Index = isLE ? (i * ElemRatio) : 11136 (i * ElemRatio + (ElemRatio - 1)); 11137 11138 assert(Index < Ops.size() && "Invalid index"); 11139 Ops[Index] = In; 11140 } 11141 11142 // The type of the new BUILD_VECTOR node. 11143 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 11144 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 11145 "Invalid vector size"); 11146 // Check if the new vector type is legal. 11147 if (!isTypeLegal(VecVT)) return SDValue(); 11148 11149 // Make the new BUILD_VECTOR. 11150 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 11151 11152 // The new BUILD_VECTOR node has the potential to be further optimized. 11153 AddToWorklist(BV.getNode()); 11154 // Bitcast to the desired type. 11155 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11156 } 11157 11158 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 11159 EVT VT = N->getValueType(0); 11160 11161 unsigned NumInScalars = N->getNumOperands(); 11162 SDLoc dl(N); 11163 11164 EVT SrcVT = MVT::Other; 11165 unsigned Opcode = ISD::DELETED_NODE; 11166 unsigned NumDefs = 0; 11167 11168 for (unsigned i = 0; i != NumInScalars; ++i) { 11169 SDValue In = N->getOperand(i); 11170 unsigned Opc = In.getOpcode(); 11171 11172 if (Opc == ISD::UNDEF) 11173 continue; 11174 11175 // If all scalar values are floats and converted from integers. 11176 if (Opcode == ISD::DELETED_NODE && 11177 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 11178 Opcode = Opc; 11179 } 11180 11181 if (Opc != Opcode) 11182 return SDValue(); 11183 11184 EVT InVT = In.getOperand(0).getValueType(); 11185 11186 // If all scalar values are typed differently, bail out. It's chosen to 11187 // simplify BUILD_VECTOR of integer types. 11188 if (SrcVT == MVT::Other) 11189 SrcVT = InVT; 11190 if (SrcVT != InVT) 11191 return SDValue(); 11192 NumDefs++; 11193 } 11194 11195 // If the vector has just one element defined, it's not worth to fold it into 11196 // a vectorized one. 11197 if (NumDefs < 2) 11198 return SDValue(); 11199 11200 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 11201 && "Should only handle conversion from integer to float."); 11202 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 11203 11204 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 11205 11206 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 11207 return SDValue(); 11208 11209 // Just because the floating-point vector type is legal does not necessarily 11210 // mean that the corresponding integer vector type is. 11211 if (!isTypeLegal(NVT)) 11212 return SDValue(); 11213 11214 SmallVector<SDValue, 8> Opnds; 11215 for (unsigned i = 0; i != NumInScalars; ++i) { 11216 SDValue In = N->getOperand(i); 11217 11218 if (In.getOpcode() == ISD::UNDEF) 11219 Opnds.push_back(DAG.getUNDEF(SrcVT)); 11220 else 11221 Opnds.push_back(In.getOperand(0)); 11222 } 11223 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 11224 AddToWorklist(BV.getNode()); 11225 11226 return DAG.getNode(Opcode, dl, VT, BV); 11227 } 11228 11229 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 11230 unsigned NumInScalars = N->getNumOperands(); 11231 SDLoc dl(N); 11232 EVT VT = N->getValueType(0); 11233 11234 // A vector built entirely of undefs is undef. 11235 if (ISD::allOperandsUndef(N)) 11236 return DAG.getUNDEF(VT); 11237 11238 SDValue V = reduceBuildVecExtToExtBuildVec(N); 11239 if (V.getNode()) 11240 return V; 11241 11242 V = reduceBuildVecConvertToConvertBuildVec(N); 11243 if (V.getNode()) 11244 return V; 11245 11246 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 11247 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 11248 // at most two distinct vectors, turn this into a shuffle node. 11249 11250 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 11251 if (!isTypeLegal(VT)) 11252 return SDValue(); 11253 11254 // May only combine to shuffle after legalize if shuffle is legal. 11255 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 11256 return SDValue(); 11257 11258 SDValue VecIn1, VecIn2; 11259 bool UsesZeroVector = false; 11260 for (unsigned i = 0; i != NumInScalars; ++i) { 11261 SDValue Op = N->getOperand(i); 11262 // Ignore undef inputs. 11263 if (Op.getOpcode() == ISD::UNDEF) continue; 11264 11265 // See if we can combine this build_vector into a blend with a zero vector. 11266 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant && 11267 cast<ConstantSDNode>(Op.getNode())->isNullValue()) || 11268 (Op.getOpcode() == ISD::ConstantFP && 11269 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) { 11270 UsesZeroVector = true; 11271 continue; 11272 } 11273 11274 // If this input is something other than a EXTRACT_VECTOR_ELT with a 11275 // constant index, bail out. 11276 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11277 !isa<ConstantSDNode>(Op.getOperand(1))) { 11278 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11279 break; 11280 } 11281 11282 // We allow up to two distinct input vectors. 11283 SDValue ExtractedFromVec = Op.getOperand(0); 11284 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 11285 continue; 11286 11287 if (!VecIn1.getNode()) { 11288 VecIn1 = ExtractedFromVec; 11289 } else if (!VecIn2.getNode() && !UsesZeroVector) { 11290 VecIn2 = ExtractedFromVec; 11291 } else { 11292 // Too many inputs. 11293 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11294 break; 11295 } 11296 } 11297 11298 // If everything is good, we can make a shuffle operation. 11299 if (VecIn1.getNode()) { 11300 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 11301 SmallVector<int, 8> Mask; 11302 for (unsigned i = 0; i != NumInScalars; ++i) { 11303 unsigned Opcode = N->getOperand(i).getOpcode(); 11304 if (Opcode == ISD::UNDEF) { 11305 Mask.push_back(-1); 11306 continue; 11307 } 11308 11309 // Operands can also be zero. 11310 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 11311 assert(UsesZeroVector && 11312 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 11313 "Unexpected node found!"); 11314 Mask.push_back(NumInScalars+i); 11315 continue; 11316 } 11317 11318 // If extracting from the first vector, just use the index directly. 11319 SDValue Extract = N->getOperand(i); 11320 SDValue ExtVal = Extract.getOperand(1); 11321 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 11322 if (Extract.getOperand(0) == VecIn1) { 11323 Mask.push_back(ExtIndex); 11324 continue; 11325 } 11326 11327 // Otherwise, use InIdx + InputVecSize 11328 Mask.push_back(InNumElements + ExtIndex); 11329 } 11330 11331 // Avoid introducing illegal shuffles with zero. 11332 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 11333 return SDValue(); 11334 11335 // We can't generate a shuffle node with mismatched input and output types. 11336 // Attempt to transform a single input vector to the correct type. 11337 if ((VT != VecIn1.getValueType())) { 11338 // If the input vector type has a different base type to the output 11339 // vector type, bail out. 11340 EVT VTElemType = VT.getVectorElementType(); 11341 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 11342 (VecIn2.getNode() && 11343 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 11344 return SDValue(); 11345 11346 // If the input vector is too small, widen it. 11347 // We only support widening of vectors which are half the size of the 11348 // output registers. For example XMM->YMM widening on X86 with AVX. 11349 EVT VecInT = VecIn1.getValueType(); 11350 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 11351 // If we only have one small input, widen it by adding undef values. 11352 if (!VecIn2.getNode()) 11353 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 11354 DAG.getUNDEF(VecIn1.getValueType())); 11355 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 11356 // If we have two small inputs of the same type, try to concat them. 11357 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 11358 VecIn2 = SDValue(nullptr, 0); 11359 } else 11360 return SDValue(); 11361 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 11362 // If the input vector is too large, try to split it. 11363 // We don't support having two input vectors that are too large. 11364 if (VecIn2.getNode()) 11365 return SDValue(); 11366 11367 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 11368 return SDValue(); 11369 11370 // Try to replace VecIn1 with two extract_subvectors 11371 // No need to update the masks, they should still be correct. 11372 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11373 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy())); 11374 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11375 DAG.getConstant(0, TLI.getVectorIdxTy())); 11376 UsesZeroVector = false; 11377 } else 11378 return SDValue(); 11379 } 11380 11381 if (UsesZeroVector) 11382 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) : 11383 DAG.getConstantFP(0.0, VT); 11384 else 11385 // If VecIn2 is unused then change it to undef. 11386 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 11387 11388 // Check that we were able to transform all incoming values to the same 11389 // type. 11390 if (VecIn2.getValueType() != VecIn1.getValueType() || 11391 VecIn1.getValueType() != VT) 11392 return SDValue(); 11393 11394 // Return the new VECTOR_SHUFFLE node. 11395 SDValue Ops[2]; 11396 Ops[0] = VecIn1; 11397 Ops[1] = VecIn2; 11398 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 11399 } 11400 11401 return SDValue(); 11402 } 11403 11404 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 11405 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 11406 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 11407 // inputs come from at most two distinct vectors, turn this into a shuffle 11408 // node. 11409 11410 // If we only have one input vector, we don't need to do any concatenation. 11411 if (N->getNumOperands() == 1) 11412 return N->getOperand(0); 11413 11414 // Check if all of the operands are undefs. 11415 EVT VT = N->getValueType(0); 11416 if (ISD::allOperandsUndef(N)) 11417 return DAG.getUNDEF(VT); 11418 11419 // Optimize concat_vectors where one of the vectors is undef. 11420 if (N->getNumOperands() == 2 && 11421 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 11422 SDValue In = N->getOperand(0); 11423 assert(In.getValueType().isVector() && "Must concat vectors"); 11424 11425 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 11426 if (In->getOpcode() == ISD::BITCAST && 11427 !In->getOperand(0)->getValueType(0).isVector()) { 11428 SDValue Scalar = In->getOperand(0); 11429 EVT SclTy = Scalar->getValueType(0); 11430 11431 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 11432 return SDValue(); 11433 11434 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 11435 VT.getSizeInBits() / SclTy.getSizeInBits()); 11436 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 11437 return SDValue(); 11438 11439 SDLoc dl = SDLoc(N); 11440 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 11441 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 11442 } 11443 } 11444 11445 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 11446 // We have already tested above for an UNDEF only concatenation. 11447 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 11448 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 11449 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 11450 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 11451 }; 11452 bool AllBuildVectorsOrUndefs = 11453 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 11454 if (AllBuildVectorsOrUndefs) { 11455 SmallVector<SDValue, 8> Opnds; 11456 EVT SVT = VT.getScalarType(); 11457 11458 EVT MinVT = SVT; 11459 if (!SVT.isFloatingPoint()) { 11460 // If BUILD_VECTOR are from built from integer, they may have different 11461 // operand types. Get the smallest type and truncate all operands to it. 11462 bool FoundMinVT = false; 11463 for (const SDValue &Op : N->ops()) 11464 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 11465 EVT OpSVT = Op.getOperand(0)->getValueType(0); 11466 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 11467 FoundMinVT = true; 11468 } 11469 assert(FoundMinVT && "Concat vector type mismatch"); 11470 } 11471 11472 for (const SDValue &Op : N->ops()) { 11473 EVT OpVT = Op.getValueType(); 11474 unsigned NumElts = OpVT.getVectorNumElements(); 11475 11476 if (ISD::UNDEF == Op.getOpcode()) 11477 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 11478 11479 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 11480 if (SVT.isFloatingPoint()) { 11481 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 11482 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 11483 } else { 11484 for (unsigned i = 0; i != NumElts; ++i) 11485 Opnds.push_back( 11486 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 11487 } 11488 } 11489 } 11490 11491 assert(VT.getVectorNumElements() == Opnds.size() && 11492 "Concat vector type mismatch"); 11493 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 11494 } 11495 11496 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 11497 // nodes often generate nop CONCAT_VECTOR nodes. 11498 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 11499 // place the incoming vectors at the exact same location. 11500 SDValue SingleSource = SDValue(); 11501 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 11502 11503 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11504 SDValue Op = N->getOperand(i); 11505 11506 if (Op.getOpcode() == ISD::UNDEF) 11507 continue; 11508 11509 // Check if this is the identity extract: 11510 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 11511 return SDValue(); 11512 11513 // Find the single incoming vector for the extract_subvector. 11514 if (SingleSource.getNode()) { 11515 if (Op.getOperand(0) != SingleSource) 11516 return SDValue(); 11517 } else { 11518 SingleSource = Op.getOperand(0); 11519 11520 // Check the source type is the same as the type of the result. 11521 // If not, this concat may extend the vector, so we can not 11522 // optimize it away. 11523 if (SingleSource.getValueType() != N->getValueType(0)) 11524 return SDValue(); 11525 } 11526 11527 unsigned IdentityIndex = i * PartNumElem; 11528 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 11529 // The extract index must be constant. 11530 if (!CS) 11531 return SDValue(); 11532 11533 // Check that we are reading from the identity index. 11534 if (CS->getZExtValue() != IdentityIndex) 11535 return SDValue(); 11536 } 11537 11538 if (SingleSource.getNode()) 11539 return SingleSource; 11540 11541 return SDValue(); 11542 } 11543 11544 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 11545 EVT NVT = N->getValueType(0); 11546 SDValue V = N->getOperand(0); 11547 11548 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 11549 // Combine: 11550 // (extract_subvec (concat V1, V2, ...), i) 11551 // Into: 11552 // Vi if possible 11553 // Only operand 0 is checked as 'concat' assumes all inputs of the same 11554 // type. 11555 if (V->getOperand(0).getValueType() != NVT) 11556 return SDValue(); 11557 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11558 unsigned NumElems = NVT.getVectorNumElements(); 11559 assert((Idx % NumElems) == 0 && 11560 "IDX in concat is not a multiple of the result vector length."); 11561 return V->getOperand(Idx / NumElems); 11562 } 11563 11564 // Skip bitcasting 11565 if (V->getOpcode() == ISD::BITCAST) 11566 V = V.getOperand(0); 11567 11568 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 11569 SDLoc dl(N); 11570 // Handle only simple case where vector being inserted and vector 11571 // being extracted are of same type, and are half size of larger vectors. 11572 EVT BigVT = V->getOperand(0).getValueType(); 11573 EVT SmallVT = V->getOperand(1).getValueType(); 11574 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 11575 return SDValue(); 11576 11577 // Only handle cases where both indexes are constants with the same type. 11578 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11579 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 11580 11581 if (InsIdx && ExtIdx && 11582 InsIdx->getValueType(0).getSizeInBits() <= 64 && 11583 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 11584 // Combine: 11585 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 11586 // Into: 11587 // indices are equal or bit offsets are equal => V1 11588 // otherwise => (extract_subvec V1, ExtIdx) 11589 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 11590 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 11591 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 11592 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 11593 DAG.getNode(ISD::BITCAST, dl, 11594 N->getOperand(0).getValueType(), 11595 V->getOperand(0)), N->getOperand(1)); 11596 } 11597 } 11598 11599 return SDValue(); 11600 } 11601 11602 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 11603 SDValue V, SelectionDAG &DAG) { 11604 SDLoc DL(V); 11605 EVT VT = V.getValueType(); 11606 11607 switch (V.getOpcode()) { 11608 default: 11609 return V; 11610 11611 case ISD::CONCAT_VECTORS: { 11612 EVT OpVT = V->getOperand(0).getValueType(); 11613 int OpSize = OpVT.getVectorNumElements(); 11614 SmallBitVector OpUsedElements(OpSize, false); 11615 bool FoundSimplification = false; 11616 SmallVector<SDValue, 4> NewOps; 11617 NewOps.reserve(V->getNumOperands()); 11618 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 11619 SDValue Op = V->getOperand(i); 11620 bool OpUsed = false; 11621 for (int j = 0; j < OpSize; ++j) 11622 if (UsedElements[i * OpSize + j]) { 11623 OpUsedElements[j] = true; 11624 OpUsed = true; 11625 } 11626 NewOps.push_back( 11627 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 11628 : DAG.getUNDEF(OpVT)); 11629 FoundSimplification |= Op == NewOps.back(); 11630 OpUsedElements.reset(); 11631 } 11632 if (FoundSimplification) 11633 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 11634 return V; 11635 } 11636 11637 case ISD::INSERT_SUBVECTOR: { 11638 SDValue BaseV = V->getOperand(0); 11639 SDValue SubV = V->getOperand(1); 11640 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 11641 if (!IdxN) 11642 return V; 11643 11644 int SubSize = SubV.getValueType().getVectorNumElements(); 11645 int Idx = IdxN->getZExtValue(); 11646 bool SubVectorUsed = false; 11647 SmallBitVector SubUsedElements(SubSize, false); 11648 for (int i = 0; i < SubSize; ++i) 11649 if (UsedElements[i + Idx]) { 11650 SubVectorUsed = true; 11651 SubUsedElements[i] = true; 11652 UsedElements[i + Idx] = false; 11653 } 11654 11655 // Now recurse on both the base and sub vectors. 11656 SDValue SimplifiedSubV = 11657 SubVectorUsed 11658 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 11659 : DAG.getUNDEF(SubV.getValueType()); 11660 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 11661 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 11662 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 11663 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 11664 return V; 11665 } 11666 } 11667 } 11668 11669 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 11670 SDValue N1, SelectionDAG &DAG) { 11671 EVT VT = SVN->getValueType(0); 11672 int NumElts = VT.getVectorNumElements(); 11673 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 11674 for (int M : SVN->getMask()) 11675 if (M >= 0 && M < NumElts) 11676 N0UsedElements[M] = true; 11677 else if (M >= NumElts) 11678 N1UsedElements[M - NumElts] = true; 11679 11680 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 11681 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 11682 if (S0 == N0 && S1 == N1) 11683 return SDValue(); 11684 11685 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 11686 } 11687 11688 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 11689 // or turn a shuffle of a single concat into simpler shuffle then concat. 11690 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 11691 EVT VT = N->getValueType(0); 11692 unsigned NumElts = VT.getVectorNumElements(); 11693 11694 SDValue N0 = N->getOperand(0); 11695 SDValue N1 = N->getOperand(1); 11696 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11697 11698 SmallVector<SDValue, 4> Ops; 11699 EVT ConcatVT = N0.getOperand(0).getValueType(); 11700 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 11701 unsigned NumConcats = NumElts / NumElemsPerConcat; 11702 11703 // Special case: shuffle(concat(A,B)) can be more efficiently represented 11704 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 11705 // half vector elements. 11706 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 11707 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 11708 SVN->getMask().end(), [](int i) { return i == -1; })) { 11709 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 11710 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat)); 11711 N1 = DAG.getUNDEF(ConcatVT); 11712 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 11713 } 11714 11715 // Look at every vector that's inserted. We're looking for exact 11716 // subvector-sized copies from a concatenated vector 11717 for (unsigned I = 0; I != NumConcats; ++I) { 11718 // Make sure we're dealing with a copy. 11719 unsigned Begin = I * NumElemsPerConcat; 11720 bool AllUndef = true, NoUndef = true; 11721 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 11722 if (SVN->getMaskElt(J) >= 0) 11723 AllUndef = false; 11724 else 11725 NoUndef = false; 11726 } 11727 11728 if (NoUndef) { 11729 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 11730 return SDValue(); 11731 11732 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 11733 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 11734 return SDValue(); 11735 11736 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 11737 if (FirstElt < N0.getNumOperands()) 11738 Ops.push_back(N0.getOperand(FirstElt)); 11739 else 11740 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 11741 11742 } else if (AllUndef) { 11743 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 11744 } else { // Mixed with general masks and undefs, can't do optimization. 11745 return SDValue(); 11746 } 11747 } 11748 11749 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 11750 } 11751 11752 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 11753 EVT VT = N->getValueType(0); 11754 unsigned NumElts = VT.getVectorNumElements(); 11755 11756 SDValue N0 = N->getOperand(0); 11757 SDValue N1 = N->getOperand(1); 11758 11759 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 11760 11761 // Canonicalize shuffle undef, undef -> undef 11762 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 11763 return DAG.getUNDEF(VT); 11764 11765 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11766 11767 // Canonicalize shuffle v, v -> v, undef 11768 if (N0 == N1) { 11769 SmallVector<int, 8> NewMask; 11770 for (unsigned i = 0; i != NumElts; ++i) { 11771 int Idx = SVN->getMaskElt(i); 11772 if (Idx >= (int)NumElts) Idx -= NumElts; 11773 NewMask.push_back(Idx); 11774 } 11775 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 11776 &NewMask[0]); 11777 } 11778 11779 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 11780 if (N0.getOpcode() == ISD::UNDEF) { 11781 SmallVector<int, 8> NewMask; 11782 for (unsigned i = 0; i != NumElts; ++i) { 11783 int Idx = SVN->getMaskElt(i); 11784 if (Idx >= 0) { 11785 if (Idx >= (int)NumElts) 11786 Idx -= NumElts; 11787 else 11788 Idx = -1; // remove reference to lhs 11789 } 11790 NewMask.push_back(Idx); 11791 } 11792 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 11793 &NewMask[0]); 11794 } 11795 11796 // Remove references to rhs if it is undef 11797 if (N1.getOpcode() == ISD::UNDEF) { 11798 bool Changed = false; 11799 SmallVector<int, 8> NewMask; 11800 for (unsigned i = 0; i != NumElts; ++i) { 11801 int Idx = SVN->getMaskElt(i); 11802 if (Idx >= (int)NumElts) { 11803 Idx = -1; 11804 Changed = true; 11805 } 11806 NewMask.push_back(Idx); 11807 } 11808 if (Changed) 11809 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 11810 } 11811 11812 // If it is a splat, check if the argument vector is another splat or a 11813 // build_vector. 11814 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 11815 SDNode *V = N0.getNode(); 11816 11817 // If this is a bit convert that changes the element type of the vector but 11818 // not the number of vector elements, look through it. Be careful not to 11819 // look though conversions that change things like v4f32 to v2f64. 11820 if (V->getOpcode() == ISD::BITCAST) { 11821 SDValue ConvInput = V->getOperand(0); 11822 if (ConvInput.getValueType().isVector() && 11823 ConvInput.getValueType().getVectorNumElements() == NumElts) 11824 V = ConvInput.getNode(); 11825 } 11826 11827 if (V->getOpcode() == ISD::BUILD_VECTOR) { 11828 assert(V->getNumOperands() == NumElts && 11829 "BUILD_VECTOR has wrong number of operands"); 11830 SDValue Base; 11831 bool AllSame = true; 11832 for (unsigned i = 0; i != NumElts; ++i) { 11833 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 11834 Base = V->getOperand(i); 11835 break; 11836 } 11837 } 11838 // Splat of <u, u, u, u>, return <u, u, u, u> 11839 if (!Base.getNode()) 11840 return N0; 11841 for (unsigned i = 0; i != NumElts; ++i) { 11842 if (V->getOperand(i) != Base) { 11843 AllSame = false; 11844 break; 11845 } 11846 } 11847 // Splat of <x, x, x, x>, return <x, x, x, x> 11848 if (AllSame) 11849 return N0; 11850 11851 // Canonicalize any other splat as a build_vector. 11852 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 11853 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 11854 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 11855 V->getValueType(0), Ops); 11856 11857 // We may have jumped through bitcasts, so the type of the 11858 // BUILD_VECTOR may not match the type of the shuffle. 11859 if (V->getValueType(0) != VT) 11860 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 11861 return NewBV; 11862 } 11863 } 11864 11865 // There are various patterns used to build up a vector from smaller vectors, 11866 // subvectors, or elements. Scan chains of these and replace unused insertions 11867 // or components with undef. 11868 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 11869 return S; 11870 11871 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 11872 Level < AfterLegalizeVectorOps && 11873 (N1.getOpcode() == ISD::UNDEF || 11874 (N1.getOpcode() == ISD::CONCAT_VECTORS && 11875 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 11876 SDValue V = partitionShuffleOfConcats(N, DAG); 11877 11878 if (V.getNode()) 11879 return V; 11880 } 11881 11882 // Canonicalize shuffles according to rules: 11883 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 11884 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 11885 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 11886 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 11887 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 11888 TLI.isTypeLegal(VT)) { 11889 // The incoming shuffle must be of the same type as the result of the 11890 // current shuffle. 11891 assert(N1->getOperand(0).getValueType() == VT && 11892 "Shuffle types don't match"); 11893 11894 SDValue SV0 = N1->getOperand(0); 11895 SDValue SV1 = N1->getOperand(1); 11896 bool HasSameOp0 = N0 == SV0; 11897 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 11898 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 11899 // Commute the operands of this shuffle so that next rule 11900 // will trigger. 11901 return DAG.getCommutedVectorShuffle(*SVN); 11902 } 11903 11904 // Try to fold according to rules: 11905 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 11906 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 11907 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 11908 // Don't try to fold shuffles with illegal type. 11909 // Only fold if this shuffle is the only user of the other shuffle. 11910 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 11911 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 11912 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 11913 11914 // The incoming shuffle must be of the same type as the result of the 11915 // current shuffle. 11916 assert(OtherSV->getOperand(0).getValueType() == VT && 11917 "Shuffle types don't match"); 11918 11919 SDValue SV0, SV1; 11920 SmallVector<int, 4> Mask; 11921 // Compute the combined shuffle mask for a shuffle with SV0 as the first 11922 // operand, and SV1 as the second operand. 11923 for (unsigned i = 0; i != NumElts; ++i) { 11924 int Idx = SVN->getMaskElt(i); 11925 if (Idx < 0) { 11926 // Propagate Undef. 11927 Mask.push_back(Idx); 11928 continue; 11929 } 11930 11931 SDValue CurrentVec; 11932 if (Idx < (int)NumElts) { 11933 // This shuffle index refers to the inner shuffle N0. Lookup the inner 11934 // shuffle mask to identify which vector is actually referenced. 11935 Idx = OtherSV->getMaskElt(Idx); 11936 if (Idx < 0) { 11937 // Propagate Undef. 11938 Mask.push_back(Idx); 11939 continue; 11940 } 11941 11942 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 11943 : OtherSV->getOperand(1); 11944 } else { 11945 // This shuffle index references an element within N1. 11946 CurrentVec = N1; 11947 } 11948 11949 // Simple case where 'CurrentVec' is UNDEF. 11950 if (CurrentVec.getOpcode() == ISD::UNDEF) { 11951 Mask.push_back(-1); 11952 continue; 11953 } 11954 11955 // Canonicalize the shuffle index. We don't know yet if CurrentVec 11956 // will be the first or second operand of the combined shuffle. 11957 Idx = Idx % NumElts; 11958 if (!SV0.getNode() || SV0 == CurrentVec) { 11959 // Ok. CurrentVec is the left hand side. 11960 // Update the mask accordingly. 11961 SV0 = CurrentVec; 11962 Mask.push_back(Idx); 11963 continue; 11964 } 11965 11966 // Bail out if we cannot convert the shuffle pair into a single shuffle. 11967 if (SV1.getNode() && SV1 != CurrentVec) 11968 return SDValue(); 11969 11970 // Ok. CurrentVec is the right hand side. 11971 // Update the mask accordingly. 11972 SV1 = CurrentVec; 11973 Mask.push_back(Idx + NumElts); 11974 } 11975 11976 // Check if all indices in Mask are Undef. In case, propagate Undef. 11977 bool isUndefMask = true; 11978 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 11979 isUndefMask &= Mask[i] < 0; 11980 11981 if (isUndefMask) 11982 return DAG.getUNDEF(VT); 11983 11984 if (!SV0.getNode()) 11985 SV0 = DAG.getUNDEF(VT); 11986 if (!SV1.getNode()) 11987 SV1 = DAG.getUNDEF(VT); 11988 11989 // Avoid introducing shuffles with illegal mask. 11990 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 11991 // Compute the commuted shuffle mask and test again. 11992 for (unsigned i = 0; i != NumElts; ++i) { 11993 int idx = Mask[i]; 11994 if (idx < 0) 11995 continue; 11996 else if (idx < (int)NumElts) 11997 Mask[i] = idx + NumElts; 11998 else 11999 Mask[i] = idx - NumElts; 12000 } 12001 12002 if (!TLI.isShuffleMaskLegal(Mask, VT)) 12003 return SDValue(); 12004 12005 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 12006 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 12007 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 12008 std::swap(SV0, SV1); 12009 } 12010 12011 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12012 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12013 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12014 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 12015 } 12016 12017 return SDValue(); 12018 } 12019 12020 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 12021 SDValue N0 = N->getOperand(0); 12022 SDValue N2 = N->getOperand(2); 12023 12024 // If the input vector is a concatenation, and the insert replaces 12025 // one of the halves, we can optimize into a single concat_vectors. 12026 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12027 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 12028 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 12029 EVT VT = N->getValueType(0); 12030 12031 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12032 // (concat_vectors Z, Y) 12033 if (InsIdx == 0) 12034 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12035 N->getOperand(1), N0.getOperand(1)); 12036 12037 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12038 // (concat_vectors X, Z) 12039 if (InsIdx == VT.getVectorNumElements()/2) 12040 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12041 N0.getOperand(0), N->getOperand(1)); 12042 } 12043 12044 return SDValue(); 12045 } 12046 12047 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 12048 /// with the destination vector and a zero vector. 12049 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 12050 /// vector_shuffle V, Zero, <0, 4, 2, 4> 12051 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 12052 EVT VT = N->getValueType(0); 12053 SDLoc dl(N); 12054 SDValue LHS = N->getOperand(0); 12055 SDValue RHS = N->getOperand(1); 12056 if (N->getOpcode() == ISD::AND) { 12057 if (RHS.getOpcode() == ISD::BITCAST) 12058 RHS = RHS.getOperand(0); 12059 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 12060 SmallVector<int, 8> Indices; 12061 unsigned NumElts = RHS.getNumOperands(); 12062 for (unsigned i = 0; i != NumElts; ++i) { 12063 SDValue Elt = RHS.getOperand(i); 12064 if (!isa<ConstantSDNode>(Elt)) 12065 return SDValue(); 12066 12067 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 12068 Indices.push_back(i); 12069 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 12070 Indices.push_back(NumElts+i); 12071 else 12072 return SDValue(); 12073 } 12074 12075 // Let's see if the target supports this vector_shuffle and make sure 12076 // we're not running after operation legalization where it may have 12077 // custom lowered the vector shuffles. 12078 EVT RVT = RHS.getValueType(); 12079 if (LegalOperations || !TLI.isVectorClearMaskLegal(Indices, RVT)) 12080 return SDValue(); 12081 12082 // Return the new VECTOR_SHUFFLE node. 12083 EVT EltVT = RVT.getVectorElementType(); 12084 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 12085 DAG.getConstant(0, EltVT)); 12086 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps); 12087 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 12088 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 12089 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 12090 } 12091 } 12092 12093 return SDValue(); 12094 } 12095 12096 /// Visit a binary vector operation, like ADD. 12097 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 12098 assert(N->getValueType(0).isVector() && 12099 "SimplifyVBinOp only works on vectors!"); 12100 12101 SDValue LHS = N->getOperand(0); 12102 SDValue RHS = N->getOperand(1); 12103 SDValue Shuffle = XformToShuffleWithZero(N); 12104 if (Shuffle.getNode()) return Shuffle; 12105 12106 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 12107 // this operation. 12108 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 12109 RHS.getOpcode() == ISD::BUILD_VECTOR) { 12110 // Check if both vectors are constants. If not bail out. 12111 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 12112 cast<BuildVectorSDNode>(RHS)->isConstant())) 12113 return SDValue(); 12114 12115 SmallVector<SDValue, 8> Ops; 12116 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 12117 SDValue LHSOp = LHS.getOperand(i); 12118 SDValue RHSOp = RHS.getOperand(i); 12119 12120 // Can't fold divide by zero. 12121 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 12122 N->getOpcode() == ISD::FDIV) { 12123 if ((RHSOp.getOpcode() == ISD::Constant && 12124 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 12125 (RHSOp.getOpcode() == ISD::ConstantFP && 12126 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 12127 break; 12128 } 12129 12130 EVT VT = LHSOp.getValueType(); 12131 EVT RVT = RHSOp.getValueType(); 12132 if (RVT != VT) { 12133 // Integer BUILD_VECTOR operands may have types larger than the element 12134 // size (e.g., when the element type is not legal). Prior to type 12135 // legalization, the types may not match between the two BUILD_VECTORS. 12136 // Truncate one of the operands to make them match. 12137 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 12138 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 12139 } else { 12140 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 12141 VT = RVT; 12142 } 12143 } 12144 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 12145 LHSOp, RHSOp); 12146 if (FoldOp.getOpcode() != ISD::UNDEF && 12147 FoldOp.getOpcode() != ISD::Constant && 12148 FoldOp.getOpcode() != ISD::ConstantFP) 12149 break; 12150 Ops.push_back(FoldOp); 12151 AddToWorklist(FoldOp.getNode()); 12152 } 12153 12154 if (Ops.size() == LHS.getNumOperands()) 12155 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 12156 } 12157 12158 // Type legalization might introduce new shuffles in the DAG. 12159 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 12160 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 12161 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 12162 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 12163 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 12164 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 12165 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 12166 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 12167 12168 if (SVN0->getMask().equals(SVN1->getMask())) { 12169 EVT VT = N->getValueType(0); 12170 SDValue UndefVector = LHS.getOperand(1); 12171 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 12172 LHS.getOperand(0), RHS.getOperand(0)); 12173 AddUsersToWorklist(N); 12174 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 12175 &SVN0->getMask()[0]); 12176 } 12177 } 12178 12179 return SDValue(); 12180 } 12181 12182 /// Visit a binary vector operation, like FABS/FNEG. 12183 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 12184 assert(N->getValueType(0).isVector() && 12185 "SimplifyVUnaryOp only works on vectors!"); 12186 12187 SDValue N0 = N->getOperand(0); 12188 12189 if (N0.getOpcode() != ISD::BUILD_VECTOR) 12190 return SDValue(); 12191 12192 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 12193 SmallVector<SDValue, 8> Ops; 12194 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 12195 SDValue Op = N0.getOperand(i); 12196 if (Op.getOpcode() != ISD::UNDEF && 12197 Op.getOpcode() != ISD::ConstantFP) 12198 break; 12199 EVT EltVT = Op.getValueType(); 12200 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 12201 if (FoldOp.getOpcode() != ISD::UNDEF && 12202 FoldOp.getOpcode() != ISD::ConstantFP) 12203 break; 12204 Ops.push_back(FoldOp); 12205 AddToWorklist(FoldOp.getNode()); 12206 } 12207 12208 if (Ops.size() != N0.getNumOperands()) 12209 return SDValue(); 12210 12211 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops); 12212 } 12213 12214 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 12215 SDValue N1, SDValue N2){ 12216 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 12217 12218 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 12219 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 12220 12221 // If we got a simplified select_cc node back from SimplifySelectCC, then 12222 // break it down into a new SETCC node, and a new SELECT node, and then return 12223 // the SELECT node, since we were called with a SELECT node. 12224 if (SCC.getNode()) { 12225 // Check to see if we got a select_cc back (to turn into setcc/select). 12226 // Otherwise, just return whatever node we got back, like fabs. 12227 if (SCC.getOpcode() == ISD::SELECT_CC) { 12228 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 12229 N0.getValueType(), 12230 SCC.getOperand(0), SCC.getOperand(1), 12231 SCC.getOperand(4)); 12232 AddToWorklist(SETCC.getNode()); 12233 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 12234 SCC.getOperand(2), SCC.getOperand(3)); 12235 } 12236 12237 return SCC; 12238 } 12239 return SDValue(); 12240 } 12241 12242 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 12243 /// being selected between, see if we can simplify the select. Callers of this 12244 /// should assume that TheSelect is deleted if this returns true. As such, they 12245 /// should return the appropriate thing (e.g. the node) back to the top-level of 12246 /// the DAG combiner loop to avoid it being looked at. 12247 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 12248 SDValue RHS) { 12249 12250 // Cannot simplify select with vector condition 12251 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 12252 12253 // If this is a select from two identical things, try to pull the operation 12254 // through the select. 12255 if (LHS.getOpcode() != RHS.getOpcode() || 12256 !LHS.hasOneUse() || !RHS.hasOneUse()) 12257 return false; 12258 12259 // If this is a load and the token chain is identical, replace the select 12260 // of two loads with a load through a select of the address to load from. 12261 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 12262 // constants have been dropped into the constant pool. 12263 if (LHS.getOpcode() == ISD::LOAD) { 12264 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 12265 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 12266 12267 // Token chains must be identical. 12268 if (LHS.getOperand(0) != RHS.getOperand(0) || 12269 // Do not let this transformation reduce the number of volatile loads. 12270 LLD->isVolatile() || RLD->isVolatile() || 12271 // If this is an EXTLOAD, the VT's must match. 12272 LLD->getMemoryVT() != RLD->getMemoryVT() || 12273 // If this is an EXTLOAD, the kind of extension must match. 12274 (LLD->getExtensionType() != RLD->getExtensionType() && 12275 // The only exception is if one of the extensions is anyext. 12276 LLD->getExtensionType() != ISD::EXTLOAD && 12277 RLD->getExtensionType() != ISD::EXTLOAD) || 12278 // FIXME: this discards src value information. This is 12279 // over-conservative. It would be beneficial to be able to remember 12280 // both potential memory locations. Since we are discarding 12281 // src value info, don't do the transformation if the memory 12282 // locations are not in the default address space. 12283 LLD->getPointerInfo().getAddrSpace() != 0 || 12284 RLD->getPointerInfo().getAddrSpace() != 0 || 12285 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 12286 LLD->getBasePtr().getValueType())) 12287 return false; 12288 12289 // Check that the select condition doesn't reach either load. If so, 12290 // folding this will induce a cycle into the DAG. If not, this is safe to 12291 // xform, so create a select of the addresses. 12292 SDValue Addr; 12293 if (TheSelect->getOpcode() == ISD::SELECT) { 12294 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 12295 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 12296 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 12297 return false; 12298 // The loads must not depend on one another. 12299 if (LLD->isPredecessorOf(RLD) || 12300 RLD->isPredecessorOf(LLD)) 12301 return false; 12302 Addr = DAG.getSelect(SDLoc(TheSelect), 12303 LLD->getBasePtr().getValueType(), 12304 TheSelect->getOperand(0), LLD->getBasePtr(), 12305 RLD->getBasePtr()); 12306 } else { // Otherwise SELECT_CC 12307 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 12308 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 12309 12310 if ((LLD->hasAnyUseOfValue(1) && 12311 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 12312 (RLD->hasAnyUseOfValue(1) && 12313 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 12314 return false; 12315 12316 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 12317 LLD->getBasePtr().getValueType(), 12318 TheSelect->getOperand(0), 12319 TheSelect->getOperand(1), 12320 LLD->getBasePtr(), RLD->getBasePtr(), 12321 TheSelect->getOperand(4)); 12322 } 12323 12324 SDValue Load; 12325 // It is safe to replace the two loads if they have different alignments, 12326 // but the new load must be the minimum (most restrictive) alignment of the 12327 // inputs. 12328 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 12329 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 12330 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 12331 Load = DAG.getLoad(TheSelect->getValueType(0), 12332 SDLoc(TheSelect), 12333 // FIXME: Discards pointer and AA info. 12334 LLD->getChain(), Addr, MachinePointerInfo(), 12335 LLD->isVolatile(), LLD->isNonTemporal(), 12336 isInvariant, Alignment); 12337 } else { 12338 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 12339 RLD->getExtensionType() : LLD->getExtensionType(), 12340 SDLoc(TheSelect), 12341 TheSelect->getValueType(0), 12342 // FIXME: Discards pointer and AA info. 12343 LLD->getChain(), Addr, MachinePointerInfo(), 12344 LLD->getMemoryVT(), LLD->isVolatile(), 12345 LLD->isNonTemporal(), isInvariant, Alignment); 12346 } 12347 12348 // Users of the select now use the result of the load. 12349 CombineTo(TheSelect, Load); 12350 12351 // Users of the old loads now use the new load's chain. We know the 12352 // old-load value is dead now. 12353 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 12354 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 12355 return true; 12356 } 12357 12358 return false; 12359 } 12360 12361 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 12362 /// where 'cond' is the comparison specified by CC. 12363 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 12364 SDValue N2, SDValue N3, 12365 ISD::CondCode CC, bool NotExtCompare) { 12366 // (x ? y : y) -> y. 12367 if (N2 == N3) return N2; 12368 12369 EVT VT = N2.getValueType(); 12370 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 12371 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 12372 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 12373 12374 // Determine if the condition we're dealing with is constant 12375 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 12376 N0, N1, CC, DL, false); 12377 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 12378 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 12379 12380 // fold select_cc true, x, y -> x 12381 if (SCCC && !SCCC->isNullValue()) 12382 return N2; 12383 // fold select_cc false, x, y -> y 12384 if (SCCC && SCCC->isNullValue()) 12385 return N3; 12386 12387 // Check to see if we can simplify the select into an fabs node 12388 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 12389 // Allow either -0.0 or 0.0 12390 if (CFP->getValueAPF().isZero()) { 12391 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 12392 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 12393 N0 == N2 && N3.getOpcode() == ISD::FNEG && 12394 N2 == N3.getOperand(0)) 12395 return DAG.getNode(ISD::FABS, DL, VT, N0); 12396 12397 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 12398 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 12399 N0 == N3 && N2.getOpcode() == ISD::FNEG && 12400 N2.getOperand(0) == N3) 12401 return DAG.getNode(ISD::FABS, DL, VT, N3); 12402 } 12403 } 12404 12405 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 12406 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 12407 // in it. This is a win when the constant is not otherwise available because 12408 // it replaces two constant pool loads with one. We only do this if the FP 12409 // type is known to be legal, because if it isn't, then we are before legalize 12410 // types an we want the other legalization to happen first (e.g. to avoid 12411 // messing with soft float) and if the ConstantFP is not legal, because if 12412 // it is legal, we may not need to store the FP constant in a constant pool. 12413 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 12414 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 12415 if (TLI.isTypeLegal(N2.getValueType()) && 12416 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 12417 TargetLowering::Legal && 12418 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 12419 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 12420 // If both constants have multiple uses, then we won't need to do an 12421 // extra load, they are likely around in registers for other users. 12422 (TV->hasOneUse() || FV->hasOneUse())) { 12423 Constant *Elts[] = { 12424 const_cast<ConstantFP*>(FV->getConstantFPValue()), 12425 const_cast<ConstantFP*>(TV->getConstantFPValue()) 12426 }; 12427 Type *FPTy = Elts[0]->getType(); 12428 const DataLayout &TD = *TLI.getDataLayout(); 12429 12430 // Create a ConstantArray of the two constants. 12431 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 12432 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 12433 TD.getPrefTypeAlignment(FPTy)); 12434 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 12435 12436 // Get the offsets to the 0 and 1 element of the array so that we can 12437 // select between them. 12438 SDValue Zero = DAG.getIntPtrConstant(0); 12439 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 12440 SDValue One = DAG.getIntPtrConstant(EltSize); 12441 12442 SDValue Cond = DAG.getSetCC(DL, 12443 getSetCCResultType(N0.getValueType()), 12444 N0, N1, CC); 12445 AddToWorklist(Cond.getNode()); 12446 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 12447 Cond, One, Zero); 12448 AddToWorklist(CstOffset.getNode()); 12449 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 12450 CstOffset); 12451 AddToWorklist(CPIdx.getNode()); 12452 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 12453 MachinePointerInfo::getConstantPool(), false, 12454 false, false, Alignment); 12455 12456 } 12457 } 12458 12459 // Check to see if we can perform the "gzip trick", transforming 12460 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 12461 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 12462 (N1C->isNullValue() || // (a < 0) ? b : 0 12463 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 12464 EVT XType = N0.getValueType(); 12465 EVT AType = N2.getValueType(); 12466 if (XType.bitsGE(AType)) { 12467 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 12468 // single-bit constant. 12469 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 12470 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 12471 ShCtV = XType.getSizeInBits()-ShCtV-1; 12472 SDValue ShCt = DAG.getConstant(ShCtV, 12473 getShiftAmountTy(N0.getValueType())); 12474 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 12475 XType, N0, ShCt); 12476 AddToWorklist(Shift.getNode()); 12477 12478 if (XType.bitsGT(AType)) { 12479 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 12480 AddToWorklist(Shift.getNode()); 12481 } 12482 12483 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 12484 } 12485 12486 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 12487 XType, N0, 12488 DAG.getConstant(XType.getSizeInBits()-1, 12489 getShiftAmountTy(N0.getValueType()))); 12490 AddToWorklist(Shift.getNode()); 12491 12492 if (XType.bitsGT(AType)) { 12493 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 12494 AddToWorklist(Shift.getNode()); 12495 } 12496 12497 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 12498 } 12499 } 12500 12501 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 12502 // where y is has a single bit set. 12503 // A plaintext description would be, we can turn the SELECT_CC into an AND 12504 // when the condition can be materialized as an all-ones register. Any 12505 // single bit-test can be materialized as an all-ones register with 12506 // shift-left and shift-right-arith. 12507 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 12508 N0->getValueType(0) == VT && 12509 N1C && N1C->isNullValue() && 12510 N2C && N2C->isNullValue()) { 12511 SDValue AndLHS = N0->getOperand(0); 12512 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12513 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 12514 // Shift the tested bit over the sign bit. 12515 APInt AndMask = ConstAndRHS->getAPIntValue(); 12516 SDValue ShlAmt = 12517 DAG.getConstant(AndMask.countLeadingZeros(), 12518 getShiftAmountTy(AndLHS.getValueType())); 12519 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 12520 12521 // Now arithmetic right shift it all the way over, so the result is either 12522 // all-ones, or zero. 12523 SDValue ShrAmt = 12524 DAG.getConstant(AndMask.getBitWidth()-1, 12525 getShiftAmountTy(Shl.getValueType())); 12526 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 12527 12528 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 12529 } 12530 } 12531 12532 // fold select C, 16, 0 -> shl C, 4 12533 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 12534 TLI.getBooleanContents(N0.getValueType()) == 12535 TargetLowering::ZeroOrOneBooleanContent) { 12536 12537 // If the caller doesn't want us to simplify this into a zext of a compare, 12538 // don't do it. 12539 if (NotExtCompare && N2C->getAPIntValue() == 1) 12540 return SDValue(); 12541 12542 // Get a SetCC of the condition 12543 // NOTE: Don't create a SETCC if it's not legal on this target. 12544 if (!LegalOperations || 12545 TLI.isOperationLegal(ISD::SETCC, 12546 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 12547 SDValue Temp, SCC; 12548 // cast from setcc result type to select result type 12549 if (LegalTypes) { 12550 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 12551 N0, N1, CC); 12552 if (N2.getValueType().bitsLT(SCC.getValueType())) 12553 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 12554 N2.getValueType()); 12555 else 12556 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 12557 N2.getValueType(), SCC); 12558 } else { 12559 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 12560 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 12561 N2.getValueType(), SCC); 12562 } 12563 12564 AddToWorklist(SCC.getNode()); 12565 AddToWorklist(Temp.getNode()); 12566 12567 if (N2C->getAPIntValue() == 1) 12568 return Temp; 12569 12570 // shl setcc result by log2 n2c 12571 return DAG.getNode( 12572 ISD::SHL, DL, N2.getValueType(), Temp, 12573 DAG.getConstant(N2C->getAPIntValue().logBase2(), 12574 getShiftAmountTy(Temp.getValueType()))); 12575 } 12576 } 12577 12578 // Check to see if this is the equivalent of setcc 12579 // FIXME: Turn all of these into setcc if setcc if setcc is legal 12580 // otherwise, go ahead with the folds. 12581 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 12582 EVT XType = N0.getValueType(); 12583 if (!LegalOperations || 12584 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 12585 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 12586 if (Res.getValueType() != VT) 12587 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 12588 return Res; 12589 } 12590 12591 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 12592 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 12593 (!LegalOperations || 12594 TLI.isOperationLegal(ISD::CTLZ, XType))) { 12595 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 12596 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 12597 DAG.getConstant(Log2_32(XType.getSizeInBits()), 12598 getShiftAmountTy(Ctlz.getValueType()))); 12599 } 12600 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 12601 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 12602 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 12603 XType, DAG.getConstant(0, XType), N0); 12604 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 12605 return DAG.getNode(ISD::SRL, DL, XType, 12606 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 12607 DAG.getConstant(XType.getSizeInBits()-1, 12608 getShiftAmountTy(XType))); 12609 } 12610 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 12611 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 12612 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 12613 DAG.getConstant(XType.getSizeInBits()-1, 12614 getShiftAmountTy(N0.getValueType()))); 12615 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 12616 } 12617 } 12618 12619 // Check to see if this is an integer abs. 12620 // select_cc setg[te] X, 0, X, -X -> 12621 // select_cc setgt X, -1, X, -X -> 12622 // select_cc setl[te] X, 0, -X, X -> 12623 // select_cc setlt X, 1, -X, X -> 12624 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 12625 if (N1C) { 12626 ConstantSDNode *SubC = nullptr; 12627 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 12628 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 12629 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 12630 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 12631 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 12632 (N1C->isOne() && CC == ISD::SETLT)) && 12633 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 12634 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 12635 12636 EVT XType = N0.getValueType(); 12637 if (SubC && SubC->isNullValue() && XType.isInteger()) { 12638 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 12639 N0, 12640 DAG.getConstant(XType.getSizeInBits()-1, 12641 getShiftAmountTy(N0.getValueType()))); 12642 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 12643 XType, N0, Shift); 12644 AddToWorklist(Shift.getNode()); 12645 AddToWorklist(Add.getNode()); 12646 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 12647 } 12648 } 12649 12650 return SDValue(); 12651 } 12652 12653 /// This is a stub for TargetLowering::SimplifySetCC. 12654 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 12655 SDValue N1, ISD::CondCode Cond, 12656 SDLoc DL, bool foldBooleans) { 12657 TargetLowering::DAGCombinerInfo 12658 DagCombineInfo(DAG, Level, false, this); 12659 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 12660 } 12661 12662 /// Given an ISD::SDIV node expressing a divide by constant, return 12663 /// a DAG expression to select that will generate the same value by multiplying 12664 /// by a magic number. 12665 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 12666 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 12667 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12668 if (!C) 12669 return SDValue(); 12670 12671 // Avoid division by zero. 12672 if (!C->getAPIntValue()) 12673 return SDValue(); 12674 12675 std::vector<SDNode*> Built; 12676 SDValue S = 12677 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 12678 12679 for (SDNode *N : Built) 12680 AddToWorklist(N); 12681 return S; 12682 } 12683 12684 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 12685 /// DAG expression that will generate the same value by right shifting. 12686 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 12687 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12688 if (!C) 12689 return SDValue(); 12690 12691 // Avoid division by zero. 12692 if (!C->getAPIntValue()) 12693 return SDValue(); 12694 12695 std::vector<SDNode *> Built; 12696 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 12697 12698 for (SDNode *N : Built) 12699 AddToWorklist(N); 12700 return S; 12701 } 12702 12703 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 12704 /// expression that will generate the same value by multiplying by a magic 12705 /// number. 12706 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 12707 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 12708 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12709 if (!C) 12710 return SDValue(); 12711 12712 // Avoid division by zero. 12713 if (!C->getAPIntValue()) 12714 return SDValue(); 12715 12716 std::vector<SDNode*> Built; 12717 SDValue S = 12718 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 12719 12720 for (SDNode *N : Built) 12721 AddToWorklist(N); 12722 return S; 12723 } 12724 12725 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) { 12726 if (Level >= AfterLegalizeDAG) 12727 return SDValue(); 12728 12729 // Expose the DAG combiner to the target combiner implementations. 12730 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 12731 12732 unsigned Iterations = 0; 12733 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 12734 if (Iterations) { 12735 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12736 // For the reciprocal, we need to find the zero of the function: 12737 // F(X) = A X - 1 [which has a zero at X = 1/A] 12738 // => 12739 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 12740 // does not require additional intermediate precision] 12741 EVT VT = Op.getValueType(); 12742 SDLoc DL(Op); 12743 SDValue FPOne = DAG.getConstantFP(1.0, VT); 12744 12745 AddToWorklist(Est.getNode()); 12746 12747 // Newton iterations: Est = Est + Est (1 - Arg * Est) 12748 for (unsigned i = 0; i < Iterations; ++i) { 12749 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est); 12750 AddToWorklist(NewEst.getNode()); 12751 12752 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst); 12753 AddToWorklist(NewEst.getNode()); 12754 12755 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 12756 AddToWorklist(NewEst.getNode()); 12757 12758 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst); 12759 AddToWorklist(Est.getNode()); 12760 } 12761 } 12762 return Est; 12763 } 12764 12765 return SDValue(); 12766 } 12767 12768 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12769 /// For the reciprocal sqrt, we need to find the zero of the function: 12770 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 12771 /// => 12772 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 12773 /// As a result, we precompute A/2 prior to the iteration loop. 12774 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 12775 unsigned Iterations) { 12776 EVT VT = Arg.getValueType(); 12777 SDLoc DL(Arg); 12778 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT); 12779 12780 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 12781 // this entire sequence requires only one FP constant. 12782 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg); 12783 AddToWorklist(HalfArg.getNode()); 12784 12785 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg); 12786 AddToWorklist(HalfArg.getNode()); 12787 12788 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 12789 for (unsigned i = 0; i < Iterations; ++i) { 12790 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 12791 AddToWorklist(NewEst.getNode()); 12792 12793 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst); 12794 AddToWorklist(NewEst.getNode()); 12795 12796 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst); 12797 AddToWorklist(NewEst.getNode()); 12798 12799 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 12800 AddToWorklist(Est.getNode()); 12801 } 12802 return Est; 12803 } 12804 12805 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12806 /// For the reciprocal sqrt, we need to find the zero of the function: 12807 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 12808 /// => 12809 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 12810 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 12811 unsigned Iterations) { 12812 EVT VT = Arg.getValueType(); 12813 SDLoc DL(Arg); 12814 SDValue MinusThree = DAG.getConstantFP(-3.0, VT); 12815 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT); 12816 12817 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 12818 for (unsigned i = 0; i < Iterations; ++i) { 12819 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf); 12820 AddToWorklist(HalfEst.getNode()); 12821 12822 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 12823 AddToWorklist(Est.getNode()); 12824 12825 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg); 12826 AddToWorklist(Est.getNode()); 12827 12828 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree); 12829 AddToWorklist(Est.getNode()); 12830 12831 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst); 12832 AddToWorklist(Est.getNode()); 12833 } 12834 return Est; 12835 } 12836 12837 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) { 12838 if (Level >= AfterLegalizeDAG) 12839 return SDValue(); 12840 12841 // Expose the DAG combiner to the target combiner implementations. 12842 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 12843 unsigned Iterations = 0; 12844 bool UseOneConstNR = false; 12845 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 12846 AddToWorklist(Est.getNode()); 12847 if (Iterations) { 12848 Est = UseOneConstNR ? 12849 BuildRsqrtNROneConst(Op, Est, Iterations) : 12850 BuildRsqrtNRTwoConst(Op, Est, Iterations); 12851 } 12852 return Est; 12853 } 12854 12855 return SDValue(); 12856 } 12857 12858 /// Return true if base is a frame index, which is known not to alias with 12859 /// anything but itself. Provides base object and offset as results. 12860 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 12861 const GlobalValue *&GV, const void *&CV) { 12862 // Assume it is a primitive operation. 12863 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 12864 12865 // If it's an adding a simple constant then integrate the offset. 12866 if (Base.getOpcode() == ISD::ADD) { 12867 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 12868 Base = Base.getOperand(0); 12869 Offset += C->getZExtValue(); 12870 } 12871 } 12872 12873 // Return the underlying GlobalValue, and update the Offset. Return false 12874 // for GlobalAddressSDNode since the same GlobalAddress may be represented 12875 // by multiple nodes with different offsets. 12876 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 12877 GV = G->getGlobal(); 12878 Offset += G->getOffset(); 12879 return false; 12880 } 12881 12882 // Return the underlying Constant value, and update the Offset. Return false 12883 // for ConstantSDNodes since the same constant pool entry may be represented 12884 // by multiple nodes with different offsets. 12885 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 12886 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 12887 : (const void *)C->getConstVal(); 12888 Offset += C->getOffset(); 12889 return false; 12890 } 12891 // If it's any of the following then it can't alias with anything but itself. 12892 return isa<FrameIndexSDNode>(Base); 12893 } 12894 12895 /// Return true if there is any possibility that the two addresses overlap. 12896 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 12897 // If they are the same then they must be aliases. 12898 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 12899 12900 // If they are both volatile then they cannot be reordered. 12901 if (Op0->isVolatile() && Op1->isVolatile()) return true; 12902 12903 // Gather base node and offset information. 12904 SDValue Base1, Base2; 12905 int64_t Offset1, Offset2; 12906 const GlobalValue *GV1, *GV2; 12907 const void *CV1, *CV2; 12908 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 12909 Base1, Offset1, GV1, CV1); 12910 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 12911 Base2, Offset2, GV2, CV2); 12912 12913 // If they have a same base address then check to see if they overlap. 12914 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 12915 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 12916 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 12917 12918 // It is possible for different frame indices to alias each other, mostly 12919 // when tail call optimization reuses return address slots for arguments. 12920 // To catch this case, look up the actual index of frame indices to compute 12921 // the real alias relationship. 12922 if (isFrameIndex1 && isFrameIndex2) { 12923 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 12924 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 12925 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 12926 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 12927 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 12928 } 12929 12930 // Otherwise, if we know what the bases are, and they aren't identical, then 12931 // we know they cannot alias. 12932 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 12933 return false; 12934 12935 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 12936 // compared to the size and offset of the access, we may be able to prove they 12937 // do not alias. This check is conservative for now to catch cases created by 12938 // splitting vector types. 12939 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 12940 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 12941 (Op0->getMemoryVT().getSizeInBits() >> 3 == 12942 Op1->getMemoryVT().getSizeInBits() >> 3) && 12943 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 12944 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 12945 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 12946 12947 // There is no overlap between these relatively aligned accesses of similar 12948 // size, return no alias. 12949 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 12950 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 12951 return false; 12952 } 12953 12954 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 12955 ? CombinerGlobalAA 12956 : DAG.getSubtarget().useAA(); 12957 #ifndef NDEBUG 12958 if (CombinerAAOnlyFunc.getNumOccurrences() && 12959 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12960 UseAA = false; 12961 #endif 12962 if (UseAA && 12963 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 12964 // Use alias analysis information. 12965 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 12966 Op1->getSrcValueOffset()); 12967 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 12968 Op0->getSrcValueOffset() - MinOffset; 12969 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 12970 Op1->getSrcValueOffset() - MinOffset; 12971 AliasAnalysis::AliasResult AAResult = 12972 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 12973 Overlap1, 12974 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 12975 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 12976 Overlap2, 12977 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 12978 if (AAResult == AliasAnalysis::NoAlias) 12979 return false; 12980 } 12981 12982 // Otherwise we have to assume they alias. 12983 return true; 12984 } 12985 12986 /// Walk up chain skipping non-aliasing memory nodes, 12987 /// looking for aliasing nodes and adding them to the Aliases vector. 12988 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 12989 SmallVectorImpl<SDValue> &Aliases) { 12990 SmallVector<SDValue, 8> Chains; // List of chains to visit. 12991 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 12992 12993 // Get alias information for node. 12994 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 12995 12996 // Starting off. 12997 Chains.push_back(OriginalChain); 12998 unsigned Depth = 0; 12999 13000 // Look at each chain and determine if it is an alias. If so, add it to the 13001 // aliases list. If not, then continue up the chain looking for the next 13002 // candidate. 13003 while (!Chains.empty()) { 13004 SDValue Chain = Chains.back(); 13005 Chains.pop_back(); 13006 13007 // For TokenFactor nodes, look at each operand and only continue up the 13008 // chain until we find two aliases. If we've seen two aliases, assume we'll 13009 // find more and revert to original chain since the xform is unlikely to be 13010 // profitable. 13011 // 13012 // FIXME: The depth check could be made to return the last non-aliasing 13013 // chain we found before we hit a tokenfactor rather than the original 13014 // chain. 13015 if (Depth > 6 || Aliases.size() == 2) { 13016 Aliases.clear(); 13017 Aliases.push_back(OriginalChain); 13018 return; 13019 } 13020 13021 // Don't bother if we've been before. 13022 if (!Visited.insert(Chain.getNode()).second) 13023 continue; 13024 13025 switch (Chain.getOpcode()) { 13026 case ISD::EntryToken: 13027 // Entry token is ideal chain operand, but handled in FindBetterChain. 13028 break; 13029 13030 case ISD::LOAD: 13031 case ISD::STORE: { 13032 // Get alias information for Chain. 13033 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 13034 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 13035 13036 // If chain is alias then stop here. 13037 if (!(IsLoad && IsOpLoad) && 13038 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 13039 Aliases.push_back(Chain); 13040 } else { 13041 // Look further up the chain. 13042 Chains.push_back(Chain.getOperand(0)); 13043 ++Depth; 13044 } 13045 break; 13046 } 13047 13048 case ISD::TokenFactor: 13049 // We have to check each of the operands of the token factor for "small" 13050 // token factors, so we queue them up. Adding the operands to the queue 13051 // (stack) in reverse order maintains the original order and increases the 13052 // likelihood that getNode will find a matching token factor (CSE.) 13053 if (Chain.getNumOperands() > 16) { 13054 Aliases.push_back(Chain); 13055 break; 13056 } 13057 for (unsigned n = Chain.getNumOperands(); n;) 13058 Chains.push_back(Chain.getOperand(--n)); 13059 ++Depth; 13060 break; 13061 13062 default: 13063 // For all other instructions we will just have to take what we can get. 13064 Aliases.push_back(Chain); 13065 break; 13066 } 13067 } 13068 13069 // We need to be careful here to also search for aliases through the 13070 // value operand of a store, etc. Consider the following situation: 13071 // Token1 = ... 13072 // L1 = load Token1, %52 13073 // S1 = store Token1, L1, %51 13074 // L2 = load Token1, %52+8 13075 // S2 = store Token1, L2, %51+8 13076 // Token2 = Token(S1, S2) 13077 // L3 = load Token2, %53 13078 // S3 = store Token2, L3, %52 13079 // L4 = load Token2, %53+8 13080 // S4 = store Token2, L4, %52+8 13081 // If we search for aliases of S3 (which loads address %52), and we look 13082 // only through the chain, then we'll miss the trivial dependence on L1 13083 // (which also loads from %52). We then might change all loads and 13084 // stores to use Token1 as their chain operand, which could result in 13085 // copying %53 into %52 before copying %52 into %51 (which should 13086 // happen first). 13087 // 13088 // The problem is, however, that searching for such data dependencies 13089 // can become expensive, and the cost is not directly related to the 13090 // chain depth. Instead, we'll rule out such configurations here by 13091 // insisting that we've visited all chain users (except for users 13092 // of the original chain, which is not necessary). When doing this, 13093 // we need to look through nodes we don't care about (otherwise, things 13094 // like register copies will interfere with trivial cases). 13095 13096 SmallVector<const SDNode *, 16> Worklist; 13097 for (const SDNode *N : Visited) 13098 if (N != OriginalChain.getNode()) 13099 Worklist.push_back(N); 13100 13101 while (!Worklist.empty()) { 13102 const SDNode *M = Worklist.pop_back_val(); 13103 13104 // We have already visited M, and want to make sure we've visited any uses 13105 // of M that we care about. For uses that we've not visisted, and don't 13106 // care about, queue them to the worklist. 13107 13108 for (SDNode::use_iterator UI = M->use_begin(), 13109 UIE = M->use_end(); UI != UIE; ++UI) 13110 if (UI.getUse().getValueType() == MVT::Other && 13111 Visited.insert(*UI).second) { 13112 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 13113 // We've not visited this use, and we care about it (it could have an 13114 // ordering dependency with the original node). 13115 Aliases.clear(); 13116 Aliases.push_back(OriginalChain); 13117 return; 13118 } 13119 13120 // We've not visited this use, but we don't care about it. Mark it as 13121 // visited and enqueue it to the worklist. 13122 Worklist.push_back(*UI); 13123 } 13124 } 13125 } 13126 13127 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 13128 /// (aliasing node.) 13129 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 13130 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 13131 13132 // Accumulate all the aliases to this node. 13133 GatherAllAliases(N, OldChain, Aliases); 13134 13135 // If no operands then chain to entry token. 13136 if (Aliases.size() == 0) 13137 return DAG.getEntryNode(); 13138 13139 // If a single operand then chain to it. We don't need to revisit it. 13140 if (Aliases.size() == 1) 13141 return Aliases[0]; 13142 13143 // Construct a custom tailored token factor. 13144 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 13145 } 13146 13147 /// This is the entry point for the file. 13148 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 13149 CodeGenOpt::Level OptLevel) { 13150 /// This is the main entry point to this class. 13151 DAGCombiner(*this, AA, OptLevel).Run(Level); 13152 } 13153