DAGCombiner.cpp revision 51a0280d296405cb1fdb268e5387867e0db2e46e
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#define DEBUG_TYPE "dagcombine" 20#include "llvm/CodeGen/SelectionDAG.h" 21#include "llvm/ADT/SmallPtrSet.h" 22#include "llvm/ADT/Statistic.h" 23#include "llvm/Analysis/AliasAnalysis.h" 24#include "llvm/CodeGen/MachineFrameInfo.h" 25#include "llvm/CodeGen/MachineFunction.h" 26#include "llvm/IR/DataLayout.h" 27#include "llvm/IR/DerivedTypes.h" 28#include "llvm/IR/Function.h" 29#include "llvm/IR/LLVMContext.h" 30#include "llvm/Support/CommandLine.h" 31#include "llvm/Support/Debug.h" 32#include "llvm/Support/ErrorHandling.h" 33#include "llvm/Support/MathExtras.h" 34#include "llvm/Support/raw_ostream.h" 35#include "llvm/Target/TargetLowering.h" 36#include "llvm/Target/TargetMachine.h" 37#include "llvm/Target/TargetOptions.h" 38#include <algorithm> 39using namespace llvm; 40 41STATISTIC(NodesCombined , "Number of dag nodes combined"); 42STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 43STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 44STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 45STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 46 47namespace { 48 static cl::opt<bool> 49 CombinerAA("combiner-alias-analysis", cl::Hidden, 50 cl::desc("Turn on alias analysis during testing")); 51 52 static cl::opt<bool> 53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 54 cl::desc("Include global information in alias analysis")); 55 56//------------------------------ DAGCombiner ---------------------------------// 57 58 class DAGCombiner { 59 SelectionDAG &DAG; 60 const TargetLowering &TLI; 61 CombineLevel Level; 62 CodeGenOpt::Level OptLevel; 63 bool LegalOperations; 64 bool LegalTypes; 65 66 // Worklist of all of the nodes that need to be simplified. 67 // 68 // This has the semantics that when adding to the worklist, 69 // the item added must be next to be processed. It should 70 // also only appear once. The naive approach to this takes 71 // linear time. 72 // 73 // To reduce the insert/remove time to logarithmic, we use 74 // a set and a vector to maintain our worklist. 75 // 76 // The set contains the items on the worklist, but does not 77 // maintain the order they should be visited. 78 // 79 // The vector maintains the order nodes should be visited, but may 80 // contain duplicate or removed nodes. When choosing a node to 81 // visit, we pop off the order stack until we find an item that is 82 // also in the contents set. All operations are O(log N). 83 SmallPtrSet<SDNode*, 64> WorkListContents; 84 SmallVector<SDNode*, 64> WorkListOrder; 85 86 // AA - Used for DAG load/store alias analysis. 87 AliasAnalysis &AA; 88 89 /// AddUsersToWorkList - When an instruction is simplified, add all users of 90 /// the instruction to the work lists because they might get more simplified 91 /// now. 92 /// 93 void AddUsersToWorkList(SDNode *N) { 94 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 95 UI != UE; ++UI) 96 AddToWorkList(*UI); 97 } 98 99 /// visit - call the node-specific routine that knows how to fold each 100 /// particular type of node. 101 SDValue visit(SDNode *N); 102 103 public: 104 /// AddToWorkList - Add to the work list making sure its instance is at the 105 /// back (next to be processed.) 106 void AddToWorkList(SDNode *N) { 107 WorkListContents.insert(N); 108 WorkListOrder.push_back(N); 109 } 110 111 /// removeFromWorkList - remove all instances of N from the worklist. 112 /// 113 void removeFromWorkList(SDNode *N) { 114 WorkListContents.erase(N); 115 } 116 117 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 118 bool AddTo = true); 119 120 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 121 return CombineTo(N, &Res, 1, AddTo); 122 } 123 124 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 125 bool AddTo = true) { 126 SDValue To[] = { Res0, Res1 }; 127 return CombineTo(N, To, 2, AddTo); 128 } 129 130 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 131 132 private: 133 134 /// SimplifyDemandedBits - Check the specified integer node value to see if 135 /// it can be simplified or if things it uses can be simplified by bit 136 /// propagation. If so, return true. 137 bool SimplifyDemandedBits(SDValue Op) { 138 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 139 APInt Demanded = APInt::getAllOnesValue(BitWidth); 140 return SimplifyDemandedBits(Op, Demanded); 141 } 142 143 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 144 145 bool CombineToPreIndexedLoadStore(SDNode *N); 146 bool CombineToPostIndexedLoadStore(SDNode *N); 147 148 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 149 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 150 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 151 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 152 SDValue PromoteIntBinOp(SDValue Op); 153 SDValue PromoteIntShiftOp(SDValue Op); 154 SDValue PromoteExtend(SDValue Op); 155 bool PromoteLoad(SDValue Op); 156 157 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 158 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 159 ISD::NodeType ExtType); 160 161 /// combine - call the node-specific routine that knows how to fold each 162 /// particular type of node. If that doesn't do anything, try the 163 /// target-specific DAG combines. 164 SDValue combine(SDNode *N); 165 166 // Visitation implementation - Implement dag node combining for different 167 // node types. The semantics are as follows: 168 // Return Value: 169 // SDValue.getNode() == 0 - No change was made 170 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 171 // otherwise - N should be replaced by the returned Operand. 172 // 173 SDValue visitTokenFactor(SDNode *N); 174 SDValue visitMERGE_VALUES(SDNode *N); 175 SDValue visitADD(SDNode *N); 176 SDValue visitSUB(SDNode *N); 177 SDValue visitADDC(SDNode *N); 178 SDValue visitSUBC(SDNode *N); 179 SDValue visitADDE(SDNode *N); 180 SDValue visitSUBE(SDNode *N); 181 SDValue visitMUL(SDNode *N); 182 SDValue visitSDIV(SDNode *N); 183 SDValue visitUDIV(SDNode *N); 184 SDValue visitSREM(SDNode *N); 185 SDValue visitUREM(SDNode *N); 186 SDValue visitMULHU(SDNode *N); 187 SDValue visitMULHS(SDNode *N); 188 SDValue visitSMUL_LOHI(SDNode *N); 189 SDValue visitUMUL_LOHI(SDNode *N); 190 SDValue visitSMULO(SDNode *N); 191 SDValue visitUMULO(SDNode *N); 192 SDValue visitSDIVREM(SDNode *N); 193 SDValue visitUDIVREM(SDNode *N); 194 SDValue visitAND(SDNode *N); 195 SDValue visitOR(SDNode *N); 196 SDValue visitXOR(SDNode *N); 197 SDValue SimplifyVBinOp(SDNode *N); 198 SDValue SimplifyVUnaryOp(SDNode *N); 199 SDValue visitSHL(SDNode *N); 200 SDValue visitSRA(SDNode *N); 201 SDValue visitSRL(SDNode *N); 202 SDValue visitCTLZ(SDNode *N); 203 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 204 SDValue visitCTTZ(SDNode *N); 205 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 206 SDValue visitCTPOP(SDNode *N); 207 SDValue visitSELECT(SDNode *N); 208 SDValue visitVSELECT(SDNode *N); 209 SDValue visitSELECT_CC(SDNode *N); 210 SDValue visitSETCC(SDNode *N); 211 SDValue visitSIGN_EXTEND(SDNode *N); 212 SDValue visitZERO_EXTEND(SDNode *N); 213 SDValue visitANY_EXTEND(SDNode *N); 214 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 215 SDValue visitTRUNCATE(SDNode *N); 216 SDValue visitBITCAST(SDNode *N); 217 SDValue visitBUILD_PAIR(SDNode *N); 218 SDValue visitFADD(SDNode *N); 219 SDValue visitFSUB(SDNode *N); 220 SDValue visitFMUL(SDNode *N); 221 SDValue visitFMA(SDNode *N); 222 SDValue visitFDIV(SDNode *N); 223 SDValue visitFREM(SDNode *N); 224 SDValue visitFCOPYSIGN(SDNode *N); 225 SDValue visitSINT_TO_FP(SDNode *N); 226 SDValue visitUINT_TO_FP(SDNode *N); 227 SDValue visitFP_TO_SINT(SDNode *N); 228 SDValue visitFP_TO_UINT(SDNode *N); 229 SDValue visitFP_ROUND(SDNode *N); 230 SDValue visitFP_ROUND_INREG(SDNode *N); 231 SDValue visitFP_EXTEND(SDNode *N); 232 SDValue visitFNEG(SDNode *N); 233 SDValue visitFABS(SDNode *N); 234 SDValue visitFCEIL(SDNode *N); 235 SDValue visitFTRUNC(SDNode *N); 236 SDValue visitFFLOOR(SDNode *N); 237 SDValue visitBRCOND(SDNode *N); 238 SDValue visitBR_CC(SDNode *N); 239 SDValue visitLOAD(SDNode *N); 240 SDValue visitSTORE(SDNode *N); 241 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 242 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 243 SDValue visitBUILD_VECTOR(SDNode *N); 244 SDValue visitCONCAT_VECTORS(SDNode *N); 245 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 246 SDValue visitVECTOR_SHUFFLE(SDNode *N); 247 248 SDValue XformToShuffleWithZero(SDNode *N); 249 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 250 251 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 252 253 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 254 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 255 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 256 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 257 SDValue N3, ISD::CondCode CC, 258 bool NotExtCompare = false); 259 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 260 SDLoc DL, bool foldBooleans = true); 261 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 262 unsigned HiOp); 263 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 264 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 265 SDValue BuildSDIV(SDNode *N); 266 SDValue BuildUDIV(SDNode *N); 267 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 268 bool DemandHighBits = true); 269 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 270 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 271 SDValue ReduceLoadWidth(SDNode *N); 272 SDValue ReduceLoadOpStoreWidth(SDNode *N); 273 SDValue TransformFPLoadStorePair(SDNode *N); 274 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 275 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 276 277 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 278 279 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 280 /// looking for aliasing nodes and adding them to the Aliases vector. 281 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 282 SmallVectorImpl<SDValue> &Aliases); 283 284 /// isAlias - Return true if there is any possibility that the two addresses 285 /// overlap. 286 bool isAlias(SDValue Ptr1, int64_t Size1, 287 const Value *SrcValue1, int SrcValueOffset1, 288 unsigned SrcValueAlign1, 289 const MDNode *TBAAInfo1, 290 SDValue Ptr2, int64_t Size2, 291 const Value *SrcValue2, int SrcValueOffset2, 292 unsigned SrcValueAlign2, 293 const MDNode *TBAAInfo2) const; 294 295 /// isAlias - Return true if there is any possibility that the two addresses 296 /// overlap. 297 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1); 298 299 /// FindAliasInfo - Extracts the relevant alias information from the memory 300 /// node. Returns true if the operand was a load. 301 bool FindAliasInfo(SDNode *N, 302 SDValue &Ptr, int64_t &Size, 303 const Value *&SrcValue, int &SrcValueOffset, 304 unsigned &SrcValueAlignment, 305 const MDNode *&TBAAInfo) const; 306 307 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 308 /// looking for a better chain (aliasing node.) 309 SDValue FindBetterChain(SDNode *N, SDValue Chain); 310 311 /// Merge consecutive store operations into a wide store. 312 /// This optimization uses wide integers or vectors when possible. 313 /// \return True if some memory operations were changed. 314 bool MergeConsecutiveStores(StoreSDNode *N); 315 316 public: 317 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 318 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 319 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {} 320 321 /// Run - runs the dag combiner on all nodes in the work list 322 void Run(CombineLevel AtLevel); 323 324 SelectionDAG &getDAG() const { return DAG; } 325 326 /// getShiftAmountTy - Returns a type large enough to hold any valid 327 /// shift amount - before type legalization these can be huge. 328 EVT getShiftAmountTy(EVT LHSTy) { 329 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 330 if (LHSTy.isVector()) 331 return LHSTy; 332 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy(); 333 } 334 335 /// isTypeLegal - This method returns true if we are running before type 336 /// legalization or if the specified VT is legal. 337 bool isTypeLegal(const EVT &VT) { 338 if (!LegalTypes) return true; 339 return TLI.isTypeLegal(VT); 340 } 341 342 /// getSetCCResultType - Convenience wrapper around 343 /// TargetLowering::getSetCCResultType 344 EVT getSetCCResultType(EVT VT) const { 345 return TLI.getSetCCResultType(*DAG.getContext(), VT); 346 } 347 }; 348} 349 350 351namespace { 352/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 353/// nodes from the worklist. 354class WorkListRemover : public SelectionDAG::DAGUpdateListener { 355 DAGCombiner &DC; 356public: 357 explicit WorkListRemover(DAGCombiner &dc) 358 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 359 360 virtual void NodeDeleted(SDNode *N, SDNode *E) { 361 DC.removeFromWorkList(N); 362 } 363}; 364} 365 366//===----------------------------------------------------------------------===// 367// TargetLowering::DAGCombinerInfo implementation 368//===----------------------------------------------------------------------===// 369 370void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 371 ((DAGCombiner*)DC)->AddToWorkList(N); 372} 373 374void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 375 ((DAGCombiner*)DC)->removeFromWorkList(N); 376} 377 378SDValue TargetLowering::DAGCombinerInfo:: 379CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 380 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 381} 382 383SDValue TargetLowering::DAGCombinerInfo:: 384CombineTo(SDNode *N, SDValue Res, bool AddTo) { 385 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 386} 387 388 389SDValue TargetLowering::DAGCombinerInfo:: 390CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 391 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 392} 393 394void TargetLowering::DAGCombinerInfo:: 395CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 396 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 397} 398 399//===----------------------------------------------------------------------===// 400// Helper Functions 401//===----------------------------------------------------------------------===// 402 403/// isNegatibleForFree - Return 1 if we can compute the negated form of the 404/// specified expression for the same cost as the expression itself, or 2 if we 405/// can compute the negated form more cheaply than the expression itself. 406static char isNegatibleForFree(SDValue Op, bool LegalOperations, 407 const TargetLowering &TLI, 408 const TargetOptions *Options, 409 unsigned Depth = 0) { 410 // fneg is removable even if it has multiple uses. 411 if (Op.getOpcode() == ISD::FNEG) return 2; 412 413 // Don't allow anything with multiple uses. 414 if (!Op.hasOneUse()) return 0; 415 416 // Don't recurse exponentially. 417 if (Depth > 6) return 0; 418 419 switch (Op.getOpcode()) { 420 default: return false; 421 case ISD::ConstantFP: 422 // Don't invert constant FP values after legalize. The negated constant 423 // isn't necessarily legal. 424 return LegalOperations ? 0 : 1; 425 case ISD::FADD: 426 // FIXME: determine better conditions for this xform. 427 if (!Options->UnsafeFPMath) return 0; 428 429 // After operation legalization, it might not be legal to create new FSUBs. 430 if (LegalOperations && 431 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 432 return 0; 433 434 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 435 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 436 Options, Depth + 1)) 437 return V; 438 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 439 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 440 Depth + 1); 441 case ISD::FSUB: 442 // We can't turn -(A-B) into B-A when we honor signed zeros. 443 if (!Options->UnsafeFPMath) return 0; 444 445 // fold (fneg (fsub A, B)) -> (fsub B, A) 446 return 1; 447 448 case ISD::FMUL: 449 case ISD::FDIV: 450 if (Options->HonorSignDependentRoundingFPMath()) return 0; 451 452 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 453 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 454 Options, Depth + 1)) 455 return V; 456 457 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 458 Depth + 1); 459 460 case ISD::FP_EXTEND: 461 case ISD::FP_ROUND: 462 case ISD::FSIN: 463 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 464 Depth + 1); 465 } 466} 467 468/// GetNegatedExpression - If isNegatibleForFree returns true, this function 469/// returns the newly negated expression. 470static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 471 bool LegalOperations, unsigned Depth = 0) { 472 // fneg is removable even if it has multiple uses. 473 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 474 475 // Don't allow anything with multiple uses. 476 assert(Op.hasOneUse() && "Unknown reuse!"); 477 478 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 479 switch (Op.getOpcode()) { 480 default: llvm_unreachable("Unknown code"); 481 case ISD::ConstantFP: { 482 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 483 V.changeSign(); 484 return DAG.getConstantFP(V, Op.getValueType()); 485 } 486 case ISD::FADD: 487 // FIXME: determine better conditions for this xform. 488 assert(DAG.getTarget().Options.UnsafeFPMath); 489 490 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 491 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 492 DAG.getTargetLoweringInfo(), 493 &DAG.getTarget().Options, Depth+1)) 494 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 495 GetNegatedExpression(Op.getOperand(0), DAG, 496 LegalOperations, Depth+1), 497 Op.getOperand(1)); 498 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 499 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 500 GetNegatedExpression(Op.getOperand(1), DAG, 501 LegalOperations, Depth+1), 502 Op.getOperand(0)); 503 case ISD::FSUB: 504 // We can't turn -(A-B) into B-A when we honor signed zeros. 505 assert(DAG.getTarget().Options.UnsafeFPMath); 506 507 // fold (fneg (fsub 0, B)) -> B 508 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 509 if (N0CFP->getValueAPF().isZero()) 510 return Op.getOperand(1); 511 512 // fold (fneg (fsub A, B)) -> (fsub B, A) 513 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 514 Op.getOperand(1), Op.getOperand(0)); 515 516 case ISD::FMUL: 517 case ISD::FDIV: 518 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 519 520 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 521 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 522 DAG.getTargetLoweringInfo(), 523 &DAG.getTarget().Options, Depth+1)) 524 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 525 GetNegatedExpression(Op.getOperand(0), DAG, 526 LegalOperations, Depth+1), 527 Op.getOperand(1)); 528 529 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 530 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 531 Op.getOperand(0), 532 GetNegatedExpression(Op.getOperand(1), DAG, 533 LegalOperations, Depth+1)); 534 535 case ISD::FP_EXTEND: 536 case ISD::FSIN: 537 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 538 GetNegatedExpression(Op.getOperand(0), DAG, 539 LegalOperations, Depth+1)); 540 case ISD::FP_ROUND: 541 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 542 GetNegatedExpression(Op.getOperand(0), DAG, 543 LegalOperations, Depth+1), 544 Op.getOperand(1)); 545 } 546} 547 548 549// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 550// that selects between the values 1 and 0, making it equivalent to a setcc. 551// Also, set the incoming LHS, RHS, and CC references to the appropriate 552// nodes based on the type of node we are checking. This simplifies life a 553// bit for the callers. 554static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 555 SDValue &CC) { 556 if (N.getOpcode() == ISD::SETCC) { 557 LHS = N.getOperand(0); 558 RHS = N.getOperand(1); 559 CC = N.getOperand(2); 560 return true; 561 } 562 if (N.getOpcode() == ISD::SELECT_CC && 563 N.getOperand(2).getOpcode() == ISD::Constant && 564 N.getOperand(3).getOpcode() == ISD::Constant && 565 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 566 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 567 LHS = N.getOperand(0); 568 RHS = N.getOperand(1); 569 CC = N.getOperand(4); 570 return true; 571 } 572 return false; 573} 574 575// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 576// one use. If this is true, it allows the users to invert the operation for 577// free when it is profitable to do so. 578static bool isOneUseSetCC(SDValue N) { 579 SDValue N0, N1, N2; 580 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 581 return true; 582 return false; 583} 584 585SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 586 SDValue N0, SDValue N1) { 587 EVT VT = N0.getValueType(); 588 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) { 589 if (isa<ConstantSDNode>(N1)) { 590 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 591 SDValue OpNode = 592 DAG.FoldConstantArithmetic(Opc, VT, 593 cast<ConstantSDNode>(N0.getOperand(1)), 594 cast<ConstantSDNode>(N1)); 595 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 596 } 597 if (N0.hasOneUse()) { 598 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use 599 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, 600 N0.getOperand(0), N1); 601 AddToWorkList(OpNode.getNode()); 602 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 603 } 604 } 605 606 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) { 607 if (isa<ConstantSDNode>(N0)) { 608 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 609 SDValue OpNode = 610 DAG.FoldConstantArithmetic(Opc, VT, 611 cast<ConstantSDNode>(N1.getOperand(1)), 612 cast<ConstantSDNode>(N0)); 613 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 614 } 615 if (N1.hasOneUse()) { 616 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use 617 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, 618 N1.getOperand(0), N0); 619 AddToWorkList(OpNode.getNode()); 620 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 621 } 622 } 623 624 return SDValue(); 625} 626 627SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 628 bool AddTo) { 629 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 630 ++NodesCombined; 631 DEBUG(dbgs() << "\nReplacing.1 "; 632 N->dump(&DAG); 633 dbgs() << "\nWith: "; 634 To[0].getNode()->dump(&DAG); 635 dbgs() << " and " << NumTo-1 << " other values\n"; 636 for (unsigned i = 0, e = NumTo; i != e; ++i) 637 assert((!To[i].getNode() || 638 N->getValueType(i) == To[i].getValueType()) && 639 "Cannot combine value to value of different type!")); 640 WorkListRemover DeadNodes(*this); 641 DAG.ReplaceAllUsesWith(N, To); 642 if (AddTo) { 643 // Push the new nodes and any users onto the worklist 644 for (unsigned i = 0, e = NumTo; i != e; ++i) { 645 if (To[i].getNode()) { 646 AddToWorkList(To[i].getNode()); 647 AddUsersToWorkList(To[i].getNode()); 648 } 649 } 650 } 651 652 // Finally, if the node is now dead, remove it from the graph. The node 653 // may not be dead if the replacement process recursively simplified to 654 // something else needing this node. 655 if (N->use_empty()) { 656 // Nodes can be reintroduced into the worklist. Make sure we do not 657 // process a node that has been replaced. 658 removeFromWorkList(N); 659 660 // Finally, since the node is now dead, remove it from the graph. 661 DAG.DeleteNode(N); 662 } 663 return SDValue(N, 0); 664} 665 666void DAGCombiner:: 667CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 668 // Replace all uses. If any nodes become isomorphic to other nodes and 669 // are deleted, make sure to remove them from our worklist. 670 WorkListRemover DeadNodes(*this); 671 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 672 673 // Push the new node and any (possibly new) users onto the worklist. 674 AddToWorkList(TLO.New.getNode()); 675 AddUsersToWorkList(TLO.New.getNode()); 676 677 // Finally, if the node is now dead, remove it from the graph. The node 678 // may not be dead if the replacement process recursively simplified to 679 // something else needing this node. 680 if (TLO.Old.getNode()->use_empty()) { 681 removeFromWorkList(TLO.Old.getNode()); 682 683 // If the operands of this node are only used by the node, they will now 684 // be dead. Make sure to visit them first to delete dead nodes early. 685 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 686 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 687 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 688 689 DAG.DeleteNode(TLO.Old.getNode()); 690 } 691} 692 693/// SimplifyDemandedBits - Check the specified integer node value to see if 694/// it can be simplified or if things it uses can be simplified by bit 695/// propagation. If so, return true. 696bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 697 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 698 APInt KnownZero, KnownOne; 699 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 700 return false; 701 702 // Revisit the node. 703 AddToWorkList(Op.getNode()); 704 705 // Replace the old value with the new one. 706 ++NodesCombined; 707 DEBUG(dbgs() << "\nReplacing.2 "; 708 TLO.Old.getNode()->dump(&DAG); 709 dbgs() << "\nWith: "; 710 TLO.New.getNode()->dump(&DAG); 711 dbgs() << '\n'); 712 713 CommitTargetLoweringOpt(TLO); 714 return true; 715} 716 717void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 718 SDLoc dl(Load); 719 EVT VT = Load->getValueType(0); 720 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 721 722 DEBUG(dbgs() << "\nReplacing.9 "; 723 Load->dump(&DAG); 724 dbgs() << "\nWith: "; 725 Trunc.getNode()->dump(&DAG); 726 dbgs() << '\n'); 727 WorkListRemover DeadNodes(*this); 728 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 729 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 730 removeFromWorkList(Load); 731 DAG.DeleteNode(Load); 732 AddToWorkList(Trunc.getNode()); 733} 734 735SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 736 Replace = false; 737 SDLoc dl(Op); 738 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 739 EVT MemVT = LD->getMemoryVT(); 740 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 741 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 742 : ISD::EXTLOAD) 743 : LD->getExtensionType(); 744 Replace = true; 745 return DAG.getExtLoad(ExtType, dl, PVT, 746 LD->getChain(), LD->getBasePtr(), 747 LD->getPointerInfo(), 748 MemVT, LD->isVolatile(), 749 LD->isNonTemporal(), LD->getAlignment()); 750 } 751 752 unsigned Opc = Op.getOpcode(); 753 switch (Opc) { 754 default: break; 755 case ISD::AssertSext: 756 return DAG.getNode(ISD::AssertSext, dl, PVT, 757 SExtPromoteOperand(Op.getOperand(0), PVT), 758 Op.getOperand(1)); 759 case ISD::AssertZext: 760 return DAG.getNode(ISD::AssertZext, dl, PVT, 761 ZExtPromoteOperand(Op.getOperand(0), PVT), 762 Op.getOperand(1)); 763 case ISD::Constant: { 764 unsigned ExtOpc = 765 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 766 return DAG.getNode(ExtOpc, dl, PVT, Op); 767 } 768 } 769 770 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 771 return SDValue(); 772 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 773} 774 775SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 776 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 777 return SDValue(); 778 EVT OldVT = Op.getValueType(); 779 SDLoc dl(Op); 780 bool Replace = false; 781 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 782 if (NewOp.getNode() == 0) 783 return SDValue(); 784 AddToWorkList(NewOp.getNode()); 785 786 if (Replace) 787 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 788 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 789 DAG.getValueType(OldVT)); 790} 791 792SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 793 EVT OldVT = Op.getValueType(); 794 SDLoc dl(Op); 795 bool Replace = false; 796 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 797 if (NewOp.getNode() == 0) 798 return SDValue(); 799 AddToWorkList(NewOp.getNode()); 800 801 if (Replace) 802 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 803 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 804} 805 806/// PromoteIntBinOp - Promote the specified integer binary operation if the 807/// target indicates it is beneficial. e.g. On x86, it's usually better to 808/// promote i16 operations to i32 since i16 instructions are longer. 809SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 810 if (!LegalOperations) 811 return SDValue(); 812 813 EVT VT = Op.getValueType(); 814 if (VT.isVector() || !VT.isInteger()) 815 return SDValue(); 816 817 // If operation type is 'undesirable', e.g. i16 on x86, consider 818 // promoting it. 819 unsigned Opc = Op.getOpcode(); 820 if (TLI.isTypeDesirableForOp(Opc, VT)) 821 return SDValue(); 822 823 EVT PVT = VT; 824 // Consult target whether it is a good idea to promote this operation and 825 // what's the right type to promote it to. 826 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 827 assert(PVT != VT && "Don't know what type to promote to!"); 828 829 bool Replace0 = false; 830 SDValue N0 = Op.getOperand(0); 831 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 832 if (NN0.getNode() == 0) 833 return SDValue(); 834 835 bool Replace1 = false; 836 SDValue N1 = Op.getOperand(1); 837 SDValue NN1; 838 if (N0 == N1) 839 NN1 = NN0; 840 else { 841 NN1 = PromoteOperand(N1, PVT, Replace1); 842 if (NN1.getNode() == 0) 843 return SDValue(); 844 } 845 846 AddToWorkList(NN0.getNode()); 847 if (NN1.getNode()) 848 AddToWorkList(NN1.getNode()); 849 850 if (Replace0) 851 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 852 if (Replace1) 853 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 854 855 DEBUG(dbgs() << "\nPromoting "; 856 Op.getNode()->dump(&DAG)); 857 SDLoc dl(Op); 858 return DAG.getNode(ISD::TRUNCATE, dl, VT, 859 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 860 } 861 return SDValue(); 862} 863 864/// PromoteIntShiftOp - Promote the specified integer shift operation if the 865/// target indicates it is beneficial. e.g. On x86, it's usually better to 866/// promote i16 operations to i32 since i16 instructions are longer. 867SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 868 if (!LegalOperations) 869 return SDValue(); 870 871 EVT VT = Op.getValueType(); 872 if (VT.isVector() || !VT.isInteger()) 873 return SDValue(); 874 875 // If operation type is 'undesirable', e.g. i16 on x86, consider 876 // promoting it. 877 unsigned Opc = Op.getOpcode(); 878 if (TLI.isTypeDesirableForOp(Opc, VT)) 879 return SDValue(); 880 881 EVT PVT = VT; 882 // Consult target whether it is a good idea to promote this operation and 883 // what's the right type to promote it to. 884 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 885 assert(PVT != VT && "Don't know what type to promote to!"); 886 887 bool Replace = false; 888 SDValue N0 = Op.getOperand(0); 889 if (Opc == ISD::SRA) 890 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 891 else if (Opc == ISD::SRL) 892 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 893 else 894 N0 = PromoteOperand(N0, PVT, Replace); 895 if (N0.getNode() == 0) 896 return SDValue(); 897 898 AddToWorkList(N0.getNode()); 899 if (Replace) 900 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 901 902 DEBUG(dbgs() << "\nPromoting "; 903 Op.getNode()->dump(&DAG)); 904 SDLoc dl(Op); 905 return DAG.getNode(ISD::TRUNCATE, dl, VT, 906 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 907 } 908 return SDValue(); 909} 910 911SDValue DAGCombiner::PromoteExtend(SDValue Op) { 912 if (!LegalOperations) 913 return SDValue(); 914 915 EVT VT = Op.getValueType(); 916 if (VT.isVector() || !VT.isInteger()) 917 return SDValue(); 918 919 // If operation type is 'undesirable', e.g. i16 on x86, consider 920 // promoting it. 921 unsigned Opc = Op.getOpcode(); 922 if (TLI.isTypeDesirableForOp(Opc, VT)) 923 return SDValue(); 924 925 EVT PVT = VT; 926 // Consult target whether it is a good idea to promote this operation and 927 // what's the right type to promote it to. 928 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 929 assert(PVT != VT && "Don't know what type to promote to!"); 930 // fold (aext (aext x)) -> (aext x) 931 // fold (aext (zext x)) -> (zext x) 932 // fold (aext (sext x)) -> (sext x) 933 DEBUG(dbgs() << "\nPromoting "; 934 Op.getNode()->dump(&DAG)); 935 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 936 } 937 return SDValue(); 938} 939 940bool DAGCombiner::PromoteLoad(SDValue Op) { 941 if (!LegalOperations) 942 return false; 943 944 EVT VT = Op.getValueType(); 945 if (VT.isVector() || !VT.isInteger()) 946 return false; 947 948 // If operation type is 'undesirable', e.g. i16 on x86, consider 949 // promoting it. 950 unsigned Opc = Op.getOpcode(); 951 if (TLI.isTypeDesirableForOp(Opc, VT)) 952 return false; 953 954 EVT PVT = VT; 955 // Consult target whether it is a good idea to promote this operation and 956 // what's the right type to promote it to. 957 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 958 assert(PVT != VT && "Don't know what type to promote to!"); 959 960 SDLoc dl(Op); 961 SDNode *N = Op.getNode(); 962 LoadSDNode *LD = cast<LoadSDNode>(N); 963 EVT MemVT = LD->getMemoryVT(); 964 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 965 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 966 : ISD::EXTLOAD) 967 : LD->getExtensionType(); 968 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 969 LD->getChain(), LD->getBasePtr(), 970 LD->getPointerInfo(), 971 MemVT, LD->isVolatile(), 972 LD->isNonTemporal(), LD->getAlignment()); 973 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 974 975 DEBUG(dbgs() << "\nPromoting "; 976 N->dump(&DAG); 977 dbgs() << "\nTo: "; 978 Result.getNode()->dump(&DAG); 979 dbgs() << '\n'); 980 WorkListRemover DeadNodes(*this); 981 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 983 removeFromWorkList(N); 984 DAG.DeleteNode(N); 985 AddToWorkList(Result.getNode()); 986 return true; 987 } 988 return false; 989} 990 991 992//===----------------------------------------------------------------------===// 993// Main DAG Combiner implementation 994//===----------------------------------------------------------------------===// 995 996void DAGCombiner::Run(CombineLevel AtLevel) { 997 // set the instance variables, so that the various visit routines may use it. 998 Level = AtLevel; 999 LegalOperations = Level >= AfterLegalizeVectorOps; 1000 LegalTypes = Level >= AfterLegalizeTypes; 1001 1002 // Add all the dag nodes to the worklist. 1003 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1004 E = DAG.allnodes_end(); I != E; ++I) 1005 AddToWorkList(I); 1006 1007 // Create a dummy node (which is not added to allnodes), that adds a reference 1008 // to the root node, preventing it from being deleted, and tracking any 1009 // changes of the root. 1010 HandleSDNode Dummy(DAG.getRoot()); 1011 1012 // The root of the dag may dangle to deleted nodes until the dag combiner is 1013 // done. Set it to null to avoid confusion. 1014 DAG.setRoot(SDValue()); 1015 1016 // while the worklist isn't empty, find a node and 1017 // try and combine it. 1018 while (!WorkListContents.empty()) { 1019 SDNode *N; 1020 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates. 1021 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1022 // worklist *should* contain, and check the node we want to visit is should 1023 // actually be visited. 1024 do { 1025 N = WorkListOrder.pop_back_val(); 1026 } while (!WorkListContents.erase(N)); 1027 1028 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1029 // N is deleted from the DAG, since they too may now be dead or may have a 1030 // reduced number of uses, allowing other xforms. 1031 if (N->use_empty() && N != &Dummy) { 1032 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1033 AddToWorkList(N->getOperand(i).getNode()); 1034 1035 DAG.DeleteNode(N); 1036 continue; 1037 } 1038 1039 SDValue RV = combine(N); 1040 1041 if (RV.getNode() == 0) 1042 continue; 1043 1044 ++NodesCombined; 1045 1046 // If we get back the same node we passed in, rather than a new node or 1047 // zero, we know that the node must have defined multiple values and 1048 // CombineTo was used. Since CombineTo takes care of the worklist 1049 // mechanics for us, we have no work to do in this case. 1050 if (RV.getNode() == N) 1051 continue; 1052 1053 assert(N->getOpcode() != ISD::DELETED_NODE && 1054 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1055 "Node was deleted but visit returned new node!"); 1056 1057 DEBUG(dbgs() << "\nReplacing.3 "; 1058 N->dump(&DAG); 1059 dbgs() << "\nWith: "; 1060 RV.getNode()->dump(&DAG); 1061 dbgs() << '\n'); 1062 1063 // Transfer debug value. 1064 DAG.TransferDbgValues(SDValue(N, 0), RV); 1065 WorkListRemover DeadNodes(*this); 1066 if (N->getNumValues() == RV.getNode()->getNumValues()) 1067 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1068 else { 1069 assert(N->getValueType(0) == RV.getValueType() && 1070 N->getNumValues() == 1 && "Type mismatch"); 1071 SDValue OpV = RV; 1072 DAG.ReplaceAllUsesWith(N, &OpV); 1073 } 1074 1075 // Push the new node and any users onto the worklist 1076 AddToWorkList(RV.getNode()); 1077 AddUsersToWorkList(RV.getNode()); 1078 1079 // Add any uses of the old node to the worklist in case this node is the 1080 // last one that uses them. They may become dead after this node is 1081 // deleted. 1082 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1083 AddToWorkList(N->getOperand(i).getNode()); 1084 1085 // Finally, if the node is now dead, remove it from the graph. The node 1086 // may not be dead if the replacement process recursively simplified to 1087 // something else needing this node. 1088 if (N->use_empty()) { 1089 // Nodes can be reintroduced into the worklist. Make sure we do not 1090 // process a node that has been replaced. 1091 removeFromWorkList(N); 1092 1093 // Finally, since the node is now dead, remove it from the graph. 1094 DAG.DeleteNode(N); 1095 } 1096 } 1097 1098 // If the root changed (e.g. it was a dead load, update the root). 1099 DAG.setRoot(Dummy.getValue()); 1100 DAG.RemoveDeadNodes(); 1101} 1102 1103SDValue DAGCombiner::visit(SDNode *N) { 1104 switch (N->getOpcode()) { 1105 default: break; 1106 case ISD::TokenFactor: return visitTokenFactor(N); 1107 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1108 case ISD::ADD: return visitADD(N); 1109 case ISD::SUB: return visitSUB(N); 1110 case ISD::ADDC: return visitADDC(N); 1111 case ISD::SUBC: return visitSUBC(N); 1112 case ISD::ADDE: return visitADDE(N); 1113 case ISD::SUBE: return visitSUBE(N); 1114 case ISD::MUL: return visitMUL(N); 1115 case ISD::SDIV: return visitSDIV(N); 1116 case ISD::UDIV: return visitUDIV(N); 1117 case ISD::SREM: return visitSREM(N); 1118 case ISD::UREM: return visitUREM(N); 1119 case ISD::MULHU: return visitMULHU(N); 1120 case ISD::MULHS: return visitMULHS(N); 1121 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1122 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1123 case ISD::SMULO: return visitSMULO(N); 1124 case ISD::UMULO: return visitUMULO(N); 1125 case ISD::SDIVREM: return visitSDIVREM(N); 1126 case ISD::UDIVREM: return visitUDIVREM(N); 1127 case ISD::AND: return visitAND(N); 1128 case ISD::OR: return visitOR(N); 1129 case ISD::XOR: return visitXOR(N); 1130 case ISD::SHL: return visitSHL(N); 1131 case ISD::SRA: return visitSRA(N); 1132 case ISD::SRL: return visitSRL(N); 1133 case ISD::CTLZ: return visitCTLZ(N); 1134 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1135 case ISD::CTTZ: return visitCTTZ(N); 1136 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1137 case ISD::CTPOP: return visitCTPOP(N); 1138 case ISD::SELECT: return visitSELECT(N); 1139 case ISD::VSELECT: return visitVSELECT(N); 1140 case ISD::SELECT_CC: return visitSELECT_CC(N); 1141 case ISD::SETCC: return visitSETCC(N); 1142 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1143 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1144 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1145 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1146 case ISD::TRUNCATE: return visitTRUNCATE(N); 1147 case ISD::BITCAST: return visitBITCAST(N); 1148 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1149 case ISD::FADD: return visitFADD(N); 1150 case ISD::FSUB: return visitFSUB(N); 1151 case ISD::FMUL: return visitFMUL(N); 1152 case ISD::FMA: return visitFMA(N); 1153 case ISD::FDIV: return visitFDIV(N); 1154 case ISD::FREM: return visitFREM(N); 1155 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1156 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1157 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1158 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1159 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1160 case ISD::FP_ROUND: return visitFP_ROUND(N); 1161 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1162 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1163 case ISD::FNEG: return visitFNEG(N); 1164 case ISD::FABS: return visitFABS(N); 1165 case ISD::FFLOOR: return visitFFLOOR(N); 1166 case ISD::FCEIL: return visitFCEIL(N); 1167 case ISD::FTRUNC: return visitFTRUNC(N); 1168 case ISD::BRCOND: return visitBRCOND(N); 1169 case ISD::BR_CC: return visitBR_CC(N); 1170 case ISD::LOAD: return visitLOAD(N); 1171 case ISD::STORE: return visitSTORE(N); 1172 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1173 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1174 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1175 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1176 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1177 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1178 } 1179 return SDValue(); 1180} 1181 1182SDValue DAGCombiner::combine(SDNode *N) { 1183 SDValue RV = visit(N); 1184 1185 // If nothing happened, try a target-specific DAG combine. 1186 if (RV.getNode() == 0) { 1187 assert(N->getOpcode() != ISD::DELETED_NODE && 1188 "Node was deleted but visit returned NULL!"); 1189 1190 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1191 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1192 1193 // Expose the DAG combiner to the target combiner impls. 1194 TargetLowering::DAGCombinerInfo 1195 DagCombineInfo(DAG, Level, false, this); 1196 1197 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1198 } 1199 } 1200 1201 // If nothing happened still, try promoting the operation. 1202 if (RV.getNode() == 0) { 1203 switch (N->getOpcode()) { 1204 default: break; 1205 case ISD::ADD: 1206 case ISD::SUB: 1207 case ISD::MUL: 1208 case ISD::AND: 1209 case ISD::OR: 1210 case ISD::XOR: 1211 RV = PromoteIntBinOp(SDValue(N, 0)); 1212 break; 1213 case ISD::SHL: 1214 case ISD::SRA: 1215 case ISD::SRL: 1216 RV = PromoteIntShiftOp(SDValue(N, 0)); 1217 break; 1218 case ISD::SIGN_EXTEND: 1219 case ISD::ZERO_EXTEND: 1220 case ISD::ANY_EXTEND: 1221 RV = PromoteExtend(SDValue(N, 0)); 1222 break; 1223 case ISD::LOAD: 1224 if (PromoteLoad(SDValue(N, 0))) 1225 RV = SDValue(N, 0); 1226 break; 1227 } 1228 } 1229 1230 // If N is a commutative binary node, try commuting it to enable more 1231 // sdisel CSE. 1232 if (RV.getNode() == 0 && 1233 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1234 N->getNumValues() == 1) { 1235 SDValue N0 = N->getOperand(0); 1236 SDValue N1 = N->getOperand(1); 1237 1238 // Constant operands are canonicalized to RHS. 1239 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1240 SDValue Ops[] = { N1, N0 }; 1241 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1242 Ops, 2); 1243 if (CSENode) 1244 return SDValue(CSENode, 0); 1245 } 1246 } 1247 1248 return RV; 1249} 1250 1251/// getInputChainForNode - Given a node, return its input chain if it has one, 1252/// otherwise return a null sd operand. 1253static SDValue getInputChainForNode(SDNode *N) { 1254 if (unsigned NumOps = N->getNumOperands()) { 1255 if (N->getOperand(0).getValueType() == MVT::Other) 1256 return N->getOperand(0); 1257 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1258 return N->getOperand(NumOps-1); 1259 for (unsigned i = 1; i < NumOps-1; ++i) 1260 if (N->getOperand(i).getValueType() == MVT::Other) 1261 return N->getOperand(i); 1262 } 1263 return SDValue(); 1264} 1265 1266SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1267 // If N has two operands, where one has an input chain equal to the other, 1268 // the 'other' chain is redundant. 1269 if (N->getNumOperands() == 2) { 1270 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1271 return N->getOperand(0); 1272 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1273 return N->getOperand(1); 1274 } 1275 1276 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1277 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1278 SmallPtrSet<SDNode*, 16> SeenOps; 1279 bool Changed = false; // If we should replace this token factor. 1280 1281 // Start out with this token factor. 1282 TFs.push_back(N); 1283 1284 // Iterate through token factors. The TFs grows when new token factors are 1285 // encountered. 1286 for (unsigned i = 0; i < TFs.size(); ++i) { 1287 SDNode *TF = TFs[i]; 1288 1289 // Check each of the operands. 1290 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1291 SDValue Op = TF->getOperand(i); 1292 1293 switch (Op.getOpcode()) { 1294 case ISD::EntryToken: 1295 // Entry tokens don't need to be added to the list. They are 1296 // rededundant. 1297 Changed = true; 1298 break; 1299 1300 case ISD::TokenFactor: 1301 if (Op.hasOneUse() && 1302 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1303 // Queue up for processing. 1304 TFs.push_back(Op.getNode()); 1305 // Clean up in case the token factor is removed. 1306 AddToWorkList(Op.getNode()); 1307 Changed = true; 1308 break; 1309 } 1310 // Fall thru 1311 1312 default: 1313 // Only add if it isn't already in the list. 1314 if (SeenOps.insert(Op.getNode())) 1315 Ops.push_back(Op); 1316 else 1317 Changed = true; 1318 break; 1319 } 1320 } 1321 } 1322 1323 SDValue Result; 1324 1325 // If we've change things around then replace token factor. 1326 if (Changed) { 1327 if (Ops.empty()) { 1328 // The entry token is the only possible outcome. 1329 Result = DAG.getEntryNode(); 1330 } else { 1331 // New and improved token factor. 1332 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), 1333 MVT::Other, &Ops[0], Ops.size()); 1334 } 1335 1336 // Don't add users to work list. 1337 return CombineTo(N, Result, false); 1338 } 1339 1340 return Result; 1341} 1342 1343/// MERGE_VALUES can always be eliminated. 1344SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1345 WorkListRemover DeadNodes(*this); 1346 // Replacing results may cause a different MERGE_VALUES to suddenly 1347 // be CSE'd with N, and carry its uses with it. Iterate until no 1348 // uses remain, to ensure that the node can be safely deleted. 1349 // First add the users of this node to the work list so that they 1350 // can be tried again once they have new operands. 1351 AddUsersToWorkList(N); 1352 do { 1353 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1354 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1355 } while (!N->use_empty()); 1356 removeFromWorkList(N); 1357 DAG.DeleteNode(N); 1358 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1359} 1360 1361static 1362SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1, 1363 SelectionDAG &DAG) { 1364 EVT VT = N0.getValueType(); 1365 SDValue N00 = N0.getOperand(0); 1366 SDValue N01 = N0.getOperand(1); 1367 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1368 1369 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1370 isa<ConstantSDNode>(N00.getOperand(1))) { 1371 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1372 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT, 1373 DAG.getNode(ISD::SHL, SDLoc(N00), VT, 1374 N00.getOperand(0), N01), 1375 DAG.getNode(ISD::SHL, SDLoc(N01), VT, 1376 N00.getOperand(1), N01)); 1377 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1378 } 1379 1380 return SDValue(); 1381} 1382 1383SDValue DAGCombiner::visitADD(SDNode *N) { 1384 SDValue N0 = N->getOperand(0); 1385 SDValue N1 = N->getOperand(1); 1386 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1387 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1388 EVT VT = N0.getValueType(); 1389 1390 // fold vector ops 1391 if (VT.isVector()) { 1392 SDValue FoldedVOp = SimplifyVBinOp(N); 1393 if (FoldedVOp.getNode()) return FoldedVOp; 1394 1395 // fold (add x, 0) -> x, vector edition 1396 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1397 return N0; 1398 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1399 return N1; 1400 } 1401 1402 // fold (add x, undef) -> undef 1403 if (N0.getOpcode() == ISD::UNDEF) 1404 return N0; 1405 if (N1.getOpcode() == ISD::UNDEF) 1406 return N1; 1407 // fold (add c1, c2) -> c1+c2 1408 if (N0C && N1C) 1409 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1410 // canonicalize constant to RHS 1411 if (N0C && !N1C) 1412 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1413 // fold (add x, 0) -> x 1414 if (N1C && N1C->isNullValue()) 1415 return N0; 1416 // fold (add Sym, c) -> Sym+c 1417 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1418 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1419 GA->getOpcode() == ISD::GlobalAddress) 1420 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1421 GA->getOffset() + 1422 (uint64_t)N1C->getSExtValue()); 1423 // fold ((c1-A)+c2) -> (c1+c2)-A 1424 if (N1C && N0.getOpcode() == ISD::SUB) 1425 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1426 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1427 DAG.getConstant(N1C->getAPIntValue()+ 1428 N0C->getAPIntValue(), VT), 1429 N0.getOperand(1)); 1430 // reassociate add 1431 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1432 if (RADD.getNode() != 0) 1433 return RADD; 1434 // fold ((0-A) + B) -> B-A 1435 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1436 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1437 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1438 // fold (A + (0-B)) -> A-B 1439 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1440 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1441 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1442 // fold (A+(B-A)) -> B 1443 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1444 return N1.getOperand(0); 1445 // fold ((B-A)+A) -> B 1446 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1447 return N0.getOperand(0); 1448 // fold (A+(B-(A+C))) to (B-C) 1449 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1450 N0 == N1.getOperand(1).getOperand(0)) 1451 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1452 N1.getOperand(1).getOperand(1)); 1453 // fold (A+(B-(C+A))) to (B-C) 1454 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1455 N0 == N1.getOperand(1).getOperand(1)) 1456 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1457 N1.getOperand(1).getOperand(0)); 1458 // fold (A+((B-A)+or-C)) to (B+or-C) 1459 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1460 N1.getOperand(0).getOpcode() == ISD::SUB && 1461 N0 == N1.getOperand(0).getOperand(1)) 1462 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1463 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1464 1465 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1466 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1467 SDValue N00 = N0.getOperand(0); 1468 SDValue N01 = N0.getOperand(1); 1469 SDValue N10 = N1.getOperand(0); 1470 SDValue N11 = N1.getOperand(1); 1471 1472 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1473 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1474 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1475 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1476 } 1477 1478 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1479 return SDValue(N, 0); 1480 1481 // fold (a+b) -> (a|b) iff a and b share no bits. 1482 if (VT.isInteger() && !VT.isVector()) { 1483 APInt LHSZero, LHSOne; 1484 APInt RHSZero, RHSOne; 1485 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1486 1487 if (LHSZero.getBoolValue()) { 1488 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1489 1490 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1491 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1492 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1493 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1494 } 1495 } 1496 1497 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1498 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1499 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG); 1500 if (Result.getNode()) return Result; 1501 } 1502 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1503 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG); 1504 if (Result.getNode()) return Result; 1505 } 1506 1507 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1508 if (N1.getOpcode() == ISD::SHL && 1509 N1.getOperand(0).getOpcode() == ISD::SUB) 1510 if (ConstantSDNode *C = 1511 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1512 if (C->getAPIntValue() == 0) 1513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1514 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1515 N1.getOperand(0).getOperand(1), 1516 N1.getOperand(1))); 1517 if (N0.getOpcode() == ISD::SHL && 1518 N0.getOperand(0).getOpcode() == ISD::SUB) 1519 if (ConstantSDNode *C = 1520 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1521 if (C->getAPIntValue() == 0) 1522 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1523 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1524 N0.getOperand(0).getOperand(1), 1525 N0.getOperand(1))); 1526 1527 if (N1.getOpcode() == ISD::AND) { 1528 SDValue AndOp0 = N1.getOperand(0); 1529 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1530 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1531 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1532 1533 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1534 // and similar xforms where the inner op is either ~0 or 0. 1535 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1536 SDLoc DL(N); 1537 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1538 } 1539 } 1540 1541 // add (sext i1), X -> sub X, (zext i1) 1542 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1543 N0.getOperand(0).getValueType() == MVT::i1 && 1544 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1545 SDLoc DL(N); 1546 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1547 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1548 } 1549 1550 return SDValue(); 1551} 1552 1553SDValue DAGCombiner::visitADDC(SDNode *N) { 1554 SDValue N0 = N->getOperand(0); 1555 SDValue N1 = N->getOperand(1); 1556 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1557 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1558 EVT VT = N0.getValueType(); 1559 1560 // If the flag result is dead, turn this into an ADD. 1561 if (!N->hasAnyUseOfValue(1)) 1562 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1563 DAG.getNode(ISD::CARRY_FALSE, 1564 SDLoc(N), MVT::Glue)); 1565 1566 // canonicalize constant to RHS. 1567 if (N0C && !N1C) 1568 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1569 1570 // fold (addc x, 0) -> x + no carry out 1571 if (N1C && N1C->isNullValue()) 1572 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1573 SDLoc(N), MVT::Glue)); 1574 1575 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1576 APInt LHSZero, LHSOne; 1577 APInt RHSZero, RHSOne; 1578 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1579 1580 if (LHSZero.getBoolValue()) { 1581 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1582 1583 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1584 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1585 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1586 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1587 DAG.getNode(ISD::CARRY_FALSE, 1588 SDLoc(N), MVT::Glue)); 1589 } 1590 1591 return SDValue(); 1592} 1593 1594SDValue DAGCombiner::visitADDE(SDNode *N) { 1595 SDValue N0 = N->getOperand(0); 1596 SDValue N1 = N->getOperand(1); 1597 SDValue CarryIn = N->getOperand(2); 1598 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1599 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1600 1601 // canonicalize constant to RHS 1602 if (N0C && !N1C) 1603 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1604 N1, N0, CarryIn); 1605 1606 // fold (adde x, y, false) -> (addc x, y) 1607 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1608 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1609 1610 return SDValue(); 1611} 1612 1613// Since it may not be valid to emit a fold to zero for vector initializers 1614// check if we can before folding. 1615static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1616 SelectionDAG &DAG, 1617 bool LegalOperations, bool LegalTypes) { 1618 if (!VT.isVector()) 1619 return DAG.getConstant(0, VT); 1620 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) { 1621 // Produce a vector of zeros. 1622 EVT ElemTy = VT.getVectorElementType(); 1623 if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) == 1624 TargetLowering::TypePromoteInteger) 1625 ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy); 1626 assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) && 1627 "Type for zero vector elements is not legal"); 1628 SDValue El = DAG.getConstant(0, ElemTy); 1629 std::vector<SDValue> Ops(VT.getVectorNumElements(), El); 1630 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 1631 &Ops[0], Ops.size()); 1632 } 1633 return SDValue(); 1634} 1635 1636SDValue DAGCombiner::visitSUB(SDNode *N) { 1637 SDValue N0 = N->getOperand(0); 1638 SDValue N1 = N->getOperand(1); 1639 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1640 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1641 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 : 1642 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1643 EVT VT = N0.getValueType(); 1644 1645 // fold vector ops 1646 if (VT.isVector()) { 1647 SDValue FoldedVOp = SimplifyVBinOp(N); 1648 if (FoldedVOp.getNode()) return FoldedVOp; 1649 1650 // fold (sub x, 0) -> x, vector edition 1651 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1652 return N0; 1653 } 1654 1655 // fold (sub x, x) -> 0 1656 // FIXME: Refactor this and xor and other similar operations together. 1657 if (N0 == N1) 1658 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1659 // fold (sub c1, c2) -> c1-c2 1660 if (N0C && N1C) 1661 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1662 // fold (sub x, c) -> (add x, -c) 1663 if (N1C) 1664 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1665 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1666 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1667 if (N0C && N0C->isAllOnesValue()) 1668 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1669 // fold A-(A-B) -> B 1670 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1671 return N1.getOperand(1); 1672 // fold (A+B)-A -> B 1673 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1674 return N0.getOperand(1); 1675 // fold (A+B)-B -> A 1676 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1677 return N0.getOperand(0); 1678 // fold C2-(A+C1) -> (C2-C1)-A 1679 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1680 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1681 VT); 1682 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1683 N1.getOperand(0)); 1684 } 1685 // fold ((A+(B+or-C))-B) -> A+or-C 1686 if (N0.getOpcode() == ISD::ADD && 1687 (N0.getOperand(1).getOpcode() == ISD::SUB || 1688 N0.getOperand(1).getOpcode() == ISD::ADD) && 1689 N0.getOperand(1).getOperand(0) == N1) 1690 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1691 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1692 // fold ((A+(C+B))-B) -> A+C 1693 if (N0.getOpcode() == ISD::ADD && 1694 N0.getOperand(1).getOpcode() == ISD::ADD && 1695 N0.getOperand(1).getOperand(1) == N1) 1696 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1697 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1698 // fold ((A-(B-C))-C) -> A-B 1699 if (N0.getOpcode() == ISD::SUB && 1700 N0.getOperand(1).getOpcode() == ISD::SUB && 1701 N0.getOperand(1).getOperand(1) == N1) 1702 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1703 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1704 1705 // If either operand of a sub is undef, the result is undef 1706 if (N0.getOpcode() == ISD::UNDEF) 1707 return N0; 1708 if (N1.getOpcode() == ISD::UNDEF) 1709 return N1; 1710 1711 // If the relocation model supports it, consider symbol offsets. 1712 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1713 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1714 // fold (sub Sym, c) -> Sym-c 1715 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1716 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1717 GA->getOffset() - 1718 (uint64_t)N1C->getSExtValue()); 1719 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1720 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1721 if (GA->getGlobal() == GB->getGlobal()) 1722 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1723 VT); 1724 } 1725 1726 return SDValue(); 1727} 1728 1729SDValue DAGCombiner::visitSUBC(SDNode *N) { 1730 SDValue N0 = N->getOperand(0); 1731 SDValue N1 = N->getOperand(1); 1732 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1733 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1734 EVT VT = N0.getValueType(); 1735 1736 // If the flag result is dead, turn this into an SUB. 1737 if (!N->hasAnyUseOfValue(1)) 1738 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1739 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1740 MVT::Glue)); 1741 1742 // fold (subc x, x) -> 0 + no borrow 1743 if (N0 == N1) 1744 return CombineTo(N, DAG.getConstant(0, VT), 1745 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1746 MVT::Glue)); 1747 1748 // fold (subc x, 0) -> x + no borrow 1749 if (N1C && N1C->isNullValue()) 1750 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1751 MVT::Glue)); 1752 1753 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1754 if (N0C && N0C->isAllOnesValue()) 1755 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1756 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1757 MVT::Glue)); 1758 1759 return SDValue(); 1760} 1761 1762SDValue DAGCombiner::visitSUBE(SDNode *N) { 1763 SDValue N0 = N->getOperand(0); 1764 SDValue N1 = N->getOperand(1); 1765 SDValue CarryIn = N->getOperand(2); 1766 1767 // fold (sube x, y, false) -> (subc x, y) 1768 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1769 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1770 1771 return SDValue(); 1772} 1773 1774/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 1775/// all the same constant or undefined. 1776static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 1777 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 1778 if (!C) 1779 return false; 1780 1781 APInt SplatUndef; 1782 unsigned SplatBitSize; 1783 bool HasAnyUndefs; 1784 EVT EltVT = N->getValueType(0).getVectorElementType(); 1785 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 1786 HasAnyUndefs) && 1787 EltVT.getSizeInBits() >= SplatBitSize); 1788} 1789 1790SDValue DAGCombiner::visitMUL(SDNode *N) { 1791 SDValue N0 = N->getOperand(0); 1792 SDValue N1 = N->getOperand(1); 1793 EVT VT = N0.getValueType(); 1794 1795 // fold (mul x, undef) -> 0 1796 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1797 return DAG.getConstant(0, VT); 1798 1799 bool N0IsConst = false; 1800 bool N1IsConst = false; 1801 APInt ConstValue0, ConstValue1; 1802 // fold vector ops 1803 if (VT.isVector()) { 1804 SDValue FoldedVOp = SimplifyVBinOp(N); 1805 if (FoldedVOp.getNode()) return FoldedVOp; 1806 1807 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1808 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1809 } else { 1810 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0; 1811 ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt(); 1812 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0; 1813 ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt(); 1814 } 1815 1816 // fold (mul c1, c2) -> c1*c2 1817 if (N0IsConst && N1IsConst) 1818 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1819 1820 // canonicalize constant to RHS 1821 if (N0IsConst && !N1IsConst) 1822 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1823 // fold (mul x, 0) -> 0 1824 if (N1IsConst && ConstValue1 == 0) 1825 return N1; 1826 // fold (mul x, 1) -> x 1827 if (N1IsConst && ConstValue1 == 1) 1828 return N0; 1829 // fold (mul x, -1) -> 0-x 1830 if (N1IsConst && ConstValue1.isAllOnesValue()) 1831 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1832 DAG.getConstant(0, VT), N0); 1833 // fold (mul x, (1 << c)) -> x << c 1834 if (N1IsConst && ConstValue1.isPowerOf2()) 1835 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1836 DAG.getConstant(ConstValue1.logBase2(), 1837 getShiftAmountTy(N0.getValueType()))); 1838 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1839 if (N1IsConst && (-ConstValue1).isPowerOf2()) { 1840 unsigned Log2Val = (-ConstValue1).logBase2(); 1841 // FIXME: If the input is something that is easily negated (e.g. a 1842 // single-use add), we should put the negate there. 1843 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1844 DAG.getConstant(0, VT), 1845 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1846 DAG.getConstant(Log2Val, 1847 getShiftAmountTy(N0.getValueType())))); 1848 } 1849 1850 APInt Val; 1851 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1852 if (N1IsConst && N0.getOpcode() == ISD::SHL && 1853 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1854 isa<ConstantSDNode>(N0.getOperand(1)))) { 1855 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 1856 N1, N0.getOperand(1)); 1857 AddToWorkList(C3.getNode()); 1858 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 1859 N0.getOperand(0), C3); 1860 } 1861 1862 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1863 // use. 1864 { 1865 SDValue Sh(0,0), Y(0,0); 1866 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1867 if (N0.getOpcode() == ISD::SHL && 1868 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1869 isa<ConstantSDNode>(N0.getOperand(1))) && 1870 N0.getNode()->hasOneUse()) { 1871 Sh = N0; Y = N1; 1872 } else if (N1.getOpcode() == ISD::SHL && 1873 isa<ConstantSDNode>(N1.getOperand(1)) && 1874 N1.getNode()->hasOneUse()) { 1875 Sh = N1; Y = N0; 1876 } 1877 1878 if (Sh.getNode()) { 1879 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 1880 Sh.getOperand(0), Y); 1881 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 1882 Mul, Sh.getOperand(1)); 1883 } 1884 } 1885 1886 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1887 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1888 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1889 isa<ConstantSDNode>(N0.getOperand(1)))) 1890 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1891 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 1892 N0.getOperand(0), N1), 1893 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 1894 N0.getOperand(1), N1)); 1895 1896 // reassociate mul 1897 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 1898 if (RMUL.getNode() != 0) 1899 return RMUL; 1900 1901 return SDValue(); 1902} 1903 1904SDValue DAGCombiner::visitSDIV(SDNode *N) { 1905 SDValue N0 = N->getOperand(0); 1906 SDValue N1 = N->getOperand(1); 1907 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1908 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1909 EVT VT = N->getValueType(0); 1910 1911 // fold vector ops 1912 if (VT.isVector()) { 1913 SDValue FoldedVOp = SimplifyVBinOp(N); 1914 if (FoldedVOp.getNode()) return FoldedVOp; 1915 } 1916 1917 // fold (sdiv c1, c2) -> c1/c2 1918 if (N0C && N1C && !N1C->isNullValue()) 1919 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1920 // fold (sdiv X, 1) -> X 1921 if (N1C && N1C->getAPIntValue() == 1LL) 1922 return N0; 1923 // fold (sdiv X, -1) -> 0-X 1924 if (N1C && N1C->isAllOnesValue()) 1925 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1926 DAG.getConstant(0, VT), N0); 1927 // If we know the sign bits of both operands are zero, strength reduce to a 1928 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1929 if (!VT.isVector()) { 1930 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1931 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 1932 N0, N1); 1933 } 1934 // fold (sdiv X, pow2) -> simple ops after legalize 1935 if (N1C && !N1C->isNullValue() && 1936 (N1C->getAPIntValue().isPowerOf2() || 1937 (-N1C->getAPIntValue()).isPowerOf2())) { 1938 // If dividing by powers of two is cheap, then don't perform the following 1939 // fold. 1940 if (TLI.isPow2DivCheap()) 1941 return SDValue(); 1942 1943 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1944 1945 // Splat the sign bit into the register 1946 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 1947 DAG.getConstant(VT.getSizeInBits()-1, 1948 getShiftAmountTy(N0.getValueType()))); 1949 AddToWorkList(SGN.getNode()); 1950 1951 // Add (N0 < 0) ? abs2 - 1 : 0; 1952 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 1953 DAG.getConstant(VT.getSizeInBits() - lg2, 1954 getShiftAmountTy(SGN.getValueType()))); 1955 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 1956 AddToWorkList(SRL.getNode()); 1957 AddToWorkList(ADD.getNode()); // Divide by pow2 1958 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 1959 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 1960 1961 // If we're dividing by a positive value, we're done. Otherwise, we must 1962 // negate the result. 1963 if (N1C->getAPIntValue().isNonNegative()) 1964 return SRA; 1965 1966 AddToWorkList(SRA.getNode()); 1967 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1968 DAG.getConstant(0, VT), SRA); 1969 } 1970 1971 // if integer divide is expensive and we satisfy the requirements, emit an 1972 // alternate sequence. 1973 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1974 SDValue Op = BuildSDIV(N); 1975 if (Op.getNode()) return Op; 1976 } 1977 1978 // undef / X -> 0 1979 if (N0.getOpcode() == ISD::UNDEF) 1980 return DAG.getConstant(0, VT); 1981 // X / undef -> undef 1982 if (N1.getOpcode() == ISD::UNDEF) 1983 return N1; 1984 1985 return SDValue(); 1986} 1987 1988SDValue DAGCombiner::visitUDIV(SDNode *N) { 1989 SDValue N0 = N->getOperand(0); 1990 SDValue N1 = N->getOperand(1); 1991 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1992 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1993 EVT VT = N->getValueType(0); 1994 1995 // fold vector ops 1996 if (VT.isVector()) { 1997 SDValue FoldedVOp = SimplifyVBinOp(N); 1998 if (FoldedVOp.getNode()) return FoldedVOp; 1999 } 2000 2001 // fold (udiv c1, c2) -> c1/c2 2002 if (N0C && N1C && !N1C->isNullValue()) 2003 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2004 // fold (udiv x, (1 << c)) -> x >>u c 2005 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2006 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2007 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2008 getShiftAmountTy(N0.getValueType()))); 2009 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2010 if (N1.getOpcode() == ISD::SHL) { 2011 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2012 if (SHC->getAPIntValue().isPowerOf2()) { 2013 EVT ADDVT = N1.getOperand(1).getValueType(); 2014 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2015 N1.getOperand(1), 2016 DAG.getConstant(SHC->getAPIntValue() 2017 .logBase2(), 2018 ADDVT)); 2019 AddToWorkList(Add.getNode()); 2020 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2021 } 2022 } 2023 } 2024 // fold (udiv x, c) -> alternate 2025 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2026 SDValue Op = BuildUDIV(N); 2027 if (Op.getNode()) return Op; 2028 } 2029 2030 // undef / X -> 0 2031 if (N0.getOpcode() == ISD::UNDEF) 2032 return DAG.getConstant(0, VT); 2033 // X / undef -> undef 2034 if (N1.getOpcode() == ISD::UNDEF) 2035 return N1; 2036 2037 return SDValue(); 2038} 2039 2040SDValue DAGCombiner::visitSREM(SDNode *N) { 2041 SDValue N0 = N->getOperand(0); 2042 SDValue N1 = N->getOperand(1); 2043 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2044 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2045 EVT VT = N->getValueType(0); 2046 2047 // fold (srem c1, c2) -> c1%c2 2048 if (N0C && N1C && !N1C->isNullValue()) 2049 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2050 // If we know the sign bits of both operands are zero, strength reduce to a 2051 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2052 if (!VT.isVector()) { 2053 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2054 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2055 } 2056 2057 // If X/C can be simplified by the division-by-constant logic, lower 2058 // X%C to the equivalent of X-X/C*C. 2059 if (N1C && !N1C->isNullValue()) { 2060 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2061 AddToWorkList(Div.getNode()); 2062 SDValue OptimizedDiv = combine(Div.getNode()); 2063 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2064 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2065 OptimizedDiv, N1); 2066 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2067 AddToWorkList(Mul.getNode()); 2068 return Sub; 2069 } 2070 } 2071 2072 // undef % X -> 0 2073 if (N0.getOpcode() == ISD::UNDEF) 2074 return DAG.getConstant(0, VT); 2075 // X % undef -> undef 2076 if (N1.getOpcode() == ISD::UNDEF) 2077 return N1; 2078 2079 return SDValue(); 2080} 2081 2082SDValue DAGCombiner::visitUREM(SDNode *N) { 2083 SDValue N0 = N->getOperand(0); 2084 SDValue N1 = N->getOperand(1); 2085 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2086 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2087 EVT VT = N->getValueType(0); 2088 2089 // fold (urem c1, c2) -> c1%c2 2090 if (N0C && N1C && !N1C->isNullValue()) 2091 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2092 // fold (urem x, pow2) -> (and x, pow2-1) 2093 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2094 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2095 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2096 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2097 if (N1.getOpcode() == ISD::SHL) { 2098 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2099 if (SHC->getAPIntValue().isPowerOf2()) { 2100 SDValue Add = 2101 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2102 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2103 VT)); 2104 AddToWorkList(Add.getNode()); 2105 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2106 } 2107 } 2108 } 2109 2110 // If X/C can be simplified by the division-by-constant logic, lower 2111 // X%C to the equivalent of X-X/C*C. 2112 if (N1C && !N1C->isNullValue()) { 2113 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2114 AddToWorkList(Div.getNode()); 2115 SDValue OptimizedDiv = combine(Div.getNode()); 2116 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2117 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2118 OptimizedDiv, N1); 2119 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2120 AddToWorkList(Mul.getNode()); 2121 return Sub; 2122 } 2123 } 2124 2125 // undef % X -> 0 2126 if (N0.getOpcode() == ISD::UNDEF) 2127 return DAG.getConstant(0, VT); 2128 // X % undef -> undef 2129 if (N1.getOpcode() == ISD::UNDEF) 2130 return N1; 2131 2132 return SDValue(); 2133} 2134 2135SDValue DAGCombiner::visitMULHS(SDNode *N) { 2136 SDValue N0 = N->getOperand(0); 2137 SDValue N1 = N->getOperand(1); 2138 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2139 EVT VT = N->getValueType(0); 2140 SDLoc DL(N); 2141 2142 // fold (mulhs x, 0) -> 0 2143 if (N1C && N1C->isNullValue()) 2144 return N1; 2145 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2146 if (N1C && N1C->getAPIntValue() == 1) 2147 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2148 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2149 getShiftAmountTy(N0.getValueType()))); 2150 // fold (mulhs x, undef) -> 0 2151 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2152 return DAG.getConstant(0, VT); 2153 2154 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2155 // plus a shift. 2156 if (VT.isSimple() && !VT.isVector()) { 2157 MVT Simple = VT.getSimpleVT(); 2158 unsigned SimpleSize = Simple.getSizeInBits(); 2159 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2160 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2161 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2162 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2163 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2164 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2165 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2166 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2167 } 2168 } 2169 2170 return SDValue(); 2171} 2172 2173SDValue DAGCombiner::visitMULHU(SDNode *N) { 2174 SDValue N0 = N->getOperand(0); 2175 SDValue N1 = N->getOperand(1); 2176 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2177 EVT VT = N->getValueType(0); 2178 SDLoc DL(N); 2179 2180 // fold (mulhu x, 0) -> 0 2181 if (N1C && N1C->isNullValue()) 2182 return N1; 2183 // fold (mulhu x, 1) -> 0 2184 if (N1C && N1C->getAPIntValue() == 1) 2185 return DAG.getConstant(0, N0.getValueType()); 2186 // fold (mulhu x, undef) -> 0 2187 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2188 return DAG.getConstant(0, VT); 2189 2190 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2191 // plus a shift. 2192 if (VT.isSimple() && !VT.isVector()) { 2193 MVT Simple = VT.getSimpleVT(); 2194 unsigned SimpleSize = Simple.getSizeInBits(); 2195 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2196 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2197 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2198 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2199 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2200 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2201 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2202 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2203 } 2204 } 2205 2206 return SDValue(); 2207} 2208 2209/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2210/// compute two values. LoOp and HiOp give the opcodes for the two computations 2211/// that are being performed. Return true if a simplification was made. 2212/// 2213SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2214 unsigned HiOp) { 2215 // If the high half is not needed, just compute the low half. 2216 bool HiExists = N->hasAnyUseOfValue(1); 2217 if (!HiExists && 2218 (!LegalOperations || 2219 TLI.isOperationLegal(LoOp, N->getValueType(0)))) { 2220 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2221 N->op_begin(), N->getNumOperands()); 2222 return CombineTo(N, Res, Res); 2223 } 2224 2225 // If the low half is not needed, just compute the high half. 2226 bool LoExists = N->hasAnyUseOfValue(0); 2227 if (!LoExists && 2228 (!LegalOperations || 2229 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2230 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2231 N->op_begin(), N->getNumOperands()); 2232 return CombineTo(N, Res, Res); 2233 } 2234 2235 // If both halves are used, return as it is. 2236 if (LoExists && HiExists) 2237 return SDValue(); 2238 2239 // If the two computed results can be simplified separately, separate them. 2240 if (LoExists) { 2241 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2242 N->op_begin(), N->getNumOperands()); 2243 AddToWorkList(Lo.getNode()); 2244 SDValue LoOpt = combine(Lo.getNode()); 2245 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2246 (!LegalOperations || 2247 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2248 return CombineTo(N, LoOpt, LoOpt); 2249 } 2250 2251 if (HiExists) { 2252 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2253 N->op_begin(), N->getNumOperands()); 2254 AddToWorkList(Hi.getNode()); 2255 SDValue HiOpt = combine(Hi.getNode()); 2256 if (HiOpt.getNode() && HiOpt != Hi && 2257 (!LegalOperations || 2258 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2259 return CombineTo(N, HiOpt, HiOpt); 2260 } 2261 2262 return SDValue(); 2263} 2264 2265SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2266 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2267 if (Res.getNode()) return Res; 2268 2269 EVT VT = N->getValueType(0); 2270 SDLoc DL(N); 2271 2272 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2273 // plus a shift. 2274 if (VT.isSimple() && !VT.isVector()) { 2275 MVT Simple = VT.getSimpleVT(); 2276 unsigned SimpleSize = Simple.getSizeInBits(); 2277 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2278 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2279 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2280 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2281 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2282 // Compute the high part as N1. 2283 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2284 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2285 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2286 // Compute the low part as N0. 2287 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2288 return CombineTo(N, Lo, Hi); 2289 } 2290 } 2291 2292 return SDValue(); 2293} 2294 2295SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2296 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2297 if (Res.getNode()) return Res; 2298 2299 EVT VT = N->getValueType(0); 2300 SDLoc DL(N); 2301 2302 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2303 // plus a shift. 2304 if (VT.isSimple() && !VT.isVector()) { 2305 MVT Simple = VT.getSimpleVT(); 2306 unsigned SimpleSize = Simple.getSizeInBits(); 2307 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2308 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2309 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2310 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2311 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2312 // Compute the high part as N1. 2313 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2314 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2315 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2316 // Compute the low part as N0. 2317 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2318 return CombineTo(N, Lo, Hi); 2319 } 2320 } 2321 2322 return SDValue(); 2323} 2324 2325SDValue DAGCombiner::visitSMULO(SDNode *N) { 2326 // (smulo x, 2) -> (saddo x, x) 2327 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2328 if (C2->getAPIntValue() == 2) 2329 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2330 N->getOperand(0), N->getOperand(0)); 2331 2332 return SDValue(); 2333} 2334 2335SDValue DAGCombiner::visitUMULO(SDNode *N) { 2336 // (umulo x, 2) -> (uaddo x, x) 2337 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2338 if (C2->getAPIntValue() == 2) 2339 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2340 N->getOperand(0), N->getOperand(0)); 2341 2342 return SDValue(); 2343} 2344 2345SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2347 if (Res.getNode()) return Res; 2348 2349 return SDValue(); 2350} 2351 2352SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2353 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2354 if (Res.getNode()) return Res; 2355 2356 return SDValue(); 2357} 2358 2359/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2360/// two operands of the same opcode, try to simplify it. 2361SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2362 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2363 EVT VT = N0.getValueType(); 2364 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2365 2366 // Bail early if none of these transforms apply. 2367 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2368 2369 // For each of OP in AND/OR/XOR: 2370 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2371 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2372 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2373 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2374 // 2375 // do not sink logical op inside of a vector extend, since it may combine 2376 // into a vsetcc. 2377 EVT Op0VT = N0.getOperand(0).getValueType(); 2378 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2379 N0.getOpcode() == ISD::SIGN_EXTEND || 2380 // Avoid infinite looping with PromoteIntBinOp. 2381 (N0.getOpcode() == ISD::ANY_EXTEND && 2382 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2383 (N0.getOpcode() == ISD::TRUNCATE && 2384 (!TLI.isZExtFree(VT, Op0VT) || 2385 !TLI.isTruncateFree(Op0VT, VT)) && 2386 TLI.isTypeLegal(Op0VT))) && 2387 !VT.isVector() && 2388 Op0VT == N1.getOperand(0).getValueType() && 2389 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2390 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2391 N0.getOperand(0).getValueType(), 2392 N0.getOperand(0), N1.getOperand(0)); 2393 AddToWorkList(ORNode.getNode()); 2394 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2395 } 2396 2397 // For each of OP in SHL/SRL/SRA/AND... 2398 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2399 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2400 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2401 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2402 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2403 N0.getOperand(1) == N1.getOperand(1)) { 2404 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2405 N0.getOperand(0).getValueType(), 2406 N0.getOperand(0), N1.getOperand(0)); 2407 AddToWorkList(ORNode.getNode()); 2408 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2409 ORNode, N0.getOperand(1)); 2410 } 2411 2412 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2413 // Only perform this optimization after type legalization and before 2414 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2415 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2416 // we don't want to undo this promotion. 2417 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2418 // on scalars. 2419 if ((N0.getOpcode() == ISD::BITCAST || 2420 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2421 Level == AfterLegalizeTypes) { 2422 SDValue In0 = N0.getOperand(0); 2423 SDValue In1 = N1.getOperand(0); 2424 EVT In0Ty = In0.getValueType(); 2425 EVT In1Ty = In1.getValueType(); 2426 SDLoc DL(N); 2427 // If both incoming values are integers, and the original types are the 2428 // same. 2429 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2430 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2431 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2432 AddToWorkList(Op.getNode()); 2433 return BC; 2434 } 2435 } 2436 2437 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2438 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2439 // If both shuffles use the same mask, and both shuffle within a single 2440 // vector, then it is worthwhile to move the swizzle after the operation. 2441 // The type-legalizer generates this pattern when loading illegal 2442 // vector types from memory. In many cases this allows additional shuffle 2443 // optimizations. 2444 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 2445 N0.getOperand(1).getOpcode() == ISD::UNDEF && 2446 N1.getOperand(1).getOpcode() == ISD::UNDEF) { 2447 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2448 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2449 2450 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() && 2451 "Inputs to shuffles are not the same type"); 2452 2453 unsigned NumElts = VT.getVectorNumElements(); 2454 2455 // Check that both shuffles use the same mask. The masks are known to be of 2456 // the same length because the result vector type is the same. 2457 bool SameMask = true; 2458 for (unsigned i = 0; i != NumElts; ++i) { 2459 int Idx0 = SVN0->getMaskElt(i); 2460 int Idx1 = SVN1->getMaskElt(i); 2461 if (Idx0 != Idx1) { 2462 SameMask = false; 2463 break; 2464 } 2465 } 2466 2467 if (SameMask) { 2468 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2469 N0.getOperand(0), N1.getOperand(0)); 2470 AddToWorkList(Op.getNode()); 2471 return DAG.getVectorShuffle(VT, SDLoc(N), Op, 2472 DAG.getUNDEF(VT), &SVN0->getMask()[0]); 2473 } 2474 } 2475 2476 return SDValue(); 2477} 2478 2479SDValue DAGCombiner::visitAND(SDNode *N) { 2480 SDValue N0 = N->getOperand(0); 2481 SDValue N1 = N->getOperand(1); 2482 SDValue LL, LR, RL, RR, CC0, CC1; 2483 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2484 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2485 EVT VT = N1.getValueType(); 2486 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2487 2488 // fold vector ops 2489 if (VT.isVector()) { 2490 SDValue FoldedVOp = SimplifyVBinOp(N); 2491 if (FoldedVOp.getNode()) return FoldedVOp; 2492 2493 // fold (and x, 0) -> 0, vector edition 2494 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2495 return N0; 2496 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2497 return N1; 2498 2499 // fold (and x, -1) -> x, vector edition 2500 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2501 return N1; 2502 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2503 return N0; 2504 } 2505 2506 // fold (and x, undef) -> 0 2507 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2508 return DAG.getConstant(0, VT); 2509 // fold (and c1, c2) -> c1&c2 2510 if (N0C && N1C) 2511 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2512 // canonicalize constant to RHS 2513 if (N0C && !N1C) 2514 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2515 // fold (and x, -1) -> x 2516 if (N1C && N1C->isAllOnesValue()) 2517 return N0; 2518 // if (and x, c) is known to be zero, return 0 2519 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2520 APInt::getAllOnesValue(BitWidth))) 2521 return DAG.getConstant(0, VT); 2522 // reassociate and 2523 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2524 if (RAND.getNode() != 0) 2525 return RAND; 2526 // fold (and (or x, C), D) -> D if (C & D) == D 2527 if (N1C && N0.getOpcode() == ISD::OR) 2528 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2529 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2530 return N1; 2531 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2532 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2533 SDValue N0Op0 = N0.getOperand(0); 2534 APInt Mask = ~N1C->getAPIntValue(); 2535 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2536 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2537 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2538 N0.getValueType(), N0Op0); 2539 2540 // Replace uses of the AND with uses of the Zero extend node. 2541 CombineTo(N, Zext); 2542 2543 // We actually want to replace all uses of the any_extend with the 2544 // zero_extend, to avoid duplicating things. This will later cause this 2545 // AND to be folded. 2546 CombineTo(N0.getNode(), Zext); 2547 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2548 } 2549 } 2550 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2551 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2552 // already be zero by virtue of the width of the base type of the load. 2553 // 2554 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2555 // more cases. 2556 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2557 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2558 N0.getOpcode() == ISD::LOAD) { 2559 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2560 N0 : N0.getOperand(0) ); 2561 2562 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2563 // This can be a pure constant or a vector splat, in which case we treat the 2564 // vector as a scalar and use the splat value. 2565 APInt Constant = APInt::getNullValue(1); 2566 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2567 Constant = C->getAPIntValue(); 2568 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2569 APInt SplatValue, SplatUndef; 2570 unsigned SplatBitSize; 2571 bool HasAnyUndefs; 2572 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2573 SplatBitSize, HasAnyUndefs); 2574 if (IsSplat) { 2575 // Undef bits can contribute to a possible optimisation if set, so 2576 // set them. 2577 SplatValue |= SplatUndef; 2578 2579 // The splat value may be something like "0x00FFFFFF", which means 0 for 2580 // the first vector value and FF for the rest, repeating. We need a mask 2581 // that will apply equally to all members of the vector, so AND all the 2582 // lanes of the constant together. 2583 EVT VT = Vector->getValueType(0); 2584 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2585 2586 // If the splat value has been compressed to a bitlength lower 2587 // than the size of the vector lane, we need to re-expand it to 2588 // the lane size. 2589 if (BitWidth > SplatBitSize) 2590 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2591 SplatBitSize < BitWidth; 2592 SplatBitSize = SplatBitSize * 2) 2593 SplatValue |= SplatValue.shl(SplatBitSize); 2594 2595 Constant = APInt::getAllOnesValue(BitWidth); 2596 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2597 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2598 } 2599 } 2600 2601 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2602 // actually legal and isn't going to get expanded, else this is a false 2603 // optimisation. 2604 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2605 Load->getMemoryVT()); 2606 2607 // Resize the constant to the same size as the original memory access before 2608 // extension. If it is still the AllOnesValue then this AND is completely 2609 // unneeded. 2610 Constant = 2611 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2612 2613 bool B; 2614 switch (Load->getExtensionType()) { 2615 default: B = false; break; 2616 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2617 case ISD::ZEXTLOAD: 2618 case ISD::NON_EXTLOAD: B = true; break; 2619 } 2620 2621 if (B && Constant.isAllOnesValue()) { 2622 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2623 // preserve semantics once we get rid of the AND. 2624 SDValue NewLoad(Load, 0); 2625 if (Load->getExtensionType() == ISD::EXTLOAD) { 2626 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2627 Load->getValueType(0), SDLoc(Load), 2628 Load->getChain(), Load->getBasePtr(), 2629 Load->getOffset(), Load->getMemoryVT(), 2630 Load->getMemOperand()); 2631 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2632 if (Load->getNumValues() == 3) { 2633 // PRE/POST_INC loads have 3 values. 2634 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2635 NewLoad.getValue(2) }; 2636 CombineTo(Load, To, 3, true); 2637 } else { 2638 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2639 } 2640 } 2641 2642 // Fold the AND away, taking care not to fold to the old load node if we 2643 // replaced it. 2644 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2645 2646 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2647 } 2648 } 2649 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2650 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2651 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2652 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2653 2654 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2655 LL.getValueType().isInteger()) { 2656 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2657 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2658 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2659 LR.getValueType(), LL, RL); 2660 AddToWorkList(ORNode.getNode()); 2661 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2662 } 2663 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2664 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2665 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2666 LR.getValueType(), LL, RL); 2667 AddToWorkList(ANDNode.getNode()); 2668 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2669 } 2670 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2671 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2672 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2673 LR.getValueType(), LL, RL); 2674 AddToWorkList(ORNode.getNode()); 2675 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2676 } 2677 } 2678 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2679 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2680 Op0 == Op1 && LL.getValueType().isInteger() && 2681 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2682 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2683 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2684 cast<ConstantSDNode>(RR)->isNullValue()))) { 2685 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2686 LL, DAG.getConstant(1, LL.getValueType())); 2687 AddToWorkList(ADDNode.getNode()); 2688 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2689 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2690 } 2691 // canonicalize equivalent to ll == rl 2692 if (LL == RR && LR == RL) { 2693 Op1 = ISD::getSetCCSwappedOperands(Op1); 2694 std::swap(RL, RR); 2695 } 2696 if (LL == RL && LR == RR) { 2697 bool isInteger = LL.getValueType().isInteger(); 2698 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2699 if (Result != ISD::SETCC_INVALID && 2700 (!LegalOperations || 2701 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2702 TLI.isOperationLegal(ISD::SETCC, 2703 getSetCCResultType(N0.getSimpleValueType()))))) 2704 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2705 LL, LR, Result); 2706 } 2707 } 2708 2709 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2710 if (N0.getOpcode() == N1.getOpcode()) { 2711 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2712 if (Tmp.getNode()) return Tmp; 2713 } 2714 2715 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2716 // fold (and (sra)) -> (and (srl)) when possible. 2717 if (!VT.isVector() && 2718 SimplifyDemandedBits(SDValue(N, 0))) 2719 return SDValue(N, 0); 2720 2721 // fold (zext_inreg (extload x)) -> (zextload x) 2722 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2723 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2724 EVT MemVT = LN0->getMemoryVT(); 2725 // If we zero all the possible extended bits, then we can turn this into 2726 // a zextload if we are running before legalize or the operation is legal. 2727 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2728 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2729 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2730 ((!LegalOperations && !LN0->isVolatile()) || 2731 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2732 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2733 LN0->getChain(), LN0->getBasePtr(), 2734 LN0->getPointerInfo(), MemVT, 2735 LN0->isVolatile(), LN0->isNonTemporal(), 2736 LN0->getAlignment()); 2737 AddToWorkList(N); 2738 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2739 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2740 } 2741 } 2742 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2743 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2744 N0.hasOneUse()) { 2745 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2746 EVT MemVT = LN0->getMemoryVT(); 2747 // If we zero all the possible extended bits, then we can turn this into 2748 // a zextload if we are running before legalize or the operation is legal. 2749 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2750 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2751 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2752 ((!LegalOperations && !LN0->isVolatile()) || 2753 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2754 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2755 LN0->getChain(), 2756 LN0->getBasePtr(), LN0->getPointerInfo(), 2757 MemVT, 2758 LN0->isVolatile(), LN0->isNonTemporal(), 2759 LN0->getAlignment()); 2760 AddToWorkList(N); 2761 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2762 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2763 } 2764 } 2765 2766 // fold (and (load x), 255) -> (zextload x, i8) 2767 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2768 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2769 if (N1C && (N0.getOpcode() == ISD::LOAD || 2770 (N0.getOpcode() == ISD::ANY_EXTEND && 2771 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2772 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2773 LoadSDNode *LN0 = HasAnyExt 2774 ? cast<LoadSDNode>(N0.getOperand(0)) 2775 : cast<LoadSDNode>(N0); 2776 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2777 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2778 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2779 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2780 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2781 EVT LoadedVT = LN0->getMemoryVT(); 2782 2783 if (ExtVT == LoadedVT && 2784 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2785 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2786 2787 SDValue NewLoad = 2788 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2789 LN0->getChain(), LN0->getBasePtr(), 2790 LN0->getPointerInfo(), 2791 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2792 LN0->getAlignment()); 2793 AddToWorkList(N); 2794 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2795 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2796 } 2797 2798 // Do not change the width of a volatile load. 2799 // Do not generate loads of non-round integer types since these can 2800 // be expensive (and would be wrong if the type is not byte sized). 2801 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2802 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2803 EVT PtrType = LN0->getOperand(1).getValueType(); 2804 2805 unsigned Alignment = LN0->getAlignment(); 2806 SDValue NewPtr = LN0->getBasePtr(); 2807 2808 // For big endian targets, we need to add an offset to the pointer 2809 // to load the correct bytes. For little endian systems, we merely 2810 // need to read fewer bytes from the same pointer. 2811 if (TLI.isBigEndian()) { 2812 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2813 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2814 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2815 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 2816 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2817 Alignment = MinAlign(Alignment, PtrOff); 2818 } 2819 2820 AddToWorkList(NewPtr.getNode()); 2821 2822 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2823 SDValue Load = 2824 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2825 LN0->getChain(), NewPtr, 2826 LN0->getPointerInfo(), 2827 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2828 Alignment); 2829 AddToWorkList(N); 2830 CombineTo(LN0, Load, Load.getValue(1)); 2831 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2832 } 2833 } 2834 } 2835 } 2836 2837 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2838 VT.getSizeInBits() <= 64) { 2839 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2840 APInt ADDC = ADDI->getAPIntValue(); 2841 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2842 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2843 // immediate for an add, but it is legal if its top c2 bits are set, 2844 // transform the ADD so the immediate doesn't need to be materialized 2845 // in a register. 2846 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2847 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2848 SRLI->getZExtValue()); 2849 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2850 ADDC |= Mask; 2851 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2852 SDValue NewAdd = 2853 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2854 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2855 CombineTo(N0.getNode(), NewAdd); 2856 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2857 } 2858 } 2859 } 2860 } 2861 } 2862 } 2863 2864 return SDValue(); 2865} 2866 2867/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2868/// 2869SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2870 bool DemandHighBits) { 2871 if (!LegalOperations) 2872 return SDValue(); 2873 2874 EVT VT = N->getValueType(0); 2875 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2876 return SDValue(); 2877 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2878 return SDValue(); 2879 2880 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2881 bool LookPassAnd0 = false; 2882 bool LookPassAnd1 = false; 2883 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2884 std::swap(N0, N1); 2885 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2886 std::swap(N0, N1); 2887 if (N0.getOpcode() == ISD::AND) { 2888 if (!N0.getNode()->hasOneUse()) 2889 return SDValue(); 2890 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2891 if (!N01C || N01C->getZExtValue() != 0xFF00) 2892 return SDValue(); 2893 N0 = N0.getOperand(0); 2894 LookPassAnd0 = true; 2895 } 2896 2897 if (N1.getOpcode() == ISD::AND) { 2898 if (!N1.getNode()->hasOneUse()) 2899 return SDValue(); 2900 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2901 if (!N11C || N11C->getZExtValue() != 0xFF) 2902 return SDValue(); 2903 N1 = N1.getOperand(0); 2904 LookPassAnd1 = true; 2905 } 2906 2907 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2908 std::swap(N0, N1); 2909 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2910 return SDValue(); 2911 if (!N0.getNode()->hasOneUse() || 2912 !N1.getNode()->hasOneUse()) 2913 return SDValue(); 2914 2915 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2916 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2917 if (!N01C || !N11C) 2918 return SDValue(); 2919 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 2920 return SDValue(); 2921 2922 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 2923 SDValue N00 = N0->getOperand(0); 2924 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 2925 if (!N00.getNode()->hasOneUse()) 2926 return SDValue(); 2927 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 2928 if (!N001C || N001C->getZExtValue() != 0xFF) 2929 return SDValue(); 2930 N00 = N00.getOperand(0); 2931 LookPassAnd0 = true; 2932 } 2933 2934 SDValue N10 = N1->getOperand(0); 2935 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 2936 if (!N10.getNode()->hasOneUse()) 2937 return SDValue(); 2938 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 2939 if (!N101C || N101C->getZExtValue() != 0xFF00) 2940 return SDValue(); 2941 N10 = N10.getOperand(0); 2942 LookPassAnd1 = true; 2943 } 2944 2945 if (N00 != N10) 2946 return SDValue(); 2947 2948 // Make sure everything beyond the low halfword is zero since the SRL 16 2949 // will clear the top bits. 2950 unsigned OpSizeInBits = VT.getSizeInBits(); 2951 if (DemandHighBits && OpSizeInBits > 16 && 2952 (!LookPassAnd0 || !LookPassAnd1) && 2953 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16))) 2954 return SDValue(); 2955 2956 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 2957 if (OpSizeInBits > 16) 2958 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 2959 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 2960 return Res; 2961} 2962 2963/// isBSwapHWordElement - Return true if the specified node is an element 2964/// that makes up a 32-bit packed halfword byteswap. i.e. 2965/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 2966static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) { 2967 if (!N.getNode()->hasOneUse()) 2968 return false; 2969 2970 unsigned Opc = N.getOpcode(); 2971 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 2972 return false; 2973 2974 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2975 if (!N1C) 2976 return false; 2977 2978 unsigned Num; 2979 switch (N1C->getZExtValue()) { 2980 default: 2981 return false; 2982 case 0xFF: Num = 0; break; 2983 case 0xFF00: Num = 1; break; 2984 case 0xFF0000: Num = 2; break; 2985 case 0xFF000000: Num = 3; break; 2986 } 2987 2988 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 2989 SDValue N0 = N.getOperand(0); 2990 if (Opc == ISD::AND) { 2991 if (Num == 0 || Num == 2) { 2992 // (x >> 8) & 0xff 2993 // (x >> 8) & 0xff0000 2994 if (N0.getOpcode() != ISD::SRL) 2995 return false; 2996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2997 if (!C || C->getZExtValue() != 8) 2998 return false; 2999 } else { 3000 // (x << 8) & 0xff00 3001 // (x << 8) & 0xff000000 3002 if (N0.getOpcode() != ISD::SHL) 3003 return false; 3004 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3005 if (!C || C->getZExtValue() != 8) 3006 return false; 3007 } 3008 } else if (Opc == ISD::SHL) { 3009 // (x & 0xff) << 8 3010 // (x & 0xff0000) << 8 3011 if (Num != 0 && Num != 2) 3012 return false; 3013 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3014 if (!C || C->getZExtValue() != 8) 3015 return false; 3016 } else { // Opc == ISD::SRL 3017 // (x & 0xff00) >> 8 3018 // (x & 0xff000000) >> 8 3019 if (Num != 1 && Num != 3) 3020 return false; 3021 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3022 if (!C || C->getZExtValue() != 8) 3023 return false; 3024 } 3025 3026 if (Parts[Num]) 3027 return false; 3028 3029 Parts[Num] = N0.getOperand(0).getNode(); 3030 return true; 3031} 3032 3033/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 3034/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3035/// => (rotl (bswap x), 16) 3036SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3037 if (!LegalOperations) 3038 return SDValue(); 3039 3040 EVT VT = N->getValueType(0); 3041 if (VT != MVT::i32) 3042 return SDValue(); 3043 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3044 return SDValue(); 3045 3046 SmallVector<SDNode*,4> Parts(4, (SDNode*)0); 3047 // Look for either 3048 // (or (or (and), (and)), (or (and), (and))) 3049 // (or (or (or (and), (and)), (and)), (and)) 3050 if (N0.getOpcode() != ISD::OR) 3051 return SDValue(); 3052 SDValue N00 = N0.getOperand(0); 3053 SDValue N01 = N0.getOperand(1); 3054 3055 if (N1.getOpcode() == ISD::OR && 3056 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3057 // (or (or (and), (and)), (or (and), (and))) 3058 SDValue N000 = N00.getOperand(0); 3059 if (!isBSwapHWordElement(N000, Parts)) 3060 return SDValue(); 3061 3062 SDValue N001 = N00.getOperand(1); 3063 if (!isBSwapHWordElement(N001, Parts)) 3064 return SDValue(); 3065 SDValue N010 = N01.getOperand(0); 3066 if (!isBSwapHWordElement(N010, Parts)) 3067 return SDValue(); 3068 SDValue N011 = N01.getOperand(1); 3069 if (!isBSwapHWordElement(N011, Parts)) 3070 return SDValue(); 3071 } else { 3072 // (or (or (or (and), (and)), (and)), (and)) 3073 if (!isBSwapHWordElement(N1, Parts)) 3074 return SDValue(); 3075 if (!isBSwapHWordElement(N01, Parts)) 3076 return SDValue(); 3077 if (N00.getOpcode() != ISD::OR) 3078 return SDValue(); 3079 SDValue N000 = N00.getOperand(0); 3080 if (!isBSwapHWordElement(N000, Parts)) 3081 return SDValue(); 3082 SDValue N001 = N00.getOperand(1); 3083 if (!isBSwapHWordElement(N001, Parts)) 3084 return SDValue(); 3085 } 3086 3087 // Make sure the parts are all coming from the same node. 3088 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3089 return SDValue(); 3090 3091 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3092 SDValue(Parts[0],0)); 3093 3094 // Result of the bswap should be rotated by 16. If it's not legal, than 3095 // do (x << 16) | (x >> 16). 3096 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3097 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3098 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3099 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3100 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3101 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3102 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3103 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3104} 3105 3106SDValue DAGCombiner::visitOR(SDNode *N) { 3107 SDValue N0 = N->getOperand(0); 3108 SDValue N1 = N->getOperand(1); 3109 SDValue LL, LR, RL, RR, CC0, CC1; 3110 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3111 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3112 EVT VT = N1.getValueType(); 3113 3114 // fold vector ops 3115 if (VT.isVector()) { 3116 SDValue FoldedVOp = SimplifyVBinOp(N); 3117 if (FoldedVOp.getNode()) return FoldedVOp; 3118 3119 // fold (or x, 0) -> x, vector edition 3120 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3121 return N1; 3122 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3123 return N0; 3124 3125 // fold (or x, -1) -> -1, vector edition 3126 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3127 return N0; 3128 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3129 return N1; 3130 } 3131 3132 // fold (or x, undef) -> -1 3133 if (!LegalOperations && 3134 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3135 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3136 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3137 } 3138 // fold (or c1, c2) -> c1|c2 3139 if (N0C && N1C) 3140 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3141 // canonicalize constant to RHS 3142 if (N0C && !N1C) 3143 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3144 // fold (or x, 0) -> x 3145 if (N1C && N1C->isNullValue()) 3146 return N0; 3147 // fold (or x, -1) -> -1 3148 if (N1C && N1C->isAllOnesValue()) 3149 return N1; 3150 // fold (or x, c) -> c iff (x & ~c) == 0 3151 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3152 return N1; 3153 3154 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3155 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3156 if (BSwap.getNode() != 0) 3157 return BSwap; 3158 BSwap = MatchBSwapHWordLow(N, N0, N1); 3159 if (BSwap.getNode() != 0) 3160 return BSwap; 3161 3162 // reassociate or 3163 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3164 if (ROR.getNode() != 0) 3165 return ROR; 3166 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3167 // iff (c1 & c2) == 0. 3168 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3169 isa<ConstantSDNode>(N0.getOperand(1))) { 3170 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3171 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) 3172 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3173 DAG.getNode(ISD::OR, SDLoc(N0), VT, 3174 N0.getOperand(0), N1), 3175 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)); 3176 } 3177 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3178 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3179 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3180 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3181 3182 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3183 LL.getValueType().isInteger()) { 3184 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3185 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3186 if (cast<ConstantSDNode>(LR)->isNullValue() && 3187 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3188 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3189 LR.getValueType(), LL, RL); 3190 AddToWorkList(ORNode.getNode()); 3191 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3192 } 3193 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3194 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3195 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3196 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3197 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3198 LR.getValueType(), LL, RL); 3199 AddToWorkList(ANDNode.getNode()); 3200 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3201 } 3202 } 3203 // canonicalize equivalent to ll == rl 3204 if (LL == RR && LR == RL) { 3205 Op1 = ISD::getSetCCSwappedOperands(Op1); 3206 std::swap(RL, RR); 3207 } 3208 if (LL == RL && LR == RR) { 3209 bool isInteger = LL.getValueType().isInteger(); 3210 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3211 if (Result != ISD::SETCC_INVALID && 3212 (!LegalOperations || 3213 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3214 TLI.isOperationLegal(ISD::SETCC, 3215 getSetCCResultType(N0.getValueType()))))) 3216 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3217 LL, LR, Result); 3218 } 3219 } 3220 3221 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3222 if (N0.getOpcode() == N1.getOpcode()) { 3223 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3224 if (Tmp.getNode()) return Tmp; 3225 } 3226 3227 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3228 if (N0.getOpcode() == ISD::AND && 3229 N1.getOpcode() == ISD::AND && 3230 N0.getOperand(1).getOpcode() == ISD::Constant && 3231 N1.getOperand(1).getOpcode() == ISD::Constant && 3232 // Don't increase # computations. 3233 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3234 // We can only do this xform if we know that bits from X that are set in C2 3235 // but not in C1 are already zero. Likewise for Y. 3236 const APInt &LHSMask = 3237 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3238 const APInt &RHSMask = 3239 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3240 3241 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3242 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3243 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3244 N0.getOperand(0), N1.getOperand(0)); 3245 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3246 DAG.getConstant(LHSMask | RHSMask, VT)); 3247 } 3248 } 3249 3250 // See if this is some rotate idiom. 3251 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3252 return SDValue(Rot, 0); 3253 3254 // Simplify the operands using demanded-bits information. 3255 if (!VT.isVector() && 3256 SimplifyDemandedBits(SDValue(N, 0))) 3257 return SDValue(N, 0); 3258 3259 return SDValue(); 3260} 3261 3262/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3263static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3264 if (Op.getOpcode() == ISD::AND) { 3265 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3266 Mask = Op.getOperand(1); 3267 Op = Op.getOperand(0); 3268 } else { 3269 return false; 3270 } 3271 } 3272 3273 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3274 Shift = Op; 3275 return true; 3276 } 3277 3278 return false; 3279} 3280 3281// MatchRotate - Handle an 'or' of two operands. If this is one of the many 3282// idioms for rotate, and if the target supports rotation instructions, generate 3283// a rot[lr]. 3284SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3285 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3286 EVT VT = LHS.getValueType(); 3287 if (!TLI.isTypeLegal(VT)) return 0; 3288 3289 // The target must have at least one rotate flavor. 3290 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3291 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3292 if (!HasROTL && !HasROTR) return 0; 3293 3294 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3295 SDValue LHSShift; // The shift. 3296 SDValue LHSMask; // AND value if any. 3297 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3298 return 0; // Not part of a rotate. 3299 3300 SDValue RHSShift; // The shift. 3301 SDValue RHSMask; // AND value if any. 3302 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3303 return 0; // Not part of a rotate. 3304 3305 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3306 return 0; // Not shifting the same value. 3307 3308 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3309 return 0; // Shifts must disagree. 3310 3311 // Canonicalize shl to left side in a shl/srl pair. 3312 if (RHSShift.getOpcode() == ISD::SHL) { 3313 std::swap(LHS, RHS); 3314 std::swap(LHSShift, RHSShift); 3315 std::swap(LHSMask , RHSMask ); 3316 } 3317 3318 unsigned OpSizeInBits = VT.getSizeInBits(); 3319 SDValue LHSShiftArg = LHSShift.getOperand(0); 3320 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3321 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3322 3323 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3324 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3325 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3326 RHSShiftAmt.getOpcode() == ISD::Constant) { 3327 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3328 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3329 if ((LShVal + RShVal) != OpSizeInBits) 3330 return 0; 3331 3332 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3333 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3334 3335 // If there is an AND of either shifted operand, apply it to the result. 3336 if (LHSMask.getNode() || RHSMask.getNode()) { 3337 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3338 3339 if (LHSMask.getNode()) { 3340 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3341 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3342 } 3343 if (RHSMask.getNode()) { 3344 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3345 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3346 } 3347 3348 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3349 } 3350 3351 return Rot.getNode(); 3352 } 3353 3354 // If there is a mask here, and we have a variable shift, we can't be sure 3355 // that we're masking out the right stuff. 3356 if (LHSMask.getNode() || RHSMask.getNode()) 3357 return 0; 3358 3359 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y) 3360 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y)) 3361 if (RHSShiftAmt.getOpcode() == ISD::SUB && 3362 LHSShiftAmt == RHSShiftAmt.getOperand(1)) { 3363 if (ConstantSDNode *SUBC = 3364 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) { 3365 if (SUBC->getAPIntValue() == OpSizeInBits) 3366 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg, 3367 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 3368 } 3369 } 3370 3371 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y) 3372 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y)) 3373 if (LHSShiftAmt.getOpcode() == ISD::SUB && 3374 RHSShiftAmt == LHSShiftAmt.getOperand(1)) 3375 if (ConstantSDNode *SUBC = 3376 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) 3377 if (SUBC->getAPIntValue() == OpSizeInBits) 3378 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg, 3379 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 3380 3381 // Look for sign/zext/any-extended or truncate cases: 3382 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3383 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3384 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3385 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3386 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3387 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3388 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3389 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3390 SDValue LExtOp0 = LHSShiftAmt.getOperand(0); 3391 SDValue RExtOp0 = RHSShiftAmt.getOperand(0); 3392 if (RExtOp0.getOpcode() == ISD::SUB && 3393 RExtOp0.getOperand(1) == LExtOp0) { 3394 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3395 // (rotl x, y) 3396 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3397 // (rotr x, (sub 32, y)) 3398 if (ConstantSDNode *SUBC = 3399 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) 3400 if (SUBC->getAPIntValue() == OpSizeInBits) 3401 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3402 LHSShiftArg, 3403 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 3404 } else if (LExtOp0.getOpcode() == ISD::SUB && 3405 RExtOp0 == LExtOp0.getOperand(1)) { 3406 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3407 // (rotr x, y) 3408 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3409 // (rotl x, (sub 32, y)) 3410 if (ConstantSDNode *SUBC = 3411 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) 3412 if (SUBC->getAPIntValue() == OpSizeInBits) 3413 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, 3414 LHSShiftArg, 3415 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 3416 } 3417 } 3418 3419 return 0; 3420} 3421 3422SDValue DAGCombiner::visitXOR(SDNode *N) { 3423 SDValue N0 = N->getOperand(0); 3424 SDValue N1 = N->getOperand(1); 3425 SDValue LHS, RHS, CC; 3426 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3427 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3428 EVT VT = N0.getValueType(); 3429 3430 // fold vector ops 3431 if (VT.isVector()) { 3432 SDValue FoldedVOp = SimplifyVBinOp(N); 3433 if (FoldedVOp.getNode()) return FoldedVOp; 3434 3435 // fold (xor x, 0) -> x, vector edition 3436 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3437 return N1; 3438 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3439 return N0; 3440 } 3441 3442 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3443 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3444 return DAG.getConstant(0, VT); 3445 // fold (xor x, undef) -> undef 3446 if (N0.getOpcode() == ISD::UNDEF) 3447 return N0; 3448 if (N1.getOpcode() == ISD::UNDEF) 3449 return N1; 3450 // fold (xor c1, c2) -> c1^c2 3451 if (N0C && N1C) 3452 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3453 // canonicalize constant to RHS 3454 if (N0C && !N1C) 3455 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3456 // fold (xor x, 0) -> x 3457 if (N1C && N1C->isNullValue()) 3458 return N0; 3459 // reassociate xor 3460 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3461 if (RXOR.getNode() != 0) 3462 return RXOR; 3463 3464 // fold !(x cc y) -> (x !cc y) 3465 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3466 bool isInt = LHS.getValueType().isInteger(); 3467 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3468 isInt); 3469 3470 if (!LegalOperations || 3471 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3472 switch (N0.getOpcode()) { 3473 default: 3474 llvm_unreachable("Unhandled SetCC Equivalent!"); 3475 case ISD::SETCC: 3476 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3477 case ISD::SELECT_CC: 3478 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3479 N0.getOperand(3), NotCC); 3480 } 3481 } 3482 } 3483 3484 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3485 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3486 N0.getNode()->hasOneUse() && 3487 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3488 SDValue V = N0.getOperand(0); 3489 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3490 DAG.getConstant(1, V.getValueType())); 3491 AddToWorkList(V.getNode()); 3492 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3493 } 3494 3495 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3496 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3497 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3498 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3499 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3500 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3501 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3502 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3503 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3504 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3505 } 3506 } 3507 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3508 if (N1C && N1C->isAllOnesValue() && 3509 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3510 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3511 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3512 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3513 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3514 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3515 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3516 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3517 } 3518 } 3519 // fold (xor (and x, y), y) -> (and (not x), y) 3520 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3521 N0->getOperand(1) == N1) { 3522 SDValue X = N0->getOperand(0); 3523 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3524 AddToWorkList(NotX.getNode()); 3525 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3526 } 3527 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3528 if (N1C && N0.getOpcode() == ISD::XOR) { 3529 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3530 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3531 if (N00C) 3532 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3533 DAG.getConstant(N1C->getAPIntValue() ^ 3534 N00C->getAPIntValue(), VT)); 3535 if (N01C) 3536 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3537 DAG.getConstant(N1C->getAPIntValue() ^ 3538 N01C->getAPIntValue(), VT)); 3539 } 3540 // fold (xor x, x) -> 0 3541 if (N0 == N1) 3542 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3543 3544 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3545 if (N0.getOpcode() == N1.getOpcode()) { 3546 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3547 if (Tmp.getNode()) return Tmp; 3548 } 3549 3550 // Simplify the expression using non-local knowledge. 3551 if (!VT.isVector() && 3552 SimplifyDemandedBits(SDValue(N, 0))) 3553 return SDValue(N, 0); 3554 3555 return SDValue(); 3556} 3557 3558/// visitShiftByConstant - Handle transforms common to the three shifts, when 3559/// the shift amount is a constant. 3560SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 3561 SDNode *LHS = N->getOperand(0).getNode(); 3562 if (!LHS->hasOneUse()) return SDValue(); 3563 3564 // We want to pull some binops through shifts, so that we have (and (shift)) 3565 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3566 // thing happens with address calculations, so it's important to canonicalize 3567 // it. 3568 bool HighBitSet = false; // Can we transform this if the high bit is set? 3569 3570 switch (LHS->getOpcode()) { 3571 default: return SDValue(); 3572 case ISD::OR: 3573 case ISD::XOR: 3574 HighBitSet = false; // We can only transform sra if the high bit is clear. 3575 break; 3576 case ISD::AND: 3577 HighBitSet = true; // We can only transform sra if the high bit is set. 3578 break; 3579 case ISD::ADD: 3580 if (N->getOpcode() != ISD::SHL) 3581 return SDValue(); // only shl(add) not sr[al](add). 3582 HighBitSet = false; // We can only transform sra if the high bit is clear. 3583 break; 3584 } 3585 3586 // We require the RHS of the binop to be a constant as well. 3587 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3588 if (!BinOpCst) return SDValue(); 3589 3590 // FIXME: disable this unless the input to the binop is a shift by a constant. 3591 // If it is not a shift, it pessimizes some common cases like: 3592 // 3593 // void foo(int *X, int i) { X[i & 1235] = 1; } 3594 // int bar(int *X, int i) { return X[i & 255]; } 3595 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3596 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3597 BinOpLHSVal->getOpcode() != ISD::SRA && 3598 BinOpLHSVal->getOpcode() != ISD::SRL) || 3599 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3600 return SDValue(); 3601 3602 EVT VT = N->getValueType(0); 3603 3604 // If this is a signed shift right, and the high bit is modified by the 3605 // logical operation, do not perform the transformation. The highBitSet 3606 // boolean indicates the value of the high bit of the constant which would 3607 // cause it to be modified for this operation. 3608 if (N->getOpcode() == ISD::SRA) { 3609 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3610 if (BinOpRHSSignSet != HighBitSet) 3611 return SDValue(); 3612 } 3613 3614 // Fold the constants, shifting the binop RHS by the shift amount. 3615 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 3616 N->getValueType(0), 3617 LHS->getOperand(1), N->getOperand(1)); 3618 3619 // Create the new shift. 3620 SDValue NewShift = DAG.getNode(N->getOpcode(), 3621 SDLoc(LHS->getOperand(0)), 3622 VT, LHS->getOperand(0), N->getOperand(1)); 3623 3624 // Create the new binop. 3625 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 3626} 3627 3628SDValue DAGCombiner::visitSHL(SDNode *N) { 3629 SDValue N0 = N->getOperand(0); 3630 SDValue N1 = N->getOperand(1); 3631 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3632 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3633 EVT VT = N0.getValueType(); 3634 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3635 3636 // fold (shl c1, c2) -> c1<<c2 3637 if (N0C && N1C) 3638 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3639 // fold (shl 0, x) -> 0 3640 if (N0C && N0C->isNullValue()) 3641 return N0; 3642 // fold (shl x, c >= size(x)) -> undef 3643 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3644 return DAG.getUNDEF(VT); 3645 // fold (shl x, 0) -> x 3646 if (N1C && N1C->isNullValue()) 3647 return N0; 3648 // fold (shl undef, x) -> 0 3649 if (N0.getOpcode() == ISD::UNDEF) 3650 return DAG.getConstant(0, VT); 3651 // if (shl x, c) is known to be zero, return 0 3652 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3653 APInt::getAllOnesValue(OpSizeInBits))) 3654 return DAG.getConstant(0, VT); 3655 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3656 if (N1.getOpcode() == ISD::TRUNCATE && 3657 N1.getOperand(0).getOpcode() == ISD::AND && 3658 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3659 SDValue N101 = N1.getOperand(0).getOperand(1); 3660 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3661 EVT TruncVT = N1.getValueType(); 3662 SDValue N100 = N1.getOperand(0).getOperand(0); 3663 APInt TruncC = N101C->getAPIntValue(); 3664 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3665 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 3666 DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 3667 DAG.getNode(ISD::TRUNCATE, 3668 SDLoc(N), 3669 TruncVT, N100), 3670 DAG.getConstant(TruncC, TruncVT))); 3671 } 3672 } 3673 3674 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3675 return SDValue(N, 0); 3676 3677 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3678 if (N1C && N0.getOpcode() == ISD::SHL && 3679 N0.getOperand(1).getOpcode() == ISD::Constant) { 3680 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3681 uint64_t c2 = N1C->getZExtValue(); 3682 if (c1 + c2 >= OpSizeInBits) 3683 return DAG.getConstant(0, VT); 3684 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3685 DAG.getConstant(c1 + c2, N1.getValueType())); 3686 } 3687 3688 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3689 // For this to be valid, the second form must not preserve any of the bits 3690 // that are shifted out by the inner shift in the first form. This means 3691 // the outer shift size must be >= the number of bits added by the ext. 3692 // As a corollary, we don't care what kind of ext it is. 3693 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3694 N0.getOpcode() == ISD::ANY_EXTEND || 3695 N0.getOpcode() == ISD::SIGN_EXTEND) && 3696 N0.getOperand(0).getOpcode() == ISD::SHL && 3697 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3698 uint64_t c1 = 3699 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3700 uint64_t c2 = N1C->getZExtValue(); 3701 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3702 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3703 if (c2 >= OpSizeInBits - InnerShiftSize) { 3704 if (c1 + c2 >= OpSizeInBits) 3705 return DAG.getConstant(0, VT); 3706 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 3707 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 3708 N0.getOperand(0)->getOperand(0)), 3709 DAG.getConstant(c1 + c2, N1.getValueType())); 3710 } 3711 } 3712 3713 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 3714 // (and (srl x, (sub c1, c2), MASK) 3715 // Only fold this if the inner shift has no other uses -- if it does, folding 3716 // this will increase the total number of instructions. 3717 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 3718 N0.getOperand(1).getOpcode() == ISD::Constant) { 3719 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3720 if (c1 < VT.getSizeInBits()) { 3721 uint64_t c2 = N1C->getZExtValue(); 3722 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3723 VT.getSizeInBits() - c1); 3724 SDValue Shift; 3725 if (c2 > c1) { 3726 Mask = Mask.shl(c2-c1); 3727 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3728 DAG.getConstant(c2-c1, N1.getValueType())); 3729 } else { 3730 Mask = Mask.lshr(c1-c2); 3731 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 3732 DAG.getConstant(c1-c2, N1.getValueType())); 3733 } 3734 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 3735 DAG.getConstant(Mask, VT)); 3736 } 3737 } 3738 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 3739 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 3740 SDValue HiBitsMask = 3741 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 3742 VT.getSizeInBits() - 3743 N1C->getZExtValue()), 3744 VT); 3745 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 3746 HiBitsMask); 3747 } 3748 3749 if (N1C) { 3750 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 3751 if (NewSHL.getNode()) 3752 return NewSHL; 3753 } 3754 3755 return SDValue(); 3756} 3757 3758SDValue DAGCombiner::visitSRA(SDNode *N) { 3759 SDValue N0 = N->getOperand(0); 3760 SDValue N1 = N->getOperand(1); 3761 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3762 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3763 EVT VT = N0.getValueType(); 3764 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3765 3766 // fold (sra c1, c2) -> (sra c1, c2) 3767 if (N0C && N1C) 3768 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 3769 // fold (sra 0, x) -> 0 3770 if (N0C && N0C->isNullValue()) 3771 return N0; 3772 // fold (sra -1, x) -> -1 3773 if (N0C && N0C->isAllOnesValue()) 3774 return N0; 3775 // fold (sra x, (setge c, size(x))) -> undef 3776 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3777 return DAG.getUNDEF(VT); 3778 // fold (sra x, 0) -> x 3779 if (N1C && N1C->isNullValue()) 3780 return N0; 3781 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 3782 // sext_inreg. 3783 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 3784 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 3785 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 3786 if (VT.isVector()) 3787 ExtVT = EVT::getVectorVT(*DAG.getContext(), 3788 ExtVT, VT.getVectorNumElements()); 3789 if ((!LegalOperations || 3790 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 3791 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 3792 N0.getOperand(0), DAG.getValueType(ExtVT)); 3793 } 3794 3795 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 3796 if (N1C && N0.getOpcode() == ISD::SRA) { 3797 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3798 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 3799 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 3800 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 3801 DAG.getConstant(Sum, N1C->getValueType(0))); 3802 } 3803 } 3804 3805 // fold (sra (shl X, m), (sub result_size, n)) 3806 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 3807 // result_size - n != m. 3808 // If truncate is free for the target sext(shl) is likely to result in better 3809 // code. 3810 if (N0.getOpcode() == ISD::SHL) { 3811 // Get the two constanst of the shifts, CN0 = m, CN = n. 3812 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3813 if (N01C && N1C) { 3814 // Determine what the truncate's result bitsize and type would be. 3815 EVT TruncVT = 3816 EVT::getIntegerVT(*DAG.getContext(), 3817 OpSizeInBits - N1C->getZExtValue()); 3818 // Determine the residual right-shift amount. 3819 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 3820 3821 // If the shift is not a no-op (in which case this should be just a sign 3822 // extend already), the truncated to type is legal, sign_extend is legal 3823 // on that type, and the truncate to that type is both legal and free, 3824 // perform the transform. 3825 if ((ShiftAmt > 0) && 3826 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 3827 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 3828 TLI.isTruncateFree(VT, TruncVT)) { 3829 3830 SDValue Amt = DAG.getConstant(ShiftAmt, 3831 getShiftAmountTy(N0.getOperand(0).getValueType())); 3832 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 3833 N0.getOperand(0), Amt); 3834 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 3835 Shift); 3836 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 3837 N->getValueType(0), Trunc); 3838 } 3839 } 3840 } 3841 3842 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 3843 if (N1.getOpcode() == ISD::TRUNCATE && 3844 N1.getOperand(0).getOpcode() == ISD::AND && 3845 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3846 SDValue N101 = N1.getOperand(0).getOperand(1); 3847 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3848 EVT TruncVT = N1.getValueType(); 3849 SDValue N100 = N1.getOperand(0).getOperand(0); 3850 APInt TruncC = N101C->getAPIntValue(); 3851 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 3852 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 3853 DAG.getNode(ISD::AND, SDLoc(N), 3854 TruncVT, 3855 DAG.getNode(ISD::TRUNCATE, 3856 SDLoc(N), 3857 TruncVT, N100), 3858 DAG.getConstant(TruncC, TruncVT))); 3859 } 3860 } 3861 3862 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2)) 3863 // if c1 is equal to the number of bits the trunc removes 3864 if (N0.getOpcode() == ISD::TRUNCATE && 3865 (N0.getOperand(0).getOpcode() == ISD::SRL || 3866 N0.getOperand(0).getOpcode() == ISD::SRA) && 3867 N0.getOperand(0).hasOneUse() && 3868 N0.getOperand(0).getOperand(1).hasOneUse() && 3869 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 3870 EVT LargeVT = N0.getOperand(0).getValueType(); 3871 ConstantSDNode *LargeShiftAmt = 3872 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1)); 3873 3874 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits == 3875 LargeShiftAmt->getZExtValue()) { 3876 SDValue Amt = 3877 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(), 3878 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType())); 3879 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 3880 N0.getOperand(0).getOperand(0), Amt); 3881 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 3882 } 3883 } 3884 3885 // Simplify, based on bits shifted out of the LHS. 3886 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3887 return SDValue(N, 0); 3888 3889 3890 // If the sign bit is known to be zero, switch this to a SRL. 3891 if (DAG.SignBitIsZero(N0)) 3892 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 3893 3894 if (N1C) { 3895 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 3896 if (NewSRA.getNode()) 3897 return NewSRA; 3898 } 3899 3900 return SDValue(); 3901} 3902 3903SDValue DAGCombiner::visitSRL(SDNode *N) { 3904 SDValue N0 = N->getOperand(0); 3905 SDValue N1 = N->getOperand(1); 3906 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3907 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3908 EVT VT = N0.getValueType(); 3909 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3910 3911 // fold (srl c1, c2) -> c1 >>u c2 3912 if (N0C && N1C) 3913 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 3914 // fold (srl 0, x) -> 0 3915 if (N0C && N0C->isNullValue()) 3916 return N0; 3917 // fold (srl x, c >= size(x)) -> undef 3918 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3919 return DAG.getUNDEF(VT); 3920 // fold (srl x, 0) -> x 3921 if (N1C && N1C->isNullValue()) 3922 return N0; 3923 // if (srl x, c) is known to be zero, return 0 3924 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3925 APInt::getAllOnesValue(OpSizeInBits))) 3926 return DAG.getConstant(0, VT); 3927 3928 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 3929 if (N1C && N0.getOpcode() == ISD::SRL && 3930 N0.getOperand(1).getOpcode() == ISD::Constant) { 3931 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3932 uint64_t c2 = N1C->getZExtValue(); 3933 if (c1 + c2 >= OpSizeInBits) 3934 return DAG.getConstant(0, VT); 3935 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 3936 DAG.getConstant(c1 + c2, N1.getValueType())); 3937 } 3938 3939 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 3940 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 3941 N0.getOperand(0).getOpcode() == ISD::SRL && 3942 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3943 uint64_t c1 = 3944 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3945 uint64_t c2 = N1C->getZExtValue(); 3946 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3947 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 3948 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3949 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 3950 if (c1 + OpSizeInBits == InnerShiftSize) { 3951 if (c1 + c2 >= InnerShiftSize) 3952 return DAG.getConstant(0, VT); 3953 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 3954 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 3955 N0.getOperand(0)->getOperand(0), 3956 DAG.getConstant(c1 + c2, ShiftCountVT))); 3957 } 3958 } 3959 3960 // fold (srl (shl x, c), c) -> (and x, cst2) 3961 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 3962 N0.getValueSizeInBits() <= 64) { 3963 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 3964 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 3965 DAG.getConstant(~0ULL >> ShAmt, VT)); 3966 } 3967 3968 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 3969 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3970 // Shifting in all undef bits? 3971 EVT SmallVT = N0.getOperand(0).getValueType(); 3972 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 3973 return DAG.getUNDEF(VT); 3974 3975 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 3976 uint64_t ShiftAmt = N1C->getZExtValue(); 3977 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 3978 N0.getOperand(0), 3979 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 3980 AddToWorkList(SmallShift.getNode()); 3981 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt); 3982 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3983 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 3984 DAG.getConstant(Mask, VT)); 3985 } 3986 } 3987 3988 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 3989 // bit, which is unmodified by sra. 3990 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 3991 if (N0.getOpcode() == ISD::SRA) 3992 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 3993 } 3994 3995 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 3996 if (N1C && N0.getOpcode() == ISD::CTLZ && 3997 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 3998 APInt KnownZero, KnownOne; 3999 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 4000 4001 // If any of the input bits are KnownOne, then the input couldn't be all 4002 // zeros, thus the result of the srl will always be zero. 4003 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4004 4005 // If all of the bits input the to ctlz node are known to be zero, then 4006 // the result of the ctlz is "32" and the result of the shift is one. 4007 APInt UnknownBits = ~KnownZero; 4008 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4009 4010 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4011 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4012 // Okay, we know that only that the single bit specified by UnknownBits 4013 // could be set on input to the CTLZ node. If this bit is set, the SRL 4014 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4015 // to an SRL/XOR pair, which is likely to simplify more. 4016 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4017 SDValue Op = N0.getOperand(0); 4018 4019 if (ShAmt) { 4020 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4021 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4022 AddToWorkList(Op.getNode()); 4023 } 4024 4025 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4026 Op, DAG.getConstant(1, VT)); 4027 } 4028 } 4029 4030 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4031 if (N1.getOpcode() == ISD::TRUNCATE && 4032 N1.getOperand(0).getOpcode() == ISD::AND && 4033 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 4034 SDValue N101 = N1.getOperand(0).getOperand(1); 4035 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 4036 EVT TruncVT = N1.getValueType(); 4037 SDValue N100 = N1.getOperand(0).getOperand(0); 4038 APInt TruncC = N101C->getAPIntValue(); 4039 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 4040 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 4041 DAG.getNode(ISD::AND, SDLoc(N), 4042 TruncVT, 4043 DAG.getNode(ISD::TRUNCATE, 4044 SDLoc(N), 4045 TruncVT, N100), 4046 DAG.getConstant(TruncC, TruncVT))); 4047 } 4048 } 4049 4050 // fold operands of srl based on knowledge that the low bits are not 4051 // demanded. 4052 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4053 return SDValue(N, 0); 4054 4055 if (N1C) { 4056 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 4057 if (NewSRL.getNode()) 4058 return NewSRL; 4059 } 4060 4061 // Attempt to convert a srl of a load into a narrower zero-extending load. 4062 SDValue NarrowLoad = ReduceLoadWidth(N); 4063 if (NarrowLoad.getNode()) 4064 return NarrowLoad; 4065 4066 // Here is a common situation. We want to optimize: 4067 // 4068 // %a = ... 4069 // %b = and i32 %a, 2 4070 // %c = srl i32 %b, 1 4071 // brcond i32 %c ... 4072 // 4073 // into 4074 // 4075 // %a = ... 4076 // %b = and %a, 2 4077 // %c = setcc eq %b, 0 4078 // brcond %c ... 4079 // 4080 // However when after the source operand of SRL is optimized into AND, the SRL 4081 // itself may not be optimized further. Look for it and add the BRCOND into 4082 // the worklist. 4083 if (N->hasOneUse()) { 4084 SDNode *Use = *N->use_begin(); 4085 if (Use->getOpcode() == ISD::BRCOND) 4086 AddToWorkList(Use); 4087 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4088 // Also look pass the truncate. 4089 Use = *Use->use_begin(); 4090 if (Use->getOpcode() == ISD::BRCOND) 4091 AddToWorkList(Use); 4092 } 4093 } 4094 4095 return SDValue(); 4096} 4097 4098SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4099 SDValue N0 = N->getOperand(0); 4100 EVT VT = N->getValueType(0); 4101 4102 // fold (ctlz c1) -> c2 4103 if (isa<ConstantSDNode>(N0)) 4104 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4105 return SDValue(); 4106} 4107 4108SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4109 SDValue N0 = N->getOperand(0); 4110 EVT VT = N->getValueType(0); 4111 4112 // fold (ctlz_zero_undef c1) -> c2 4113 if (isa<ConstantSDNode>(N0)) 4114 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4115 return SDValue(); 4116} 4117 4118SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4119 SDValue N0 = N->getOperand(0); 4120 EVT VT = N->getValueType(0); 4121 4122 // fold (cttz c1) -> c2 4123 if (isa<ConstantSDNode>(N0)) 4124 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4125 return SDValue(); 4126} 4127 4128SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4129 SDValue N0 = N->getOperand(0); 4130 EVT VT = N->getValueType(0); 4131 4132 // fold (cttz_zero_undef c1) -> c2 4133 if (isa<ConstantSDNode>(N0)) 4134 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4135 return SDValue(); 4136} 4137 4138SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4139 SDValue N0 = N->getOperand(0); 4140 EVT VT = N->getValueType(0); 4141 4142 // fold (ctpop c1) -> c2 4143 if (isa<ConstantSDNode>(N0)) 4144 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4145 return SDValue(); 4146} 4147 4148SDValue DAGCombiner::visitSELECT(SDNode *N) { 4149 SDValue N0 = N->getOperand(0); 4150 SDValue N1 = N->getOperand(1); 4151 SDValue N2 = N->getOperand(2); 4152 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4153 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4154 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4155 EVT VT = N->getValueType(0); 4156 EVT VT0 = N0.getValueType(); 4157 4158 // fold (select C, X, X) -> X 4159 if (N1 == N2) 4160 return N1; 4161 // fold (select true, X, Y) -> X 4162 if (N0C && !N0C->isNullValue()) 4163 return N1; 4164 // fold (select false, X, Y) -> Y 4165 if (N0C && N0C->isNullValue()) 4166 return N2; 4167 // fold (select C, 1, X) -> (or C, X) 4168 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4169 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4170 // fold (select C, 0, 1) -> (xor C, 1) 4171 if (VT.isInteger() && 4172 (VT0 == MVT::i1 || 4173 (VT0.isInteger() && 4174 TLI.getBooleanContents(false) == 4175 TargetLowering::ZeroOrOneBooleanContent)) && 4176 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4177 SDValue XORNode; 4178 if (VT == VT0) 4179 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4180 N0, DAG.getConstant(1, VT0)); 4181 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4182 N0, DAG.getConstant(1, VT0)); 4183 AddToWorkList(XORNode.getNode()); 4184 if (VT.bitsGT(VT0)) 4185 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4186 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4187 } 4188 // fold (select C, 0, X) -> (and (not C), X) 4189 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4190 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4191 AddToWorkList(NOTNode.getNode()); 4192 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4193 } 4194 // fold (select C, X, 1) -> (or (not C), X) 4195 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4196 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4197 AddToWorkList(NOTNode.getNode()); 4198 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4199 } 4200 // fold (select C, X, 0) -> (and C, X) 4201 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4202 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4203 // fold (select X, X, Y) -> (or X, Y) 4204 // fold (select X, 1, Y) -> (or X, Y) 4205 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4206 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4207 // fold (select X, Y, X) -> (and X, Y) 4208 // fold (select X, Y, 0) -> (and X, Y) 4209 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4210 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4211 4212 // If we can fold this based on the true/false value, do so. 4213 if (SimplifySelectOps(N, N1, N2)) 4214 return SDValue(N, 0); // Don't revisit N. 4215 4216 // fold selects based on a setcc into other things, such as min/max/abs 4217 if (N0.getOpcode() == ISD::SETCC) { 4218 // FIXME: 4219 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4220 // having to say they don't support SELECT_CC on every type the DAG knows 4221 // about, since there is no way to mark an opcode illegal at all value types 4222 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4223 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4224 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4225 N0.getOperand(0), N0.getOperand(1), 4226 N1, N2, N0.getOperand(2)); 4227 return SimplifySelect(SDLoc(N), N0, N1, N2); 4228 } 4229 4230 return SDValue(); 4231} 4232 4233SDValue DAGCombiner::visitVSELECT(SDNode *N) { 4234 SDValue N0 = N->getOperand(0); 4235 SDValue N1 = N->getOperand(1); 4236 SDValue N2 = N->getOperand(2); 4237 SDLoc DL(N); 4238 4239 // Canonicalize integer abs. 4240 // vselect (setg[te] X, 0), X, -X -> 4241 // vselect (setgt X, -1), X, -X -> 4242 // vselect (setl[te] X, 0), -X, X -> 4243 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 4244 if (N0.getOpcode() == ISD::SETCC) { 4245 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4246 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4247 bool isAbs = false; 4248 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 4249 4250 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 4251 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 4252 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 4253 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 4254 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 4255 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 4256 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4257 4258 if (isAbs) { 4259 EVT VT = LHS.getValueType(); 4260 SDValue Shift = DAG.getNode( 4261 ISD::SRA, DL, VT, LHS, 4262 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 4263 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 4264 AddToWorkList(Shift.getNode()); 4265 AddToWorkList(Add.getNode()); 4266 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 4267 } 4268 } 4269 4270 return SDValue(); 4271} 4272 4273SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4274 SDValue N0 = N->getOperand(0); 4275 SDValue N1 = N->getOperand(1); 4276 SDValue N2 = N->getOperand(2); 4277 SDValue N3 = N->getOperand(3); 4278 SDValue N4 = N->getOperand(4); 4279 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4280 4281 // fold select_cc lhs, rhs, x, x, cc -> x 4282 if (N2 == N3) 4283 return N2; 4284 4285 // Determine if the condition we're dealing with is constant 4286 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 4287 N0, N1, CC, SDLoc(N), false); 4288 if (SCC.getNode()) { 4289 AddToWorkList(SCC.getNode()); 4290 4291 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 4292 if (!SCCC->isNullValue()) 4293 return N2; // cond always true -> true val 4294 else 4295 return N3; // cond always false -> false val 4296 } 4297 4298 // Fold to a simpler select_cc 4299 if (SCC.getOpcode() == ISD::SETCC) 4300 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 4301 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4302 SCC.getOperand(2)); 4303 } 4304 4305 // If we can fold this based on the true/false value, do so. 4306 if (SimplifySelectOps(N, N2, N3)) 4307 return SDValue(N, 0); // Don't revisit N. 4308 4309 // fold select_cc into other things, such as min/max/abs 4310 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 4311} 4312 4313SDValue DAGCombiner::visitSETCC(SDNode *N) { 4314 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4315 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4316 SDLoc(N)); 4317} 4318 4319// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4320// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4321// transformation. Returns true if extension are possible and the above 4322// mentioned transformation is profitable. 4323static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4324 unsigned ExtOpc, 4325 SmallVectorImpl<SDNode *> &ExtendNodes, 4326 const TargetLowering &TLI) { 4327 bool HasCopyToRegUses = false; 4328 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4329 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4330 UE = N0.getNode()->use_end(); 4331 UI != UE; ++UI) { 4332 SDNode *User = *UI; 4333 if (User == N) 4334 continue; 4335 if (UI.getUse().getResNo() != N0.getResNo()) 4336 continue; 4337 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4338 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4339 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4340 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4341 // Sign bits will be lost after a zext. 4342 return false; 4343 bool Add = false; 4344 for (unsigned i = 0; i != 2; ++i) { 4345 SDValue UseOp = User->getOperand(i); 4346 if (UseOp == N0) 4347 continue; 4348 if (!isa<ConstantSDNode>(UseOp)) 4349 return false; 4350 Add = true; 4351 } 4352 if (Add) 4353 ExtendNodes.push_back(User); 4354 continue; 4355 } 4356 // If truncates aren't free and there are users we can't 4357 // extend, it isn't worthwhile. 4358 if (!isTruncFree) 4359 return false; 4360 // Remember if this value is live-out. 4361 if (User->getOpcode() == ISD::CopyToReg) 4362 HasCopyToRegUses = true; 4363 } 4364 4365 if (HasCopyToRegUses) { 4366 bool BothLiveOut = false; 4367 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4368 UI != UE; ++UI) { 4369 SDUse &Use = UI.getUse(); 4370 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4371 BothLiveOut = true; 4372 break; 4373 } 4374 } 4375 if (BothLiveOut) 4376 // Both unextended and extended values are live out. There had better be 4377 // a good reason for the transformation. 4378 return ExtendNodes.size(); 4379 } 4380 return true; 4381} 4382 4383void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 4384 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 4385 ISD::NodeType ExtType) { 4386 // Extend SetCC uses if necessary. 4387 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4388 SDNode *SetCC = SetCCs[i]; 4389 SmallVector<SDValue, 4> Ops; 4390 4391 for (unsigned j = 0; j != 2; ++j) { 4392 SDValue SOp = SetCC->getOperand(j); 4393 if (SOp == Trunc) 4394 Ops.push_back(ExtLoad); 4395 else 4396 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4397 } 4398 4399 Ops.push_back(SetCC->getOperand(2)); 4400 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4401 &Ops[0], Ops.size())); 4402 } 4403} 4404 4405SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4406 SDValue N0 = N->getOperand(0); 4407 EVT VT = N->getValueType(0); 4408 4409 // fold (sext c1) -> c1 4410 if (isa<ConstantSDNode>(N0)) 4411 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0); 4412 4413 // fold (sext (sext x)) -> (sext x) 4414 // fold (sext (aext x)) -> (sext x) 4415 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4416 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 4417 N0.getOperand(0)); 4418 4419 if (N0.getOpcode() == ISD::TRUNCATE) { 4420 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4421 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4422 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4423 if (NarrowLoad.getNode()) { 4424 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4425 if (NarrowLoad.getNode() != N0.getNode()) { 4426 CombineTo(N0.getNode(), NarrowLoad); 4427 // CombineTo deleted the truncate, if needed, but not what's under it. 4428 AddToWorkList(oye); 4429 } 4430 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4431 } 4432 4433 // See if the value being truncated is already sign extended. If so, just 4434 // eliminate the trunc/sext pair. 4435 SDValue Op = N0.getOperand(0); 4436 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4437 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4438 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4439 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4440 4441 if (OpBits == DestBits) { 4442 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4443 // bits, it is already ready. 4444 if (NumSignBits > DestBits-MidBits) 4445 return Op; 4446 } else if (OpBits < DestBits) { 4447 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4448 // bits, just sext from i32. 4449 if (NumSignBits > OpBits-MidBits) 4450 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 4451 } else { 4452 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4453 // bits, just truncate to i32. 4454 if (NumSignBits > OpBits-MidBits) 4455 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4456 } 4457 4458 // fold (sext (truncate x)) -> (sextinreg x). 4459 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4460 N0.getValueType())) { 4461 if (OpBits < DestBits) 4462 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 4463 else if (OpBits > DestBits) 4464 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 4465 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 4466 DAG.getValueType(N0.getValueType())); 4467 } 4468 } 4469 4470 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4471 // None of the supported targets knows how to perform load and sign extend 4472 // on vectors in one instruction. We only perform this transformation on 4473 // scalars. 4474 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4475 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4476 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4477 bool DoXform = true; 4478 SmallVector<SDNode*, 4> SetCCs; 4479 if (!N0.hasOneUse()) 4480 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4481 if (DoXform) { 4482 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4483 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4484 LN0->getChain(), 4485 LN0->getBasePtr(), LN0->getPointerInfo(), 4486 N0.getValueType(), 4487 LN0->isVolatile(), LN0->isNonTemporal(), 4488 LN0->getAlignment()); 4489 CombineTo(N, ExtLoad); 4490 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4491 N0.getValueType(), ExtLoad); 4492 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4493 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4494 ISD::SIGN_EXTEND); 4495 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4496 } 4497 } 4498 4499 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4500 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4501 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4502 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4503 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4504 EVT MemVT = LN0->getMemoryVT(); 4505 if ((!LegalOperations && !LN0->isVolatile()) || 4506 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4507 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4508 LN0->getChain(), 4509 LN0->getBasePtr(), LN0->getPointerInfo(), 4510 MemVT, 4511 LN0->isVolatile(), LN0->isNonTemporal(), 4512 LN0->getAlignment()); 4513 CombineTo(N, ExtLoad); 4514 CombineTo(N0.getNode(), 4515 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4516 N0.getValueType(), ExtLoad), 4517 ExtLoad.getValue(1)); 4518 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4519 } 4520 } 4521 4522 // fold (sext (and/or/xor (load x), cst)) -> 4523 // (and/or/xor (sextload x), (sext cst)) 4524 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4525 N0.getOpcode() == ISD::XOR) && 4526 isa<LoadSDNode>(N0.getOperand(0)) && 4527 N0.getOperand(1).getOpcode() == ISD::Constant && 4528 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4529 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4530 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4531 if (LN0->getExtensionType() != ISD::ZEXTLOAD) { 4532 bool DoXform = true; 4533 SmallVector<SDNode*, 4> SetCCs; 4534 if (!N0.hasOneUse()) 4535 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4536 SetCCs, TLI); 4537 if (DoXform) { 4538 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 4539 LN0->getChain(), LN0->getBasePtr(), 4540 LN0->getPointerInfo(), 4541 LN0->getMemoryVT(), 4542 LN0->isVolatile(), 4543 LN0->isNonTemporal(), 4544 LN0->getAlignment()); 4545 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4546 Mask = Mask.sext(VT.getSizeInBits()); 4547 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 4548 ExtLoad, DAG.getConstant(Mask, VT)); 4549 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4550 SDLoc(N0.getOperand(0)), 4551 N0.getOperand(0).getValueType(), ExtLoad); 4552 CombineTo(N, And); 4553 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4554 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4555 ISD::SIGN_EXTEND); 4556 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4557 } 4558 } 4559 } 4560 4561 if (N0.getOpcode() == ISD::SETCC) { 4562 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4563 // Only do this before legalize for now. 4564 if (VT.isVector() && !LegalOperations && 4565 TLI.getBooleanContents(true) == 4566 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4567 EVT N0VT = N0.getOperand(0).getValueType(); 4568 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 4569 // of the same size as the compared operands. Only optimize sext(setcc()) 4570 // if this is the case. 4571 EVT SVT = getSetCCResultType(N0VT); 4572 4573 // We know that the # elements of the results is the same as the 4574 // # elements of the compare (and the # elements of the compare result 4575 // for that matter). Check to see that they are the same size. If so, 4576 // we know that the element size of the sext'd result matches the 4577 // element size of the compare operands. 4578 if (VT.getSizeInBits() == SVT.getSizeInBits()) 4579 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 4580 N0.getOperand(1), 4581 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4582 4583 // If the desired elements are smaller or larger than the source 4584 // elements we can use a matching integer vector type and then 4585 // truncate/sign extend 4586 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 4587 if (SVT == MatchingVectorType) { 4588 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 4589 N0.getOperand(0), N0.getOperand(1), 4590 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4591 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 4592 } 4593 } 4594 4595 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc) 4596 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 4597 SDValue NegOne = 4598 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 4599 SDValue SCC = 4600 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 4601 NegOne, DAG.getConstant(0, VT), 4602 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4603 if (SCC.getNode()) return SCC; 4604 if (!VT.isVector() && 4605 (!LegalOperations || 4606 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) { 4607 return DAG.getSelect(SDLoc(N), VT, 4608 DAG.getSetCC(SDLoc(N), 4609 getSetCCResultType(VT), 4610 N0.getOperand(0), N0.getOperand(1), 4611 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4612 NegOne, DAG.getConstant(0, VT)); 4613 } 4614 } 4615 4616 // fold (sext x) -> (zext x) if the sign bit is known zero. 4617 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 4618 DAG.SignBitIsZero(N0)) 4619 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 4620 4621 return SDValue(); 4622} 4623 4624// isTruncateOf - If N is a truncate of some other value, return true, record 4625// the value being truncated in Op and which of Op's bits are zero in KnownZero. 4626// This function computes KnownZero to avoid a duplicated call to 4627// ComputeMaskedBits in the caller. 4628static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 4629 APInt &KnownZero) { 4630 APInt KnownOne; 4631 if (N->getOpcode() == ISD::TRUNCATE) { 4632 Op = N->getOperand(0); 4633 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4634 return true; 4635 } 4636 4637 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 4638 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 4639 return false; 4640 4641 SDValue Op0 = N->getOperand(0); 4642 SDValue Op1 = N->getOperand(1); 4643 assert(Op0.getValueType() == Op1.getValueType()); 4644 4645 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 4646 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 4647 if (COp0 && COp0->isNullValue()) 4648 Op = Op1; 4649 else if (COp1 && COp1->isNullValue()) 4650 Op = Op0; 4651 else 4652 return false; 4653 4654 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4655 4656 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 4657 return false; 4658 4659 return true; 4660} 4661 4662SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 4663 SDValue N0 = N->getOperand(0); 4664 EVT VT = N->getValueType(0); 4665 4666 // fold (zext c1) -> c1 4667 if (isa<ConstantSDNode>(N0)) 4668 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 4669 // fold (zext (zext x)) -> (zext x) 4670 // fold (zext (aext x)) -> (zext x) 4671 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4672 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 4673 N0.getOperand(0)); 4674 4675 // fold (zext (truncate x)) -> (zext x) or 4676 // (zext (truncate x)) -> (truncate x) 4677 // This is valid when the truncated bits of x are already zero. 4678 // FIXME: We should extend this to work for vectors too. 4679 SDValue Op; 4680 APInt KnownZero; 4681 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 4682 APInt TruncatedBits = 4683 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 4684 APInt(Op.getValueSizeInBits(), 0) : 4685 APInt::getBitsSet(Op.getValueSizeInBits(), 4686 N0.getValueSizeInBits(), 4687 std::min(Op.getValueSizeInBits(), 4688 VT.getSizeInBits())); 4689 if (TruncatedBits == (KnownZero & TruncatedBits)) { 4690 if (VT.bitsGT(Op.getValueType())) 4691 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 4692 if (VT.bitsLT(Op.getValueType())) 4693 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4694 4695 return Op; 4696 } 4697 } 4698 4699 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4700 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 4701 if (N0.getOpcode() == ISD::TRUNCATE) { 4702 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4703 if (NarrowLoad.getNode()) { 4704 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4705 if (NarrowLoad.getNode() != N0.getNode()) { 4706 CombineTo(N0.getNode(), NarrowLoad); 4707 // CombineTo deleted the truncate, if needed, but not what's under it. 4708 AddToWorkList(oye); 4709 } 4710 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4711 } 4712 } 4713 4714 // fold (zext (truncate x)) -> (and x, mask) 4715 if (N0.getOpcode() == ISD::TRUNCATE && 4716 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 4717 4718 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4719 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 4720 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4721 if (NarrowLoad.getNode()) { 4722 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4723 if (NarrowLoad.getNode() != N0.getNode()) { 4724 CombineTo(N0.getNode(), NarrowLoad); 4725 // CombineTo deleted the truncate, if needed, but not what's under it. 4726 AddToWorkList(oye); 4727 } 4728 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4729 } 4730 4731 SDValue Op = N0.getOperand(0); 4732 if (Op.getValueType().bitsLT(VT)) { 4733 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 4734 AddToWorkList(Op.getNode()); 4735 } else if (Op.getValueType().bitsGT(VT)) { 4736 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4737 AddToWorkList(Op.getNode()); 4738 } 4739 return DAG.getZeroExtendInReg(Op, SDLoc(N), 4740 N0.getValueType().getScalarType()); 4741 } 4742 4743 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 4744 // if either of the casts is not free. 4745 if (N0.getOpcode() == ISD::AND && 4746 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4747 N0.getOperand(1).getOpcode() == ISD::Constant && 4748 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4749 N0.getValueType()) || 4750 !TLI.isZExtFree(N0.getValueType(), VT))) { 4751 SDValue X = N0.getOperand(0).getOperand(0); 4752 if (X.getValueType().bitsLT(VT)) { 4753 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 4754 } else if (X.getValueType().bitsGT(VT)) { 4755 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 4756 } 4757 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4758 Mask = Mask.zext(VT.getSizeInBits()); 4759 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4760 X, DAG.getConstant(Mask, VT)); 4761 } 4762 4763 // fold (zext (load x)) -> (zext (truncate (zextload x))) 4764 // None of the supported targets knows how to perform load and vector_zext 4765 // on vectors in one instruction. We only perform this transformation on 4766 // scalars. 4767 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4768 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4769 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 4770 bool DoXform = true; 4771 SmallVector<SDNode*, 4> SetCCs; 4772 if (!N0.hasOneUse()) 4773 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 4774 if (DoXform) { 4775 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4776 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 4777 LN0->getChain(), 4778 LN0->getBasePtr(), LN0->getPointerInfo(), 4779 N0.getValueType(), 4780 LN0->isVolatile(), LN0->isNonTemporal(), 4781 LN0->getAlignment()); 4782 CombineTo(N, ExtLoad); 4783 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4784 N0.getValueType(), ExtLoad); 4785 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4786 4787 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4788 ISD::ZERO_EXTEND); 4789 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4790 } 4791 } 4792 4793 // fold (zext (and/or/xor (load x), cst)) -> 4794 // (and/or/xor (zextload x), (zext cst)) 4795 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4796 N0.getOpcode() == ISD::XOR) && 4797 isa<LoadSDNode>(N0.getOperand(0)) && 4798 N0.getOperand(1).getOpcode() == ISD::Constant && 4799 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 4800 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4801 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4802 if (LN0->getExtensionType() != ISD::SEXTLOAD) { 4803 bool DoXform = true; 4804 SmallVector<SDNode*, 4> SetCCs; 4805 if (!N0.hasOneUse()) 4806 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 4807 SetCCs, TLI); 4808 if (DoXform) { 4809 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 4810 LN0->getChain(), LN0->getBasePtr(), 4811 LN0->getPointerInfo(), 4812 LN0->getMemoryVT(), 4813 LN0->isVolatile(), 4814 LN0->isNonTemporal(), 4815 LN0->getAlignment()); 4816 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4817 Mask = Mask.zext(VT.getSizeInBits()); 4818 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 4819 ExtLoad, DAG.getConstant(Mask, VT)); 4820 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4821 SDLoc(N0.getOperand(0)), 4822 N0.getOperand(0).getValueType(), ExtLoad); 4823 CombineTo(N, And); 4824 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4825 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4826 ISD::ZERO_EXTEND); 4827 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4828 } 4829 } 4830 } 4831 4832 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 4833 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 4834 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4835 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4836 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4837 EVT MemVT = LN0->getMemoryVT(); 4838 if ((!LegalOperations && !LN0->isVolatile()) || 4839 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 4840 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 4841 LN0->getChain(), 4842 LN0->getBasePtr(), LN0->getPointerInfo(), 4843 MemVT, 4844 LN0->isVolatile(), LN0->isNonTemporal(), 4845 LN0->getAlignment()); 4846 CombineTo(N, ExtLoad); 4847 CombineTo(N0.getNode(), 4848 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 4849 ExtLoad), 4850 ExtLoad.getValue(1)); 4851 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4852 } 4853 } 4854 4855 if (N0.getOpcode() == ISD::SETCC) { 4856 if (!LegalOperations && VT.isVector()) { 4857 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 4858 // Only do this before legalize for now. 4859 EVT N0VT = N0.getOperand(0).getValueType(); 4860 EVT EltVT = VT.getVectorElementType(); 4861 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 4862 DAG.getConstant(1, EltVT)); 4863 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4864 // We know that the # elements of the results is the same as the 4865 // # elements of the compare (and the # elements of the compare result 4866 // for that matter). Check to see that they are the same size. If so, 4867 // we know that the element size of the sext'd result matches the 4868 // element size of the compare operands. 4869 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4870 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 4871 N0.getOperand(1), 4872 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4873 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 4874 &OneOps[0], OneOps.size())); 4875 4876 // If the desired elements are smaller or larger than the source 4877 // elements we can use a matching integer vector type and then 4878 // truncate/sign extend 4879 EVT MatchingElementType = 4880 EVT::getIntegerVT(*DAG.getContext(), 4881 N0VT.getScalarType().getSizeInBits()); 4882 EVT MatchingVectorType = 4883 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4884 N0VT.getVectorNumElements()); 4885 SDValue VsetCC = 4886 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 4887 N0.getOperand(1), 4888 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4889 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4890 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 4891 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 4892 &OneOps[0], OneOps.size())); 4893 } 4894 4895 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 4896 SDValue SCC = 4897 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 4898 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 4899 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4900 if (SCC.getNode()) return SCC; 4901 } 4902 4903 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 4904 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 4905 isa<ConstantSDNode>(N0.getOperand(1)) && 4906 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 4907 N0.hasOneUse()) { 4908 SDValue ShAmt = N0.getOperand(1); 4909 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 4910 if (N0.getOpcode() == ISD::SHL) { 4911 SDValue InnerZExt = N0.getOperand(0); 4912 // If the original shl may be shifting out bits, do not perform this 4913 // transformation. 4914 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 4915 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 4916 if (ShAmtVal > KnownZeroBits) 4917 return SDValue(); 4918 } 4919 4920 SDLoc DL(N); 4921 4922 // Ensure that the shift amount is wide enough for the shifted value. 4923 if (VT.getSizeInBits() >= 256) 4924 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 4925 4926 return DAG.getNode(N0.getOpcode(), DL, VT, 4927 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 4928 ShAmt); 4929 } 4930 4931 return SDValue(); 4932} 4933 4934SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 4935 SDValue N0 = N->getOperand(0); 4936 EVT VT = N->getValueType(0); 4937 4938 // fold (aext c1) -> c1 4939 if (isa<ConstantSDNode>(N0)) 4940 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0); 4941 // fold (aext (aext x)) -> (aext x) 4942 // fold (aext (zext x)) -> (zext x) 4943 // fold (aext (sext x)) -> (sext x) 4944 if (N0.getOpcode() == ISD::ANY_EXTEND || 4945 N0.getOpcode() == ISD::ZERO_EXTEND || 4946 N0.getOpcode() == ISD::SIGN_EXTEND) 4947 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 4948 4949 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 4950 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 4951 if (N0.getOpcode() == ISD::TRUNCATE) { 4952 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4953 if (NarrowLoad.getNode()) { 4954 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4955 if (NarrowLoad.getNode() != N0.getNode()) { 4956 CombineTo(N0.getNode(), NarrowLoad); 4957 // CombineTo deleted the truncate, if needed, but not what's under it. 4958 AddToWorkList(oye); 4959 } 4960 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4961 } 4962 } 4963 4964 // fold (aext (truncate x)) 4965 if (N0.getOpcode() == ISD::TRUNCATE) { 4966 SDValue TruncOp = N0.getOperand(0); 4967 if (TruncOp.getValueType() == VT) 4968 return TruncOp; // x iff x size == zext size. 4969 if (TruncOp.getValueType().bitsGT(VT)) 4970 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 4971 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 4972 } 4973 4974 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 4975 // if the trunc is not free. 4976 if (N0.getOpcode() == ISD::AND && 4977 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4978 N0.getOperand(1).getOpcode() == ISD::Constant && 4979 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4980 N0.getValueType())) { 4981 SDValue X = N0.getOperand(0).getOperand(0); 4982 if (X.getValueType().bitsLT(VT)) { 4983 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 4984 } else if (X.getValueType().bitsGT(VT)) { 4985 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 4986 } 4987 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4988 Mask = Mask.zext(VT.getSizeInBits()); 4989 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4990 X, DAG.getConstant(Mask, VT)); 4991 } 4992 4993 // fold (aext (load x)) -> (aext (truncate (extload x))) 4994 // None of the supported targets knows how to perform load and any_ext 4995 // on vectors in one instruction. We only perform this transformation on 4996 // scalars. 4997 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4998 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4999 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 5000 bool DoXform = true; 5001 SmallVector<SDNode*, 4> SetCCs; 5002 if (!N0.hasOneUse()) 5003 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5004 if (DoXform) { 5005 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5006 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5007 LN0->getChain(), 5008 LN0->getBasePtr(), LN0->getPointerInfo(), 5009 N0.getValueType(), 5010 LN0->isVolatile(), LN0->isNonTemporal(), 5011 LN0->getAlignment()); 5012 CombineTo(N, ExtLoad); 5013 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5014 N0.getValueType(), ExtLoad); 5015 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5016 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5017 ISD::ANY_EXTEND); 5018 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5019 } 5020 } 5021 5022 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5023 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5024 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5025 if (N0.getOpcode() == ISD::LOAD && 5026 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5027 N0.hasOneUse()) { 5028 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5029 EVT MemVT = LN0->getMemoryVT(); 5030 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N), 5031 VT, LN0->getChain(), LN0->getBasePtr(), 5032 LN0->getPointerInfo(), MemVT, 5033 LN0->isVolatile(), LN0->isNonTemporal(), 5034 LN0->getAlignment()); 5035 CombineTo(N, ExtLoad); 5036 CombineTo(N0.getNode(), 5037 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5038 N0.getValueType(), ExtLoad), 5039 ExtLoad.getValue(1)); 5040 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5041 } 5042 5043 if (N0.getOpcode() == ISD::SETCC) { 5044 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 5045 // Only do this before legalize for now. 5046 if (VT.isVector() && !LegalOperations) { 5047 EVT N0VT = N0.getOperand(0).getValueType(); 5048 // We know that the # elements of the results is the same as the 5049 // # elements of the compare (and the # elements of the compare result 5050 // for that matter). Check to see that they are the same size. If so, 5051 // we know that the element size of the sext'd result matches the 5052 // element size of the compare operands. 5053 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5054 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5055 N0.getOperand(1), 5056 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5057 // If the desired elements are smaller or larger than the source 5058 // elements we can use a matching integer vector type and then 5059 // truncate/sign extend 5060 else { 5061 EVT MatchingElementType = 5062 EVT::getIntegerVT(*DAG.getContext(), 5063 N0VT.getScalarType().getSizeInBits()); 5064 EVT MatchingVectorType = 5065 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5066 N0VT.getVectorNumElements()); 5067 SDValue VsetCC = 5068 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5069 N0.getOperand(1), 5070 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5071 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5072 } 5073 } 5074 5075 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5076 SDValue SCC = 5077 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5078 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5079 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5080 if (SCC.getNode()) 5081 return SCC; 5082 } 5083 5084 return SDValue(); 5085} 5086 5087/// GetDemandedBits - See if the specified operand can be simplified with the 5088/// knowledge that only the bits specified by Mask are used. If so, return the 5089/// simpler operand, otherwise return a null SDValue. 5090SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5091 switch (V.getOpcode()) { 5092 default: break; 5093 case ISD::Constant: { 5094 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5095 assert(CV != 0 && "Const value should be ConstSDNode."); 5096 const APInt &CVal = CV->getAPIntValue(); 5097 APInt NewVal = CVal & Mask; 5098 if (NewVal != CVal) 5099 return DAG.getConstant(NewVal, V.getValueType()); 5100 break; 5101 } 5102 case ISD::OR: 5103 case ISD::XOR: 5104 // If the LHS or RHS don't contribute bits to the or, drop them. 5105 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 5106 return V.getOperand(1); 5107 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 5108 return V.getOperand(0); 5109 break; 5110 case ISD::SRL: 5111 // Only look at single-use SRLs. 5112 if (!V.getNode()->hasOneUse()) 5113 break; 5114 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 5115 // See if we can recursively simplify the LHS. 5116 unsigned Amt = RHSC->getZExtValue(); 5117 5118 // Watch out for shift count overflow though. 5119 if (Amt >= Mask.getBitWidth()) break; 5120 APInt NewMask = Mask << Amt; 5121 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 5122 if (SimplifyLHS.getNode()) 5123 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 5124 SimplifyLHS, V.getOperand(1)); 5125 } 5126 } 5127 return SDValue(); 5128} 5129 5130/// ReduceLoadWidth - If the result of a wider load is shifted to right of N 5131/// bits and then truncated to a narrower type and where N is a multiple 5132/// of number of bits of the narrower type, transform it to a narrower load 5133/// from address + N / num of bits of new type. If the result is to be 5134/// extended, also fold the extension to form a extending load. 5135SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 5136 unsigned Opc = N->getOpcode(); 5137 5138 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 5139 SDValue N0 = N->getOperand(0); 5140 EVT VT = N->getValueType(0); 5141 EVT ExtVT = VT; 5142 5143 // This transformation isn't valid for vector loads. 5144 if (VT.isVector()) 5145 return SDValue(); 5146 5147 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 5148 // extended to VT. 5149 if (Opc == ISD::SIGN_EXTEND_INREG) { 5150 ExtType = ISD::SEXTLOAD; 5151 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5152 } else if (Opc == ISD::SRL) { 5153 // Another special-case: SRL is basically zero-extending a narrower value. 5154 ExtType = ISD::ZEXTLOAD; 5155 N0 = SDValue(N, 0); 5156 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5157 if (!N01) return SDValue(); 5158 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5159 VT.getSizeInBits() - N01->getZExtValue()); 5160 } 5161 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5162 return SDValue(); 5163 5164 unsigned EVTBits = ExtVT.getSizeInBits(); 5165 5166 // Do not generate loads of non-round integer types since these can 5167 // be expensive (and would be wrong if the type is not byte sized). 5168 if (!ExtVT.isRound()) 5169 return SDValue(); 5170 5171 unsigned ShAmt = 0; 5172 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5173 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5174 ShAmt = N01->getZExtValue(); 5175 // Is the shift amount a multiple of size of VT? 5176 if ((ShAmt & (EVTBits-1)) == 0) { 5177 N0 = N0.getOperand(0); 5178 // Is the load width a multiple of size of VT? 5179 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5180 return SDValue(); 5181 } 5182 5183 // At this point, we must have a load or else we can't do the transform. 5184 if (!isa<LoadSDNode>(N0)) return SDValue(); 5185 5186 // Because a SRL must be assumed to *need* to zero-extend the high bits 5187 // (as opposed to anyext the high bits), we can't combine the zextload 5188 // lowering of SRL and an sextload. 5189 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 5190 return SDValue(); 5191 5192 // If the shift amount is larger than the input type then we're not 5193 // accessing any of the loaded bytes. If the load was a zextload/extload 5194 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5195 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5196 return SDValue(); 5197 } 5198 } 5199 5200 // If the load is shifted left (and the result isn't shifted back right), 5201 // we can fold the truncate through the shift. 5202 unsigned ShLeftAmt = 0; 5203 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5204 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5205 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5206 ShLeftAmt = N01->getZExtValue(); 5207 N0 = N0.getOperand(0); 5208 } 5209 } 5210 5211 // If we haven't found a load, we can't narrow it. Don't transform one with 5212 // multiple uses, this would require adding a new load. 5213 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 5214 return SDValue(); 5215 5216 // Don't change the width of a volatile load. 5217 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5218 if (LN0->isVolatile()) 5219 return SDValue(); 5220 5221 // Verify that we are actually reducing a load width here. 5222 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 5223 return SDValue(); 5224 5225 // For the transform to be legal, the load must produce only two values 5226 // (the value loaded and the chain). Don't transform a pre-increment 5227 // load, for example, which produces an extra value. Otherwise the 5228 // transformation is not equivalent, and the downstream logic to replace 5229 // uses gets things wrong. 5230 if (LN0->getNumValues() > 2) 5231 return SDValue(); 5232 5233 // If the load that we're shrinking is an extload and we're not just 5234 // discarding the extension we can't simply shrink the load. Bail. 5235 // TODO: It would be possible to merge the extensions in some cases. 5236 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 5237 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 5238 return SDValue(); 5239 5240 EVT PtrType = N0.getOperand(1).getValueType(); 5241 5242 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5243 // It's not possible to generate a constant of extended or untyped type. 5244 return SDValue(); 5245 5246 // For big endian targets, we need to adjust the offset to the pointer to 5247 // load the correct bytes. 5248 if (TLI.isBigEndian()) { 5249 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5250 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5251 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5252 } 5253 5254 uint64_t PtrOff = ShAmt / 8; 5255 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5256 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 5257 PtrType, LN0->getBasePtr(), 5258 DAG.getConstant(PtrOff, PtrType)); 5259 AddToWorkList(NewPtr.getNode()); 5260 5261 SDValue Load; 5262 if (ExtType == ISD::NON_EXTLOAD) 5263 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 5264 LN0->getPointerInfo().getWithOffset(PtrOff), 5265 LN0->isVolatile(), LN0->isNonTemporal(), 5266 LN0->isInvariant(), NewAlign); 5267 else 5268 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 5269 LN0->getPointerInfo().getWithOffset(PtrOff), 5270 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5271 NewAlign); 5272 5273 // Replace the old load's chain with the new load's chain. 5274 WorkListRemover DeadNodes(*this); 5275 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5276 5277 // Shift the result left, if we've swallowed a left shift. 5278 SDValue Result = Load; 5279 if (ShLeftAmt != 0) { 5280 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5281 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5282 ShImmTy = VT; 5283 // If the shift amount is as large as the result size (but, presumably, 5284 // no larger than the source) then the useful bits of the result are 5285 // zero; we can't simply return the shortened shift, because the result 5286 // of that operation is undefined. 5287 if (ShLeftAmt >= VT.getSizeInBits()) 5288 Result = DAG.getConstant(0, VT); 5289 else 5290 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 5291 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5292 } 5293 5294 // Return the new loaded value. 5295 return Result; 5296} 5297 5298SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5299 SDValue N0 = N->getOperand(0); 5300 SDValue N1 = N->getOperand(1); 5301 EVT VT = N->getValueType(0); 5302 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5303 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5304 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5305 5306 // fold (sext_in_reg c1) -> c1 5307 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5308 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 5309 5310 // If the input is already sign extended, just drop the extension. 5311 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5312 return N0; 5313 5314 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5315 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5316 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 5317 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5318 N0.getOperand(0), N1); 5319 5320 // fold (sext_in_reg (sext x)) -> (sext x) 5321 // fold (sext_in_reg (aext x)) -> (sext x) 5322 // if x is small enough. 5323 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5324 SDValue N00 = N0.getOperand(0); 5325 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5326 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5327 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 5328 } 5329 5330 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5331 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5332 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 5333 5334 // fold operands of sext_in_reg based on knowledge that the top bits are not 5335 // demanded. 5336 if (SimplifyDemandedBits(SDValue(N, 0))) 5337 return SDValue(N, 0); 5338 5339 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5340 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5341 SDValue NarrowLoad = ReduceLoadWidth(N); 5342 if (NarrowLoad.getNode()) 5343 return NarrowLoad; 5344 5345 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5346 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5347 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5348 if (N0.getOpcode() == ISD::SRL) { 5349 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5350 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5351 // We can turn this into an SRA iff the input to the SRL is already sign 5352 // extended enough. 5353 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5354 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5355 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 5356 N0.getOperand(0), N0.getOperand(1)); 5357 } 5358 } 5359 5360 // fold (sext_inreg (extload x)) -> (sextload x) 5361 if (ISD::isEXTLoad(N0.getNode()) && 5362 ISD::isUNINDEXEDLoad(N0.getNode()) && 5363 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5364 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5365 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5366 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5367 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5368 LN0->getChain(), 5369 LN0->getBasePtr(), LN0->getPointerInfo(), 5370 EVT, 5371 LN0->isVolatile(), LN0->isNonTemporal(), 5372 LN0->getAlignment()); 5373 CombineTo(N, ExtLoad); 5374 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5375 AddToWorkList(ExtLoad.getNode()); 5376 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5377 } 5378 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5379 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5380 N0.hasOneUse() && 5381 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5382 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5383 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5384 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5385 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5386 LN0->getChain(), 5387 LN0->getBasePtr(), LN0->getPointerInfo(), 5388 EVT, 5389 LN0->isVolatile(), LN0->isNonTemporal(), 5390 LN0->getAlignment()); 5391 CombineTo(N, ExtLoad); 5392 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5393 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5394 } 5395 5396 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5397 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5398 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5399 N0.getOperand(1), false); 5400 if (BSwap.getNode() != 0) 5401 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5402 BSwap, N1); 5403 } 5404 5405 return SDValue(); 5406} 5407 5408SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5409 SDValue N0 = N->getOperand(0); 5410 EVT VT = N->getValueType(0); 5411 bool isLE = TLI.isLittleEndian(); 5412 5413 // noop truncate 5414 if (N0.getValueType() == N->getValueType(0)) 5415 return N0; 5416 // fold (truncate c1) -> c1 5417 if (isa<ConstantSDNode>(N0)) 5418 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 5419 // fold (truncate (truncate x)) -> (truncate x) 5420 if (N0.getOpcode() == ISD::TRUNCATE) 5421 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5422 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5423 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5424 N0.getOpcode() == ISD::SIGN_EXTEND || 5425 N0.getOpcode() == ISD::ANY_EXTEND) { 5426 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5427 // if the source is smaller than the dest, we still need an extend 5428 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5429 N0.getOperand(0)); 5430 if (N0.getOperand(0).getValueType().bitsGT(VT)) 5431 // if the source is larger than the dest, than we just need the truncate 5432 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5433 // if the source and dest are the same type, we can drop both the extend 5434 // and the truncate. 5435 return N0.getOperand(0); 5436 } 5437 5438 // Fold extract-and-trunc into a narrow extract. For example: 5439 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5440 // i32 y = TRUNCATE(i64 x) 5441 // -- becomes -- 5442 // v16i8 b = BITCAST (v2i64 val) 5443 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5444 // 5445 // Note: We only run this optimization after type legalization (which often 5446 // creates this pattern) and before operation legalization after which 5447 // we need to be more careful about the vector instructions that we generate. 5448 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5449 LegalTypes && !LegalOperations && N0->hasOneUse()) { 5450 5451 EVT VecTy = N0.getOperand(0).getValueType(); 5452 EVT ExTy = N0.getValueType(); 5453 EVT TrTy = N->getValueType(0); 5454 5455 unsigned NumElem = VecTy.getVectorNumElements(); 5456 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5457 5458 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5459 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5460 5461 SDValue EltNo = N0->getOperand(1); 5462 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5463 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5464 EVT IndexTy = TLI.getVectorIdxTy(); 5465 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5466 5467 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 5468 NVT, N0.getOperand(0)); 5469 5470 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5471 SDLoc(N), TrTy, V, 5472 DAG.getConstant(Index, IndexTy)); 5473 } 5474 } 5475 5476 // Fold a series of buildvector, bitcast, and truncate if possible. 5477 // For example fold 5478 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 5479 // (2xi32 (buildvector x, y)). 5480 if (Level == AfterLegalizeVectorOps && VT.isVector() && 5481 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 5482 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 5483 N0.getOperand(0).hasOneUse()) { 5484 5485 SDValue BuildVect = N0.getOperand(0); 5486 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 5487 EVT TruncVecEltTy = VT.getVectorElementType(); 5488 5489 // Check that the element types match. 5490 if (BuildVectEltTy == TruncVecEltTy) { 5491 // Now we only need to compute the offset of the truncated elements. 5492 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 5493 unsigned TruncVecNumElts = VT.getVectorNumElements(); 5494 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 5495 5496 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 5497 "Invalid number of elements"); 5498 5499 SmallVector<SDValue, 8> Opnds; 5500 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 5501 Opnds.push_back(BuildVect.getOperand(i)); 5502 5503 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0], 5504 Opnds.size()); 5505 } 5506 } 5507 5508 // See if we can simplify the input to this truncate through knowledge that 5509 // only the low bits are being used. 5510 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5511 // Currently we only perform this optimization on scalars because vectors 5512 // may have different active low bits. 5513 if (!VT.isVector()) { 5514 SDValue Shorter = 5515 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5516 VT.getSizeInBits())); 5517 if (Shorter.getNode()) 5518 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 5519 } 5520 // fold (truncate (load x)) -> (smaller load x) 5521 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5522 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5523 SDValue Reduced = ReduceLoadWidth(N); 5524 if (Reduced.getNode()) 5525 return Reduced; 5526 } 5527 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 5528 // where ... are all 'undef'. 5529 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 5530 SmallVector<EVT, 8> VTs; 5531 SDValue V; 5532 unsigned Idx = 0; 5533 unsigned NumDefs = 0; 5534 5535 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 5536 SDValue X = N0.getOperand(i); 5537 if (X.getOpcode() != ISD::UNDEF) { 5538 V = X; 5539 Idx = i; 5540 NumDefs++; 5541 } 5542 // Stop if more than one members are non-undef. 5543 if (NumDefs > 1) 5544 break; 5545 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 5546 VT.getVectorElementType(), 5547 X.getValueType().getVectorNumElements())); 5548 } 5549 5550 if (NumDefs == 0) 5551 return DAG.getUNDEF(VT); 5552 5553 if (NumDefs == 1) { 5554 assert(V.getNode() && "The single defined operand is empty!"); 5555 SmallVector<SDValue, 8> Opnds; 5556 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 5557 if (i != Idx) { 5558 Opnds.push_back(DAG.getUNDEF(VTs[i])); 5559 continue; 5560 } 5561 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 5562 AddToWorkList(NV.getNode()); 5563 Opnds.push_back(NV); 5564 } 5565 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 5566 &Opnds[0], Opnds.size()); 5567 } 5568 } 5569 5570 // Simplify the operands using demanded-bits information. 5571 if (!VT.isVector() && 5572 SimplifyDemandedBits(SDValue(N, 0))) 5573 return SDValue(N, 0); 5574 5575 return SDValue(); 5576} 5577 5578static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 5579 SDValue Elt = N->getOperand(i); 5580 if (Elt.getOpcode() != ISD::MERGE_VALUES) 5581 return Elt.getNode(); 5582 return Elt.getOperand(Elt.getResNo()).getNode(); 5583} 5584 5585/// CombineConsecutiveLoads - build_pair (load, load) -> load 5586/// if load locations are consecutive. 5587SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 5588 assert(N->getOpcode() == ISD::BUILD_PAIR); 5589 5590 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 5591 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 5592 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 5593 LD1->getPointerInfo().getAddrSpace() != 5594 LD2->getPointerInfo().getAddrSpace()) 5595 return SDValue(); 5596 EVT LD1VT = LD1->getValueType(0); 5597 5598 if (ISD::isNON_EXTLoad(LD2) && 5599 LD2->hasOneUse() && 5600 // If both are volatile this would reduce the number of volatile loads. 5601 // If one is volatile it might be ok, but play conservative and bail out. 5602 !LD1->isVolatile() && 5603 !LD2->isVolatile() && 5604 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 5605 unsigned Align = LD1->getAlignment(); 5606 unsigned NewAlign = TLI.getDataLayout()-> 5607 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5608 5609 if (NewAlign <= Align && 5610 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 5611 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 5612 LD1->getBasePtr(), LD1->getPointerInfo(), 5613 false, false, false, Align); 5614 } 5615 5616 return SDValue(); 5617} 5618 5619SDValue DAGCombiner::visitBITCAST(SDNode *N) { 5620 SDValue N0 = N->getOperand(0); 5621 EVT VT = N->getValueType(0); 5622 5623 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 5624 // Only do this before legalize, since afterward the target may be depending 5625 // on the bitconvert. 5626 // First check to see if this is all constant. 5627 if (!LegalTypes && 5628 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 5629 VT.isVector()) { 5630 bool isSimple = true; 5631 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) 5632 if (N0.getOperand(i).getOpcode() != ISD::UNDEF && 5633 N0.getOperand(i).getOpcode() != ISD::Constant && 5634 N0.getOperand(i).getOpcode() != ISD::ConstantFP) { 5635 isSimple = false; 5636 break; 5637 } 5638 5639 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 5640 assert(!DestEltVT.isVector() && 5641 "Element type of vector ValueType must not be vector!"); 5642 if (isSimple) 5643 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 5644 } 5645 5646 // If the input is a constant, let getNode fold it. 5647 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 5648 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 5649 if (Res.getNode() != N) { 5650 if (!LegalOperations || 5651 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 5652 return Res; 5653 5654 // Folding it resulted in an illegal node, and it's too late to 5655 // do that. Clean up the old node and forego the transformation. 5656 // Ideally this won't happen very often, because instcombine 5657 // and the earlier dagcombine runs (where illegal nodes are 5658 // permitted) should have folded most of them already. 5659 DAG.DeleteNode(Res.getNode()); 5660 } 5661 } 5662 5663 // (conv (conv x, t1), t2) -> (conv x, t2) 5664 if (N0.getOpcode() == ISD::BITCAST) 5665 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 5666 N0.getOperand(0)); 5667 5668 // fold (conv (load x)) -> (load (conv*)x) 5669 // If the resultant load doesn't need a higher alignment than the original! 5670 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 5671 // Do not change the width of a volatile load. 5672 !cast<LoadSDNode>(N0)->isVolatile() && 5673 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) { 5674 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5675 unsigned Align = TLI.getDataLayout()-> 5676 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5677 unsigned OrigAlign = LN0->getAlignment(); 5678 5679 if (Align <= OrigAlign) { 5680 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 5681 LN0->getBasePtr(), LN0->getPointerInfo(), 5682 LN0->isVolatile(), LN0->isNonTemporal(), 5683 LN0->isInvariant(), OrigAlign); 5684 AddToWorkList(N); 5685 CombineTo(N0.getNode(), 5686 DAG.getNode(ISD::BITCAST, SDLoc(N0), 5687 N0.getValueType(), Load), 5688 Load.getValue(1)); 5689 return Load; 5690 } 5691 } 5692 5693 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 5694 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 5695 // This often reduces constant pool loads. 5696 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 5697 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 5698 N0.getNode()->hasOneUse() && VT.isInteger() && 5699 !VT.isVector() && !N0.getValueType().isVector()) { 5700 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 5701 N0.getOperand(0)); 5702 AddToWorkList(NewConv.getNode()); 5703 5704 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5705 if (N0.getOpcode() == ISD::FNEG) 5706 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 5707 NewConv, DAG.getConstant(SignBit, VT)); 5708 assert(N0.getOpcode() == ISD::FABS); 5709 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5710 NewConv, DAG.getConstant(~SignBit, VT)); 5711 } 5712 5713 // fold (bitconvert (fcopysign cst, x)) -> 5714 // (or (and (bitconvert x), sign), (and cst, (not sign))) 5715 // Note that we don't handle (copysign x, cst) because this can always be 5716 // folded to an fneg or fabs. 5717 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 5718 isa<ConstantFPSDNode>(N0.getOperand(0)) && 5719 VT.isInteger() && !VT.isVector()) { 5720 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 5721 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 5722 if (isTypeLegal(IntXVT)) { 5723 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 5724 IntXVT, N0.getOperand(1)); 5725 AddToWorkList(X.getNode()); 5726 5727 // If X has a different width than the result/lhs, sext it or truncate it. 5728 unsigned VTWidth = VT.getSizeInBits(); 5729 if (OrigXWidth < VTWidth) { 5730 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 5731 AddToWorkList(X.getNode()); 5732 } else if (OrigXWidth > VTWidth) { 5733 // To get the sign bit in the right place, we have to shift it right 5734 // before truncating. 5735 X = DAG.getNode(ISD::SRL, SDLoc(X), 5736 X.getValueType(), X, 5737 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 5738 AddToWorkList(X.getNode()); 5739 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5740 AddToWorkList(X.getNode()); 5741 } 5742 5743 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5744 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 5745 X, DAG.getConstant(SignBit, VT)); 5746 AddToWorkList(X.getNode()); 5747 5748 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 5749 VT, N0.getOperand(0)); 5750 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 5751 Cst, DAG.getConstant(~SignBit, VT)); 5752 AddToWorkList(Cst.getNode()); 5753 5754 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 5755 } 5756 } 5757 5758 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 5759 if (N0.getOpcode() == ISD::BUILD_PAIR) { 5760 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 5761 if (CombineLD.getNode()) 5762 return CombineLD; 5763 } 5764 5765 return SDValue(); 5766} 5767 5768SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 5769 EVT VT = N->getValueType(0); 5770 return CombineConsecutiveLoads(N, VT); 5771} 5772 5773/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 5774/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 5775/// destination element value type. 5776SDValue DAGCombiner:: 5777ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 5778 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 5779 5780 // If this is already the right type, we're done. 5781 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 5782 5783 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 5784 unsigned DstBitSize = DstEltVT.getSizeInBits(); 5785 5786 // If this is a conversion of N elements of one type to N elements of another 5787 // type, convert each element. This handles FP<->INT cases. 5788 if (SrcBitSize == DstBitSize) { 5789 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5790 BV->getValueType(0).getVectorNumElements()); 5791 5792 // Due to the FP element handling below calling this routine recursively, 5793 // we can end up with a scalar-to-vector node here. 5794 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 5795 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 5796 DAG.getNode(ISD::BITCAST, SDLoc(BV), 5797 DstEltVT, BV->getOperand(0))); 5798 5799 SmallVector<SDValue, 8> Ops; 5800 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5801 SDValue Op = BV->getOperand(i); 5802 // If the vector element type is not legal, the BUILD_VECTOR operands 5803 // are promoted and implicitly truncated. Make that explicit here. 5804 if (Op.getValueType() != SrcEltVT) 5805 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 5806 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 5807 DstEltVT, Op)); 5808 AddToWorkList(Ops.back().getNode()); 5809 } 5810 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 5811 &Ops[0], Ops.size()); 5812 } 5813 5814 // Otherwise, we're growing or shrinking the elements. To avoid having to 5815 // handle annoying details of growing/shrinking FP values, we convert them to 5816 // int first. 5817 if (SrcEltVT.isFloatingPoint()) { 5818 // Convert the input float vector to a int vector where the elements are the 5819 // same sizes. 5820 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 5821 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 5822 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 5823 SrcEltVT = IntVT; 5824 } 5825 5826 // Now we know the input is an integer vector. If the output is a FP type, 5827 // convert to integer first, then to FP of the right size. 5828 if (DstEltVT.isFloatingPoint()) { 5829 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 5830 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 5831 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 5832 5833 // Next, convert to FP elements of the same size. 5834 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 5835 } 5836 5837 // Okay, we know the src/dst types are both integers of differing types. 5838 // Handling growing first. 5839 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 5840 if (SrcBitSize < DstBitSize) { 5841 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 5842 5843 SmallVector<SDValue, 8> Ops; 5844 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 5845 i += NumInputsPerOutput) { 5846 bool isLE = TLI.isLittleEndian(); 5847 APInt NewBits = APInt(DstBitSize, 0); 5848 bool EltIsUndef = true; 5849 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 5850 // Shift the previously computed bits over. 5851 NewBits <<= SrcBitSize; 5852 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 5853 if (Op.getOpcode() == ISD::UNDEF) continue; 5854 EltIsUndef = false; 5855 5856 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 5857 zextOrTrunc(SrcBitSize).zext(DstBitSize); 5858 } 5859 5860 if (EltIsUndef) 5861 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5862 else 5863 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 5864 } 5865 5866 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 5867 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 5868 &Ops[0], Ops.size()); 5869 } 5870 5871 // Finally, this must be the case where we are shrinking elements: each input 5872 // turns into multiple outputs. 5873 bool isS2V = ISD::isScalarToVector(BV); 5874 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 5875 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5876 NumOutputsPerInput*BV->getNumOperands()); 5877 SmallVector<SDValue, 8> Ops; 5878 5879 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5880 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 5881 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 5882 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5883 continue; 5884 } 5885 5886 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 5887 getAPIntValue().zextOrTrunc(SrcBitSize); 5888 5889 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 5890 APInt ThisVal = OpVal.trunc(DstBitSize); 5891 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 5892 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 5893 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 5894 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 5895 Ops[0]); 5896 OpVal = OpVal.lshr(DstBitSize); 5897 } 5898 5899 // For big endian targets, swap the order of the pieces of each element. 5900 if (TLI.isBigEndian()) 5901 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 5902 } 5903 5904 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 5905 &Ops[0], Ops.size()); 5906} 5907 5908SDValue DAGCombiner::visitFADD(SDNode *N) { 5909 SDValue N0 = N->getOperand(0); 5910 SDValue N1 = N->getOperand(1); 5911 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5912 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5913 EVT VT = N->getValueType(0); 5914 5915 // fold vector ops 5916 if (VT.isVector()) { 5917 SDValue FoldedVOp = SimplifyVBinOp(N); 5918 if (FoldedVOp.getNode()) return FoldedVOp; 5919 } 5920 5921 // fold (fadd c1, c2) -> c1 + c2 5922 if (N0CFP && N1CFP) 5923 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 5924 // canonicalize constant to RHS 5925 if (N0CFP && !N1CFP) 5926 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 5927 // fold (fadd A, 0) -> A 5928 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5929 N1CFP->getValueAPF().isZero()) 5930 return N0; 5931 // fold (fadd A, (fneg B)) -> (fsub A, B) 5932 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5933 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5934 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 5935 GetNegatedExpression(N1, DAG, LegalOperations)); 5936 // fold (fadd (fneg A), B) -> (fsub B, A) 5937 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5938 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5939 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 5940 GetNegatedExpression(N0, DAG, LegalOperations)); 5941 5942 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 5943 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5944 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 5945 isa<ConstantFPSDNode>(N0.getOperand(1))) 5946 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 5947 DAG.getNode(ISD::FADD, SDLoc(N), VT, 5948 N0.getOperand(1), N1)); 5949 5950 // No FP constant should be created after legalization as Instruction 5951 // Selection pass has hard time in dealing with FP constant. 5952 // 5953 // We don't need test this condition for transformation like following, as 5954 // the DAG being transformed implies it is legal to take FP constant as 5955 // operand. 5956 // 5957 // (fadd (fmul c, x), x) -> (fmul c+1, x) 5958 // 5959 bool AllowNewFpConst = (Level < AfterLegalizeDAG); 5960 5961 // If allow, fold (fadd (fneg x), x) -> 0.0 5962 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 5963 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 5964 return DAG.getConstantFP(0.0, VT); 5965 5966 // If allow, fold (fadd x, (fneg x)) -> 0.0 5967 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 5968 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 5969 return DAG.getConstantFP(0.0, VT); 5970 5971 // In unsafe math mode, we can fold chains of FADD's of the same value 5972 // into multiplications. This transform is not safe in general because 5973 // we are reducing the number of rounding steps. 5974 if (DAG.getTarget().Options.UnsafeFPMath && 5975 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 5976 !N0CFP && !N1CFP) { 5977 if (N0.getOpcode() == ISD::FMUL) { 5978 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 5979 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 5980 5981 // (fadd (fmul c, x), x) -> (fmul x, c+1) 5982 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 5983 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 5984 SDValue(CFP00, 0), 5985 DAG.getConstantFP(1.0, VT)); 5986 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 5987 N1, NewCFP); 5988 } 5989 5990 // (fadd (fmul x, c), x) -> (fmul x, c+1) 5991 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 5992 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 5993 SDValue(CFP01, 0), 5994 DAG.getConstantFP(1.0, VT)); 5995 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 5996 N1, NewCFP); 5997 } 5998 5999 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2) 6000 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 6001 N1.getOperand(0) == N1.getOperand(1) && 6002 N0.getOperand(1) == N1.getOperand(0)) { 6003 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6004 SDValue(CFP00, 0), 6005 DAG.getConstantFP(2.0, VT)); 6006 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6007 N0.getOperand(1), NewCFP); 6008 } 6009 6010 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6011 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6012 N1.getOperand(0) == N1.getOperand(1) && 6013 N0.getOperand(0) == N1.getOperand(0)) { 6014 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6015 SDValue(CFP01, 0), 6016 DAG.getConstantFP(2.0, VT)); 6017 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6018 N0.getOperand(0), NewCFP); 6019 } 6020 } 6021 6022 if (N1.getOpcode() == ISD::FMUL) { 6023 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6024 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6025 6026 // (fadd x, (fmul c, x)) -> (fmul x, c+1) 6027 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 6028 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6029 SDValue(CFP10, 0), 6030 DAG.getConstantFP(1.0, VT)); 6031 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6032 N0, NewCFP); 6033 } 6034 6035 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6036 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6037 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6038 SDValue(CFP11, 0), 6039 DAG.getConstantFP(1.0, VT)); 6040 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6041 N0, NewCFP); 6042 } 6043 6044 6045 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2) 6046 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD && 6047 N0.getOperand(0) == N0.getOperand(1) && 6048 N1.getOperand(1) == N0.getOperand(0)) { 6049 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6050 SDValue(CFP10, 0), 6051 DAG.getConstantFP(2.0, VT)); 6052 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6053 N1.getOperand(1), NewCFP); 6054 } 6055 6056 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6057 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6058 N0.getOperand(0) == N0.getOperand(1) && 6059 N1.getOperand(0) == N0.getOperand(0)) { 6060 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6061 SDValue(CFP11, 0), 6062 DAG.getConstantFP(2.0, VT)); 6063 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6064 N1.getOperand(0), NewCFP); 6065 } 6066 } 6067 6068 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) { 6069 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6070 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6071 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6072 (N0.getOperand(0) == N1)) 6073 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6074 N1, DAG.getConstantFP(3.0, VT)); 6075 } 6076 6077 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) { 6078 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6079 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6080 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6081 N1.getOperand(0) == N0) 6082 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6083 N0, DAG.getConstantFP(3.0, VT)); 6084 } 6085 6086 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6087 if (AllowNewFpConst && 6088 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6089 N0.getOperand(0) == N0.getOperand(1) && 6090 N1.getOperand(0) == N1.getOperand(1) && 6091 N0.getOperand(0) == N1.getOperand(0)) 6092 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6093 N0.getOperand(0), 6094 DAG.getConstantFP(4.0, VT)); 6095 } 6096 6097 // FADD -> FMA combines: 6098 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6099 DAG.getTarget().Options.UnsafeFPMath) && 6100 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6101 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6102 6103 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6104 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6105 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6106 N0.getOperand(0), N0.getOperand(1), N1); 6107 6108 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6109 // Note: Commutes FADD operands. 6110 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6111 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6112 N1.getOperand(0), N1.getOperand(1), N0); 6113 } 6114 6115 return SDValue(); 6116} 6117 6118SDValue DAGCombiner::visitFSUB(SDNode *N) { 6119 SDValue N0 = N->getOperand(0); 6120 SDValue N1 = N->getOperand(1); 6121 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6122 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6123 EVT VT = N->getValueType(0); 6124 SDLoc dl(N); 6125 6126 // fold vector ops 6127 if (VT.isVector()) { 6128 SDValue FoldedVOp = SimplifyVBinOp(N); 6129 if (FoldedVOp.getNode()) return FoldedVOp; 6130 } 6131 6132 // fold (fsub c1, c2) -> c1-c2 6133 if (N0CFP && N1CFP) 6134 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 6135 // fold (fsub A, 0) -> A 6136 if (DAG.getTarget().Options.UnsafeFPMath && 6137 N1CFP && N1CFP->getValueAPF().isZero()) 6138 return N0; 6139 // fold (fsub 0, B) -> -B 6140 if (DAG.getTarget().Options.UnsafeFPMath && 6141 N0CFP && N0CFP->getValueAPF().isZero()) { 6142 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6143 return GetNegatedExpression(N1, DAG, LegalOperations); 6144 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6145 return DAG.getNode(ISD::FNEG, dl, VT, N1); 6146 } 6147 // fold (fsub A, (fneg B)) -> (fadd A, B) 6148 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6149 return DAG.getNode(ISD::FADD, dl, VT, N0, 6150 GetNegatedExpression(N1, DAG, LegalOperations)); 6151 6152 // If 'unsafe math' is enabled, fold 6153 // (fsub x, x) -> 0.0 & 6154 // (fsub x, (fadd x, y)) -> (fneg y) & 6155 // (fsub x, (fadd y, x)) -> (fneg y) 6156 if (DAG.getTarget().Options.UnsafeFPMath) { 6157 if (N0 == N1) 6158 return DAG.getConstantFP(0.0f, VT); 6159 6160 if (N1.getOpcode() == ISD::FADD) { 6161 SDValue N10 = N1->getOperand(0); 6162 SDValue N11 = N1->getOperand(1); 6163 6164 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 6165 &DAG.getTarget().Options)) 6166 return GetNegatedExpression(N11, DAG, LegalOperations); 6167 6168 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 6169 &DAG.getTarget().Options)) 6170 return GetNegatedExpression(N10, DAG, LegalOperations); 6171 } 6172 } 6173 6174 // FSUB -> FMA combines: 6175 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6176 DAG.getTarget().Options.UnsafeFPMath) && 6177 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6178 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6179 6180 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 6181 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6182 return DAG.getNode(ISD::FMA, dl, VT, 6183 N0.getOperand(0), N0.getOperand(1), 6184 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6185 6186 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 6187 // Note: Commutes FSUB operands. 6188 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6189 return DAG.getNode(ISD::FMA, dl, VT, 6190 DAG.getNode(ISD::FNEG, dl, VT, 6191 N1.getOperand(0)), 6192 N1.getOperand(1), N0); 6193 6194 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 6195 if (N0.getOpcode() == ISD::FNEG && 6196 N0.getOperand(0).getOpcode() == ISD::FMUL && 6197 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 6198 SDValue N00 = N0.getOperand(0).getOperand(0); 6199 SDValue N01 = N0.getOperand(0).getOperand(1); 6200 return DAG.getNode(ISD::FMA, dl, VT, 6201 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 6202 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6203 } 6204 } 6205 6206 return SDValue(); 6207} 6208 6209SDValue DAGCombiner::visitFMUL(SDNode *N) { 6210 SDValue N0 = N->getOperand(0); 6211 SDValue N1 = N->getOperand(1); 6212 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6213 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6214 EVT VT = N->getValueType(0); 6215 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6216 6217 // fold vector ops 6218 if (VT.isVector()) { 6219 SDValue FoldedVOp = SimplifyVBinOp(N); 6220 if (FoldedVOp.getNode()) return FoldedVOp; 6221 } 6222 6223 // fold (fmul c1, c2) -> c1*c2 6224 if (N0CFP && N1CFP) 6225 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 6226 // canonicalize constant to RHS 6227 if (N0CFP && !N1CFP) 6228 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 6229 // fold (fmul A, 0) -> 0 6230 if (DAG.getTarget().Options.UnsafeFPMath && 6231 N1CFP && N1CFP->getValueAPF().isZero()) 6232 return N1; 6233 // fold (fmul A, 0) -> 0, vector edition. 6234 if (DAG.getTarget().Options.UnsafeFPMath && 6235 ISD::isBuildVectorAllZeros(N1.getNode())) 6236 return N1; 6237 // fold (fmul A, 1.0) -> A 6238 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6239 return N0; 6240 // fold (fmul X, 2.0) -> (fadd X, X) 6241 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 6242 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 6243 // fold (fmul X, -1.0) -> (fneg X) 6244 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 6245 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6246 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 6247 6248 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 6249 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6250 &DAG.getTarget().Options)) { 6251 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6252 &DAG.getTarget().Options)) { 6253 // Both can be negated for free, check to see if at least one is cheaper 6254 // negated. 6255 if (LHSNeg == 2 || RHSNeg == 2) 6256 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6257 GetNegatedExpression(N0, DAG, LegalOperations), 6258 GetNegatedExpression(N1, DAG, LegalOperations)); 6259 } 6260 } 6261 6262 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 6263 if (DAG.getTarget().Options.UnsafeFPMath && 6264 N1CFP && N0.getOpcode() == ISD::FMUL && 6265 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 6266 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 6267 DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6268 N0.getOperand(1), N1)); 6269 6270 return SDValue(); 6271} 6272 6273SDValue DAGCombiner::visitFMA(SDNode *N) { 6274 SDValue N0 = N->getOperand(0); 6275 SDValue N1 = N->getOperand(1); 6276 SDValue N2 = N->getOperand(2); 6277 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6278 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6279 EVT VT = N->getValueType(0); 6280 SDLoc dl(N); 6281 6282 if (DAG.getTarget().Options.UnsafeFPMath) { 6283 if (N0CFP && N0CFP->isZero()) 6284 return N2; 6285 if (N1CFP && N1CFP->isZero()) 6286 return N2; 6287 } 6288 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6289 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 6290 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6291 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 6292 6293 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6294 if (N0CFP && !N1CFP) 6295 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 6296 6297 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6298 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6299 N2.getOpcode() == ISD::FMUL && 6300 N0 == N2.getOperand(0) && 6301 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6302 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6303 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6304 } 6305 6306 6307 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6308 if (DAG.getTarget().Options.UnsafeFPMath && 6309 N0.getOpcode() == ISD::FMUL && N1CFP && 6310 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6311 return DAG.getNode(ISD::FMA, dl, VT, 6312 N0.getOperand(0), 6313 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6314 N2); 6315 } 6316 6317 // (fma x, 1, y) -> (fadd x, y) 6318 // (fma x, -1, y) -> (fadd (fneg x), y) 6319 if (N1CFP) { 6320 if (N1CFP->isExactlyValue(1.0)) 6321 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6322 6323 if (N1CFP->isExactlyValue(-1.0) && 6324 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6325 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6326 AddToWorkList(RHSNeg.getNode()); 6327 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6328 } 6329 } 6330 6331 // (fma x, c, x) -> (fmul x, (c+1)) 6332 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) 6333 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6334 DAG.getNode(ISD::FADD, dl, VT, 6335 N1, DAG.getConstantFP(1.0, VT))); 6336 6337 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6338 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6339 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 6340 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6341 DAG.getNode(ISD::FADD, dl, VT, 6342 N1, DAG.getConstantFP(-1.0, VT))); 6343 6344 6345 return SDValue(); 6346} 6347 6348SDValue DAGCombiner::visitFDIV(SDNode *N) { 6349 SDValue N0 = N->getOperand(0); 6350 SDValue N1 = N->getOperand(1); 6351 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6352 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6353 EVT VT = N->getValueType(0); 6354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6355 6356 // fold vector ops 6357 if (VT.isVector()) { 6358 SDValue FoldedVOp = SimplifyVBinOp(N); 6359 if (FoldedVOp.getNode()) return FoldedVOp; 6360 } 6361 6362 // fold (fdiv c1, c2) -> c1/c2 6363 if (N0CFP && N1CFP) 6364 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 6365 6366 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6367 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) { 6368 // Compute the reciprocal 1.0 / c2. 6369 APFloat N1APF = N1CFP->getValueAPF(); 6370 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6371 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6372 // Only do the transform if the reciprocal is a legal fp immediate that 6373 // isn't too nasty (eg NaN, denormal, ...). 6374 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6375 (!LegalOperations || 6376 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6377 // backend)... we should handle this gracefully after Legalize. 6378 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6379 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6380 TLI.isFPImmLegal(Recip, VT))) 6381 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 6382 DAG.getConstantFP(Recip, VT)); 6383 } 6384 6385 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6386 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6387 &DAG.getTarget().Options)) { 6388 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6389 &DAG.getTarget().Options)) { 6390 // Both can be negated for free, check to see if at least one is cheaper 6391 // negated. 6392 if (LHSNeg == 2 || RHSNeg == 2) 6393 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 6394 GetNegatedExpression(N0, DAG, LegalOperations), 6395 GetNegatedExpression(N1, DAG, LegalOperations)); 6396 } 6397 } 6398 6399 return SDValue(); 6400} 6401 6402SDValue DAGCombiner::visitFREM(SDNode *N) { 6403 SDValue N0 = N->getOperand(0); 6404 SDValue N1 = N->getOperand(1); 6405 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6406 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6407 EVT VT = N->getValueType(0); 6408 6409 // fold (frem c1, c2) -> fmod(c1,c2) 6410 if (N0CFP && N1CFP) 6411 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 6412 6413 return SDValue(); 6414} 6415 6416SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6417 SDValue N0 = N->getOperand(0); 6418 SDValue N1 = N->getOperand(1); 6419 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6420 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6421 EVT VT = N->getValueType(0); 6422 6423 if (N0CFP && N1CFP) // Constant fold 6424 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 6425 6426 if (N1CFP) { 6427 const APFloat& V = N1CFP->getValueAPF(); 6428 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6429 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6430 if (!V.isNegative()) { 6431 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6432 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6433 } else { 6434 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6435 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6436 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 6437 } 6438 } 6439 6440 // copysign(fabs(x), y) -> copysign(x, y) 6441 // copysign(fneg(x), y) -> copysign(x, y) 6442 // copysign(copysign(x,z), y) -> copysign(x, y) 6443 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6444 N0.getOpcode() == ISD::FCOPYSIGN) 6445 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6446 N0.getOperand(0), N1); 6447 6448 // copysign(x, abs(y)) -> abs(x) 6449 if (N1.getOpcode() == ISD::FABS) 6450 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6451 6452 // copysign(x, copysign(y,z)) -> copysign(x, z) 6453 if (N1.getOpcode() == ISD::FCOPYSIGN) 6454 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6455 N0, N1.getOperand(1)); 6456 6457 // copysign(x, fp_extend(y)) -> copysign(x, y) 6458 // copysign(x, fp_round(y)) -> copysign(x, y) 6459 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6460 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6461 N0, N1.getOperand(0)); 6462 6463 return SDValue(); 6464} 6465 6466SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6467 SDValue N0 = N->getOperand(0); 6468 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6469 EVT VT = N->getValueType(0); 6470 EVT OpVT = N0.getValueType(); 6471 6472 // fold (sint_to_fp c1) -> c1fp 6473 if (N0C && 6474 // ...but only if the target supports immediate floating-point values 6475 (!LegalOperations || 6476 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6477 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6478 6479 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6480 // but UINT_TO_FP is legal on this target, try to convert. 6481 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6482 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6483 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6484 if (DAG.SignBitIsZero(N0)) 6485 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6486 } 6487 6488 // The next optimizations are desireable only if SELECT_CC can be lowered. 6489 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6490 // having to say they don't support SELECT_CC on every type the DAG knows 6491 // about, since there is no way to mark an opcode illegal at all value types 6492 // (See also visitSELECT) 6493 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6494 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6495 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6496 !VT.isVector() && 6497 (!LegalOperations || 6498 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6499 SDValue Ops[] = 6500 { N0.getOperand(0), N0.getOperand(1), 6501 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6502 N0.getOperand(2) }; 6503 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6504 } 6505 6506 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6507 // (select_cc x, y, 1.0, 0.0,, cc) 6508 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6509 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6510 (!LegalOperations || 6511 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6512 SDValue Ops[] = 6513 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6514 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6515 N0.getOperand(0).getOperand(2) }; 6516 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6517 } 6518 } 6519 6520 return SDValue(); 6521} 6522 6523SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6524 SDValue N0 = N->getOperand(0); 6525 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6526 EVT VT = N->getValueType(0); 6527 EVT OpVT = N0.getValueType(); 6528 6529 // fold (uint_to_fp c1) -> c1fp 6530 if (N0C && 6531 // ...but only if the target supports immediate floating-point values 6532 (!LegalOperations || 6533 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6534 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6535 6536 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 6537 // but SINT_TO_FP is legal on this target, try to convert. 6538 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 6539 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 6540 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 6541 if (DAG.SignBitIsZero(N0)) 6542 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6543 } 6544 6545 // The next optimizations are desireable only if SELECT_CC can be lowered. 6546 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6547 // having to say they don't support SELECT_CC on every type the DAG knows 6548 // about, since there is no way to mark an opcode illegal at all value types 6549 // (See also visitSELECT) 6550 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6551 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6552 6553 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 6554 (!LegalOperations || 6555 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6556 SDValue Ops[] = 6557 { N0.getOperand(0), N0.getOperand(1), 6558 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 6559 N0.getOperand(2) }; 6560 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6561 } 6562 } 6563 6564 return SDValue(); 6565} 6566 6567SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 6568 SDValue N0 = N->getOperand(0); 6569 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6570 EVT VT = N->getValueType(0); 6571 6572 // fold (fp_to_sint c1fp) -> c1 6573 if (N0CFP) 6574 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 6575 6576 return SDValue(); 6577} 6578 6579SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 6580 SDValue N0 = N->getOperand(0); 6581 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6582 EVT VT = N->getValueType(0); 6583 6584 // fold (fp_to_uint c1fp) -> c1 6585 if (N0CFP) 6586 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 6587 6588 return SDValue(); 6589} 6590 6591SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 6592 SDValue N0 = N->getOperand(0); 6593 SDValue N1 = N->getOperand(1); 6594 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6595 EVT VT = N->getValueType(0); 6596 6597 // fold (fp_round c1fp) -> c1fp 6598 if (N0CFP) 6599 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 6600 6601 // fold (fp_round (fp_extend x)) -> x 6602 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 6603 return N0.getOperand(0); 6604 6605 // fold (fp_round (fp_round x)) -> (fp_round x) 6606 if (N0.getOpcode() == ISD::FP_ROUND) { 6607 // This is a value preserving truncation if both round's are. 6608 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 6609 N0.getNode()->getConstantOperandVal(1) == 1; 6610 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 6611 DAG.getIntPtrConstant(IsTrunc)); 6612 } 6613 6614 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 6615 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 6616 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 6617 N0.getOperand(0), N1); 6618 AddToWorkList(Tmp.getNode()); 6619 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6620 Tmp, N0.getOperand(1)); 6621 } 6622 6623 return SDValue(); 6624} 6625 6626SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 6627 SDValue N0 = N->getOperand(0); 6628 EVT VT = N->getValueType(0); 6629 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6630 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6631 6632 // fold (fp_round_inreg c1fp) -> c1fp 6633 if (N0CFP && isTypeLegal(EVT)) { 6634 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 6635 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 6636 } 6637 6638 return SDValue(); 6639} 6640 6641SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 6642 SDValue N0 = N->getOperand(0); 6643 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6644 EVT VT = N->getValueType(0); 6645 6646 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 6647 if (N->hasOneUse() && 6648 N->use_begin()->getOpcode() == ISD::FP_ROUND) 6649 return SDValue(); 6650 6651 // fold (fp_extend c1fp) -> c1fp 6652 if (N0CFP) 6653 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 6654 6655 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 6656 // value of X. 6657 if (N0.getOpcode() == ISD::FP_ROUND 6658 && N0.getNode()->getConstantOperandVal(1) == 1) { 6659 SDValue In = N0.getOperand(0); 6660 if (In.getValueType() == VT) return In; 6661 if (VT.bitsLT(In.getValueType())) 6662 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 6663 In, N0.getOperand(1)); 6664 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 6665 } 6666 6667 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 6668 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() && 6669 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6670 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 6671 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6672 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6673 LN0->getChain(), 6674 LN0->getBasePtr(), LN0->getPointerInfo(), 6675 N0.getValueType(), 6676 LN0->isVolatile(), LN0->isNonTemporal(), 6677 LN0->getAlignment()); 6678 CombineTo(N, ExtLoad); 6679 CombineTo(N0.getNode(), 6680 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 6681 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 6682 ExtLoad.getValue(1)); 6683 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6684 } 6685 6686 return SDValue(); 6687} 6688 6689SDValue DAGCombiner::visitFNEG(SDNode *N) { 6690 SDValue N0 = N->getOperand(0); 6691 EVT VT = N->getValueType(0); 6692 6693 if (VT.isVector()) { 6694 SDValue FoldedVOp = SimplifyVUnaryOp(N); 6695 if (FoldedVOp.getNode()) return FoldedVOp; 6696 } 6697 6698 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 6699 &DAG.getTarget().Options)) 6700 return GetNegatedExpression(N0, DAG, LegalOperations); 6701 6702 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 6703 // constant pool values. 6704 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 6705 !VT.isVector() && 6706 N0.getNode()->hasOneUse() && 6707 N0.getOperand(0).getValueType().isInteger()) { 6708 SDValue Int = N0.getOperand(0); 6709 EVT IntVT = Int.getValueType(); 6710 if (IntVT.isInteger() && !IntVT.isVector()) { 6711 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 6712 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6713 AddToWorkList(Int.getNode()); 6714 return DAG.getNode(ISD::BITCAST, SDLoc(N), 6715 VT, Int); 6716 } 6717 } 6718 6719 // (fneg (fmul c, x)) -> (fmul -c, x) 6720 if (N0.getOpcode() == ISD::FMUL) { 6721 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6722 if (CFP1) 6723 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6724 N0.getOperand(0), 6725 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6726 N0.getOperand(1))); 6727 } 6728 6729 return SDValue(); 6730} 6731 6732SDValue DAGCombiner::visitFCEIL(SDNode *N) { 6733 SDValue N0 = N->getOperand(0); 6734 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6735 EVT VT = N->getValueType(0); 6736 6737 // fold (fceil c1) -> fceil(c1) 6738 if (N0CFP) 6739 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 6740 6741 return SDValue(); 6742} 6743 6744SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 6745 SDValue N0 = N->getOperand(0); 6746 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6747 EVT VT = N->getValueType(0); 6748 6749 // fold (ftrunc c1) -> ftrunc(c1) 6750 if (N0CFP) 6751 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 6752 6753 return SDValue(); 6754} 6755 6756SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 6757 SDValue N0 = N->getOperand(0); 6758 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6759 EVT VT = N->getValueType(0); 6760 6761 // fold (ffloor c1) -> ffloor(c1) 6762 if (N0CFP) 6763 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 6764 6765 return SDValue(); 6766} 6767 6768SDValue DAGCombiner::visitFABS(SDNode *N) { 6769 SDValue N0 = N->getOperand(0); 6770 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6771 EVT VT = N->getValueType(0); 6772 6773 if (VT.isVector()) { 6774 SDValue FoldedVOp = SimplifyVUnaryOp(N); 6775 if (FoldedVOp.getNode()) return FoldedVOp; 6776 } 6777 6778 // fold (fabs c1) -> fabs(c1) 6779 if (N0CFP) 6780 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6781 // fold (fabs (fabs x)) -> (fabs x) 6782 if (N0.getOpcode() == ISD::FABS) 6783 return N->getOperand(0); 6784 // fold (fabs (fneg x)) -> (fabs x) 6785 // fold (fabs (fcopysign x, y)) -> (fabs x) 6786 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 6787 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 6788 6789 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 6790 // constant pool values. 6791 if (!TLI.isFAbsFree(VT) && 6792 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 6793 N0.getOperand(0).getValueType().isInteger() && 6794 !N0.getOperand(0).getValueType().isVector()) { 6795 SDValue Int = N0.getOperand(0); 6796 EVT IntVT = Int.getValueType(); 6797 if (IntVT.isInteger() && !IntVT.isVector()) { 6798 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 6799 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6800 AddToWorkList(Int.getNode()); 6801 return DAG.getNode(ISD::BITCAST, SDLoc(N), 6802 N->getValueType(0), Int); 6803 } 6804 } 6805 6806 return SDValue(); 6807} 6808 6809SDValue DAGCombiner::visitBRCOND(SDNode *N) { 6810 SDValue Chain = N->getOperand(0); 6811 SDValue N1 = N->getOperand(1); 6812 SDValue N2 = N->getOperand(2); 6813 6814 // If N is a constant we could fold this into a fallthrough or unconditional 6815 // branch. However that doesn't happen very often in normal code, because 6816 // Instcombine/SimplifyCFG should have handled the available opportunities. 6817 // If we did this folding here, it would be necessary to update the 6818 // MachineBasicBlock CFG, which is awkward. 6819 6820 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 6821 // on the target. 6822 if (N1.getOpcode() == ISD::SETCC && 6823 TLI.isOperationLegalOrCustom(ISD::BR_CC, 6824 N1.getOperand(0).getValueType())) { 6825 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 6826 Chain, N1.getOperand(2), 6827 N1.getOperand(0), N1.getOperand(1), N2); 6828 } 6829 6830 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 6831 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 6832 (N1.getOperand(0).hasOneUse() && 6833 N1.getOperand(0).getOpcode() == ISD::SRL))) { 6834 SDNode *Trunc = 0; 6835 if (N1.getOpcode() == ISD::TRUNCATE) { 6836 // Look pass the truncate. 6837 Trunc = N1.getNode(); 6838 N1 = N1.getOperand(0); 6839 } 6840 6841 // Match this pattern so that we can generate simpler code: 6842 // 6843 // %a = ... 6844 // %b = and i32 %a, 2 6845 // %c = srl i32 %b, 1 6846 // brcond i32 %c ... 6847 // 6848 // into 6849 // 6850 // %a = ... 6851 // %b = and i32 %a, 2 6852 // %c = setcc eq %b, 0 6853 // brcond %c ... 6854 // 6855 // This applies only when the AND constant value has one bit set and the 6856 // SRL constant is equal to the log2 of the AND constant. The back-end is 6857 // smart enough to convert the result into a TEST/JMP sequence. 6858 SDValue Op0 = N1.getOperand(0); 6859 SDValue Op1 = N1.getOperand(1); 6860 6861 if (Op0.getOpcode() == ISD::AND && 6862 Op1.getOpcode() == ISD::Constant) { 6863 SDValue AndOp1 = Op0.getOperand(1); 6864 6865 if (AndOp1.getOpcode() == ISD::Constant) { 6866 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 6867 6868 if (AndConst.isPowerOf2() && 6869 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 6870 SDValue SetCC = 6871 DAG.getSetCC(SDLoc(N), 6872 getSetCCResultType(Op0.getValueType()), 6873 Op0, DAG.getConstant(0, Op0.getValueType()), 6874 ISD::SETNE); 6875 6876 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 6877 MVT::Other, Chain, SetCC, N2); 6878 // Don't add the new BRCond into the worklist or else SimplifySelectCC 6879 // will convert it back to (X & C1) >> C2. 6880 CombineTo(N, NewBRCond, false); 6881 // Truncate is dead. 6882 if (Trunc) { 6883 removeFromWorkList(Trunc); 6884 DAG.DeleteNode(Trunc); 6885 } 6886 // Replace the uses of SRL with SETCC 6887 WorkListRemover DeadNodes(*this); 6888 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6889 removeFromWorkList(N1.getNode()); 6890 DAG.DeleteNode(N1.getNode()); 6891 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6892 } 6893 } 6894 } 6895 6896 if (Trunc) 6897 // Restore N1 if the above transformation doesn't match. 6898 N1 = N->getOperand(1); 6899 } 6900 6901 // Transform br(xor(x, y)) -> br(x != y) 6902 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 6903 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 6904 SDNode *TheXor = N1.getNode(); 6905 SDValue Op0 = TheXor->getOperand(0); 6906 SDValue Op1 = TheXor->getOperand(1); 6907 if (Op0.getOpcode() == Op1.getOpcode()) { 6908 // Avoid missing important xor optimizations. 6909 SDValue Tmp = visitXOR(TheXor); 6910 if (Tmp.getNode()) { 6911 if (Tmp.getNode() != TheXor) { 6912 DEBUG(dbgs() << "\nReplacing.8 "; 6913 TheXor->dump(&DAG); 6914 dbgs() << "\nWith: "; 6915 Tmp.getNode()->dump(&DAG); 6916 dbgs() << '\n'); 6917 WorkListRemover DeadNodes(*this); 6918 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 6919 removeFromWorkList(TheXor); 6920 DAG.DeleteNode(TheXor); 6921 return DAG.getNode(ISD::BRCOND, SDLoc(N), 6922 MVT::Other, Chain, Tmp, N2); 6923 } 6924 6925 // visitXOR has changed XOR's operands or replaced the XOR completely, 6926 // bail out. 6927 return SDValue(N, 0); 6928 } 6929 } 6930 6931 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 6932 bool Equal = false; 6933 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 6934 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 6935 Op0.getOpcode() == ISD::XOR) { 6936 TheXor = Op0.getNode(); 6937 Equal = true; 6938 } 6939 6940 EVT SetCCVT = N1.getValueType(); 6941 if (LegalTypes) 6942 SetCCVT = getSetCCResultType(SetCCVT); 6943 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 6944 SetCCVT, 6945 Op0, Op1, 6946 Equal ? ISD::SETEQ : ISD::SETNE); 6947 // Replace the uses of XOR with SETCC 6948 WorkListRemover DeadNodes(*this); 6949 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6950 removeFromWorkList(N1.getNode()); 6951 DAG.DeleteNode(N1.getNode()); 6952 return DAG.getNode(ISD::BRCOND, SDLoc(N), 6953 MVT::Other, Chain, SetCC, N2); 6954 } 6955 } 6956 6957 return SDValue(); 6958} 6959 6960// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 6961// 6962SDValue DAGCombiner::visitBR_CC(SDNode *N) { 6963 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 6964 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 6965 6966 // If N is a constant we could fold this into a fallthrough or unconditional 6967 // branch. However that doesn't happen very often in normal code, because 6968 // Instcombine/SimplifyCFG should have handled the available opportunities. 6969 // If we did this folding here, it would be necessary to update the 6970 // MachineBasicBlock CFG, which is awkward. 6971 6972 // Use SimplifySetCC to simplify SETCC's. 6973 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 6974 CondLHS, CondRHS, CC->get(), SDLoc(N), 6975 false); 6976 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 6977 6978 // fold to a simpler setcc 6979 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 6980 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 6981 N->getOperand(0), Simp.getOperand(2), 6982 Simp.getOperand(0), Simp.getOperand(1), 6983 N->getOperand(4)); 6984 6985 return SDValue(); 6986} 6987 6988/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 6989/// uses N as its base pointer and that N may be folded in the load / store 6990/// addressing mode. 6991static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 6992 SelectionDAG &DAG, 6993 const TargetLowering &TLI) { 6994 EVT VT; 6995 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 6996 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 6997 return false; 6998 VT = Use->getValueType(0); 6999 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 7000 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 7001 return false; 7002 VT = ST->getValue().getValueType(); 7003 } else 7004 return false; 7005 7006 TargetLowering::AddrMode AM; 7007 if (N->getOpcode() == ISD::ADD) { 7008 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7009 if (Offset) 7010 // [reg +/- imm] 7011 AM.BaseOffs = Offset->getSExtValue(); 7012 else 7013 // [reg +/- reg] 7014 AM.Scale = 1; 7015 } else if (N->getOpcode() == ISD::SUB) { 7016 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7017 if (Offset) 7018 // [reg +/- imm] 7019 AM.BaseOffs = -Offset->getSExtValue(); 7020 else 7021 // [reg +/- reg] 7022 AM.Scale = 1; 7023 } else 7024 return false; 7025 7026 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 7027} 7028 7029/// CombineToPreIndexedLoadStore - Try turning a load / store into a 7030/// pre-indexed load / store when the base pointer is an add or subtract 7031/// and it has other uses besides the load / store. After the 7032/// transformation, the new indexed load / store has effectively folded 7033/// the add / subtract in and all of its other uses are redirected to the 7034/// new load / store. 7035bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 7036 if (Level < AfterLegalizeDAG) 7037 return false; 7038 7039 bool isLoad = true; 7040 SDValue Ptr; 7041 EVT VT; 7042 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7043 if (LD->isIndexed()) 7044 return false; 7045 VT = LD->getMemoryVT(); 7046 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 7047 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 7048 return false; 7049 Ptr = LD->getBasePtr(); 7050 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7051 if (ST->isIndexed()) 7052 return false; 7053 VT = ST->getMemoryVT(); 7054 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 7055 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 7056 return false; 7057 Ptr = ST->getBasePtr(); 7058 isLoad = false; 7059 } else { 7060 return false; 7061 } 7062 7063 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 7064 // out. There is no reason to make this a preinc/predec. 7065 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 7066 Ptr.getNode()->hasOneUse()) 7067 return false; 7068 7069 // Ask the target to do addressing mode selection. 7070 SDValue BasePtr; 7071 SDValue Offset; 7072 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7073 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 7074 return false; 7075 7076 // Backends without true r+i pre-indexed forms may need to pass a 7077 // constant base with a variable offset so that constant coercion 7078 // will work with the patterns in canonical form. 7079 bool Swapped = false; 7080 if (isa<ConstantSDNode>(BasePtr)) { 7081 std::swap(BasePtr, Offset); 7082 Swapped = true; 7083 } 7084 7085 // Don't create a indexed load / store with zero offset. 7086 if (isa<ConstantSDNode>(Offset) && 7087 cast<ConstantSDNode>(Offset)->isNullValue()) 7088 return false; 7089 7090 // Try turning it into a pre-indexed load / store except when: 7091 // 1) The new base ptr is a frame index. 7092 // 2) If N is a store and the new base ptr is either the same as or is a 7093 // predecessor of the value being stored. 7094 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 7095 // that would create a cycle. 7096 // 4) All uses are load / store ops that use it as old base ptr. 7097 7098 // Check #1. Preinc'ing a frame index would require copying the stack pointer 7099 // (plus the implicit offset) to a register to preinc anyway. 7100 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7101 return false; 7102 7103 // Check #2. 7104 if (!isLoad) { 7105 SDValue Val = cast<StoreSDNode>(N)->getValue(); 7106 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 7107 return false; 7108 } 7109 7110 // If the offset is a constant, there may be other adds of constants that 7111 // can be folded with this one. We should do this to avoid having to keep 7112 // a copy of the original base pointer. 7113 SmallVector<SDNode *, 16> OtherUses; 7114 if (isa<ConstantSDNode>(Offset)) 7115 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(), 7116 E = BasePtr.getNode()->use_end(); I != E; ++I) { 7117 SDNode *Use = *I; 7118 if (Use == Ptr.getNode()) 7119 continue; 7120 7121 if (Use->isPredecessorOf(N)) 7122 continue; 7123 7124 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 7125 OtherUses.clear(); 7126 break; 7127 } 7128 7129 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 7130 if (Op1.getNode() == BasePtr.getNode()) 7131 std::swap(Op0, Op1); 7132 assert(Op0.getNode() == BasePtr.getNode() && 7133 "Use of ADD/SUB but not an operand"); 7134 7135 if (!isa<ConstantSDNode>(Op1)) { 7136 OtherUses.clear(); 7137 break; 7138 } 7139 7140 // FIXME: In some cases, we can be smarter about this. 7141 if (Op1.getValueType() != Offset.getValueType()) { 7142 OtherUses.clear(); 7143 break; 7144 } 7145 7146 OtherUses.push_back(Use); 7147 } 7148 7149 if (Swapped) 7150 std::swap(BasePtr, Offset); 7151 7152 // Now check for #3 and #4. 7153 bool RealUse = false; 7154 7155 // Caches for hasPredecessorHelper 7156 SmallPtrSet<const SDNode *, 32> Visited; 7157 SmallVector<const SDNode *, 16> Worklist; 7158 7159 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7160 E = Ptr.getNode()->use_end(); I != E; ++I) { 7161 SDNode *Use = *I; 7162 if (Use == N) 7163 continue; 7164 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 7165 return false; 7166 7167 // If Ptr may be folded in addressing mode of other use, then it's 7168 // not profitable to do this transformation. 7169 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 7170 RealUse = true; 7171 } 7172 7173 if (!RealUse) 7174 return false; 7175 7176 SDValue Result; 7177 if (isLoad) 7178 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7179 BasePtr, Offset, AM); 7180 else 7181 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7182 BasePtr, Offset, AM); 7183 ++PreIndexedNodes; 7184 ++NodesCombined; 7185 DEBUG(dbgs() << "\nReplacing.4 "; 7186 N->dump(&DAG); 7187 dbgs() << "\nWith: "; 7188 Result.getNode()->dump(&DAG); 7189 dbgs() << '\n'); 7190 WorkListRemover DeadNodes(*this); 7191 if (isLoad) { 7192 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7193 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7194 } else { 7195 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7196 } 7197 7198 // Finally, since the node is now dead, remove it from the graph. 7199 DAG.DeleteNode(N); 7200 7201 if (Swapped) 7202 std::swap(BasePtr, Offset); 7203 7204 // Replace other uses of BasePtr that can be updated to use Ptr 7205 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 7206 unsigned OffsetIdx = 1; 7207 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 7208 OffsetIdx = 0; 7209 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 7210 BasePtr.getNode() && "Expected BasePtr operand"); 7211 7212 // We need to replace ptr0 in the following expression: 7213 // x0 * offset0 + y0 * ptr0 = t0 7214 // knowing that 7215 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 7216 // 7217 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 7218 // indexed load/store and the expresion that needs to be re-written. 7219 // 7220 // Therefore, we have: 7221 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 7222 7223 ConstantSDNode *CN = 7224 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 7225 int X0, X1, Y0, Y1; 7226 APInt Offset0 = CN->getAPIntValue(); 7227 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 7228 7229 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 7230 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 7231 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 7232 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 7233 7234 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 7235 7236 APInt CNV = Offset0; 7237 if (X0 < 0) CNV = -CNV; 7238 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 7239 else CNV = CNV - Offset1; 7240 7241 // We can now generate the new expression. 7242 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 7243 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 7244 7245 SDValue NewUse = DAG.getNode(Opcode, 7246 SDLoc(OtherUses[i]), 7247 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 7248 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 7249 removeFromWorkList(OtherUses[i]); 7250 DAG.DeleteNode(OtherUses[i]); 7251 } 7252 7253 // Replace the uses of Ptr with uses of the updated base value. 7254 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 7255 removeFromWorkList(Ptr.getNode()); 7256 DAG.DeleteNode(Ptr.getNode()); 7257 7258 return true; 7259} 7260 7261/// CombineToPostIndexedLoadStore - Try to combine a load / store with a 7262/// add / sub of the base pointer node into a post-indexed load / store. 7263/// The transformation folded the add / subtract into the new indexed 7264/// load / store effectively and all of its uses are redirected to the 7265/// new load / store. 7266bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 7267 if (Level < AfterLegalizeDAG) 7268 return false; 7269 7270 bool isLoad = true; 7271 SDValue Ptr; 7272 EVT VT; 7273 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7274 if (LD->isIndexed()) 7275 return false; 7276 VT = LD->getMemoryVT(); 7277 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 7278 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 7279 return false; 7280 Ptr = LD->getBasePtr(); 7281 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7282 if (ST->isIndexed()) 7283 return false; 7284 VT = ST->getMemoryVT(); 7285 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 7286 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 7287 return false; 7288 Ptr = ST->getBasePtr(); 7289 isLoad = false; 7290 } else { 7291 return false; 7292 } 7293 7294 if (Ptr.getNode()->hasOneUse()) 7295 return false; 7296 7297 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7298 E = Ptr.getNode()->use_end(); I != E; ++I) { 7299 SDNode *Op = *I; 7300 if (Op == N || 7301 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 7302 continue; 7303 7304 SDValue BasePtr; 7305 SDValue Offset; 7306 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7307 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 7308 // Don't create a indexed load / store with zero offset. 7309 if (isa<ConstantSDNode>(Offset) && 7310 cast<ConstantSDNode>(Offset)->isNullValue()) 7311 continue; 7312 7313 // Try turning it into a post-indexed load / store except when 7314 // 1) All uses are load / store ops that use it as base ptr (and 7315 // it may be folded as addressing mmode). 7316 // 2) Op must be independent of N, i.e. Op is neither a predecessor 7317 // nor a successor of N. Otherwise, if Op is folded that would 7318 // create a cycle. 7319 7320 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7321 continue; 7322 7323 // Check for #1. 7324 bool TryNext = false; 7325 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 7326 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 7327 SDNode *Use = *II; 7328 if (Use == Ptr.getNode()) 7329 continue; 7330 7331 // If all the uses are load / store addresses, then don't do the 7332 // transformation. 7333 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 7334 bool RealUse = false; 7335 for (SDNode::use_iterator III = Use->use_begin(), 7336 EEE = Use->use_end(); III != EEE; ++III) { 7337 SDNode *UseUse = *III; 7338 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 7339 RealUse = true; 7340 } 7341 7342 if (!RealUse) { 7343 TryNext = true; 7344 break; 7345 } 7346 } 7347 } 7348 7349 if (TryNext) 7350 continue; 7351 7352 // Check for #2 7353 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 7354 SDValue Result = isLoad 7355 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7356 BasePtr, Offset, AM) 7357 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7358 BasePtr, Offset, AM); 7359 ++PostIndexedNodes; 7360 ++NodesCombined; 7361 DEBUG(dbgs() << "\nReplacing.5 "; 7362 N->dump(&DAG); 7363 dbgs() << "\nWith: "; 7364 Result.getNode()->dump(&DAG); 7365 dbgs() << '\n'); 7366 WorkListRemover DeadNodes(*this); 7367 if (isLoad) { 7368 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7369 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7370 } else { 7371 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7372 } 7373 7374 // Finally, since the node is now dead, remove it from the graph. 7375 DAG.DeleteNode(N); 7376 7377 // Replace the uses of Use with uses of the updated base value. 7378 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 7379 Result.getValue(isLoad ? 1 : 0)); 7380 removeFromWorkList(Op); 7381 DAG.DeleteNode(Op); 7382 return true; 7383 } 7384 } 7385 } 7386 7387 return false; 7388} 7389 7390SDValue DAGCombiner::visitLOAD(SDNode *N) { 7391 LoadSDNode *LD = cast<LoadSDNode>(N); 7392 SDValue Chain = LD->getChain(); 7393 SDValue Ptr = LD->getBasePtr(); 7394 7395 // If load is not volatile and there are no uses of the loaded value (and 7396 // the updated indexed value in case of indexed loads), change uses of the 7397 // chain value into uses of the chain input (i.e. delete the dead load). 7398 if (!LD->isVolatile()) { 7399 if (N->getValueType(1) == MVT::Other) { 7400 // Unindexed loads. 7401 if (!N->hasAnyUseOfValue(0)) { 7402 // It's not safe to use the two value CombineTo variant here. e.g. 7403 // v1, chain2 = load chain1, loc 7404 // v2, chain3 = load chain2, loc 7405 // v3 = add v2, c 7406 // Now we replace use of chain2 with chain1. This makes the second load 7407 // isomorphic to the one we are deleting, and thus makes this load live. 7408 DEBUG(dbgs() << "\nReplacing.6 "; 7409 N->dump(&DAG); 7410 dbgs() << "\nWith chain: "; 7411 Chain.getNode()->dump(&DAG); 7412 dbgs() << "\n"); 7413 WorkListRemover DeadNodes(*this); 7414 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7415 7416 if (N->use_empty()) { 7417 removeFromWorkList(N); 7418 DAG.DeleteNode(N); 7419 } 7420 7421 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7422 } 7423 } else { 7424 // Indexed loads. 7425 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7426 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7427 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7428 DEBUG(dbgs() << "\nReplacing.7 "; 7429 N->dump(&DAG); 7430 dbgs() << "\nWith: "; 7431 Undef.getNode()->dump(&DAG); 7432 dbgs() << " and 2 other values\n"); 7433 WorkListRemover DeadNodes(*this); 7434 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7435 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7436 DAG.getUNDEF(N->getValueType(1))); 7437 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7438 removeFromWorkList(N); 7439 DAG.DeleteNode(N); 7440 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7441 } 7442 } 7443 } 7444 7445 // If this load is directly stored, replace the load value with the stored 7446 // value. 7447 // TODO: Handle store large -> read small portion. 7448 // TODO: Handle TRUNCSTORE/LOADEXT 7449 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7450 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7451 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7452 if (PrevST->getBasePtr() == Ptr && 7453 PrevST->getValue().getValueType() == N->getValueType(0)) 7454 return CombineTo(N, Chain.getOperand(1), Chain); 7455 } 7456 } 7457 7458 // Try to infer better alignment information than the load already has. 7459 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7460 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7461 if (Align > LD->getMemOperand()->getBaseAlignment()) { 7462 SDValue NewLoad = 7463 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 7464 LD->getValueType(0), 7465 Chain, Ptr, LD->getPointerInfo(), 7466 LD->getMemoryVT(), 7467 LD->isVolatile(), LD->isNonTemporal(), Align); 7468 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 7469 } 7470 } 7471 } 7472 7473 if (CombinerAA) { 7474 // Walk up chain skipping non-aliasing memory nodes. 7475 SDValue BetterChain = FindBetterChain(N, Chain); 7476 7477 // If there is a better chain. 7478 if (Chain != BetterChain) { 7479 SDValue ReplLoad; 7480 7481 // Replace the chain to void dependency. 7482 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 7483 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 7484 BetterChain, Ptr, LD->getPointerInfo(), 7485 LD->isVolatile(), LD->isNonTemporal(), 7486 LD->isInvariant(), LD->getAlignment()); 7487 } else { 7488 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 7489 LD->getValueType(0), 7490 BetterChain, Ptr, LD->getPointerInfo(), 7491 LD->getMemoryVT(), 7492 LD->isVolatile(), 7493 LD->isNonTemporal(), 7494 LD->getAlignment()); 7495 } 7496 7497 // Create token factor to keep old chain connected. 7498 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 7499 MVT::Other, Chain, ReplLoad.getValue(1)); 7500 7501 // Make sure the new and old chains are cleaned up. 7502 AddToWorkList(Token.getNode()); 7503 7504 // Replace uses with load result and token factor. Don't add users 7505 // to work list. 7506 return CombineTo(N, ReplLoad.getValue(0), Token, false); 7507 } 7508 } 7509 7510 // Try transforming N to an indexed load. 7511 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7512 return SDValue(N, 0); 7513 7514 return SDValue(); 7515} 7516 7517/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 7518/// load is having specific bytes cleared out. If so, return the byte size 7519/// being masked out and the shift amount. 7520static std::pair<unsigned, unsigned> 7521CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 7522 std::pair<unsigned, unsigned> Result(0, 0); 7523 7524 // Check for the structure we're looking for. 7525 if (V->getOpcode() != ISD::AND || 7526 !isa<ConstantSDNode>(V->getOperand(1)) || 7527 !ISD::isNormalLoad(V->getOperand(0).getNode())) 7528 return Result; 7529 7530 // Check the chain and pointer. 7531 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 7532 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 7533 7534 // The store should be chained directly to the load or be an operand of a 7535 // tokenfactor. 7536 if (LD == Chain.getNode()) 7537 ; // ok. 7538 else if (Chain->getOpcode() != ISD::TokenFactor) 7539 return Result; // Fail. 7540 else { 7541 bool isOk = false; 7542 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 7543 if (Chain->getOperand(i).getNode() == LD) { 7544 isOk = true; 7545 break; 7546 } 7547 if (!isOk) return Result; 7548 } 7549 7550 // This only handles simple types. 7551 if (V.getValueType() != MVT::i16 && 7552 V.getValueType() != MVT::i32 && 7553 V.getValueType() != MVT::i64) 7554 return Result; 7555 7556 // Check the constant mask. Invert it so that the bits being masked out are 7557 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 7558 // follow the sign bit for uniformity. 7559 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 7560 unsigned NotMaskLZ = countLeadingZeros(NotMask); 7561 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 7562 unsigned NotMaskTZ = countTrailingZeros(NotMask); 7563 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 7564 if (NotMaskLZ == 64) return Result; // All zero mask. 7565 7566 // See if we have a continuous run of bits. If so, we have 0*1+0* 7567 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 7568 return Result; 7569 7570 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 7571 if (V.getValueType() != MVT::i64 && NotMaskLZ) 7572 NotMaskLZ -= 64-V.getValueSizeInBits(); 7573 7574 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 7575 switch (MaskedBytes) { 7576 case 1: 7577 case 2: 7578 case 4: break; 7579 default: return Result; // All one mask, or 5-byte mask. 7580 } 7581 7582 // Verify that the first bit starts at a multiple of mask so that the access 7583 // is aligned the same as the access width. 7584 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 7585 7586 Result.first = MaskedBytes; 7587 Result.second = NotMaskTZ/8; 7588 return Result; 7589} 7590 7591 7592/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 7593/// provides a value as specified by MaskInfo. If so, replace the specified 7594/// store with a narrower store of truncated IVal. 7595static SDNode * 7596ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 7597 SDValue IVal, StoreSDNode *St, 7598 DAGCombiner *DC) { 7599 unsigned NumBytes = MaskInfo.first; 7600 unsigned ByteShift = MaskInfo.second; 7601 SelectionDAG &DAG = DC->getDAG(); 7602 7603 // Check to see if IVal is all zeros in the part being masked in by the 'or' 7604 // that uses this. If not, this is not a replacement. 7605 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 7606 ByteShift*8, (ByteShift+NumBytes)*8); 7607 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 7608 7609 // Check that it is legal on the target to do this. It is legal if the new 7610 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 7611 // legalization. 7612 MVT VT = MVT::getIntegerVT(NumBytes*8); 7613 if (!DC->isTypeLegal(VT)) 7614 return 0; 7615 7616 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 7617 // shifted by ByteShift and truncated down to NumBytes. 7618 if (ByteShift) 7619 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 7620 DAG.getConstant(ByteShift*8, 7621 DC->getShiftAmountTy(IVal.getValueType()))); 7622 7623 // Figure out the offset for the store and the alignment of the access. 7624 unsigned StOffset; 7625 unsigned NewAlign = St->getAlignment(); 7626 7627 if (DAG.getTargetLoweringInfo().isLittleEndian()) 7628 StOffset = ByteShift; 7629 else 7630 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 7631 7632 SDValue Ptr = St->getBasePtr(); 7633 if (StOffset) { 7634 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 7635 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 7636 NewAlign = MinAlign(NewAlign, StOffset); 7637 } 7638 7639 // Truncate down to the new size. 7640 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 7641 7642 ++OpsNarrowed; 7643 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 7644 St->getPointerInfo().getWithOffset(StOffset), 7645 false, false, NewAlign).getNode(); 7646} 7647 7648 7649/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 7650/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 7651/// of the loaded bits, try narrowing the load and store if it would end up 7652/// being a win for performance or code size. 7653SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 7654 StoreSDNode *ST = cast<StoreSDNode>(N); 7655 if (ST->isVolatile()) 7656 return SDValue(); 7657 7658 SDValue Chain = ST->getChain(); 7659 SDValue Value = ST->getValue(); 7660 SDValue Ptr = ST->getBasePtr(); 7661 EVT VT = Value.getValueType(); 7662 7663 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 7664 return SDValue(); 7665 7666 unsigned Opc = Value.getOpcode(); 7667 7668 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 7669 // is a byte mask indicating a consecutive number of bytes, check to see if 7670 // Y is known to provide just those bytes. If so, we try to replace the 7671 // load + replace + store sequence with a single (narrower) store, which makes 7672 // the load dead. 7673 if (Opc == ISD::OR) { 7674 std::pair<unsigned, unsigned> MaskedLoad; 7675 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 7676 if (MaskedLoad.first) 7677 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7678 Value.getOperand(1), ST,this)) 7679 return SDValue(NewST, 0); 7680 7681 // Or is commutative, so try swapping X and Y. 7682 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 7683 if (MaskedLoad.first) 7684 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7685 Value.getOperand(0), ST,this)) 7686 return SDValue(NewST, 0); 7687 } 7688 7689 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 7690 Value.getOperand(1).getOpcode() != ISD::Constant) 7691 return SDValue(); 7692 7693 SDValue N0 = Value.getOperand(0); 7694 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7695 Chain == SDValue(N0.getNode(), 1)) { 7696 LoadSDNode *LD = cast<LoadSDNode>(N0); 7697 if (LD->getBasePtr() != Ptr || 7698 LD->getPointerInfo().getAddrSpace() != 7699 ST->getPointerInfo().getAddrSpace()) 7700 return SDValue(); 7701 7702 // Find the type to narrow it the load / op / store to. 7703 SDValue N1 = Value.getOperand(1); 7704 unsigned BitWidth = N1.getValueSizeInBits(); 7705 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 7706 if (Opc == ISD::AND) 7707 Imm ^= APInt::getAllOnesValue(BitWidth); 7708 if (Imm == 0 || Imm.isAllOnesValue()) 7709 return SDValue(); 7710 unsigned ShAmt = Imm.countTrailingZeros(); 7711 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 7712 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 7713 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7714 while (NewBW < BitWidth && 7715 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 7716 TLI.isNarrowingProfitable(VT, NewVT))) { 7717 NewBW = NextPowerOf2(NewBW); 7718 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7719 } 7720 if (NewBW >= BitWidth) 7721 return SDValue(); 7722 7723 // If the lsb changed does not start at the type bitwidth boundary, 7724 // start at the previous one. 7725 if (ShAmt % NewBW) 7726 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 7727 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 7728 std::min(BitWidth, ShAmt + NewBW)); 7729 if ((Imm & Mask) == Imm) { 7730 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 7731 if (Opc == ISD::AND) 7732 NewImm ^= APInt::getAllOnesValue(NewBW); 7733 uint64_t PtrOff = ShAmt / 8; 7734 // For big endian targets, we need to adjust the offset to the pointer to 7735 // load the correct bytes. 7736 if (TLI.isBigEndian()) 7737 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 7738 7739 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 7740 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 7741 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 7742 return SDValue(); 7743 7744 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 7745 Ptr.getValueType(), Ptr, 7746 DAG.getConstant(PtrOff, Ptr.getValueType())); 7747 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 7748 LD->getChain(), NewPtr, 7749 LD->getPointerInfo().getWithOffset(PtrOff), 7750 LD->isVolatile(), LD->isNonTemporal(), 7751 LD->isInvariant(), NewAlign); 7752 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 7753 DAG.getConstant(NewImm, NewVT)); 7754 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 7755 NewVal, NewPtr, 7756 ST->getPointerInfo().getWithOffset(PtrOff), 7757 false, false, NewAlign); 7758 7759 AddToWorkList(NewPtr.getNode()); 7760 AddToWorkList(NewLD.getNode()); 7761 AddToWorkList(NewVal.getNode()); 7762 WorkListRemover DeadNodes(*this); 7763 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 7764 ++OpsNarrowed; 7765 return NewST; 7766 } 7767 } 7768 7769 return SDValue(); 7770} 7771 7772/// TransformFPLoadStorePair - For a given floating point load / store pair, 7773/// if the load value isn't used by any other operations, then consider 7774/// transforming the pair to integer load / store operations if the target 7775/// deems the transformation profitable. 7776SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 7777 StoreSDNode *ST = cast<StoreSDNode>(N); 7778 SDValue Chain = ST->getChain(); 7779 SDValue Value = ST->getValue(); 7780 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 7781 Value.hasOneUse() && 7782 Chain == SDValue(Value.getNode(), 1)) { 7783 LoadSDNode *LD = cast<LoadSDNode>(Value); 7784 EVT VT = LD->getMemoryVT(); 7785 if (!VT.isFloatingPoint() || 7786 VT != ST->getMemoryVT() || 7787 LD->isNonTemporal() || 7788 ST->isNonTemporal() || 7789 LD->getPointerInfo().getAddrSpace() != 0 || 7790 ST->getPointerInfo().getAddrSpace() != 0) 7791 return SDValue(); 7792 7793 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7794 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 7795 !TLI.isOperationLegal(ISD::STORE, IntVT) || 7796 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 7797 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 7798 return SDValue(); 7799 7800 unsigned LDAlign = LD->getAlignment(); 7801 unsigned STAlign = ST->getAlignment(); 7802 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 7803 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 7804 if (LDAlign < ABIAlign || STAlign < ABIAlign) 7805 return SDValue(); 7806 7807 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 7808 LD->getChain(), LD->getBasePtr(), 7809 LD->getPointerInfo(), 7810 false, false, false, LDAlign); 7811 7812 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 7813 NewLD, ST->getBasePtr(), 7814 ST->getPointerInfo(), 7815 false, false, STAlign); 7816 7817 AddToWorkList(NewLD.getNode()); 7818 AddToWorkList(NewST.getNode()); 7819 WorkListRemover DeadNodes(*this); 7820 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 7821 ++LdStFP2Int; 7822 return NewST; 7823 } 7824 7825 return SDValue(); 7826} 7827 7828/// Helper struct to parse and store a memory address as base + index + offset. 7829/// We ignore sign extensions when it is safe to do so. 7830/// The following two expressions are not equivalent. To differentiate we need 7831/// to store whether there was a sign extension involved in the index 7832/// computation. 7833/// (load (i64 add (i64 copyfromreg %c) 7834/// (i64 signextend (add (i8 load %index) 7835/// (i8 1)))) 7836/// vs 7837/// 7838/// (load (i64 add (i64 copyfromreg %c) 7839/// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 7840/// (i32 1))))) 7841struct BaseIndexOffset { 7842 SDValue Base; 7843 SDValue Index; 7844 int64_t Offset; 7845 bool IsIndexSignExt; 7846 7847 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 7848 7849 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 7850 bool IsIndexSignExt) : 7851 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 7852 7853 bool equalBaseIndex(const BaseIndexOffset &Other) { 7854 return Other.Base == Base && Other.Index == Index && 7855 Other.IsIndexSignExt == IsIndexSignExt; 7856 } 7857 7858 /// Parses tree in Ptr for base, index, offset addresses. 7859 static BaseIndexOffset match(SDValue Ptr) { 7860 bool IsIndexSignExt = false; 7861 7862 // Just Base or possibly anything else. 7863 if (Ptr->getOpcode() != ISD::ADD) 7864 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 7865 7866 // Base + offset. 7867 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 7868 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 7869 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 7870 IsIndexSignExt); 7871 } 7872 7873 // Look at Base + Index + Offset cases. 7874 SDValue Base = Ptr->getOperand(0); 7875 SDValue IndexOffset = Ptr->getOperand(1); 7876 7877 // Skip signextends. 7878 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 7879 IndexOffset = IndexOffset->getOperand(0); 7880 IsIndexSignExt = true; 7881 } 7882 7883 // Either the case of Base + Index (no offset) or something else. 7884 if (IndexOffset->getOpcode() != ISD::ADD) 7885 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 7886 7887 // Now we have the case of Base + Index + offset. 7888 SDValue Index = IndexOffset->getOperand(0); 7889 SDValue Offset = IndexOffset->getOperand(1); 7890 7891 if (!isa<ConstantSDNode>(Offset)) 7892 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 7893 7894 // Ignore signextends. 7895 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 7896 Index = Index->getOperand(0); 7897 IsIndexSignExt = true; 7898 } else IsIndexSignExt = false; 7899 7900 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 7901 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 7902 } 7903}; 7904 7905/// Holds a pointer to an LSBaseSDNode as well as information on where it 7906/// is located in a sequence of memory operations connected by a chain. 7907struct MemOpLink { 7908 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 7909 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 7910 // Ptr to the mem node. 7911 LSBaseSDNode *MemNode; 7912 // Offset from the base ptr. 7913 int64_t OffsetFromBase; 7914 // What is the sequence number of this mem node. 7915 // Lowest mem operand in the DAG starts at zero. 7916 unsigned SequenceNum; 7917}; 7918 7919/// Sorts store nodes in a link according to their offset from a shared 7920// base ptr. 7921struct ConsecutiveMemoryChainSorter { 7922 bool operator()(MemOpLink LHS, MemOpLink RHS) { 7923 return LHS.OffsetFromBase < RHS.OffsetFromBase; 7924 } 7925}; 7926 7927bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 7928 EVT MemVT = St->getMemoryVT(); 7929 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 7930 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 7931 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 7932 7933 // Don't merge vectors into wider inputs. 7934 if (MemVT.isVector() || !MemVT.isSimple()) 7935 return false; 7936 7937 // Perform an early exit check. Do not bother looking at stored values that 7938 // are not constants or loads. 7939 SDValue StoredVal = St->getValue(); 7940 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 7941 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 7942 !IsLoadSrc) 7943 return false; 7944 7945 // Only look at ends of store sequences. 7946 SDValue Chain = SDValue(St, 1); 7947 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 7948 return false; 7949 7950 // This holds the base pointer, index, and the offset in bytes from the base 7951 // pointer. 7952 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 7953 7954 // We must have a base and an offset. 7955 if (!BasePtr.Base.getNode()) 7956 return false; 7957 7958 // Do not handle stores to undef base pointers. 7959 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 7960 return false; 7961 7962 // Save the LoadSDNodes that we find in the chain. 7963 // We need to make sure that these nodes do not interfere with 7964 // any of the store nodes. 7965 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 7966 7967 // Save the StoreSDNodes that we find in the chain. 7968 SmallVector<MemOpLink, 8> StoreNodes; 7969 7970 // Walk up the chain and look for nodes with offsets from the same 7971 // base pointer. Stop when reaching an instruction with a different kind 7972 // or instruction which has a different base pointer. 7973 unsigned Seq = 0; 7974 StoreSDNode *Index = St; 7975 while (Index) { 7976 // If the chain has more than one use, then we can't reorder the mem ops. 7977 if (Index != St && !SDValue(Index, 1)->hasOneUse()) 7978 break; 7979 7980 // Find the base pointer and offset for this memory node. 7981 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 7982 7983 // Check that the base pointer is the same as the original one. 7984 if (!Ptr.equalBaseIndex(BasePtr)) 7985 break; 7986 7987 // Check that the alignment is the same. 7988 if (Index->getAlignment() != St->getAlignment()) 7989 break; 7990 7991 // The memory operands must not be volatile. 7992 if (Index->isVolatile() || Index->isIndexed()) 7993 break; 7994 7995 // No truncation. 7996 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 7997 if (St->isTruncatingStore()) 7998 break; 7999 8000 // The stored memory type must be the same. 8001 if (Index->getMemoryVT() != MemVT) 8002 break; 8003 8004 // We do not allow unaligned stores because we want to prevent overriding 8005 // stores. 8006 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 8007 break; 8008 8009 // We found a potential memory operand to merge. 8010 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 8011 8012 // Find the next memory operand in the chain. If the next operand in the 8013 // chain is a store then move up and continue the scan with the next 8014 // memory operand. If the next operand is a load save it and use alias 8015 // information to check if it interferes with anything. 8016 SDNode *NextInChain = Index->getChain().getNode(); 8017 while (1) { 8018 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 8019 // We found a store node. Use it for the next iteration. 8020 Index = STn; 8021 break; 8022 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 8023 // Save the load node for later. Continue the scan. 8024 AliasLoadNodes.push_back(Ldn); 8025 NextInChain = Ldn->getChain().getNode(); 8026 continue; 8027 } else { 8028 Index = NULL; 8029 break; 8030 } 8031 } 8032 } 8033 8034 // Check if there is anything to merge. 8035 if (StoreNodes.size() < 2) 8036 return false; 8037 8038 // Sort the memory operands according to their distance from the base pointer. 8039 std::sort(StoreNodes.begin(), StoreNodes.end(), 8040 ConsecutiveMemoryChainSorter()); 8041 8042 // Scan the memory operations on the chain and find the first non-consecutive 8043 // store memory address. 8044 unsigned LastConsecutiveStore = 0; 8045 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 8046 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 8047 8048 // Check that the addresses are consecutive starting from the second 8049 // element in the list of stores. 8050 if (i > 0) { 8051 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 8052 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 8053 break; 8054 } 8055 8056 bool Alias = false; 8057 // Check if this store interferes with any of the loads that we found. 8058 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 8059 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 8060 Alias = true; 8061 break; 8062 } 8063 // We found a load that alias with this store. Stop the sequence. 8064 if (Alias) 8065 break; 8066 8067 // Mark this node as useful. 8068 LastConsecutiveStore = i; 8069 } 8070 8071 // The node with the lowest store address. 8072 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 8073 8074 // Store the constants into memory as one consecutive store. 8075 if (!IsLoadSrc) { 8076 unsigned LastLegalType = 0; 8077 unsigned LastLegalVectorType = 0; 8078 bool NonZero = false; 8079 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 8080 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8081 SDValue StoredVal = St->getValue(); 8082 8083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 8084 NonZero |= !C->isNullValue(); 8085 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 8086 NonZero |= !C->getConstantFPValue()->isNullValue(); 8087 } else { 8088 // Non constant. 8089 break; 8090 } 8091 8092 // Find a legal type for the constant store. 8093 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 8094 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 8095 if (TLI.isTypeLegal(StoreTy)) 8096 LastLegalType = i+1; 8097 // Or check whether a truncstore is legal. 8098 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 8099 TargetLowering::TypePromoteInteger) { 8100 EVT LegalizedStoredValueTy = 8101 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 8102 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 8103 LastLegalType = i+1; 8104 } 8105 8106 // Find a legal type for the vector store. 8107 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 8108 if (TLI.isTypeLegal(Ty)) 8109 LastLegalVectorType = i + 1; 8110 } 8111 8112 // We only use vectors if the constant is known to be zero and the 8113 // function is not marked with the noimplicitfloat attribute. 8114 if (NonZero || NoVectors) 8115 LastLegalVectorType = 0; 8116 8117 // Check if we found a legal integer type to store. 8118 if (LastLegalType == 0 && LastLegalVectorType == 0) 8119 return false; 8120 8121 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 8122 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 8123 8124 // Make sure we have something to merge. 8125 if (NumElem < 2) 8126 return false; 8127 8128 unsigned EarliestNodeUsed = 0; 8129 for (unsigned i=0; i < NumElem; ++i) { 8130 // Find a chain for the new wide-store operand. Notice that some 8131 // of the store nodes that we found may not be selected for inclusion 8132 // in the wide store. The chain we use needs to be the chain of the 8133 // earliest store node which is *used* and replaced by the wide store. 8134 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 8135 EarliestNodeUsed = i; 8136 } 8137 8138 // The earliest Node in the DAG. 8139 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 8140 SDLoc DL(StoreNodes[0].MemNode); 8141 8142 SDValue StoredVal; 8143 if (UseVector) { 8144 // Find a legal type for the vector store. 8145 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 8146 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 8147 StoredVal = DAG.getConstant(0, Ty); 8148 } else { 8149 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 8150 APInt StoreInt(StoreBW, 0); 8151 8152 // Construct a single integer constant which is made of the smaller 8153 // constant inputs. 8154 bool IsLE = TLI.isLittleEndian(); 8155 for (unsigned i = 0; i < NumElem ; ++i) { 8156 unsigned Idx = IsLE ?(NumElem - 1 - i) : i; 8157 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 8158 SDValue Val = St->getValue(); 8159 StoreInt<<=ElementSizeBytes*8; 8160 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 8161 StoreInt|=C->getAPIntValue().zext(StoreBW); 8162 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 8163 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 8164 } else { 8165 assert(false && "Invalid constant element type"); 8166 } 8167 } 8168 8169 // Create the new Load and Store operations. 8170 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 8171 StoredVal = DAG.getConstant(StoreInt, StoreTy); 8172 } 8173 8174 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 8175 FirstInChain->getBasePtr(), 8176 FirstInChain->getPointerInfo(), 8177 false, false, 8178 FirstInChain->getAlignment()); 8179 8180 // Replace the first store with the new store 8181 CombineTo(EarliestOp, NewStore); 8182 // Erase all other stores. 8183 for (unsigned i = 0; i < NumElem ; ++i) { 8184 if (StoreNodes[i].MemNode == EarliestOp) 8185 continue; 8186 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8187 // ReplaceAllUsesWith will replace all uses that existed when it was 8188 // called, but graph optimizations may cause new ones to appear. For 8189 // example, the case in pr14333 looks like 8190 // 8191 // St's chain -> St -> another store -> X 8192 // 8193 // And the only difference from St to the other store is the chain. 8194 // When we change it's chain to be St's chain they become identical, 8195 // get CSEed and the net result is that X is now a use of St. 8196 // Since we know that St is redundant, just iterate. 8197 while (!St->use_empty()) 8198 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 8199 removeFromWorkList(St); 8200 DAG.DeleteNode(St); 8201 } 8202 8203 return true; 8204 } 8205 8206 // Below we handle the case of multiple consecutive stores that 8207 // come from multiple consecutive loads. We merge them into a single 8208 // wide load and a single wide store. 8209 8210 // Look for load nodes which are used by the stored values. 8211 SmallVector<MemOpLink, 8> LoadNodes; 8212 8213 // Find acceptable loads. Loads need to have the same chain (token factor), 8214 // must not be zext, volatile, indexed, and they must be consecutive. 8215 BaseIndexOffset LdBasePtr; 8216 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 8217 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8218 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 8219 if (!Ld) break; 8220 8221 // Loads must only have one use. 8222 if (!Ld->hasNUsesOfValue(1, 0)) 8223 break; 8224 8225 // Check that the alignment is the same as the stores. 8226 if (Ld->getAlignment() != St->getAlignment()) 8227 break; 8228 8229 // The memory operands must not be volatile. 8230 if (Ld->isVolatile() || Ld->isIndexed()) 8231 break; 8232 8233 // We do not accept ext loads. 8234 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 8235 break; 8236 8237 // The stored memory type must be the same. 8238 if (Ld->getMemoryVT() != MemVT) 8239 break; 8240 8241 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 8242 // If this is not the first ptr that we check. 8243 if (LdBasePtr.Base.getNode()) { 8244 // The base ptr must be the same. 8245 if (!LdPtr.equalBaseIndex(LdBasePtr)) 8246 break; 8247 } else { 8248 // Check that all other base pointers are the same as this one. 8249 LdBasePtr = LdPtr; 8250 } 8251 8252 // We found a potential memory operand to merge. 8253 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 8254 } 8255 8256 if (LoadNodes.size() < 2) 8257 return false; 8258 8259 // Scan the memory operations on the chain and find the first non-consecutive 8260 // load memory address. These variables hold the index in the store node 8261 // array. 8262 unsigned LastConsecutiveLoad = 0; 8263 // This variable refers to the size and not index in the array. 8264 unsigned LastLegalVectorType = 0; 8265 unsigned LastLegalIntegerType = 0; 8266 StartAddress = LoadNodes[0].OffsetFromBase; 8267 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 8268 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 8269 // All loads much share the same chain. 8270 if (LoadNodes[i].MemNode->getChain() != FirstChain) 8271 break; 8272 8273 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 8274 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 8275 break; 8276 LastConsecutiveLoad = i; 8277 8278 // Find a legal type for the vector store. 8279 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 8280 if (TLI.isTypeLegal(StoreTy)) 8281 LastLegalVectorType = i + 1; 8282 8283 // Find a legal type for the integer store. 8284 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 8285 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 8286 if (TLI.isTypeLegal(StoreTy)) 8287 LastLegalIntegerType = i + 1; 8288 // Or check whether a truncstore and extload is legal. 8289 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 8290 TargetLowering::TypePromoteInteger) { 8291 EVT LegalizedStoredValueTy = 8292 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 8293 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 8294 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) && 8295 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) && 8296 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy)) 8297 LastLegalIntegerType = i+1; 8298 } 8299 } 8300 8301 // Only use vector types if the vector type is larger than the integer type. 8302 // If they are the same, use integers. 8303 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 8304 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 8305 8306 // We add +1 here because the LastXXX variables refer to location while 8307 // the NumElem refers to array/index size. 8308 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 8309 NumElem = std::min(LastLegalType, NumElem); 8310 8311 if (NumElem < 2) 8312 return false; 8313 8314 // The earliest Node in the DAG. 8315 unsigned EarliestNodeUsed = 0; 8316 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 8317 for (unsigned i=1; i<NumElem; ++i) { 8318 // Find a chain for the new wide-store operand. Notice that some 8319 // of the store nodes that we found may not be selected for inclusion 8320 // in the wide store. The chain we use needs to be the chain of the 8321 // earliest store node which is *used* and replaced by the wide store. 8322 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 8323 EarliestNodeUsed = i; 8324 } 8325 8326 // Find if it is better to use vectors or integers to load and store 8327 // to memory. 8328 EVT JointMemOpVT; 8329 if (UseVectorTy) { 8330 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 8331 } else { 8332 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 8333 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 8334 } 8335 8336 SDLoc LoadDL(LoadNodes[0].MemNode); 8337 SDLoc StoreDL(StoreNodes[0].MemNode); 8338 8339 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 8340 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 8341 FirstLoad->getChain(), 8342 FirstLoad->getBasePtr(), 8343 FirstLoad->getPointerInfo(), 8344 false, false, false, 8345 FirstLoad->getAlignment()); 8346 8347 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 8348 FirstInChain->getBasePtr(), 8349 FirstInChain->getPointerInfo(), false, false, 8350 FirstInChain->getAlignment()); 8351 8352 // Replace one of the loads with the new load. 8353 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 8354 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 8355 SDValue(NewLoad.getNode(), 1)); 8356 8357 // Remove the rest of the load chains. 8358 for (unsigned i = 1; i < NumElem ; ++i) { 8359 // Replace all chain users of the old load nodes with the chain of the new 8360 // load node. 8361 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 8362 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 8363 } 8364 8365 // Replace the first store with the new store. 8366 CombineTo(EarliestOp, NewStore); 8367 // Erase all other stores. 8368 for (unsigned i = 0; i < NumElem ; ++i) { 8369 // Remove all Store nodes. 8370 if (StoreNodes[i].MemNode == EarliestOp) 8371 continue; 8372 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8373 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 8374 removeFromWorkList(St); 8375 DAG.DeleteNode(St); 8376 } 8377 8378 return true; 8379} 8380 8381SDValue DAGCombiner::visitSTORE(SDNode *N) { 8382 StoreSDNode *ST = cast<StoreSDNode>(N); 8383 SDValue Chain = ST->getChain(); 8384 SDValue Value = ST->getValue(); 8385 SDValue Ptr = ST->getBasePtr(); 8386 8387 // If this is a store of a bit convert, store the input value if the 8388 // resultant store does not need a higher alignment than the original. 8389 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 8390 ST->isUnindexed()) { 8391 unsigned OrigAlign = ST->getAlignment(); 8392 EVT SVT = Value.getOperand(0).getValueType(); 8393 unsigned Align = TLI.getDataLayout()-> 8394 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 8395 if (Align <= OrigAlign && 8396 ((!LegalOperations && !ST->isVolatile()) || 8397 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 8398 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 8399 Ptr, ST->getPointerInfo(), ST->isVolatile(), 8400 ST->isNonTemporal(), OrigAlign); 8401 } 8402 8403 // Turn 'store undef, Ptr' -> nothing. 8404 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 8405 return Chain; 8406 8407 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 8408 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 8409 // NOTE: If the original store is volatile, this transform must not increase 8410 // the number of stores. For example, on x86-32 an f64 can be stored in one 8411 // processor operation but an i64 (which is not legal) requires two. So the 8412 // transform should not be done in this case. 8413 if (Value.getOpcode() != ISD::TargetConstantFP) { 8414 SDValue Tmp; 8415 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) { 8416 default: llvm_unreachable("Unknown FP type"); 8417 case MVT::f16: // We don't do this for these yet. 8418 case MVT::f80: 8419 case MVT::f128: 8420 case MVT::ppcf128: 8421 break; 8422 case MVT::f32: 8423 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 8424 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 8425 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 8426 bitcastToAPInt().getZExtValue(), MVT::i32); 8427 return DAG.getStore(Chain, SDLoc(N), Tmp, 8428 Ptr, ST->getPointerInfo(), ST->isVolatile(), 8429 ST->isNonTemporal(), ST->getAlignment()); 8430 } 8431 break; 8432 case MVT::f64: 8433 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 8434 !ST->isVolatile()) || 8435 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 8436 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 8437 getZExtValue(), MVT::i64); 8438 return DAG.getStore(Chain, SDLoc(N), Tmp, 8439 Ptr, ST->getPointerInfo(), ST->isVolatile(), 8440 ST->isNonTemporal(), ST->getAlignment()); 8441 } 8442 8443 if (!ST->isVolatile() && 8444 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 8445 // Many FP stores are not made apparent until after legalize, e.g. for 8446 // argument passing. Since this is so common, custom legalize the 8447 // 64-bit integer store into two 32-bit stores. 8448 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 8449 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 8450 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 8451 if (TLI.isBigEndian()) std::swap(Lo, Hi); 8452 8453 unsigned Alignment = ST->getAlignment(); 8454 bool isVolatile = ST->isVolatile(); 8455 bool isNonTemporal = ST->isNonTemporal(); 8456 8457 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 8458 Ptr, ST->getPointerInfo(), 8459 isVolatile, isNonTemporal, 8460 ST->getAlignment()); 8461 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 8462 DAG.getConstant(4, Ptr.getValueType())); 8463 Alignment = MinAlign(Alignment, 4U); 8464 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 8465 Ptr, ST->getPointerInfo().getWithOffset(4), 8466 isVolatile, isNonTemporal, 8467 Alignment); 8468 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 8469 St0, St1); 8470 } 8471 8472 break; 8473 } 8474 } 8475 } 8476 8477 // Try to infer better alignment information than the store already has. 8478 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 8479 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 8480 if (Align > ST->getAlignment()) 8481 return DAG.getTruncStore(Chain, SDLoc(N), Value, 8482 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 8483 ST->isVolatile(), ST->isNonTemporal(), Align); 8484 } 8485 } 8486 8487 // Try transforming a pair floating point load / store ops to integer 8488 // load / store ops. 8489 SDValue NewST = TransformFPLoadStorePair(N); 8490 if (NewST.getNode()) 8491 return NewST; 8492 8493 if (CombinerAA) { 8494 // Walk up chain skipping non-aliasing memory nodes. 8495 SDValue BetterChain = FindBetterChain(N, Chain); 8496 8497 // If there is a better chain. 8498 if (Chain != BetterChain) { 8499 SDValue ReplStore; 8500 8501 // Replace the chain to avoid dependency. 8502 if (ST->isTruncatingStore()) { 8503 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 8504 ST->getPointerInfo(), 8505 ST->getMemoryVT(), ST->isVolatile(), 8506 ST->isNonTemporal(), ST->getAlignment()); 8507 } else { 8508 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 8509 ST->getPointerInfo(), 8510 ST->isVolatile(), ST->isNonTemporal(), 8511 ST->getAlignment()); 8512 } 8513 8514 // Create token to keep both nodes around. 8515 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 8516 MVT::Other, Chain, ReplStore); 8517 8518 // Make sure the new and old chains are cleaned up. 8519 AddToWorkList(Token.getNode()); 8520 8521 // Don't add users to work list. 8522 return CombineTo(N, Token, false); 8523 } 8524 } 8525 8526 // Try transforming N to an indexed store. 8527 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 8528 return SDValue(N, 0); 8529 8530 // FIXME: is there such a thing as a truncating indexed store? 8531 if (ST->isTruncatingStore() && ST->isUnindexed() && 8532 Value.getValueType().isInteger()) { 8533 // See if we can simplify the input to this truncstore with knowledge that 8534 // only the low bits are being used. For example: 8535 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 8536 SDValue Shorter = 8537 GetDemandedBits(Value, 8538 APInt::getLowBitsSet( 8539 Value.getValueType().getScalarType().getSizeInBits(), 8540 ST->getMemoryVT().getScalarType().getSizeInBits())); 8541 AddToWorkList(Value.getNode()); 8542 if (Shorter.getNode()) 8543 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 8544 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 8545 ST->isVolatile(), ST->isNonTemporal(), 8546 ST->getAlignment()); 8547 8548 // Otherwise, see if we can simplify the operation with 8549 // SimplifyDemandedBits, which only works if the value has a single use. 8550 if (SimplifyDemandedBits(Value, 8551 APInt::getLowBitsSet( 8552 Value.getValueType().getScalarType().getSizeInBits(), 8553 ST->getMemoryVT().getScalarType().getSizeInBits()))) 8554 return SDValue(N, 0); 8555 } 8556 8557 // If this is a load followed by a store to the same location, then the store 8558 // is dead/noop. 8559 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 8560 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 8561 ST->isUnindexed() && !ST->isVolatile() && 8562 // There can't be any side effects between the load and store, such as 8563 // a call or store. 8564 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 8565 // The store is dead, remove it. 8566 return Chain; 8567 } 8568 } 8569 8570 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 8571 // truncating store. We can do this even if this is already a truncstore. 8572 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 8573 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 8574 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 8575 ST->getMemoryVT())) { 8576 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 8577 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 8578 ST->isVolatile(), ST->isNonTemporal(), 8579 ST->getAlignment()); 8580 } 8581 8582 // Only perform this optimization before the types are legal, because we 8583 // don't want to perform this optimization on every DAGCombine invocation. 8584 if (!LegalTypes) { 8585 bool EverChanged = false; 8586 8587 do { 8588 // There can be multiple store sequences on the same chain. 8589 // Keep trying to merge store sequences until we are unable to do so 8590 // or until we merge the last store on the chain. 8591 bool Changed = MergeConsecutiveStores(ST); 8592 EverChanged |= Changed; 8593 if (!Changed) break; 8594 } while (ST->getOpcode() != ISD::DELETED_NODE); 8595 8596 if (EverChanged) 8597 return SDValue(N, 0); 8598 } 8599 8600 return ReduceLoadOpStoreWidth(N); 8601} 8602 8603SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 8604 SDValue InVec = N->getOperand(0); 8605 SDValue InVal = N->getOperand(1); 8606 SDValue EltNo = N->getOperand(2); 8607 SDLoc dl(N); 8608 8609 // If the inserted element is an UNDEF, just use the input vector. 8610 if (InVal.getOpcode() == ISD::UNDEF) 8611 return InVec; 8612 8613 EVT VT = InVec.getValueType(); 8614 8615 // If we can't generate a legal BUILD_VECTOR, exit 8616 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 8617 return SDValue(); 8618 8619 // Check that we know which element is being inserted 8620 if (!isa<ConstantSDNode>(EltNo)) 8621 return SDValue(); 8622 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8623 8624 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 8625 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 8626 // vector elements. 8627 SmallVector<SDValue, 8> Ops; 8628 // Do not combine these two vectors if the output vector will not replace 8629 // the input vector. 8630 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 8631 Ops.append(InVec.getNode()->op_begin(), 8632 InVec.getNode()->op_end()); 8633 } else if (InVec.getOpcode() == ISD::UNDEF) { 8634 unsigned NElts = VT.getVectorNumElements(); 8635 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 8636 } else { 8637 return SDValue(); 8638 } 8639 8640 // Insert the element 8641 if (Elt < Ops.size()) { 8642 // All the operands of BUILD_VECTOR must have the same type; 8643 // we enforce that here. 8644 EVT OpVT = Ops[0].getValueType(); 8645 if (InVal.getValueType() != OpVT) 8646 InVal = OpVT.bitsGT(InVal.getValueType()) ? 8647 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 8648 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 8649 Ops[Elt] = InVal; 8650 } 8651 8652 // Return the new vector 8653 return DAG.getNode(ISD::BUILD_VECTOR, dl, 8654 VT, &Ops[0], Ops.size()); 8655} 8656 8657SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 8658 // (vextract (scalar_to_vector val, 0) -> val 8659 SDValue InVec = N->getOperand(0); 8660 EVT VT = InVec.getValueType(); 8661 EVT NVT = N->getValueType(0); 8662 8663 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 8664 // Check if the result type doesn't match the inserted element type. A 8665 // SCALAR_TO_VECTOR may truncate the inserted element and the 8666 // EXTRACT_VECTOR_ELT may widen the extracted vector. 8667 SDValue InOp = InVec.getOperand(0); 8668 if (InOp.getValueType() != NVT) { 8669 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 8670 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 8671 } 8672 return InOp; 8673 } 8674 8675 SDValue EltNo = N->getOperand(1); 8676 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 8677 8678 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 8679 // We only perform this optimization before the op legalization phase because 8680 // we may introduce new vector instructions which are not backed by TD 8681 // patterns. For example on AVX, extracting elements from a wide vector 8682 // without using extract_subvector. 8683 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 8684 && ConstEltNo && !LegalOperations) { 8685 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8686 int NumElem = VT.getVectorNumElements(); 8687 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 8688 // Find the new index to extract from. 8689 int OrigElt = SVOp->getMaskElt(Elt); 8690 8691 // Extracting an undef index is undef. 8692 if (OrigElt == -1) 8693 return DAG.getUNDEF(NVT); 8694 8695 // Select the right vector half to extract from. 8696 if (OrigElt < NumElem) { 8697 InVec = InVec->getOperand(0); 8698 } else { 8699 InVec = InVec->getOperand(1); 8700 OrigElt -= NumElem; 8701 } 8702 8703 EVT IndexTy = TLI.getVectorIdxTy(); 8704 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 8705 InVec, DAG.getConstant(OrigElt, IndexTy)); 8706 } 8707 8708 // Perform only after legalization to ensure build_vector / vector_shuffle 8709 // optimizations have already been done. 8710 if (!LegalOperations) return SDValue(); 8711 8712 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 8713 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 8714 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 8715 8716 if (ConstEltNo) { 8717 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8718 bool NewLoad = false; 8719 bool BCNumEltsChanged = false; 8720 EVT ExtVT = VT.getVectorElementType(); 8721 EVT LVT = ExtVT; 8722 8723 // If the result of load has to be truncated, then it's not necessarily 8724 // profitable. 8725 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 8726 return SDValue(); 8727 8728 if (InVec.getOpcode() == ISD::BITCAST) { 8729 // Don't duplicate a load with other uses. 8730 if (!InVec.hasOneUse()) 8731 return SDValue(); 8732 8733 EVT BCVT = InVec.getOperand(0).getValueType(); 8734 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 8735 return SDValue(); 8736 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 8737 BCNumEltsChanged = true; 8738 InVec = InVec.getOperand(0); 8739 ExtVT = BCVT.getVectorElementType(); 8740 NewLoad = true; 8741 } 8742 8743 LoadSDNode *LN0 = NULL; 8744 const ShuffleVectorSDNode *SVN = NULL; 8745 if (ISD::isNormalLoad(InVec.getNode())) { 8746 LN0 = cast<LoadSDNode>(InVec); 8747 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 8748 InVec.getOperand(0).getValueType() == ExtVT && 8749 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 8750 // Don't duplicate a load with other uses. 8751 if (!InVec.hasOneUse()) 8752 return SDValue(); 8753 8754 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 8755 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 8756 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 8757 // => 8758 // (load $addr+1*size) 8759 8760 // Don't duplicate a load with other uses. 8761 if (!InVec.hasOneUse()) 8762 return SDValue(); 8763 8764 // If the bit convert changed the number of elements, it is unsafe 8765 // to examine the mask. 8766 if (BCNumEltsChanged) 8767 return SDValue(); 8768 8769 // Select the input vector, guarding against out of range extract vector. 8770 unsigned NumElems = VT.getVectorNumElements(); 8771 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 8772 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 8773 8774 if (InVec.getOpcode() == ISD::BITCAST) { 8775 // Don't duplicate a load with other uses. 8776 if (!InVec.hasOneUse()) 8777 return SDValue(); 8778 8779 InVec = InVec.getOperand(0); 8780 } 8781 if (ISD::isNormalLoad(InVec.getNode())) { 8782 LN0 = cast<LoadSDNode>(InVec); 8783 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 8784 } 8785 } 8786 8787 // Make sure we found a non-volatile load and the extractelement is 8788 // the only use. 8789 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 8790 return SDValue(); 8791 8792 // If Idx was -1 above, Elt is going to be -1, so just return undef. 8793 if (Elt == -1) 8794 return DAG.getUNDEF(LVT); 8795 8796 unsigned Align = LN0->getAlignment(); 8797 if (NewLoad) { 8798 // Check the resultant load doesn't need a higher alignment than the 8799 // original load. 8800 unsigned NewAlign = 8801 TLI.getDataLayout() 8802 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 8803 8804 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 8805 return SDValue(); 8806 8807 Align = NewAlign; 8808 } 8809 8810 SDValue NewPtr = LN0->getBasePtr(); 8811 unsigned PtrOff = 0; 8812 8813 if (Elt) { 8814 PtrOff = LVT.getSizeInBits() * Elt / 8; 8815 EVT PtrType = NewPtr.getValueType(); 8816 if (TLI.isBigEndian()) 8817 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 8818 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr, 8819 DAG.getConstant(PtrOff, PtrType)); 8820 } 8821 8822 // The replacement we need to do here is a little tricky: we need to 8823 // replace an extractelement of a load with a load. 8824 // Use ReplaceAllUsesOfValuesWith to do the replacement. 8825 // Note that this replacement assumes that the extractvalue is the only 8826 // use of the load; that's okay because we don't want to perform this 8827 // transformation in other cases anyway. 8828 SDValue Load; 8829 SDValue Chain; 8830 if (NVT.bitsGT(LVT)) { 8831 // If the result type of vextract is wider than the load, then issue an 8832 // extending load instead. 8833 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 8834 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 8835 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(), 8836 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 8837 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align); 8838 Chain = Load.getValue(1); 8839 } else { 8840 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr, 8841 LN0->getPointerInfo().getWithOffset(PtrOff), 8842 LN0->isVolatile(), LN0->isNonTemporal(), 8843 LN0->isInvariant(), Align); 8844 Chain = Load.getValue(1); 8845 if (NVT.bitsLT(LVT)) 8846 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load); 8847 else 8848 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load); 8849 } 8850 WorkListRemover DeadNodes(*this); 8851 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 8852 SDValue To[] = { Load, Chain }; 8853 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8854 // Since we're explcitly calling ReplaceAllUses, add the new node to the 8855 // worklist explicitly as well. 8856 AddToWorkList(Load.getNode()); 8857 AddUsersToWorkList(Load.getNode()); // Add users too 8858 // Make sure to revisit this node to clean it up; it will usually be dead. 8859 AddToWorkList(N); 8860 return SDValue(N, 0); 8861 } 8862 8863 return SDValue(); 8864} 8865 8866// Simplify (build_vec (ext )) to (bitcast (build_vec )) 8867SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 8868 // We perform this optimization post type-legalization because 8869 // the type-legalizer often scalarizes integer-promoted vectors. 8870 // Performing this optimization before may create bit-casts which 8871 // will be type-legalized to complex code sequences. 8872 // We perform this optimization only before the operation legalizer because we 8873 // may introduce illegal operations. 8874 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 8875 return SDValue(); 8876 8877 unsigned NumInScalars = N->getNumOperands(); 8878 SDLoc dl(N); 8879 EVT VT = N->getValueType(0); 8880 8881 // Check to see if this is a BUILD_VECTOR of a bunch of values 8882 // which come from any_extend or zero_extend nodes. If so, we can create 8883 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 8884 // optimizations. We do not handle sign-extend because we can't fill the sign 8885 // using shuffles. 8886 EVT SourceType = MVT::Other; 8887 bool AllAnyExt = true; 8888 8889 for (unsigned i = 0; i != NumInScalars; ++i) { 8890 SDValue In = N->getOperand(i); 8891 // Ignore undef inputs. 8892 if (In.getOpcode() == ISD::UNDEF) continue; 8893 8894 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 8895 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 8896 8897 // Abort if the element is not an extension. 8898 if (!ZeroExt && !AnyExt) { 8899 SourceType = MVT::Other; 8900 break; 8901 } 8902 8903 // The input is a ZeroExt or AnyExt. Check the original type. 8904 EVT InTy = In.getOperand(0).getValueType(); 8905 8906 // Check that all of the widened source types are the same. 8907 if (SourceType == MVT::Other) 8908 // First time. 8909 SourceType = InTy; 8910 else if (InTy != SourceType) { 8911 // Multiple income types. Abort. 8912 SourceType = MVT::Other; 8913 break; 8914 } 8915 8916 // Check if all of the extends are ANY_EXTENDs. 8917 AllAnyExt &= AnyExt; 8918 } 8919 8920 // In order to have valid types, all of the inputs must be extended from the 8921 // same source type and all of the inputs must be any or zero extend. 8922 // Scalar sizes must be a power of two. 8923 EVT OutScalarTy = VT.getScalarType(); 8924 bool ValidTypes = SourceType != MVT::Other && 8925 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 8926 isPowerOf2_32(SourceType.getSizeInBits()); 8927 8928 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 8929 // turn into a single shuffle instruction. 8930 if (!ValidTypes) 8931 return SDValue(); 8932 8933 bool isLE = TLI.isLittleEndian(); 8934 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 8935 assert(ElemRatio > 1 && "Invalid element size ratio"); 8936 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 8937 DAG.getConstant(0, SourceType); 8938 8939 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 8940 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 8941 8942 // Populate the new build_vector 8943 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 8944 SDValue Cast = N->getOperand(i); 8945 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 8946 Cast.getOpcode() == ISD::ZERO_EXTEND || 8947 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 8948 SDValue In; 8949 if (Cast.getOpcode() == ISD::UNDEF) 8950 In = DAG.getUNDEF(SourceType); 8951 else 8952 In = Cast->getOperand(0); 8953 unsigned Index = isLE ? (i * ElemRatio) : 8954 (i * ElemRatio + (ElemRatio - 1)); 8955 8956 assert(Index < Ops.size() && "Invalid index"); 8957 Ops[Index] = In; 8958 } 8959 8960 // The type of the new BUILD_VECTOR node. 8961 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 8962 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 8963 "Invalid vector size"); 8964 // Check if the new vector type is legal. 8965 if (!isTypeLegal(VecVT)) return SDValue(); 8966 8967 // Make the new BUILD_VECTOR. 8968 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size()); 8969 8970 // The new BUILD_VECTOR node has the potential to be further optimized. 8971 AddToWorkList(BV.getNode()); 8972 // Bitcast to the desired type. 8973 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 8974} 8975 8976SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 8977 EVT VT = N->getValueType(0); 8978 8979 unsigned NumInScalars = N->getNumOperands(); 8980 SDLoc dl(N); 8981 8982 EVT SrcVT = MVT::Other; 8983 unsigned Opcode = ISD::DELETED_NODE; 8984 unsigned NumDefs = 0; 8985 8986 for (unsigned i = 0; i != NumInScalars; ++i) { 8987 SDValue In = N->getOperand(i); 8988 unsigned Opc = In.getOpcode(); 8989 8990 if (Opc == ISD::UNDEF) 8991 continue; 8992 8993 // If all scalar values are floats and converted from integers. 8994 if (Opcode == ISD::DELETED_NODE && 8995 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 8996 Opcode = Opc; 8997 } 8998 8999 if (Opc != Opcode) 9000 return SDValue(); 9001 9002 EVT InVT = In.getOperand(0).getValueType(); 9003 9004 // If all scalar values are typed differently, bail out. It's chosen to 9005 // simplify BUILD_VECTOR of integer types. 9006 if (SrcVT == MVT::Other) 9007 SrcVT = InVT; 9008 if (SrcVT != InVT) 9009 return SDValue(); 9010 NumDefs++; 9011 } 9012 9013 // If the vector has just one element defined, it's not worth to fold it into 9014 // a vectorized one. 9015 if (NumDefs < 2) 9016 return SDValue(); 9017 9018 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 9019 && "Should only handle conversion from integer to float."); 9020 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 9021 9022 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 9023 9024 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 9025 return SDValue(); 9026 9027 SmallVector<SDValue, 8> Opnds; 9028 for (unsigned i = 0; i != NumInScalars; ++i) { 9029 SDValue In = N->getOperand(i); 9030 9031 if (In.getOpcode() == ISD::UNDEF) 9032 Opnds.push_back(DAG.getUNDEF(SrcVT)); 9033 else 9034 Opnds.push_back(In.getOperand(0)); 9035 } 9036 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, 9037 &Opnds[0], Opnds.size()); 9038 AddToWorkList(BV.getNode()); 9039 9040 return DAG.getNode(Opcode, dl, VT, BV); 9041} 9042 9043SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 9044 unsigned NumInScalars = N->getNumOperands(); 9045 SDLoc dl(N); 9046 EVT VT = N->getValueType(0); 9047 9048 // A vector built entirely of undefs is undef. 9049 if (ISD::allOperandsUndef(N)) 9050 return DAG.getUNDEF(VT); 9051 9052 SDValue V = reduceBuildVecExtToExtBuildVec(N); 9053 if (V.getNode()) 9054 return V; 9055 9056 V = reduceBuildVecConvertToConvertBuildVec(N); 9057 if (V.getNode()) 9058 return V; 9059 9060 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 9061 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 9062 // at most two distinct vectors, turn this into a shuffle node. 9063 9064 // May only combine to shuffle after legalize if shuffle is legal. 9065 if (LegalOperations && 9066 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 9067 return SDValue(); 9068 9069 SDValue VecIn1, VecIn2; 9070 for (unsigned i = 0; i != NumInScalars; ++i) { 9071 // Ignore undef inputs. 9072 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 9073 9074 // If this input is something other than a EXTRACT_VECTOR_ELT with a 9075 // constant index, bail out. 9076 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9077 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 9078 VecIn1 = VecIn2 = SDValue(0, 0); 9079 break; 9080 } 9081 9082 // We allow up to two distinct input vectors. 9083 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 9084 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 9085 continue; 9086 9087 if (VecIn1.getNode() == 0) { 9088 VecIn1 = ExtractedFromVec; 9089 } else if (VecIn2.getNode() == 0) { 9090 VecIn2 = ExtractedFromVec; 9091 } else { 9092 // Too many inputs. 9093 VecIn1 = VecIn2 = SDValue(0, 0); 9094 break; 9095 } 9096 } 9097 9098 // If everything is good, we can make a shuffle operation. 9099 if (VecIn1.getNode()) { 9100 SmallVector<int, 8> Mask; 9101 for (unsigned i = 0; i != NumInScalars; ++i) { 9102 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 9103 Mask.push_back(-1); 9104 continue; 9105 } 9106 9107 // If extracting from the first vector, just use the index directly. 9108 SDValue Extract = N->getOperand(i); 9109 SDValue ExtVal = Extract.getOperand(1); 9110 if (Extract.getOperand(0) == VecIn1) { 9111 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 9112 if (ExtIndex > VT.getVectorNumElements()) 9113 return SDValue(); 9114 9115 Mask.push_back(ExtIndex); 9116 continue; 9117 } 9118 9119 // Otherwise, use InIdx + VecSize 9120 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 9121 Mask.push_back(Idx+NumInScalars); 9122 } 9123 9124 // We can't generate a shuffle node with mismatched input and output types. 9125 // Attempt to transform a single input vector to the correct type. 9126 if ((VT != VecIn1.getValueType())) { 9127 // We don't support shuffeling between TWO values of different types. 9128 if (VecIn2.getNode() != 0) 9129 return SDValue(); 9130 9131 // We only support widening of vectors which are half the size of the 9132 // output registers. For example XMM->YMM widening on X86 with AVX. 9133 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 9134 return SDValue(); 9135 9136 // If the input vector type has a different base type to the output 9137 // vector type, bail out. 9138 if (VecIn1.getValueType().getVectorElementType() != 9139 VT.getVectorElementType()) 9140 return SDValue(); 9141 9142 // Widen the input vector by adding undef values. 9143 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 9144 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 9145 } 9146 9147 // If VecIn2 is unused then change it to undef. 9148 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 9149 9150 // Check that we were able to transform all incoming values to the same 9151 // type. 9152 if (VecIn2.getValueType() != VecIn1.getValueType() || 9153 VecIn1.getValueType() != VT) 9154 return SDValue(); 9155 9156 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 9157 if (!isTypeLegal(VT)) 9158 return SDValue(); 9159 9160 // Return the new VECTOR_SHUFFLE node. 9161 SDValue Ops[2]; 9162 Ops[0] = VecIn1; 9163 Ops[1] = VecIn2; 9164 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 9165 } 9166 9167 return SDValue(); 9168} 9169 9170SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 9171 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 9172 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 9173 // inputs come from at most two distinct vectors, turn this into a shuffle 9174 // node. 9175 9176 // If we only have one input vector, we don't need to do any concatenation. 9177 if (N->getNumOperands() == 1) 9178 return N->getOperand(0); 9179 9180 // Check if all of the operands are undefs. 9181 if (ISD::allOperandsUndef(N)) 9182 return DAG.getUNDEF(N->getValueType(0)); 9183 9184 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 9185 // nodes often generate nop CONCAT_VECTOR nodes. 9186 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 9187 // place the incoming vectors at the exact same location. 9188 SDValue SingleSource = SDValue(); 9189 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 9190 9191 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 9192 SDValue Op = N->getOperand(i); 9193 9194 if (Op.getOpcode() == ISD::UNDEF) 9195 continue; 9196 9197 // Check if this is the identity extract: 9198 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 9199 return SDValue(); 9200 9201 // Find the single incoming vector for the extract_subvector. 9202 if (SingleSource.getNode()) { 9203 if (Op.getOperand(0) != SingleSource) 9204 return SDValue(); 9205 } else { 9206 SingleSource = Op.getOperand(0); 9207 9208 // Check the source type is the same as the type of the result. 9209 // If not, this concat may extend the vector, so we can not 9210 // optimize it away. 9211 if (SingleSource.getValueType() != N->getValueType(0)) 9212 return SDValue(); 9213 } 9214 9215 unsigned IdentityIndex = i * PartNumElem; 9216 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9217 // The extract index must be constant. 9218 if (!CS) 9219 return SDValue(); 9220 9221 // Check that we are reading from the identity index. 9222 if (CS->getZExtValue() != IdentityIndex) 9223 return SDValue(); 9224 } 9225 9226 if (SingleSource.getNode()) 9227 return SingleSource; 9228 9229 return SDValue(); 9230} 9231 9232SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 9233 EVT NVT = N->getValueType(0); 9234 SDValue V = N->getOperand(0); 9235 9236 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 9237 // Combine: 9238 // (extract_subvec (concat V1, V2, ...), i) 9239 // Into: 9240 // Vi if possible 9241 // Only operand 0 is checked as 'concat' assumes all inputs of the same type. 9242 if (V->getOperand(0).getValueType() != NVT) 9243 return SDValue(); 9244 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9245 unsigned NumElems = NVT.getVectorNumElements(); 9246 assert((Idx % NumElems) == 0 && 9247 "IDX in concat is not a multiple of the result vector length."); 9248 return V->getOperand(Idx / NumElems); 9249 } 9250 9251 // Skip bitcasting 9252 if (V->getOpcode() == ISD::BITCAST) 9253 V = V.getOperand(0); 9254 9255 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 9256 SDLoc dl(N); 9257 // Handle only simple case where vector being inserted and vector 9258 // being extracted are of same type, and are half size of larger vectors. 9259 EVT BigVT = V->getOperand(0).getValueType(); 9260 EVT SmallVT = V->getOperand(1).getValueType(); 9261 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 9262 return SDValue(); 9263 9264 // Only handle cases where both indexes are constants with the same type. 9265 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9266 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 9267 9268 if (InsIdx && ExtIdx && 9269 InsIdx->getValueType(0).getSizeInBits() <= 64 && 9270 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 9271 // Combine: 9272 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 9273 // Into: 9274 // indices are equal or bit offsets are equal => V1 9275 // otherwise => (extract_subvec V1, ExtIdx) 9276 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 9277 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 9278 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 9279 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 9280 DAG.getNode(ISD::BITCAST, dl, 9281 N->getOperand(0).getValueType(), 9282 V->getOperand(0)), N->getOperand(1)); 9283 } 9284 } 9285 9286 return SDValue(); 9287} 9288 9289// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat. 9290static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 9291 EVT VT = N->getValueType(0); 9292 unsigned NumElts = VT.getVectorNumElements(); 9293 9294 SDValue N0 = N->getOperand(0); 9295 SDValue N1 = N->getOperand(1); 9296 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9297 9298 SmallVector<SDValue, 4> Ops; 9299 EVT ConcatVT = N0.getOperand(0).getValueType(); 9300 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 9301 unsigned NumConcats = NumElts / NumElemsPerConcat; 9302 9303 // Look at every vector that's inserted. We're looking for exact 9304 // subvector-sized copies from a concatenated vector 9305 for (unsigned I = 0; I != NumConcats; ++I) { 9306 // Make sure we're dealing with a copy. 9307 unsigned Begin = I * NumElemsPerConcat; 9308 bool AllUndef = true, NoUndef = true; 9309 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 9310 if (SVN->getMaskElt(J) >= 0) 9311 AllUndef = false; 9312 else 9313 NoUndef = false; 9314 } 9315 9316 if (NoUndef) { 9317 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 9318 return SDValue(); 9319 9320 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 9321 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 9322 return SDValue(); 9323 9324 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 9325 if (FirstElt < N0.getNumOperands()) 9326 Ops.push_back(N0.getOperand(FirstElt)); 9327 else 9328 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 9329 9330 } else if (AllUndef) { 9331 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 9332 } else { // Mixed with general masks and undefs, can't do optimization. 9333 return SDValue(); 9334 } 9335 } 9336 9337 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(), 9338 Ops.size()); 9339} 9340 9341SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 9342 EVT VT = N->getValueType(0); 9343 unsigned NumElts = VT.getVectorNumElements(); 9344 9345 SDValue N0 = N->getOperand(0); 9346 SDValue N1 = N->getOperand(1); 9347 9348 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 9349 9350 // Canonicalize shuffle undef, undef -> undef 9351 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 9352 return DAG.getUNDEF(VT); 9353 9354 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 9355 9356 // Canonicalize shuffle v, v -> v, undef 9357 if (N0 == N1) { 9358 SmallVector<int, 8> NewMask; 9359 for (unsigned i = 0; i != NumElts; ++i) { 9360 int Idx = SVN->getMaskElt(i); 9361 if (Idx >= (int)NumElts) Idx -= NumElts; 9362 NewMask.push_back(Idx); 9363 } 9364 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 9365 &NewMask[0]); 9366 } 9367 9368 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 9369 if (N0.getOpcode() == ISD::UNDEF) { 9370 SmallVector<int, 8> NewMask; 9371 for (unsigned i = 0; i != NumElts; ++i) { 9372 int Idx = SVN->getMaskElt(i); 9373 if (Idx >= 0) { 9374 if (Idx >= (int)NumElts) 9375 Idx -= NumElts; 9376 else 9377 Idx = -1; // remove reference to lhs 9378 } 9379 NewMask.push_back(Idx); 9380 } 9381 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 9382 &NewMask[0]); 9383 } 9384 9385 // Remove references to rhs if it is undef 9386 if (N1.getOpcode() == ISD::UNDEF) { 9387 bool Changed = false; 9388 SmallVector<int, 8> NewMask; 9389 for (unsigned i = 0; i != NumElts; ++i) { 9390 int Idx = SVN->getMaskElt(i); 9391 if (Idx >= (int)NumElts) { 9392 Idx = -1; 9393 Changed = true; 9394 } 9395 NewMask.push_back(Idx); 9396 } 9397 if (Changed) 9398 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 9399 } 9400 9401 // If it is a splat, check if the argument vector is another splat or a 9402 // build_vector with all scalar elements the same. 9403 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 9404 SDNode *V = N0.getNode(); 9405 9406 // If this is a bit convert that changes the element type of the vector but 9407 // not the number of vector elements, look through it. Be careful not to 9408 // look though conversions that change things like v4f32 to v2f64. 9409 if (V->getOpcode() == ISD::BITCAST) { 9410 SDValue ConvInput = V->getOperand(0); 9411 if (ConvInput.getValueType().isVector() && 9412 ConvInput.getValueType().getVectorNumElements() == NumElts) 9413 V = ConvInput.getNode(); 9414 } 9415 9416 if (V->getOpcode() == ISD::BUILD_VECTOR) { 9417 assert(V->getNumOperands() == NumElts && 9418 "BUILD_VECTOR has wrong number of operands"); 9419 SDValue Base; 9420 bool AllSame = true; 9421 for (unsigned i = 0; i != NumElts; ++i) { 9422 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 9423 Base = V->getOperand(i); 9424 break; 9425 } 9426 } 9427 // Splat of <u, u, u, u>, return <u, u, u, u> 9428 if (!Base.getNode()) 9429 return N0; 9430 for (unsigned i = 0; i != NumElts; ++i) { 9431 if (V->getOperand(i) != Base) { 9432 AllSame = false; 9433 break; 9434 } 9435 } 9436 // Splat of <x, x, x, x>, return <x, x, x, x> 9437 if (AllSame) 9438 return N0; 9439 } 9440 } 9441 9442 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 9443 Level < AfterLegalizeVectorOps && 9444 (N1.getOpcode() == ISD::UNDEF || 9445 (N1.getOpcode() == ISD::CONCAT_VECTORS && 9446 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 9447 SDValue V = partitionShuffleOfConcats(N, DAG); 9448 9449 if (V.getNode()) 9450 return V; 9451 } 9452 9453 // If this shuffle node is simply a swizzle of another shuffle node, 9454 // and it reverses the swizzle of the previous shuffle then we can 9455 // optimize shuffle(shuffle(x, undef), undef) -> x. 9456 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 9457 N1.getOpcode() == ISD::UNDEF) { 9458 9459 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 9460 9461 // Shuffle nodes can only reverse shuffles with a single non-undef value. 9462 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 9463 return SDValue(); 9464 9465 // The incoming shuffle must be of the same type as the result of the 9466 // current shuffle. 9467 assert(OtherSV->getOperand(0).getValueType() == VT && 9468 "Shuffle types don't match"); 9469 9470 for (unsigned i = 0; i != NumElts; ++i) { 9471 int Idx = SVN->getMaskElt(i); 9472 assert(Idx < (int)NumElts && "Index references undef operand"); 9473 // Next, this index comes from the first value, which is the incoming 9474 // shuffle. Adopt the incoming index. 9475 if (Idx >= 0) 9476 Idx = OtherSV->getMaskElt(Idx); 9477 9478 // The combined shuffle must map each index to itself. 9479 if (Idx >= 0 && (unsigned)Idx != i) 9480 return SDValue(); 9481 } 9482 9483 return OtherSV->getOperand(0); 9484 } 9485 9486 return SDValue(); 9487} 9488 9489/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 9490/// an AND to a vector_shuffle with the destination vector and a zero vector. 9491/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 9492/// vector_shuffle V, Zero, <0, 4, 2, 4> 9493SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 9494 EVT VT = N->getValueType(0); 9495 SDLoc dl(N); 9496 SDValue LHS = N->getOperand(0); 9497 SDValue RHS = N->getOperand(1); 9498 if (N->getOpcode() == ISD::AND) { 9499 if (RHS.getOpcode() == ISD::BITCAST) 9500 RHS = RHS.getOperand(0); 9501 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 9502 SmallVector<int, 8> Indices; 9503 unsigned NumElts = RHS.getNumOperands(); 9504 for (unsigned i = 0; i != NumElts; ++i) { 9505 SDValue Elt = RHS.getOperand(i); 9506 if (!isa<ConstantSDNode>(Elt)) 9507 return SDValue(); 9508 9509 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 9510 Indices.push_back(i); 9511 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 9512 Indices.push_back(NumElts); 9513 else 9514 return SDValue(); 9515 } 9516 9517 // Let's see if the target supports this vector_shuffle. 9518 EVT RVT = RHS.getValueType(); 9519 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 9520 return SDValue(); 9521 9522 // Return the new VECTOR_SHUFFLE node. 9523 EVT EltVT = RVT.getVectorElementType(); 9524 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 9525 DAG.getConstant(0, EltVT)); 9526 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 9527 RVT, &ZeroOps[0], ZeroOps.size()); 9528 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 9529 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 9530 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 9531 } 9532 } 9533 9534 return SDValue(); 9535} 9536 9537/// SimplifyVBinOp - Visit a binary vector operation, like ADD. 9538SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 9539 assert(N->getValueType(0).isVector() && 9540 "SimplifyVBinOp only works on vectors!"); 9541 9542 SDValue LHS = N->getOperand(0); 9543 SDValue RHS = N->getOperand(1); 9544 SDValue Shuffle = XformToShuffleWithZero(N); 9545 if (Shuffle.getNode()) return Shuffle; 9546 9547 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 9548 // this operation. 9549 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 9550 RHS.getOpcode() == ISD::BUILD_VECTOR) { 9551 SmallVector<SDValue, 8> Ops; 9552 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 9553 SDValue LHSOp = LHS.getOperand(i); 9554 SDValue RHSOp = RHS.getOperand(i); 9555 // If these two elements can't be folded, bail out. 9556 if ((LHSOp.getOpcode() != ISD::UNDEF && 9557 LHSOp.getOpcode() != ISD::Constant && 9558 LHSOp.getOpcode() != ISD::ConstantFP) || 9559 (RHSOp.getOpcode() != ISD::UNDEF && 9560 RHSOp.getOpcode() != ISD::Constant && 9561 RHSOp.getOpcode() != ISD::ConstantFP)) 9562 break; 9563 9564 // Can't fold divide by zero. 9565 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 9566 N->getOpcode() == ISD::FDIV) { 9567 if ((RHSOp.getOpcode() == ISD::Constant && 9568 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 9569 (RHSOp.getOpcode() == ISD::ConstantFP && 9570 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 9571 break; 9572 } 9573 9574 EVT VT = LHSOp.getValueType(); 9575 EVT RVT = RHSOp.getValueType(); 9576 if (RVT != VT) { 9577 // Integer BUILD_VECTOR operands may have types larger than the element 9578 // size (e.g., when the element type is not legal). Prior to type 9579 // legalization, the types may not match between the two BUILD_VECTORS. 9580 // Truncate one of the operands to make them match. 9581 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 9582 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 9583 } else { 9584 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 9585 VT = RVT; 9586 } 9587 } 9588 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 9589 LHSOp, RHSOp); 9590 if (FoldOp.getOpcode() != ISD::UNDEF && 9591 FoldOp.getOpcode() != ISD::Constant && 9592 FoldOp.getOpcode() != ISD::ConstantFP) 9593 break; 9594 Ops.push_back(FoldOp); 9595 AddToWorkList(FoldOp.getNode()); 9596 } 9597 9598 if (Ops.size() == LHS.getNumOperands()) 9599 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 9600 LHS.getValueType(), &Ops[0], Ops.size()); 9601 } 9602 9603 return SDValue(); 9604} 9605 9606/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG. 9607SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 9608 assert(N->getValueType(0).isVector() && 9609 "SimplifyVUnaryOp only works on vectors!"); 9610 9611 SDValue N0 = N->getOperand(0); 9612 9613 if (N0.getOpcode() != ISD::BUILD_VECTOR) 9614 return SDValue(); 9615 9616 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 9617 SmallVector<SDValue, 8> Ops; 9618 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 9619 SDValue Op = N0.getOperand(i); 9620 if (Op.getOpcode() != ISD::UNDEF && 9621 Op.getOpcode() != ISD::ConstantFP) 9622 break; 9623 EVT EltVT = Op.getValueType(); 9624 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 9625 if (FoldOp.getOpcode() != ISD::UNDEF && 9626 FoldOp.getOpcode() != ISD::ConstantFP) 9627 break; 9628 Ops.push_back(FoldOp); 9629 AddToWorkList(FoldOp.getNode()); 9630 } 9631 9632 if (Ops.size() != N0.getNumOperands()) 9633 return SDValue(); 9634 9635 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 9636 N0.getValueType(), &Ops[0], Ops.size()); 9637} 9638 9639SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 9640 SDValue N1, SDValue N2){ 9641 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 9642 9643 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 9644 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9645 9646 // If we got a simplified select_cc node back from SimplifySelectCC, then 9647 // break it down into a new SETCC node, and a new SELECT node, and then return 9648 // the SELECT node, since we were called with a SELECT node. 9649 if (SCC.getNode()) { 9650 // Check to see if we got a select_cc back (to turn into setcc/select). 9651 // Otherwise, just return whatever node we got back, like fabs. 9652 if (SCC.getOpcode() == ISD::SELECT_CC) { 9653 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 9654 N0.getValueType(), 9655 SCC.getOperand(0), SCC.getOperand(1), 9656 SCC.getOperand(4)); 9657 AddToWorkList(SETCC.getNode()); 9658 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), 9659 SCC.getOperand(2), SCC.getOperand(3), SETCC); 9660 } 9661 9662 return SCC; 9663 } 9664 return SDValue(); 9665} 9666 9667/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 9668/// are the two values being selected between, see if we can simplify the 9669/// select. Callers of this should assume that TheSelect is deleted if this 9670/// returns true. As such, they should return the appropriate thing (e.g. the 9671/// node) back to the top-level of the DAG combiner loop to avoid it being 9672/// looked at. 9673bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 9674 SDValue RHS) { 9675 9676 // Cannot simplify select with vector condition 9677 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 9678 9679 // If this is a select from two identical things, try to pull the operation 9680 // through the select. 9681 if (LHS.getOpcode() != RHS.getOpcode() || 9682 !LHS.hasOneUse() || !RHS.hasOneUse()) 9683 return false; 9684 9685 // If this is a load and the token chain is identical, replace the select 9686 // of two loads with a load through a select of the address to load from. 9687 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 9688 // constants have been dropped into the constant pool. 9689 if (LHS.getOpcode() == ISD::LOAD) { 9690 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 9691 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 9692 9693 // Token chains must be identical. 9694 if (LHS.getOperand(0) != RHS.getOperand(0) || 9695 // Do not let this transformation reduce the number of volatile loads. 9696 LLD->isVolatile() || RLD->isVolatile() || 9697 // If this is an EXTLOAD, the VT's must match. 9698 LLD->getMemoryVT() != RLD->getMemoryVT() || 9699 // If this is an EXTLOAD, the kind of extension must match. 9700 (LLD->getExtensionType() != RLD->getExtensionType() && 9701 // The only exception is if one of the extensions is anyext. 9702 LLD->getExtensionType() != ISD::EXTLOAD && 9703 RLD->getExtensionType() != ISD::EXTLOAD) || 9704 // FIXME: this discards src value information. This is 9705 // over-conservative. It would be beneficial to be able to remember 9706 // both potential memory locations. Since we are discarding 9707 // src value info, don't do the transformation if the memory 9708 // locations are not in the default address space. 9709 LLD->getPointerInfo().getAddrSpace() != 0 || 9710 RLD->getPointerInfo().getAddrSpace() != 0 || 9711 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 9712 LLD->getBasePtr().getValueType())) 9713 return false; 9714 9715 // Check that the select condition doesn't reach either load. If so, 9716 // folding this will induce a cycle into the DAG. If not, this is safe to 9717 // xform, so create a select of the addresses. 9718 SDValue Addr; 9719 if (TheSelect->getOpcode() == ISD::SELECT) { 9720 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 9721 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 9722 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 9723 return false; 9724 // The loads must not depend on one another. 9725 if (LLD->isPredecessorOf(RLD) || 9726 RLD->isPredecessorOf(LLD)) 9727 return false; 9728 Addr = DAG.getSelect(SDLoc(TheSelect), 9729 LLD->getBasePtr().getValueType(), 9730 TheSelect->getOperand(0), LLD->getBasePtr(), 9731 RLD->getBasePtr()); 9732 } else { // Otherwise SELECT_CC 9733 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 9734 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 9735 9736 if ((LLD->hasAnyUseOfValue(1) && 9737 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 9738 (RLD->hasAnyUseOfValue(1) && 9739 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 9740 return false; 9741 9742 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 9743 LLD->getBasePtr().getValueType(), 9744 TheSelect->getOperand(0), 9745 TheSelect->getOperand(1), 9746 LLD->getBasePtr(), RLD->getBasePtr(), 9747 TheSelect->getOperand(4)); 9748 } 9749 9750 SDValue Load; 9751 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 9752 Load = DAG.getLoad(TheSelect->getValueType(0), 9753 SDLoc(TheSelect), 9754 // FIXME: Discards pointer info. 9755 LLD->getChain(), Addr, MachinePointerInfo(), 9756 LLD->isVolatile(), LLD->isNonTemporal(), 9757 LLD->isInvariant(), LLD->getAlignment()); 9758 } else { 9759 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 9760 RLD->getExtensionType() : LLD->getExtensionType(), 9761 SDLoc(TheSelect), 9762 TheSelect->getValueType(0), 9763 // FIXME: Discards pointer info. 9764 LLD->getChain(), Addr, MachinePointerInfo(), 9765 LLD->getMemoryVT(), LLD->isVolatile(), 9766 LLD->isNonTemporal(), LLD->getAlignment()); 9767 } 9768 9769 // Users of the select now use the result of the load. 9770 CombineTo(TheSelect, Load); 9771 9772 // Users of the old loads now use the new load's chain. We know the 9773 // old-load value is dead now. 9774 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 9775 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 9776 return true; 9777 } 9778 9779 return false; 9780} 9781 9782/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 9783/// where 'cond' is the comparison specified by CC. 9784SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 9785 SDValue N2, SDValue N3, 9786 ISD::CondCode CC, bool NotExtCompare) { 9787 // (x ? y : y) -> y. 9788 if (N2 == N3) return N2; 9789 9790 EVT VT = N2.getValueType(); 9791 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 9792 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 9793 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 9794 9795 // Determine if the condition we're dealing with is constant 9796 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 9797 N0, N1, CC, DL, false); 9798 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 9799 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 9800 9801 // fold select_cc true, x, y -> x 9802 if (SCCC && !SCCC->isNullValue()) 9803 return N2; 9804 // fold select_cc false, x, y -> y 9805 if (SCCC && SCCC->isNullValue()) 9806 return N3; 9807 9808 // Check to see if we can simplify the select into an fabs node 9809 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 9810 // Allow either -0.0 or 0.0 9811 if (CFP->getValueAPF().isZero()) { 9812 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 9813 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 9814 N0 == N2 && N3.getOpcode() == ISD::FNEG && 9815 N2 == N3.getOperand(0)) 9816 return DAG.getNode(ISD::FABS, DL, VT, N0); 9817 9818 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 9819 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 9820 N0 == N3 && N2.getOpcode() == ISD::FNEG && 9821 N2.getOperand(0) == N3) 9822 return DAG.getNode(ISD::FABS, DL, VT, N3); 9823 } 9824 } 9825 9826 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 9827 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 9828 // in it. This is a win when the constant is not otherwise available because 9829 // it replaces two constant pool loads with one. We only do this if the FP 9830 // type is known to be legal, because if it isn't, then we are before legalize 9831 // types an we want the other legalization to happen first (e.g. to avoid 9832 // messing with soft float) and if the ConstantFP is not legal, because if 9833 // it is legal, we may not need to store the FP constant in a constant pool. 9834 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 9835 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 9836 if (TLI.isTypeLegal(N2.getValueType()) && 9837 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 9838 TargetLowering::Legal) && 9839 // If both constants have multiple uses, then we won't need to do an 9840 // extra load, they are likely around in registers for other users. 9841 (TV->hasOneUse() || FV->hasOneUse())) { 9842 Constant *Elts[] = { 9843 const_cast<ConstantFP*>(FV->getConstantFPValue()), 9844 const_cast<ConstantFP*>(TV->getConstantFPValue()) 9845 }; 9846 Type *FPTy = Elts[0]->getType(); 9847 const DataLayout &TD = *TLI.getDataLayout(); 9848 9849 // Create a ConstantArray of the two constants. 9850 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 9851 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 9852 TD.getPrefTypeAlignment(FPTy)); 9853 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 9854 9855 // Get the offsets to the 0 and 1 element of the array so that we can 9856 // select between them. 9857 SDValue Zero = DAG.getIntPtrConstant(0); 9858 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 9859 SDValue One = DAG.getIntPtrConstant(EltSize); 9860 9861 SDValue Cond = DAG.getSetCC(DL, 9862 getSetCCResultType(N0.getValueType()), 9863 N0, N1, CC); 9864 AddToWorkList(Cond.getNode()); 9865 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 9866 Cond, One, Zero); 9867 AddToWorkList(CstOffset.getNode()); 9868 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx, 9869 CstOffset); 9870 AddToWorkList(CPIdx.getNode()); 9871 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 9872 MachinePointerInfo::getConstantPool(), false, 9873 false, false, Alignment); 9874 9875 } 9876 } 9877 9878 // Check to see if we can perform the "gzip trick", transforming 9879 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 9880 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 9881 (N1C->isNullValue() || // (a < 0) ? b : 0 9882 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 9883 EVT XType = N0.getValueType(); 9884 EVT AType = N2.getValueType(); 9885 if (XType.bitsGE(AType)) { 9886 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 9887 // single-bit constant. 9888 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 9889 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 9890 ShCtV = XType.getSizeInBits()-ShCtV-1; 9891 SDValue ShCt = DAG.getConstant(ShCtV, 9892 getShiftAmountTy(N0.getValueType())); 9893 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 9894 XType, N0, ShCt); 9895 AddToWorkList(Shift.getNode()); 9896 9897 if (XType.bitsGT(AType)) { 9898 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 9899 AddToWorkList(Shift.getNode()); 9900 } 9901 9902 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 9903 } 9904 9905 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 9906 XType, N0, 9907 DAG.getConstant(XType.getSizeInBits()-1, 9908 getShiftAmountTy(N0.getValueType()))); 9909 AddToWorkList(Shift.getNode()); 9910 9911 if (XType.bitsGT(AType)) { 9912 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 9913 AddToWorkList(Shift.getNode()); 9914 } 9915 9916 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 9917 } 9918 } 9919 9920 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 9921 // where y is has a single bit set. 9922 // A plaintext description would be, we can turn the SELECT_CC into an AND 9923 // when the condition can be materialized as an all-ones register. Any 9924 // single bit-test can be materialized as an all-ones register with 9925 // shift-left and shift-right-arith. 9926 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 9927 N0->getValueType(0) == VT && 9928 N1C && N1C->isNullValue() && 9929 N2C && N2C->isNullValue()) { 9930 SDValue AndLHS = N0->getOperand(0); 9931 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9932 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 9933 // Shift the tested bit over the sign bit. 9934 APInt AndMask = ConstAndRHS->getAPIntValue(); 9935 SDValue ShlAmt = 9936 DAG.getConstant(AndMask.countLeadingZeros(), 9937 getShiftAmountTy(AndLHS.getValueType())); 9938 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 9939 9940 // Now arithmetic right shift it all the way over, so the result is either 9941 // all-ones, or zero. 9942 SDValue ShrAmt = 9943 DAG.getConstant(AndMask.getBitWidth()-1, 9944 getShiftAmountTy(Shl.getValueType())); 9945 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 9946 9947 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 9948 } 9949 } 9950 9951 // fold select C, 16, 0 -> shl C, 4 9952 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 9953 TLI.getBooleanContents(N0.getValueType().isVector()) == 9954 TargetLowering::ZeroOrOneBooleanContent) { 9955 9956 // If the caller doesn't want us to simplify this into a zext of a compare, 9957 // don't do it. 9958 if (NotExtCompare && N2C->getAPIntValue() == 1) 9959 return SDValue(); 9960 9961 // Get a SetCC of the condition 9962 // NOTE: Don't create a SETCC if it's not legal on this target. 9963 if (!LegalOperations || 9964 TLI.isOperationLegal(ISD::SETCC, 9965 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 9966 SDValue Temp, SCC; 9967 // cast from setcc result type to select result type 9968 if (LegalTypes) { 9969 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 9970 N0, N1, CC); 9971 if (N2.getValueType().bitsLT(SCC.getValueType())) 9972 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 9973 N2.getValueType()); 9974 else 9975 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 9976 N2.getValueType(), SCC); 9977 } else { 9978 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 9979 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 9980 N2.getValueType(), SCC); 9981 } 9982 9983 AddToWorkList(SCC.getNode()); 9984 AddToWorkList(Temp.getNode()); 9985 9986 if (N2C->getAPIntValue() == 1) 9987 return Temp; 9988 9989 // shl setcc result by log2 n2c 9990 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 9991 DAG.getConstant(N2C->getAPIntValue().logBase2(), 9992 getShiftAmountTy(Temp.getValueType()))); 9993 } 9994 } 9995 9996 // Check to see if this is the equivalent of setcc 9997 // FIXME: Turn all of these into setcc if setcc if setcc is legal 9998 // otherwise, go ahead with the folds. 9999 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 10000 EVT XType = N0.getValueType(); 10001 if (!LegalOperations || 10002 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 10003 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 10004 if (Res.getValueType() != VT) 10005 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 10006 return Res; 10007 } 10008 10009 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 10010 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 10011 (!LegalOperations || 10012 TLI.isOperationLegal(ISD::CTLZ, XType))) { 10013 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 10014 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 10015 DAG.getConstant(Log2_32(XType.getSizeInBits()), 10016 getShiftAmountTy(Ctlz.getValueType()))); 10017 } 10018 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 10019 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 10020 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 10021 XType, DAG.getConstant(0, XType), N0); 10022 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 10023 return DAG.getNode(ISD::SRL, DL, XType, 10024 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 10025 DAG.getConstant(XType.getSizeInBits()-1, 10026 getShiftAmountTy(XType))); 10027 } 10028 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 10029 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 10030 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 10031 DAG.getConstant(XType.getSizeInBits()-1, 10032 getShiftAmountTy(N0.getValueType()))); 10033 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 10034 } 10035 } 10036 10037 // Check to see if this is an integer abs. 10038 // select_cc setg[te] X, 0, X, -X -> 10039 // select_cc setgt X, -1, X, -X -> 10040 // select_cc setl[te] X, 0, -X, X -> 10041 // select_cc setlt X, 1, -X, X -> 10042 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 10043 if (N1C) { 10044 ConstantSDNode *SubC = NULL; 10045 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 10046 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 10047 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 10048 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 10049 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 10050 (N1C->isOne() && CC == ISD::SETLT)) && 10051 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 10052 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 10053 10054 EVT XType = N0.getValueType(); 10055 if (SubC && SubC->isNullValue() && XType.isInteger()) { 10056 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 10057 N0, 10058 DAG.getConstant(XType.getSizeInBits()-1, 10059 getShiftAmountTy(N0.getValueType()))); 10060 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 10061 XType, N0, Shift); 10062 AddToWorkList(Shift.getNode()); 10063 AddToWorkList(Add.getNode()); 10064 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 10065 } 10066 } 10067 10068 return SDValue(); 10069} 10070 10071/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 10072SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 10073 SDValue N1, ISD::CondCode Cond, 10074 SDLoc DL, bool foldBooleans) { 10075 TargetLowering::DAGCombinerInfo 10076 DagCombineInfo(DAG, Level, false, this); 10077 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 10078} 10079 10080/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 10081/// return a DAG expression to select that will generate the same value by 10082/// multiplying by a magic number. See: 10083/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 10084SDValue DAGCombiner::BuildSDIV(SDNode *N) { 10085 std::vector<SDNode*> Built; 10086 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 10087 10088 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 10089 ii != ee; ++ii) 10090 AddToWorkList(*ii); 10091 return S; 10092} 10093 10094/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 10095/// return a DAG expression to select that will generate the same value by 10096/// multiplying by a magic number. See: 10097/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 10098SDValue DAGCombiner::BuildUDIV(SDNode *N) { 10099 std::vector<SDNode*> Built; 10100 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 10101 10102 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 10103 ii != ee; ++ii) 10104 AddToWorkList(*ii); 10105 return S; 10106} 10107 10108/// FindBaseOffset - Return true if base is a frame index, which is known not 10109// to alias with anything but itself. Provides base object and offset as 10110// results. 10111static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 10112 const GlobalValue *&GV, const void *&CV) { 10113 // Assume it is a primitive operation. 10114 Base = Ptr; Offset = 0; GV = 0; CV = 0; 10115 10116 // If it's an adding a simple constant then integrate the offset. 10117 if (Base.getOpcode() == ISD::ADD) { 10118 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 10119 Base = Base.getOperand(0); 10120 Offset += C->getZExtValue(); 10121 } 10122 } 10123 10124 // Return the underlying GlobalValue, and update the Offset. Return false 10125 // for GlobalAddressSDNode since the same GlobalAddress may be represented 10126 // by multiple nodes with different offsets. 10127 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 10128 GV = G->getGlobal(); 10129 Offset += G->getOffset(); 10130 return false; 10131 } 10132 10133 // Return the underlying Constant value, and update the Offset. Return false 10134 // for ConstantSDNodes since the same constant pool entry may be represented 10135 // by multiple nodes with different offsets. 10136 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 10137 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 10138 : (const void *)C->getConstVal(); 10139 Offset += C->getOffset(); 10140 return false; 10141 } 10142 // If it's any of the following then it can't alias with anything but itself. 10143 return isa<FrameIndexSDNode>(Base); 10144} 10145 10146/// isAlias - Return true if there is any possibility that the two addresses 10147/// overlap. 10148bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, 10149 const Value *SrcValue1, int SrcValueOffset1, 10150 unsigned SrcValueAlign1, 10151 const MDNode *TBAAInfo1, 10152 SDValue Ptr2, int64_t Size2, 10153 const Value *SrcValue2, int SrcValueOffset2, 10154 unsigned SrcValueAlign2, 10155 const MDNode *TBAAInfo2) const { 10156 // If they are the same then they must be aliases. 10157 if (Ptr1 == Ptr2) return true; 10158 10159 // Gather base node and offset information. 10160 SDValue Base1, Base2; 10161 int64_t Offset1, Offset2; 10162 const GlobalValue *GV1, *GV2; 10163 const void *CV1, *CV2; 10164 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 10165 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 10166 10167 // If they have a same base address then check to see if they overlap. 10168 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 10169 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 10170 10171 // It is possible for different frame indices to alias each other, mostly 10172 // when tail call optimization reuses return address slots for arguments. 10173 // To catch this case, look up the actual index of frame indices to compute 10174 // the real alias relationship. 10175 if (isFrameIndex1 && isFrameIndex2) { 10176 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 10177 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 10178 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 10179 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 10180 } 10181 10182 // Otherwise, if we know what the bases are, and they aren't identical, then 10183 // we know they cannot alias. 10184 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 10185 return false; 10186 10187 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 10188 // compared to the size and offset of the access, we may be able to prove they 10189 // do not alias. This check is conservative for now to catch cases created by 10190 // splitting vector types. 10191 if ((SrcValueAlign1 == SrcValueAlign2) && 10192 (SrcValueOffset1 != SrcValueOffset2) && 10193 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 10194 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 10195 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 10196 10197 // There is no overlap between these relatively aligned accesses of similar 10198 // size, return no alias. 10199 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 10200 return false; 10201 } 10202 10203 if (CombinerGlobalAA) { 10204 // Use alias analysis information. 10205 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 10206 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 10207 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 10208 AliasAnalysis::AliasResult AAResult = 10209 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1), 10210 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2)); 10211 if (AAResult == AliasAnalysis::NoAlias) 10212 return false; 10213 } 10214 10215 // Otherwise we have to assume they alias. 10216 return true; 10217} 10218 10219bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) { 10220 SDValue Ptr0, Ptr1; 10221 int64_t Size0, Size1; 10222 const Value *SrcValue0, *SrcValue1; 10223 int SrcValueOffset0, SrcValueOffset1; 10224 unsigned SrcValueAlign0, SrcValueAlign1; 10225 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1; 10226 FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0, 10227 SrcValueAlign0, SrcTBAAInfo0); 10228 FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1, 10229 SrcValueAlign1, SrcTBAAInfo1); 10230 return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0, 10231 SrcValueAlign0, SrcTBAAInfo0, 10232 Ptr1, Size1, SrcValue1, SrcValueOffset1, 10233 SrcValueAlign1, SrcTBAAInfo1); 10234} 10235 10236/// FindAliasInfo - Extracts the relevant alias information from the memory 10237/// node. Returns true if the operand was a load. 10238bool DAGCombiner::FindAliasInfo(SDNode *N, 10239 SDValue &Ptr, int64_t &Size, 10240 const Value *&SrcValue, 10241 int &SrcValueOffset, 10242 unsigned &SrcValueAlign, 10243 const MDNode *&TBAAInfo) const { 10244 LSBaseSDNode *LS = cast<LSBaseSDNode>(N); 10245 10246 Ptr = LS->getBasePtr(); 10247 Size = LS->getMemoryVT().getSizeInBits() >> 3; 10248 SrcValue = LS->getSrcValue(); 10249 SrcValueOffset = LS->getSrcValueOffset(); 10250 SrcValueAlign = LS->getOriginalAlignment(); 10251 TBAAInfo = LS->getTBAAInfo(); 10252 return isa<LoadSDNode>(LS); 10253} 10254 10255/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 10256/// looking for aliasing nodes and adding them to the Aliases vector. 10257void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 10258 SmallVectorImpl<SDValue> &Aliases) { 10259 SmallVector<SDValue, 8> Chains; // List of chains to visit. 10260 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 10261 10262 // Get alias information for node. 10263 SDValue Ptr; 10264 int64_t Size; 10265 const Value *SrcValue; 10266 int SrcValueOffset; 10267 unsigned SrcValueAlign; 10268 const MDNode *SrcTBAAInfo; 10269 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset, 10270 SrcValueAlign, SrcTBAAInfo); 10271 10272 // Starting off. 10273 Chains.push_back(OriginalChain); 10274 unsigned Depth = 0; 10275 10276 // Look at each chain and determine if it is an alias. If so, add it to the 10277 // aliases list. If not, then continue up the chain looking for the next 10278 // candidate. 10279 while (!Chains.empty()) { 10280 SDValue Chain = Chains.back(); 10281 Chains.pop_back(); 10282 10283 // For TokenFactor nodes, look at each operand and only continue up the 10284 // chain until we find two aliases. If we've seen two aliases, assume we'll 10285 // find more and revert to original chain since the xform is unlikely to be 10286 // profitable. 10287 // 10288 // FIXME: The depth check could be made to return the last non-aliasing 10289 // chain we found before we hit a tokenfactor rather than the original 10290 // chain. 10291 if (Depth > 6 || Aliases.size() == 2) { 10292 Aliases.clear(); 10293 Aliases.push_back(OriginalChain); 10294 break; 10295 } 10296 10297 // Don't bother if we've been before. 10298 if (!Visited.insert(Chain.getNode())) 10299 continue; 10300 10301 switch (Chain.getOpcode()) { 10302 case ISD::EntryToken: 10303 // Entry token is ideal chain operand, but handled in FindBetterChain. 10304 break; 10305 10306 case ISD::LOAD: 10307 case ISD::STORE: { 10308 // Get alias information for Chain. 10309 SDValue OpPtr; 10310 int64_t OpSize; 10311 const Value *OpSrcValue; 10312 int OpSrcValueOffset; 10313 unsigned OpSrcValueAlign; 10314 const MDNode *OpSrcTBAAInfo; 10315 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 10316 OpSrcValue, OpSrcValueOffset, 10317 OpSrcValueAlign, 10318 OpSrcTBAAInfo); 10319 10320 // If chain is alias then stop here. 10321 if (!(IsLoad && IsOpLoad) && 10322 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign, 10323 SrcTBAAInfo, 10324 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset, 10325 OpSrcValueAlign, OpSrcTBAAInfo)) { 10326 Aliases.push_back(Chain); 10327 } else { 10328 // Look further up the chain. 10329 Chains.push_back(Chain.getOperand(0)); 10330 ++Depth; 10331 } 10332 break; 10333 } 10334 10335 case ISD::TokenFactor: 10336 // We have to check each of the operands of the token factor for "small" 10337 // token factors, so we queue them up. Adding the operands to the queue 10338 // (stack) in reverse order maintains the original order and increases the 10339 // likelihood that getNode will find a matching token factor (CSE.) 10340 if (Chain.getNumOperands() > 16) { 10341 Aliases.push_back(Chain); 10342 break; 10343 } 10344 for (unsigned n = Chain.getNumOperands(); n;) 10345 Chains.push_back(Chain.getOperand(--n)); 10346 ++Depth; 10347 break; 10348 10349 default: 10350 // For all other instructions we will just have to take what we can get. 10351 Aliases.push_back(Chain); 10352 break; 10353 } 10354 } 10355} 10356 10357/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 10358/// for a better chain (aliasing node.) 10359SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 10360 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 10361 10362 // Accumulate all the aliases to this node. 10363 GatherAllAliases(N, OldChain, Aliases); 10364 10365 // If no operands then chain to entry token. 10366 if (Aliases.size() == 0) 10367 return DAG.getEntryNode(); 10368 10369 // If a single operand then chain to it. We don't need to revisit it. 10370 if (Aliases.size() == 1) 10371 return Aliases[0]; 10372 10373 // Construct a custom tailored token factor. 10374 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 10375 &Aliases[0], Aliases.size()); 10376} 10377 10378// SelectionDAG::Combine - This is the entry point for the file. 10379// 10380void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 10381 CodeGenOpt::Level OptLevel) { 10382 /// run - This is the main entry point to this class. 10383 /// 10384 DAGCombiner(*this, AA, OptLevel).Run(Level); 10385} 10386