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/DerivedTypes.h" 22 #include "llvm/LLVMContext.h" 23 #include "llvm/CodeGen/MachineFunction.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Target/TargetLowering.h" 28 #include "llvm/Target/TargetMachine.h" 29 #include "llvm/Target/TargetOptions.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> 38 using namespace llvm; 39 40 STATISTIC(NodesCombined , "Number of dag nodes combined"); 41 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 42 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 43 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 44 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 45 46 namespace { 47 static cl::opt<bool> 48 CombinerAA("combiner-alias-analysis", cl::Hidden, 49 cl::desc("Turn on alias analysis during testing")); 50 51 static cl::opt<bool> 52 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 53 cl::desc("Include global information in alias analysis")); 54 55 //------------------------------ DAGCombiner ---------------------------------// 56 57 class DAGCombiner { 58 SelectionDAG &DAG; 59 const TargetLowering &TLI; 60 CombineLevel Level; 61 CodeGenOpt::Level OptLevel; 62 bool LegalOperations; 63 bool LegalTypes; 64 65 // Worklist of all of the nodes that need to be simplified. 66 // 67 // This has the semantics that when adding to the worklist, 68 // the item added must be next to be processed. It should 69 // also only appear once. The naive approach to this takes 70 // linear time. 71 // 72 // To reduce the insert/remove time to logarithmic, we use 73 // a set and a vector to maintain our worklist. 74 // 75 // The set contains the items on the worklist, but does not 76 // maintain the order they should be visited. 77 // 78 // The vector maintains the order nodes should be visited, but may 79 // contain duplicate or removed nodes. When choosing a node to 80 // visit, we pop off the order stack until we find an item that is 81 // also in the contents set. All operations are O(log N). 82 SmallPtrSet<SDNode*, 64> WorkListContents; 83 SmallVector<SDNode*, 64> WorkListOrder; 84 85 // AA - Used for DAG load/store alias analysis. 86 AliasAnalysis &AA; 87 88 /// AddUsersToWorkList - When an instruction is simplified, add all users of 89 /// the instruction to the work lists because they might get more simplified 90 /// now. 91 /// 92 void AddUsersToWorkList(SDNode *N) { 93 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 94 UI != UE; ++UI) 95 AddToWorkList(*UI); 96 } 97 98 /// visit - call the node-specific routine that knows how to fold each 99 /// particular type of node. 100 SDValue visit(SDNode *N); 101 102 public: 103 /// AddToWorkList - Add to the work list making sure its instance is at the 104 /// back (next to be processed.) 105 void AddToWorkList(SDNode *N) { 106 WorkListContents.insert(N); 107 WorkListOrder.push_back(N); 108 } 109 110 /// removeFromWorkList - remove all instances of N from the worklist. 111 /// 112 void removeFromWorkList(SDNode *N) { 113 WorkListContents.erase(N); 114 } 115 116 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 117 bool AddTo = true); 118 119 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 120 return CombineTo(N, &Res, 1, AddTo); 121 } 122 123 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 124 bool AddTo = true) { 125 SDValue To[] = { Res0, Res1 }; 126 return CombineTo(N, To, 2, AddTo); 127 } 128 129 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 130 131 private: 132 133 /// SimplifyDemandedBits - Check the specified integer node value to see if 134 /// it can be simplified or if things it uses can be simplified by bit 135 /// propagation. If so, return true. 136 bool SimplifyDemandedBits(SDValue Op) { 137 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 138 APInt Demanded = APInt::getAllOnesValue(BitWidth); 139 return SimplifyDemandedBits(Op, Demanded); 140 } 141 142 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 143 144 bool CombineToPreIndexedLoadStore(SDNode *N); 145 bool CombineToPostIndexedLoadStore(SDNode *N); 146 147 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 148 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 149 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 150 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 151 SDValue PromoteIntBinOp(SDValue Op); 152 SDValue PromoteIntShiftOp(SDValue Op); 153 SDValue PromoteExtend(SDValue Op); 154 bool PromoteLoad(SDValue Op); 155 156 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs, 157 SDValue Trunc, SDValue ExtLoad, DebugLoc DL, 158 ISD::NodeType ExtType); 159 160 /// combine - call the node-specific routine that knows how to fold each 161 /// particular type of node. If that doesn't do anything, try the 162 /// target-specific DAG combines. 163 SDValue combine(SDNode *N); 164 165 // Visitation implementation - Implement dag node combining for different 166 // node types. The semantics are as follows: 167 // Return Value: 168 // SDValue.getNode() == 0 - No change was made 169 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 170 // otherwise - N should be replaced by the returned Operand. 171 // 172 SDValue visitTokenFactor(SDNode *N); 173 SDValue visitMERGE_VALUES(SDNode *N); 174 SDValue visitADD(SDNode *N); 175 SDValue visitSUB(SDNode *N); 176 SDValue visitADDC(SDNode *N); 177 SDValue visitSUBC(SDNode *N); 178 SDValue visitADDE(SDNode *N); 179 SDValue visitSUBE(SDNode *N); 180 SDValue visitMUL(SDNode *N); 181 SDValue visitSDIV(SDNode *N); 182 SDValue visitUDIV(SDNode *N); 183 SDValue visitSREM(SDNode *N); 184 SDValue visitUREM(SDNode *N); 185 SDValue visitMULHU(SDNode *N); 186 SDValue visitMULHS(SDNode *N); 187 SDValue visitSMUL_LOHI(SDNode *N); 188 SDValue visitUMUL_LOHI(SDNode *N); 189 SDValue visitSMULO(SDNode *N); 190 SDValue visitUMULO(SDNode *N); 191 SDValue visitSDIVREM(SDNode *N); 192 SDValue visitUDIVREM(SDNode *N); 193 SDValue visitAND(SDNode *N); 194 SDValue visitOR(SDNode *N); 195 SDValue visitXOR(SDNode *N); 196 SDValue SimplifyVBinOp(SDNode *N); 197 SDValue visitSHL(SDNode *N); 198 SDValue visitSRA(SDNode *N); 199 SDValue visitSRL(SDNode *N); 200 SDValue visitCTLZ(SDNode *N); 201 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 202 SDValue visitCTTZ(SDNode *N); 203 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 204 SDValue visitCTPOP(SDNode *N); 205 SDValue visitSELECT(SDNode *N); 206 SDValue visitSELECT_CC(SDNode *N); 207 SDValue visitSETCC(SDNode *N); 208 SDValue visitSIGN_EXTEND(SDNode *N); 209 SDValue visitZERO_EXTEND(SDNode *N); 210 SDValue visitANY_EXTEND(SDNode *N); 211 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 212 SDValue visitTRUNCATE(SDNode *N); 213 SDValue visitBITCAST(SDNode *N); 214 SDValue visitBUILD_PAIR(SDNode *N); 215 SDValue visitFADD(SDNode *N); 216 SDValue visitFSUB(SDNode *N); 217 SDValue visitFMUL(SDNode *N); 218 SDValue visitFMA(SDNode *N); 219 SDValue visitFDIV(SDNode *N); 220 SDValue visitFREM(SDNode *N); 221 SDValue visitFCOPYSIGN(SDNode *N); 222 SDValue visitSINT_TO_FP(SDNode *N); 223 SDValue visitUINT_TO_FP(SDNode *N); 224 SDValue visitFP_TO_SINT(SDNode *N); 225 SDValue visitFP_TO_UINT(SDNode *N); 226 SDValue visitFP_ROUND(SDNode *N); 227 SDValue visitFP_ROUND_INREG(SDNode *N); 228 SDValue visitFP_EXTEND(SDNode *N); 229 SDValue visitFNEG(SDNode *N); 230 SDValue visitFABS(SDNode *N); 231 SDValue visitFCEIL(SDNode *N); 232 SDValue visitFTRUNC(SDNode *N); 233 SDValue visitFFLOOR(SDNode *N); 234 SDValue visitBRCOND(SDNode *N); 235 SDValue visitBR_CC(SDNode *N); 236 SDValue visitLOAD(SDNode *N); 237 SDValue visitSTORE(SDNode *N); 238 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 239 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 240 SDValue visitBUILD_VECTOR(SDNode *N); 241 SDValue visitCONCAT_VECTORS(SDNode *N); 242 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 243 SDValue visitVECTOR_SHUFFLE(SDNode *N); 244 SDValue visitMEMBARRIER(SDNode *N); 245 246 SDValue XformToShuffleWithZero(SDNode *N); 247 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS); 248 249 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 250 251 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 252 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 253 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2); 254 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2, 255 SDValue N3, ISD::CondCode CC, 256 bool NotExtCompare = false); 257 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 258 DebugLoc DL, bool foldBooleans = true); 259 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 260 unsigned HiOp); 261 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 262 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 263 SDValue BuildSDIV(SDNode *N); 264 SDValue BuildUDIV(SDNode *N); 265 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 266 bool DemandHighBits = true); 267 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 268 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL); 269 SDValue ReduceLoadWidth(SDNode *N); 270 SDValue ReduceLoadOpStoreWidth(SDNode *N); 271 SDValue TransformFPLoadStorePair(SDNode *N); 272 273 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 274 275 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 276 /// looking for aliasing nodes and adding them to the Aliases vector. 277 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 278 SmallVector<SDValue, 8> &Aliases); 279 280 /// isAlias - Return true if there is any possibility that the two addresses 281 /// overlap. 282 bool isAlias(SDValue Ptr1, int64_t Size1, 283 const Value *SrcValue1, int SrcValueOffset1, 284 unsigned SrcValueAlign1, 285 const MDNode *TBAAInfo1, 286 SDValue Ptr2, int64_t Size2, 287 const Value *SrcValue2, int SrcValueOffset2, 288 unsigned SrcValueAlign2, 289 const MDNode *TBAAInfo2) const; 290 291 /// FindAliasInfo - Extracts the relevant alias information from the memory 292 /// node. Returns true if the operand was a load. 293 bool FindAliasInfo(SDNode *N, 294 SDValue &Ptr, int64_t &Size, 295 const Value *&SrcValue, int &SrcValueOffset, 296 unsigned &SrcValueAlignment, 297 const MDNode *&TBAAInfo) const; 298 299 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 300 /// looking for a better chain (aliasing node.) 301 SDValue FindBetterChain(SDNode *N, SDValue Chain); 302 303 public: 304 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 305 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 306 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {} 307 308 /// Run - runs the dag combiner on all nodes in the work list 309 void Run(CombineLevel AtLevel); 310 311 SelectionDAG &getDAG() const { return DAG; } 312 313 /// getShiftAmountTy - Returns a type large enough to hold any valid 314 /// shift amount - before type legalization these can be huge. 315 EVT getShiftAmountTy(EVT LHSTy) { 316 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy(); 317 } 318 319 /// isTypeLegal - This method returns true if we are running before type 320 /// legalization or if the specified VT is legal. 321 bool isTypeLegal(const EVT &VT) { 322 if (!LegalTypes) return true; 323 return TLI.isTypeLegal(VT); 324 } 325 }; 326 } 327 328 329 namespace { 330 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 331 /// nodes from the worklist. 332 class WorkListRemover : public SelectionDAG::DAGUpdateListener { 333 DAGCombiner &DC; 334 public: 335 explicit WorkListRemover(DAGCombiner &dc) 336 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 337 338 virtual void NodeDeleted(SDNode *N, SDNode *E) { 339 DC.removeFromWorkList(N); 340 } 341 }; 342 } 343 344 //===----------------------------------------------------------------------===// 345 // TargetLowering::DAGCombinerInfo implementation 346 //===----------------------------------------------------------------------===// 347 348 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 349 ((DAGCombiner*)DC)->AddToWorkList(N); 350 } 351 352 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 353 ((DAGCombiner*)DC)->removeFromWorkList(N); 354 } 355 356 SDValue TargetLowering::DAGCombinerInfo:: 357 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 358 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 359 } 360 361 SDValue TargetLowering::DAGCombinerInfo:: 362 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 363 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 364 } 365 366 367 SDValue TargetLowering::DAGCombinerInfo:: 368 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 369 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 370 } 371 372 void TargetLowering::DAGCombinerInfo:: 373 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 374 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 375 } 376 377 //===----------------------------------------------------------------------===// 378 // Helper Functions 379 //===----------------------------------------------------------------------===// 380 381 /// isNegatibleForFree - Return 1 if we can compute the negated form of the 382 /// specified expression for the same cost as the expression itself, or 2 if we 383 /// can compute the negated form more cheaply than the expression itself. 384 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 385 const TargetLowering &TLI, 386 const TargetOptions *Options, 387 unsigned Depth = 0) { 388 // No compile time optimizations on this type. 389 if (Op.getValueType() == MVT::ppcf128) 390 return 0; 391 392 // fneg is removable even if it has multiple uses. 393 if (Op.getOpcode() == ISD::FNEG) return 2; 394 395 // Don't allow anything with multiple uses. 396 if (!Op.hasOneUse()) return 0; 397 398 // Don't recurse exponentially. 399 if (Depth > 6) return 0; 400 401 switch (Op.getOpcode()) { 402 default: return false; 403 case ISD::ConstantFP: 404 // Don't invert constant FP values after legalize. The negated constant 405 // isn't necessarily legal. 406 return LegalOperations ? 0 : 1; 407 case ISD::FADD: 408 // FIXME: determine better conditions for this xform. 409 if (!Options->UnsafeFPMath) return 0; 410 411 // After operation legalization, it might not be legal to create new FSUBs. 412 if (LegalOperations && 413 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 414 return 0; 415 416 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 417 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 418 Options, Depth + 1)) 419 return V; 420 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 421 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 422 Depth + 1); 423 case ISD::FSUB: 424 // We can't turn -(A-B) into B-A when we honor signed zeros. 425 if (!Options->UnsafeFPMath) return 0; 426 427 // fold (fneg (fsub A, B)) -> (fsub B, A) 428 return 1; 429 430 case ISD::FMUL: 431 case ISD::FDIV: 432 if (Options->HonorSignDependentRoundingFPMath()) return 0; 433 434 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 435 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 436 Options, Depth + 1)) 437 return V; 438 439 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 440 Depth + 1); 441 442 case ISD::FP_EXTEND: 443 case ISD::FP_ROUND: 444 case ISD::FSIN: 445 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 446 Depth + 1); 447 } 448 } 449 450 /// GetNegatedExpression - If isNegatibleForFree returns true, this function 451 /// returns the newly negated expression. 452 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 453 bool LegalOperations, unsigned Depth = 0) { 454 // fneg is removable even if it has multiple uses. 455 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 456 457 // Don't allow anything with multiple uses. 458 assert(Op.hasOneUse() && "Unknown reuse!"); 459 460 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 461 switch (Op.getOpcode()) { 462 default: llvm_unreachable("Unknown code"); 463 case ISD::ConstantFP: { 464 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 465 V.changeSign(); 466 return DAG.getConstantFP(V, Op.getValueType()); 467 } 468 case ISD::FADD: 469 // FIXME: determine better conditions for this xform. 470 assert(DAG.getTarget().Options.UnsafeFPMath); 471 472 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 473 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 474 DAG.getTargetLoweringInfo(), 475 &DAG.getTarget().Options, Depth+1)) 476 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 477 GetNegatedExpression(Op.getOperand(0), DAG, 478 LegalOperations, Depth+1), 479 Op.getOperand(1)); 480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 481 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 482 GetNegatedExpression(Op.getOperand(1), DAG, 483 LegalOperations, Depth+1), 484 Op.getOperand(0)); 485 case ISD::FSUB: 486 // We can't turn -(A-B) into B-A when we honor signed zeros. 487 assert(DAG.getTarget().Options.UnsafeFPMath); 488 489 // fold (fneg (fsub 0, B)) -> B 490 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 491 if (N0CFP->getValueAPF().isZero()) 492 return Op.getOperand(1); 493 494 // fold (fneg (fsub A, B)) -> (fsub B, A) 495 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 496 Op.getOperand(1), Op.getOperand(0)); 497 498 case ISD::FMUL: 499 case ISD::FDIV: 500 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 501 502 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 503 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 504 DAG.getTargetLoweringInfo(), 505 &DAG.getTarget().Options, Depth+1)) 506 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 507 GetNegatedExpression(Op.getOperand(0), DAG, 508 LegalOperations, Depth+1), 509 Op.getOperand(1)); 510 511 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 512 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 513 Op.getOperand(0), 514 GetNegatedExpression(Op.getOperand(1), DAG, 515 LegalOperations, Depth+1)); 516 517 case ISD::FP_EXTEND: 518 case ISD::FSIN: 519 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 520 GetNegatedExpression(Op.getOperand(0), DAG, 521 LegalOperations, Depth+1)); 522 case ISD::FP_ROUND: 523 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(), 524 GetNegatedExpression(Op.getOperand(0), DAG, 525 LegalOperations, Depth+1), 526 Op.getOperand(1)); 527 } 528 } 529 530 531 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 532 // that selects between the values 1 and 0, making it equivalent to a setcc. 533 // Also, set the incoming LHS, RHS, and CC references to the appropriate 534 // nodes based on the type of node we are checking. This simplifies life a 535 // bit for the callers. 536 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 537 SDValue &CC) { 538 if (N.getOpcode() == ISD::SETCC) { 539 LHS = N.getOperand(0); 540 RHS = N.getOperand(1); 541 CC = N.getOperand(2); 542 return true; 543 } 544 if (N.getOpcode() == ISD::SELECT_CC && 545 N.getOperand(2).getOpcode() == ISD::Constant && 546 N.getOperand(3).getOpcode() == ISD::Constant && 547 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 548 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 549 LHS = N.getOperand(0); 550 RHS = N.getOperand(1); 551 CC = N.getOperand(4); 552 return true; 553 } 554 return false; 555 } 556 557 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 558 // one use. If this is true, it allows the users to invert the operation for 559 // free when it is profitable to do so. 560 static bool isOneUseSetCC(SDValue N) { 561 SDValue N0, N1, N2; 562 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 563 return true; 564 return false; 565 } 566 567 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL, 568 SDValue N0, SDValue N1) { 569 EVT VT = N0.getValueType(); 570 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) { 571 if (isa<ConstantSDNode>(N1)) { 572 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 573 SDValue OpNode = 574 DAG.FoldConstantArithmetic(Opc, VT, 575 cast<ConstantSDNode>(N0.getOperand(1)), 576 cast<ConstantSDNode>(N1)); 577 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 578 } 579 if (N0.hasOneUse()) { 580 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use 581 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 582 N0.getOperand(0), N1); 583 AddToWorkList(OpNode.getNode()); 584 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 585 } 586 } 587 588 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) { 589 if (isa<ConstantSDNode>(N0)) { 590 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 591 SDValue OpNode = 592 DAG.FoldConstantArithmetic(Opc, VT, 593 cast<ConstantSDNode>(N1.getOperand(1)), 594 cast<ConstantSDNode>(N0)); 595 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 596 } 597 if (N1.hasOneUse()) { 598 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use 599 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 600 N1.getOperand(0), N0); 601 AddToWorkList(OpNode.getNode()); 602 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 603 } 604 } 605 606 return SDValue(); 607 } 608 609 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 610 bool AddTo) { 611 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 612 ++NodesCombined; 613 DEBUG(dbgs() << "\nReplacing.1 "; 614 N->dump(&DAG); 615 dbgs() << "\nWith: "; 616 To[0].getNode()->dump(&DAG); 617 dbgs() << " and " << NumTo-1 << " other values\n"; 618 for (unsigned i = 0, e = NumTo; i != e; ++i) 619 assert((!To[i].getNode() || 620 N->getValueType(i) == To[i].getValueType()) && 621 "Cannot combine value to value of different type!")); 622 WorkListRemover DeadNodes(*this); 623 DAG.ReplaceAllUsesWith(N, To); 624 if (AddTo) { 625 // Push the new nodes and any users onto the worklist 626 for (unsigned i = 0, e = NumTo; i != e; ++i) { 627 if (To[i].getNode()) { 628 AddToWorkList(To[i].getNode()); 629 AddUsersToWorkList(To[i].getNode()); 630 } 631 } 632 } 633 634 // Finally, if the node is now dead, remove it from the graph. The node 635 // may not be dead if the replacement process recursively simplified to 636 // something else needing this node. 637 if (N->use_empty()) { 638 // Nodes can be reintroduced into the worklist. Make sure we do not 639 // process a node that has been replaced. 640 removeFromWorkList(N); 641 642 // Finally, since the node is now dead, remove it from the graph. 643 DAG.DeleteNode(N); 644 } 645 return SDValue(N, 0); 646 } 647 648 void DAGCombiner:: 649 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 650 // Replace all uses. If any nodes become isomorphic to other nodes and 651 // are deleted, make sure to remove them from our worklist. 652 WorkListRemover DeadNodes(*this); 653 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 654 655 // Push the new node and any (possibly new) users onto the worklist. 656 AddToWorkList(TLO.New.getNode()); 657 AddUsersToWorkList(TLO.New.getNode()); 658 659 // Finally, if the node is now dead, remove it from the graph. The node 660 // may not be dead if the replacement process recursively simplified to 661 // something else needing this node. 662 if (TLO.Old.getNode()->use_empty()) { 663 removeFromWorkList(TLO.Old.getNode()); 664 665 // If the operands of this node are only used by the node, they will now 666 // be dead. Make sure to visit them first to delete dead nodes early. 667 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 668 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 669 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 670 671 DAG.DeleteNode(TLO.Old.getNode()); 672 } 673 } 674 675 /// SimplifyDemandedBits - Check the specified integer node value to see if 676 /// it can be simplified or if things it uses can be simplified by bit 677 /// propagation. If so, return true. 678 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 679 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 680 APInt KnownZero, KnownOne; 681 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 682 return false; 683 684 // Revisit the node. 685 AddToWorkList(Op.getNode()); 686 687 // Replace the old value with the new one. 688 ++NodesCombined; 689 DEBUG(dbgs() << "\nReplacing.2 "; 690 TLO.Old.getNode()->dump(&DAG); 691 dbgs() << "\nWith: "; 692 TLO.New.getNode()->dump(&DAG); 693 dbgs() << '\n'); 694 695 CommitTargetLoweringOpt(TLO); 696 return true; 697 } 698 699 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 700 DebugLoc dl = Load->getDebugLoc(); 701 EVT VT = Load->getValueType(0); 702 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 703 704 DEBUG(dbgs() << "\nReplacing.9 "; 705 Load->dump(&DAG); 706 dbgs() << "\nWith: "; 707 Trunc.getNode()->dump(&DAG); 708 dbgs() << '\n'); 709 WorkListRemover DeadNodes(*this); 710 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 711 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 712 removeFromWorkList(Load); 713 DAG.DeleteNode(Load); 714 AddToWorkList(Trunc.getNode()); 715 } 716 717 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 718 Replace = false; 719 DebugLoc dl = Op.getDebugLoc(); 720 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 721 EVT MemVT = LD->getMemoryVT(); 722 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 723 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 724 : ISD::EXTLOAD) 725 : LD->getExtensionType(); 726 Replace = true; 727 return DAG.getExtLoad(ExtType, dl, PVT, 728 LD->getChain(), LD->getBasePtr(), 729 LD->getPointerInfo(), 730 MemVT, LD->isVolatile(), 731 LD->isNonTemporal(), LD->getAlignment()); 732 } 733 734 unsigned Opc = Op.getOpcode(); 735 switch (Opc) { 736 default: break; 737 case ISD::AssertSext: 738 return DAG.getNode(ISD::AssertSext, dl, PVT, 739 SExtPromoteOperand(Op.getOperand(0), PVT), 740 Op.getOperand(1)); 741 case ISD::AssertZext: 742 return DAG.getNode(ISD::AssertZext, dl, PVT, 743 ZExtPromoteOperand(Op.getOperand(0), PVT), 744 Op.getOperand(1)); 745 case ISD::Constant: { 746 unsigned ExtOpc = 747 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 748 return DAG.getNode(ExtOpc, dl, PVT, Op); 749 } 750 } 751 752 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 753 return SDValue(); 754 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 755 } 756 757 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 758 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 759 return SDValue(); 760 EVT OldVT = Op.getValueType(); 761 DebugLoc dl = Op.getDebugLoc(); 762 bool Replace = false; 763 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 764 if (NewOp.getNode() == 0) 765 return SDValue(); 766 AddToWorkList(NewOp.getNode()); 767 768 if (Replace) 769 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 770 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 771 DAG.getValueType(OldVT)); 772 } 773 774 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 775 EVT OldVT = Op.getValueType(); 776 DebugLoc dl = Op.getDebugLoc(); 777 bool Replace = false; 778 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 779 if (NewOp.getNode() == 0) 780 return SDValue(); 781 AddToWorkList(NewOp.getNode()); 782 783 if (Replace) 784 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 785 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 786 } 787 788 /// PromoteIntBinOp - Promote the specified integer binary operation if the 789 /// target indicates it is beneficial. e.g. On x86, it's usually better to 790 /// promote i16 operations to i32 since i16 instructions are longer. 791 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 792 if (!LegalOperations) 793 return SDValue(); 794 795 EVT VT = Op.getValueType(); 796 if (VT.isVector() || !VT.isInteger()) 797 return SDValue(); 798 799 // If operation type is 'undesirable', e.g. i16 on x86, consider 800 // promoting it. 801 unsigned Opc = Op.getOpcode(); 802 if (TLI.isTypeDesirableForOp(Opc, VT)) 803 return SDValue(); 804 805 EVT PVT = VT; 806 // Consult target whether it is a good idea to promote this operation and 807 // what's the right type to promote it to. 808 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 809 assert(PVT != VT && "Don't know what type to promote to!"); 810 811 bool Replace0 = false; 812 SDValue N0 = Op.getOperand(0); 813 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 814 if (NN0.getNode() == 0) 815 return SDValue(); 816 817 bool Replace1 = false; 818 SDValue N1 = Op.getOperand(1); 819 SDValue NN1; 820 if (N0 == N1) 821 NN1 = NN0; 822 else { 823 NN1 = PromoteOperand(N1, PVT, Replace1); 824 if (NN1.getNode() == 0) 825 return SDValue(); 826 } 827 828 AddToWorkList(NN0.getNode()); 829 if (NN1.getNode()) 830 AddToWorkList(NN1.getNode()); 831 832 if (Replace0) 833 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 834 if (Replace1) 835 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 836 837 DEBUG(dbgs() << "\nPromoting "; 838 Op.getNode()->dump(&DAG)); 839 DebugLoc dl = Op.getDebugLoc(); 840 return DAG.getNode(ISD::TRUNCATE, dl, VT, 841 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 842 } 843 return SDValue(); 844 } 845 846 /// PromoteIntShiftOp - Promote the specified integer shift operation if the 847 /// target indicates it is beneficial. e.g. On x86, it's usually better to 848 /// promote i16 operations to i32 since i16 instructions are longer. 849 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 850 if (!LegalOperations) 851 return SDValue(); 852 853 EVT VT = Op.getValueType(); 854 if (VT.isVector() || !VT.isInteger()) 855 return SDValue(); 856 857 // If operation type is 'undesirable', e.g. i16 on x86, consider 858 // promoting it. 859 unsigned Opc = Op.getOpcode(); 860 if (TLI.isTypeDesirableForOp(Opc, VT)) 861 return SDValue(); 862 863 EVT PVT = VT; 864 // Consult target whether it is a good idea to promote this operation and 865 // what's the right type to promote it to. 866 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 867 assert(PVT != VT && "Don't know what type to promote to!"); 868 869 bool Replace = false; 870 SDValue N0 = Op.getOperand(0); 871 if (Opc == ISD::SRA) 872 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 873 else if (Opc == ISD::SRL) 874 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 875 else 876 N0 = PromoteOperand(N0, PVT, Replace); 877 if (N0.getNode() == 0) 878 return SDValue(); 879 880 AddToWorkList(N0.getNode()); 881 if (Replace) 882 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 883 884 DEBUG(dbgs() << "\nPromoting "; 885 Op.getNode()->dump(&DAG)); 886 DebugLoc dl = Op.getDebugLoc(); 887 return DAG.getNode(ISD::TRUNCATE, dl, VT, 888 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 889 } 890 return SDValue(); 891 } 892 893 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 894 if (!LegalOperations) 895 return SDValue(); 896 897 EVT VT = Op.getValueType(); 898 if (VT.isVector() || !VT.isInteger()) 899 return SDValue(); 900 901 // If operation type is 'undesirable', e.g. i16 on x86, consider 902 // promoting it. 903 unsigned Opc = Op.getOpcode(); 904 if (TLI.isTypeDesirableForOp(Opc, VT)) 905 return SDValue(); 906 907 EVT PVT = VT; 908 // Consult target whether it is a good idea to promote this operation and 909 // what's the right type to promote it to. 910 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 911 assert(PVT != VT && "Don't know what type to promote to!"); 912 // fold (aext (aext x)) -> (aext x) 913 // fold (aext (zext x)) -> (zext x) 914 // fold (aext (sext x)) -> (sext x) 915 DEBUG(dbgs() << "\nPromoting "; 916 Op.getNode()->dump(&DAG)); 917 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0)); 918 } 919 return SDValue(); 920 } 921 922 bool DAGCombiner::PromoteLoad(SDValue Op) { 923 if (!LegalOperations) 924 return false; 925 926 EVT VT = Op.getValueType(); 927 if (VT.isVector() || !VT.isInteger()) 928 return false; 929 930 // If operation type is 'undesirable', e.g. i16 on x86, consider 931 // promoting it. 932 unsigned Opc = Op.getOpcode(); 933 if (TLI.isTypeDesirableForOp(Opc, VT)) 934 return false; 935 936 EVT PVT = VT; 937 // Consult target whether it is a good idea to promote this operation and 938 // what's the right type to promote it to. 939 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 940 assert(PVT != VT && "Don't know what type to promote to!"); 941 942 DebugLoc dl = Op.getDebugLoc(); 943 SDNode *N = Op.getNode(); 944 LoadSDNode *LD = cast<LoadSDNode>(N); 945 EVT MemVT = LD->getMemoryVT(); 946 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 947 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 948 : ISD::EXTLOAD) 949 : LD->getExtensionType(); 950 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 951 LD->getChain(), LD->getBasePtr(), 952 LD->getPointerInfo(), 953 MemVT, LD->isVolatile(), 954 LD->isNonTemporal(), LD->getAlignment()); 955 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 956 957 DEBUG(dbgs() << "\nPromoting "; 958 N->dump(&DAG); 959 dbgs() << "\nTo: "; 960 Result.getNode()->dump(&DAG); 961 dbgs() << '\n'); 962 WorkListRemover DeadNodes(*this); 963 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 964 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 965 removeFromWorkList(N); 966 DAG.DeleteNode(N); 967 AddToWorkList(Result.getNode()); 968 return true; 969 } 970 return false; 971 } 972 973 974 //===----------------------------------------------------------------------===// 975 // Main DAG Combiner implementation 976 //===----------------------------------------------------------------------===// 977 978 void DAGCombiner::Run(CombineLevel AtLevel) { 979 // set the instance variables, so that the various visit routines may use it. 980 Level = AtLevel; 981 LegalOperations = Level >= AfterLegalizeVectorOps; 982 LegalTypes = Level >= AfterLegalizeTypes; 983 984 // Add all the dag nodes to the worklist. 985 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 986 E = DAG.allnodes_end(); I != E; ++I) 987 AddToWorkList(I); 988 989 // Create a dummy node (which is not added to allnodes), that adds a reference 990 // to the root node, preventing it from being deleted, and tracking any 991 // changes of the root. 992 HandleSDNode Dummy(DAG.getRoot()); 993 994 // The root of the dag may dangle to deleted nodes until the dag combiner is 995 // done. Set it to null to avoid confusion. 996 DAG.setRoot(SDValue()); 997 998 // while the worklist isn't empty, find a node and 999 // try and combine it. 1000 while (!WorkListContents.empty()) { 1001 SDNode *N; 1002 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates. 1003 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1004 // worklist *should* contain, and check the node we want to visit is should 1005 // actually be visited. 1006 do { 1007 N = WorkListOrder.pop_back_val(); 1008 } while (!WorkListContents.erase(N)); 1009 1010 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1011 // N is deleted from the DAG, since they too may now be dead or may have a 1012 // reduced number of uses, allowing other xforms. 1013 if (N->use_empty() && N != &Dummy) { 1014 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1015 AddToWorkList(N->getOperand(i).getNode()); 1016 1017 DAG.DeleteNode(N); 1018 continue; 1019 } 1020 1021 SDValue RV = combine(N); 1022 1023 if (RV.getNode() == 0) 1024 continue; 1025 1026 ++NodesCombined; 1027 1028 // If we get back the same node we passed in, rather than a new node or 1029 // zero, we know that the node must have defined multiple values and 1030 // CombineTo was used. Since CombineTo takes care of the worklist 1031 // mechanics for us, we have no work to do in this case. 1032 if (RV.getNode() == N) 1033 continue; 1034 1035 assert(N->getOpcode() != ISD::DELETED_NODE && 1036 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1037 "Node was deleted but visit returned new node!"); 1038 1039 DEBUG(dbgs() << "\nReplacing.3 "; 1040 N->dump(&DAG); 1041 dbgs() << "\nWith: "; 1042 RV.getNode()->dump(&DAG); 1043 dbgs() << '\n'); 1044 1045 // Transfer debug value. 1046 DAG.TransferDbgValues(SDValue(N, 0), RV); 1047 WorkListRemover DeadNodes(*this); 1048 if (N->getNumValues() == RV.getNode()->getNumValues()) 1049 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1050 else { 1051 assert(N->getValueType(0) == RV.getValueType() && 1052 N->getNumValues() == 1 && "Type mismatch"); 1053 SDValue OpV = RV; 1054 DAG.ReplaceAllUsesWith(N, &OpV); 1055 } 1056 1057 // Push the new node and any users onto the worklist 1058 AddToWorkList(RV.getNode()); 1059 AddUsersToWorkList(RV.getNode()); 1060 1061 // Add any uses of the old node to the worklist in case this node is the 1062 // last one that uses them. They may become dead after this node is 1063 // deleted. 1064 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1065 AddToWorkList(N->getOperand(i).getNode()); 1066 1067 // Finally, if the node is now dead, remove it from the graph. The node 1068 // may not be dead if the replacement process recursively simplified to 1069 // something else needing this node. 1070 if (N->use_empty()) { 1071 // Nodes can be reintroduced into the worklist. Make sure we do not 1072 // process a node that has been replaced. 1073 removeFromWorkList(N); 1074 1075 // Finally, since the node is now dead, remove it from the graph. 1076 DAG.DeleteNode(N); 1077 } 1078 } 1079 1080 // If the root changed (e.g. it was a dead load, update the root). 1081 DAG.setRoot(Dummy.getValue()); 1082 DAG.RemoveDeadNodes(); 1083 } 1084 1085 SDValue DAGCombiner::visit(SDNode *N) { 1086 switch (N->getOpcode()) { 1087 default: break; 1088 case ISD::TokenFactor: return visitTokenFactor(N); 1089 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1090 case ISD::ADD: return visitADD(N); 1091 case ISD::SUB: return visitSUB(N); 1092 case ISD::ADDC: return visitADDC(N); 1093 case ISD::SUBC: return visitSUBC(N); 1094 case ISD::ADDE: return visitADDE(N); 1095 case ISD::SUBE: return visitSUBE(N); 1096 case ISD::MUL: return visitMUL(N); 1097 case ISD::SDIV: return visitSDIV(N); 1098 case ISD::UDIV: return visitUDIV(N); 1099 case ISD::SREM: return visitSREM(N); 1100 case ISD::UREM: return visitUREM(N); 1101 case ISD::MULHU: return visitMULHU(N); 1102 case ISD::MULHS: return visitMULHS(N); 1103 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1104 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1105 case ISD::SMULO: return visitSMULO(N); 1106 case ISD::UMULO: return visitUMULO(N); 1107 case ISD::SDIVREM: return visitSDIVREM(N); 1108 case ISD::UDIVREM: return visitUDIVREM(N); 1109 case ISD::AND: return visitAND(N); 1110 case ISD::OR: return visitOR(N); 1111 case ISD::XOR: return visitXOR(N); 1112 case ISD::SHL: return visitSHL(N); 1113 case ISD::SRA: return visitSRA(N); 1114 case ISD::SRL: return visitSRL(N); 1115 case ISD::CTLZ: return visitCTLZ(N); 1116 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1117 case ISD::CTTZ: return visitCTTZ(N); 1118 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1119 case ISD::CTPOP: return visitCTPOP(N); 1120 case ISD::SELECT: return visitSELECT(N); 1121 case ISD::SELECT_CC: return visitSELECT_CC(N); 1122 case ISD::SETCC: return visitSETCC(N); 1123 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1124 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1125 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1126 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1127 case ISD::TRUNCATE: return visitTRUNCATE(N); 1128 case ISD::BITCAST: return visitBITCAST(N); 1129 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1130 case ISD::FADD: return visitFADD(N); 1131 case ISD::FSUB: return visitFSUB(N); 1132 case ISD::FMUL: return visitFMUL(N); 1133 case ISD::FMA: return visitFMA(N); 1134 case ISD::FDIV: return visitFDIV(N); 1135 case ISD::FREM: return visitFREM(N); 1136 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1137 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1138 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1139 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1140 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1141 case ISD::FP_ROUND: return visitFP_ROUND(N); 1142 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1143 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1144 case ISD::FNEG: return visitFNEG(N); 1145 case ISD::FABS: return visitFABS(N); 1146 case ISD::FFLOOR: return visitFFLOOR(N); 1147 case ISD::FCEIL: return visitFCEIL(N); 1148 case ISD::FTRUNC: return visitFTRUNC(N); 1149 case ISD::BRCOND: return visitBRCOND(N); 1150 case ISD::BR_CC: return visitBR_CC(N); 1151 case ISD::LOAD: return visitLOAD(N); 1152 case ISD::STORE: return visitSTORE(N); 1153 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1154 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1155 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1156 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1157 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1158 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1159 case ISD::MEMBARRIER: return visitMEMBARRIER(N); 1160 } 1161 return SDValue(); 1162 } 1163 1164 SDValue DAGCombiner::combine(SDNode *N) { 1165 SDValue RV = visit(N); 1166 1167 // If nothing happened, try a target-specific DAG combine. 1168 if (RV.getNode() == 0) { 1169 assert(N->getOpcode() != ISD::DELETED_NODE && 1170 "Node was deleted but visit returned NULL!"); 1171 1172 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1173 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1174 1175 // Expose the DAG combiner to the target combiner impls. 1176 TargetLowering::DAGCombinerInfo 1177 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 1178 1179 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1180 } 1181 } 1182 1183 // If nothing happened still, try promoting the operation. 1184 if (RV.getNode() == 0) { 1185 switch (N->getOpcode()) { 1186 default: break; 1187 case ISD::ADD: 1188 case ISD::SUB: 1189 case ISD::MUL: 1190 case ISD::AND: 1191 case ISD::OR: 1192 case ISD::XOR: 1193 RV = PromoteIntBinOp(SDValue(N, 0)); 1194 break; 1195 case ISD::SHL: 1196 case ISD::SRA: 1197 case ISD::SRL: 1198 RV = PromoteIntShiftOp(SDValue(N, 0)); 1199 break; 1200 case ISD::SIGN_EXTEND: 1201 case ISD::ZERO_EXTEND: 1202 case ISD::ANY_EXTEND: 1203 RV = PromoteExtend(SDValue(N, 0)); 1204 break; 1205 case ISD::LOAD: 1206 if (PromoteLoad(SDValue(N, 0))) 1207 RV = SDValue(N, 0); 1208 break; 1209 } 1210 } 1211 1212 // If N is a commutative binary node, try commuting it to enable more 1213 // sdisel CSE. 1214 if (RV.getNode() == 0 && 1215 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1216 N->getNumValues() == 1) { 1217 SDValue N0 = N->getOperand(0); 1218 SDValue N1 = N->getOperand(1); 1219 1220 // Constant operands are canonicalized to RHS. 1221 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1222 SDValue Ops[] = { N1, N0 }; 1223 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1224 Ops, 2); 1225 if (CSENode) 1226 return SDValue(CSENode, 0); 1227 } 1228 } 1229 1230 return RV; 1231 } 1232 1233 /// getInputChainForNode - Given a node, return its input chain if it has one, 1234 /// otherwise return a null sd operand. 1235 static SDValue getInputChainForNode(SDNode *N) { 1236 if (unsigned NumOps = N->getNumOperands()) { 1237 if (N->getOperand(0).getValueType() == MVT::Other) 1238 return N->getOperand(0); 1239 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1240 return N->getOperand(NumOps-1); 1241 for (unsigned i = 1; i < NumOps-1; ++i) 1242 if (N->getOperand(i).getValueType() == MVT::Other) 1243 return N->getOperand(i); 1244 } 1245 return SDValue(); 1246 } 1247 1248 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1249 // If N has two operands, where one has an input chain equal to the other, 1250 // the 'other' chain is redundant. 1251 if (N->getNumOperands() == 2) { 1252 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1253 return N->getOperand(0); 1254 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1255 return N->getOperand(1); 1256 } 1257 1258 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1259 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1260 SmallPtrSet<SDNode*, 16> SeenOps; 1261 bool Changed = false; // If we should replace this token factor. 1262 1263 // Start out with this token factor. 1264 TFs.push_back(N); 1265 1266 // Iterate through token factors. The TFs grows when new token factors are 1267 // encountered. 1268 for (unsigned i = 0; i < TFs.size(); ++i) { 1269 SDNode *TF = TFs[i]; 1270 1271 // Check each of the operands. 1272 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1273 SDValue Op = TF->getOperand(i); 1274 1275 switch (Op.getOpcode()) { 1276 case ISD::EntryToken: 1277 // Entry tokens don't need to be added to the list. They are 1278 // rededundant. 1279 Changed = true; 1280 break; 1281 1282 case ISD::TokenFactor: 1283 if (Op.hasOneUse() && 1284 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1285 // Queue up for processing. 1286 TFs.push_back(Op.getNode()); 1287 // Clean up in case the token factor is removed. 1288 AddToWorkList(Op.getNode()); 1289 Changed = true; 1290 break; 1291 } 1292 // Fall thru 1293 1294 default: 1295 // Only add if it isn't already in the list. 1296 if (SeenOps.insert(Op.getNode())) 1297 Ops.push_back(Op); 1298 else 1299 Changed = true; 1300 break; 1301 } 1302 } 1303 } 1304 1305 SDValue Result; 1306 1307 // If we've change things around then replace token factor. 1308 if (Changed) { 1309 if (Ops.empty()) { 1310 // The entry token is the only possible outcome. 1311 Result = DAG.getEntryNode(); 1312 } else { 1313 // New and improved token factor. 1314 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 1315 MVT::Other, &Ops[0], Ops.size()); 1316 } 1317 1318 // Don't add users to work list. 1319 return CombineTo(N, Result, false); 1320 } 1321 1322 return Result; 1323 } 1324 1325 /// MERGE_VALUES can always be eliminated. 1326 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1327 WorkListRemover DeadNodes(*this); 1328 // Replacing results may cause a different MERGE_VALUES to suddenly 1329 // be CSE'd with N, and carry its uses with it. Iterate until no 1330 // uses remain, to ensure that the node can be safely deleted. 1331 // First add the users of this node to the work list so that they 1332 // can be tried again once they have new operands. 1333 AddUsersToWorkList(N); 1334 do { 1335 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1336 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1337 } while (!N->use_empty()); 1338 removeFromWorkList(N); 1339 DAG.DeleteNode(N); 1340 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1341 } 1342 1343 static 1344 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1, 1345 SelectionDAG &DAG) { 1346 EVT VT = N0.getValueType(); 1347 SDValue N00 = N0.getOperand(0); 1348 SDValue N01 = N0.getOperand(1); 1349 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1350 1351 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1352 isa<ConstantSDNode>(N00.getOperand(1))) { 1353 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1354 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, 1355 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT, 1356 N00.getOperand(0), N01), 1357 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT, 1358 N00.getOperand(1), N01)); 1359 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1360 } 1361 1362 return SDValue(); 1363 } 1364 1365 SDValue DAGCombiner::visitADD(SDNode *N) { 1366 SDValue N0 = N->getOperand(0); 1367 SDValue N1 = N->getOperand(1); 1368 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1370 EVT VT = N0.getValueType(); 1371 1372 // fold vector ops 1373 if (VT.isVector()) { 1374 SDValue FoldedVOp = SimplifyVBinOp(N); 1375 if (FoldedVOp.getNode()) return FoldedVOp; 1376 } 1377 1378 // fold (add x, undef) -> undef 1379 if (N0.getOpcode() == ISD::UNDEF) 1380 return N0; 1381 if (N1.getOpcode() == ISD::UNDEF) 1382 return N1; 1383 // fold (add c1, c2) -> c1+c2 1384 if (N0C && N1C) 1385 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1386 // canonicalize constant to RHS 1387 if (N0C && !N1C) 1388 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0); 1389 // fold (add x, 0) -> x 1390 if (N1C && N1C->isNullValue()) 1391 return N0; 1392 // fold (add Sym, c) -> Sym+c 1393 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1394 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1395 GA->getOpcode() == ISD::GlobalAddress) 1396 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT, 1397 GA->getOffset() + 1398 (uint64_t)N1C->getSExtValue()); 1399 // fold ((c1-A)+c2) -> (c1+c2)-A 1400 if (N1C && N0.getOpcode() == ISD::SUB) 1401 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1402 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1403 DAG.getConstant(N1C->getAPIntValue()+ 1404 N0C->getAPIntValue(), VT), 1405 N0.getOperand(1)); 1406 // reassociate add 1407 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1); 1408 if (RADD.getNode() != 0) 1409 return RADD; 1410 // fold ((0-A) + B) -> B-A 1411 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1412 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1413 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1)); 1414 // fold (A + (0-B)) -> A-B 1415 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1416 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1417 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1)); 1418 // fold (A+(B-A)) -> B 1419 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1420 return N1.getOperand(0); 1421 // fold ((B-A)+A) -> B 1422 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1423 return N0.getOperand(0); 1424 // fold (A+(B-(A+C))) to (B-C) 1425 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1426 N0 == N1.getOperand(1).getOperand(0)) 1427 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1428 N1.getOperand(1).getOperand(1)); 1429 // fold (A+(B-(C+A))) to (B-C) 1430 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1431 N0 == N1.getOperand(1).getOperand(1)) 1432 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1433 N1.getOperand(1).getOperand(0)); 1434 // fold (A+((B-A)+or-C)) to (B+or-C) 1435 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1436 N1.getOperand(0).getOpcode() == ISD::SUB && 1437 N0 == N1.getOperand(0).getOperand(1)) 1438 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT, 1439 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1440 1441 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1442 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1443 SDValue N00 = N0.getOperand(0); 1444 SDValue N01 = N0.getOperand(1); 1445 SDValue N10 = N1.getOperand(0); 1446 SDValue N11 = N1.getOperand(1); 1447 1448 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1449 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1450 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10), 1451 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11)); 1452 } 1453 1454 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1455 return SDValue(N, 0); 1456 1457 // fold (a+b) -> (a|b) iff a and b share no bits. 1458 if (VT.isInteger() && !VT.isVector()) { 1459 APInt LHSZero, LHSOne; 1460 APInt RHSZero, RHSOne; 1461 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1462 1463 if (LHSZero.getBoolValue()) { 1464 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1465 1466 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1467 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1468 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1469 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1); 1470 } 1471 } 1472 1473 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1474 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1475 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG); 1476 if (Result.getNode()) return Result; 1477 } 1478 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1479 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG); 1480 if (Result.getNode()) return Result; 1481 } 1482 1483 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1484 if (N1.getOpcode() == ISD::SHL && 1485 N1.getOperand(0).getOpcode() == ISD::SUB) 1486 if (ConstantSDNode *C = 1487 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1488 if (C->getAPIntValue() == 0) 1489 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, 1490 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1491 N1.getOperand(0).getOperand(1), 1492 N1.getOperand(1))); 1493 if (N0.getOpcode() == ISD::SHL && 1494 N0.getOperand(0).getOpcode() == ISD::SUB) 1495 if (ConstantSDNode *C = 1496 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1497 if (C->getAPIntValue() == 0) 1498 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, 1499 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1500 N0.getOperand(0).getOperand(1), 1501 N0.getOperand(1))); 1502 1503 if (N1.getOpcode() == ISD::AND) { 1504 SDValue AndOp0 = N1.getOperand(0); 1505 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1506 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1507 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1508 1509 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1510 // and similar xforms where the inner op is either ~0 or 0. 1511 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1512 DebugLoc DL = N->getDebugLoc(); 1513 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1514 } 1515 } 1516 1517 // add (sext i1), X -> sub X, (zext i1) 1518 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1519 N0.getOperand(0).getValueType() == MVT::i1 && 1520 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1521 DebugLoc DL = N->getDebugLoc(); 1522 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1523 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1524 } 1525 1526 return SDValue(); 1527 } 1528 1529 SDValue DAGCombiner::visitADDC(SDNode *N) { 1530 SDValue N0 = N->getOperand(0); 1531 SDValue N1 = N->getOperand(1); 1532 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1533 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1534 EVT VT = N0.getValueType(); 1535 1536 // If the flag result is dead, turn this into an ADD. 1537 if (!N->hasAnyUseOfValue(1)) 1538 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1), 1539 DAG.getNode(ISD::CARRY_FALSE, 1540 N->getDebugLoc(), MVT::Glue)); 1541 1542 // canonicalize constant to RHS. 1543 if (N0C && !N1C) 1544 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0); 1545 1546 // fold (addc x, 0) -> x + no carry out 1547 if (N1C && N1C->isNullValue()) 1548 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1549 N->getDebugLoc(), MVT::Glue)); 1550 1551 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1552 APInt LHSZero, LHSOne; 1553 APInt RHSZero, RHSOne; 1554 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1555 1556 if (LHSZero.getBoolValue()) { 1557 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1558 1559 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1560 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1561 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1562 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1), 1563 DAG.getNode(ISD::CARRY_FALSE, 1564 N->getDebugLoc(), MVT::Glue)); 1565 } 1566 1567 return SDValue(); 1568 } 1569 1570 SDValue DAGCombiner::visitADDE(SDNode *N) { 1571 SDValue N0 = N->getOperand(0); 1572 SDValue N1 = N->getOperand(1); 1573 SDValue CarryIn = N->getOperand(2); 1574 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1575 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1576 1577 // canonicalize constant to RHS 1578 if (N0C && !N1C) 1579 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), 1580 N1, N0, CarryIn); 1581 1582 // fold (adde x, y, false) -> (addc x, y) 1583 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1584 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1); 1585 1586 return SDValue(); 1587 } 1588 1589 // Since it may not be valid to emit a fold to zero for vector initializers 1590 // check if we can before folding. 1591 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT, 1592 SelectionDAG &DAG, bool LegalOperations) { 1593 if (!VT.isVector()) { 1594 return DAG.getConstant(0, VT); 1595 } 1596 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) { 1597 // Produce a vector of zeros. 1598 SDValue El = DAG.getConstant(0, VT.getVectorElementType()); 1599 std::vector<SDValue> Ops(VT.getVectorNumElements(), El); 1600 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 1601 &Ops[0], Ops.size()); 1602 } 1603 return SDValue(); 1604 } 1605 1606 SDValue DAGCombiner::visitSUB(SDNode *N) { 1607 SDValue N0 = N->getOperand(0); 1608 SDValue N1 = N->getOperand(1); 1609 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1610 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1611 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 : 1612 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1613 EVT VT = N0.getValueType(); 1614 1615 // fold vector ops 1616 if (VT.isVector()) { 1617 SDValue FoldedVOp = SimplifyVBinOp(N); 1618 if (FoldedVOp.getNode()) return FoldedVOp; 1619 } 1620 1621 // fold (sub x, x) -> 0 1622 // FIXME: Refactor this and xor and other similar operations together. 1623 if (N0 == N1) 1624 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations); 1625 // fold (sub c1, c2) -> c1-c2 1626 if (N0C && N1C) 1627 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1628 // fold (sub x, c) -> (add x, -c) 1629 if (N1C) 1630 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, 1631 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1632 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1633 if (N0C && N0C->isAllOnesValue()) 1634 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 1635 // fold A-(A-B) -> B 1636 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1637 return N1.getOperand(1); 1638 // fold (A+B)-A -> B 1639 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1640 return N0.getOperand(1); 1641 // fold (A+B)-B -> A 1642 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1643 return N0.getOperand(0); 1644 // fold C2-(A+C1) -> (C2-C1)-A 1645 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1646 SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT); 1647 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC, 1648 N1.getOperand(0)); 1649 } 1650 // fold ((A+(B+or-C))-B) -> A+or-C 1651 if (N0.getOpcode() == ISD::ADD && 1652 (N0.getOperand(1).getOpcode() == ISD::SUB || 1653 N0.getOperand(1).getOpcode() == ISD::ADD) && 1654 N0.getOperand(1).getOperand(0) == N1) 1655 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT, 1656 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1657 // fold ((A+(C+B))-B) -> A+C 1658 if (N0.getOpcode() == ISD::ADD && 1659 N0.getOperand(1).getOpcode() == ISD::ADD && 1660 N0.getOperand(1).getOperand(1) == N1) 1661 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1662 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1663 // fold ((A-(B-C))-C) -> A-B 1664 if (N0.getOpcode() == ISD::SUB && 1665 N0.getOperand(1).getOpcode() == ISD::SUB && 1666 N0.getOperand(1).getOperand(1) == N1) 1667 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1668 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1669 1670 // If either operand of a sub is undef, the result is undef 1671 if (N0.getOpcode() == ISD::UNDEF) 1672 return N0; 1673 if (N1.getOpcode() == ISD::UNDEF) 1674 return N1; 1675 1676 // If the relocation model supports it, consider symbol offsets. 1677 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1678 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1679 // fold (sub Sym, c) -> Sym-c 1680 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1681 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT, 1682 GA->getOffset() - 1683 (uint64_t)N1C->getSExtValue()); 1684 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1685 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1686 if (GA->getGlobal() == GB->getGlobal()) 1687 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1688 VT); 1689 } 1690 1691 return SDValue(); 1692 } 1693 1694 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1695 SDValue N0 = N->getOperand(0); 1696 SDValue N1 = N->getOperand(1); 1697 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1698 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1699 EVT VT = N0.getValueType(); 1700 1701 // If the flag result is dead, turn this into an SUB. 1702 if (!N->hasAnyUseOfValue(1)) 1703 return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1), 1704 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1705 MVT::Glue)); 1706 1707 // fold (subc x, x) -> 0 + no borrow 1708 if (N0 == N1) 1709 return CombineTo(N, DAG.getConstant(0, VT), 1710 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1711 MVT::Glue)); 1712 1713 // fold (subc x, 0) -> x + no borrow 1714 if (N1C && N1C->isNullValue()) 1715 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1716 MVT::Glue)); 1717 1718 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1719 if (N0C && N0C->isAllOnesValue()) 1720 return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0), 1721 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1722 MVT::Glue)); 1723 1724 return SDValue(); 1725 } 1726 1727 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1728 SDValue N0 = N->getOperand(0); 1729 SDValue N1 = N->getOperand(1); 1730 SDValue CarryIn = N->getOperand(2); 1731 1732 // fold (sube x, y, false) -> (subc x, y) 1733 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1734 return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1); 1735 1736 return SDValue(); 1737 } 1738 1739 SDValue DAGCombiner::visitMUL(SDNode *N) { 1740 SDValue N0 = N->getOperand(0); 1741 SDValue N1 = N->getOperand(1); 1742 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1743 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1744 EVT VT = N0.getValueType(); 1745 1746 // fold vector ops 1747 if (VT.isVector()) { 1748 SDValue FoldedVOp = SimplifyVBinOp(N); 1749 if (FoldedVOp.getNode()) return FoldedVOp; 1750 } 1751 1752 // fold (mul x, undef) -> 0 1753 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1754 return DAG.getConstant(0, VT); 1755 // fold (mul c1, c2) -> c1*c2 1756 if (N0C && N1C) 1757 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C); 1758 // canonicalize constant to RHS 1759 if (N0C && !N1C) 1760 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0); 1761 // fold (mul x, 0) -> 0 1762 if (N1C && N1C->isNullValue()) 1763 return N1; 1764 // fold (mul x, -1) -> 0-x 1765 if (N1C && N1C->isAllOnesValue()) 1766 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1767 DAG.getConstant(0, VT), N0); 1768 // fold (mul x, (1 << c)) -> x << c 1769 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1770 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1771 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1772 getShiftAmountTy(N0.getValueType()))); 1773 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1774 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) { 1775 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2(); 1776 // FIXME: If the input is something that is easily negated (e.g. a 1777 // single-use add), we should put the negate there. 1778 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1779 DAG.getConstant(0, VT), 1780 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1781 DAG.getConstant(Log2Val, 1782 getShiftAmountTy(N0.getValueType())))); 1783 } 1784 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1785 if (N1C && N0.getOpcode() == ISD::SHL && 1786 isa<ConstantSDNode>(N0.getOperand(1))) { 1787 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1788 N1, N0.getOperand(1)); 1789 AddToWorkList(C3.getNode()); 1790 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1791 N0.getOperand(0), C3); 1792 } 1793 1794 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1795 // use. 1796 { 1797 SDValue Sh(0,0), Y(0,0); 1798 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1799 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) && 1800 N0.getNode()->hasOneUse()) { 1801 Sh = N0; Y = N1; 1802 } else if (N1.getOpcode() == ISD::SHL && 1803 isa<ConstantSDNode>(N1.getOperand(1)) && 1804 N1.getNode()->hasOneUse()) { 1805 Sh = N1; Y = N0; 1806 } 1807 1808 if (Sh.getNode()) { 1809 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1810 Sh.getOperand(0), Y); 1811 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1812 Mul, Sh.getOperand(1)); 1813 } 1814 } 1815 1816 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1817 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1818 isa<ConstantSDNode>(N0.getOperand(1))) 1819 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1820 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT, 1821 N0.getOperand(0), N1), 1822 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT, 1823 N0.getOperand(1), N1)); 1824 1825 // reassociate mul 1826 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1); 1827 if (RMUL.getNode() != 0) 1828 return RMUL; 1829 1830 return SDValue(); 1831 } 1832 1833 SDValue DAGCombiner::visitSDIV(SDNode *N) { 1834 SDValue N0 = N->getOperand(0); 1835 SDValue N1 = N->getOperand(1); 1836 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1837 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1838 EVT VT = N->getValueType(0); 1839 1840 // fold vector ops 1841 if (VT.isVector()) { 1842 SDValue FoldedVOp = SimplifyVBinOp(N); 1843 if (FoldedVOp.getNode()) return FoldedVOp; 1844 } 1845 1846 // fold (sdiv c1, c2) -> c1/c2 1847 if (N0C && N1C && !N1C->isNullValue()) 1848 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1849 // fold (sdiv X, 1) -> X 1850 if (N1C && N1C->getAPIntValue() == 1LL) 1851 return N0; 1852 // fold (sdiv X, -1) -> 0-X 1853 if (N1C && N1C->isAllOnesValue()) 1854 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1855 DAG.getConstant(0, VT), N0); 1856 // If we know the sign bits of both operands are zero, strength reduce to a 1857 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1858 if (!VT.isVector()) { 1859 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1860 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(), 1861 N0, N1); 1862 } 1863 // fold (sdiv X, pow2) -> simple ops after legalize 1864 if (N1C && !N1C->isNullValue() && 1865 (N1C->getAPIntValue().isPowerOf2() || 1866 (-N1C->getAPIntValue()).isPowerOf2())) { 1867 // If dividing by powers of two is cheap, then don't perform the following 1868 // fold. 1869 if (TLI.isPow2DivCheap()) 1870 return SDValue(); 1871 1872 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1873 1874 // Splat the sign bit into the register 1875 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 1876 DAG.getConstant(VT.getSizeInBits()-1, 1877 getShiftAmountTy(N0.getValueType()))); 1878 AddToWorkList(SGN.getNode()); 1879 1880 // Add (N0 < 0) ? abs2 - 1 : 0; 1881 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN, 1882 DAG.getConstant(VT.getSizeInBits() - lg2, 1883 getShiftAmountTy(SGN.getValueType()))); 1884 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL); 1885 AddToWorkList(SRL.getNode()); 1886 AddToWorkList(ADD.getNode()); // Divide by pow2 1887 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD, 1888 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 1889 1890 // If we're dividing by a positive value, we're done. Otherwise, we must 1891 // negate the result. 1892 if (N1C->getAPIntValue().isNonNegative()) 1893 return SRA; 1894 1895 AddToWorkList(SRA.getNode()); 1896 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1897 DAG.getConstant(0, VT), SRA); 1898 } 1899 1900 // if integer divide is expensive and we satisfy the requirements, emit an 1901 // alternate sequence. 1902 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1903 SDValue Op = BuildSDIV(N); 1904 if (Op.getNode()) return Op; 1905 } 1906 1907 // undef / X -> 0 1908 if (N0.getOpcode() == ISD::UNDEF) 1909 return DAG.getConstant(0, VT); 1910 // X / undef -> undef 1911 if (N1.getOpcode() == ISD::UNDEF) 1912 return N1; 1913 1914 return SDValue(); 1915 } 1916 1917 SDValue DAGCombiner::visitUDIV(SDNode *N) { 1918 SDValue N0 = N->getOperand(0); 1919 SDValue N1 = N->getOperand(1); 1920 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1921 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1922 EVT VT = N->getValueType(0); 1923 1924 // fold vector ops 1925 if (VT.isVector()) { 1926 SDValue FoldedVOp = SimplifyVBinOp(N); 1927 if (FoldedVOp.getNode()) return FoldedVOp; 1928 } 1929 1930 // fold (udiv c1, c2) -> c1/c2 1931 if (N0C && N1C && !N1C->isNullValue()) 1932 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 1933 // fold (udiv x, (1 << c)) -> x >>u c 1934 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1935 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 1936 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1937 getShiftAmountTy(N0.getValueType()))); 1938 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 1939 if (N1.getOpcode() == ISD::SHL) { 1940 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 1941 if (SHC->getAPIntValue().isPowerOf2()) { 1942 EVT ADDVT = N1.getOperand(1).getValueType(); 1943 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT, 1944 N1.getOperand(1), 1945 DAG.getConstant(SHC->getAPIntValue() 1946 .logBase2(), 1947 ADDVT)); 1948 AddToWorkList(Add.getNode()); 1949 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add); 1950 } 1951 } 1952 } 1953 // fold (udiv x, c) -> alternate 1954 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1955 SDValue Op = BuildUDIV(N); 1956 if (Op.getNode()) return Op; 1957 } 1958 1959 // undef / X -> 0 1960 if (N0.getOpcode() == ISD::UNDEF) 1961 return DAG.getConstant(0, VT); 1962 // X / undef -> undef 1963 if (N1.getOpcode() == ISD::UNDEF) 1964 return N1; 1965 1966 return SDValue(); 1967 } 1968 1969 SDValue DAGCombiner::visitSREM(SDNode *N) { 1970 SDValue N0 = N->getOperand(0); 1971 SDValue N1 = N->getOperand(1); 1972 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1974 EVT VT = N->getValueType(0); 1975 1976 // fold (srem c1, c2) -> c1%c2 1977 if (N0C && N1C && !N1C->isNullValue()) 1978 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 1979 // If we know the sign bits of both operands are zero, strength reduce to a 1980 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 1981 if (!VT.isVector()) { 1982 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1983 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1); 1984 } 1985 1986 // If X/C can be simplified by the division-by-constant logic, lower 1987 // X%C to the equivalent of X-X/C*C. 1988 if (N1C && !N1C->isNullValue()) { 1989 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1); 1990 AddToWorkList(Div.getNode()); 1991 SDValue OptimizedDiv = combine(Div.getNode()); 1992 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 1993 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1994 OptimizedDiv, N1); 1995 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 1996 AddToWorkList(Mul.getNode()); 1997 return Sub; 1998 } 1999 } 2000 2001 // undef % X -> 0 2002 if (N0.getOpcode() == ISD::UNDEF) 2003 return DAG.getConstant(0, VT); 2004 // X % undef -> undef 2005 if (N1.getOpcode() == ISD::UNDEF) 2006 return N1; 2007 2008 return SDValue(); 2009 } 2010 2011 SDValue DAGCombiner::visitUREM(SDNode *N) { 2012 SDValue N0 = N->getOperand(0); 2013 SDValue N1 = N->getOperand(1); 2014 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2015 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2016 EVT VT = N->getValueType(0); 2017 2018 // fold (urem c1, c2) -> c1%c2 2019 if (N0C && N1C && !N1C->isNullValue()) 2020 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2021 // fold (urem x, pow2) -> (and x, pow2-1) 2022 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2023 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, 2024 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2025 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2026 if (N1.getOpcode() == ISD::SHL) { 2027 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2028 if (SHC->getAPIntValue().isPowerOf2()) { 2029 SDValue Add = 2030 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, 2031 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2032 VT)); 2033 AddToWorkList(Add.getNode()); 2034 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add); 2035 } 2036 } 2037 } 2038 2039 // If X/C can be simplified by the division-by-constant logic, lower 2040 // X%C to the equivalent of X-X/C*C. 2041 if (N1C && !N1C->isNullValue()) { 2042 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1); 2043 AddToWorkList(Div.getNode()); 2044 SDValue OptimizedDiv = combine(Div.getNode()); 2045 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2046 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 2047 OptimizedDiv, N1); 2048 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 2049 AddToWorkList(Mul.getNode()); 2050 return Sub; 2051 } 2052 } 2053 2054 // undef % X -> 0 2055 if (N0.getOpcode() == ISD::UNDEF) 2056 return DAG.getConstant(0, VT); 2057 // X % undef -> undef 2058 if (N1.getOpcode() == ISD::UNDEF) 2059 return N1; 2060 2061 return SDValue(); 2062 } 2063 2064 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2065 SDValue N0 = N->getOperand(0); 2066 SDValue N1 = N->getOperand(1); 2067 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2068 EVT VT = N->getValueType(0); 2069 DebugLoc DL = N->getDebugLoc(); 2070 2071 // fold (mulhs x, 0) -> 0 2072 if (N1C && N1C->isNullValue()) 2073 return N1; 2074 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2075 if (N1C && N1C->getAPIntValue() == 1) 2076 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0, 2077 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2078 getShiftAmountTy(N0.getValueType()))); 2079 // fold (mulhs x, undef) -> 0 2080 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2081 return DAG.getConstant(0, VT); 2082 2083 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2084 // plus a shift. 2085 if (VT.isSimple() && !VT.isVector()) { 2086 MVT Simple = VT.getSimpleVT(); 2087 unsigned SimpleSize = Simple.getSizeInBits(); 2088 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2089 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2090 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2091 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2092 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2093 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2094 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2095 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2096 } 2097 } 2098 2099 return SDValue(); 2100 } 2101 2102 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2103 SDValue N0 = N->getOperand(0); 2104 SDValue N1 = N->getOperand(1); 2105 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2106 EVT VT = N->getValueType(0); 2107 DebugLoc DL = N->getDebugLoc(); 2108 2109 // fold (mulhu x, 0) -> 0 2110 if (N1C && N1C->isNullValue()) 2111 return N1; 2112 // fold (mulhu x, 1) -> 0 2113 if (N1C && N1C->getAPIntValue() == 1) 2114 return DAG.getConstant(0, N0.getValueType()); 2115 // fold (mulhu x, undef) -> 0 2116 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2117 return DAG.getConstant(0, VT); 2118 2119 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2120 // plus a shift. 2121 if (VT.isSimple() && !VT.isVector()) { 2122 MVT Simple = VT.getSimpleVT(); 2123 unsigned SimpleSize = Simple.getSizeInBits(); 2124 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2125 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2126 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2127 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2128 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2129 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2130 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2131 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2132 } 2133 } 2134 2135 return SDValue(); 2136 } 2137 2138 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2139 /// compute two values. LoOp and HiOp give the opcodes for the two computations 2140 /// that are being performed. Return true if a simplification was made. 2141 /// 2142 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2143 unsigned HiOp) { 2144 // If the high half is not needed, just compute the low half. 2145 bool HiExists = N->hasAnyUseOfValue(1); 2146 if (!HiExists && 2147 (!LegalOperations || 2148 TLI.isOperationLegal(LoOp, N->getValueType(0)))) { 2149 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 2150 N->op_begin(), N->getNumOperands()); 2151 return CombineTo(N, Res, Res); 2152 } 2153 2154 // If the low half is not needed, just compute the high half. 2155 bool LoExists = N->hasAnyUseOfValue(0); 2156 if (!LoExists && 2157 (!LegalOperations || 2158 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2159 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 2160 N->op_begin(), N->getNumOperands()); 2161 return CombineTo(N, Res, Res); 2162 } 2163 2164 // If both halves are used, return as it is. 2165 if (LoExists && HiExists) 2166 return SDValue(); 2167 2168 // If the two computed results can be simplified separately, separate them. 2169 if (LoExists) { 2170 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 2171 N->op_begin(), N->getNumOperands()); 2172 AddToWorkList(Lo.getNode()); 2173 SDValue LoOpt = combine(Lo.getNode()); 2174 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2175 (!LegalOperations || 2176 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2177 return CombineTo(N, LoOpt, LoOpt); 2178 } 2179 2180 if (HiExists) { 2181 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 2182 N->op_begin(), N->getNumOperands()); 2183 AddToWorkList(Hi.getNode()); 2184 SDValue HiOpt = combine(Hi.getNode()); 2185 if (HiOpt.getNode() && HiOpt != Hi && 2186 (!LegalOperations || 2187 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2188 return CombineTo(N, HiOpt, HiOpt); 2189 } 2190 2191 return SDValue(); 2192 } 2193 2194 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2195 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2196 if (Res.getNode()) return Res; 2197 2198 EVT VT = N->getValueType(0); 2199 DebugLoc DL = N->getDebugLoc(); 2200 2201 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2202 // plus a shift. 2203 if (VT.isSimple() && !VT.isVector()) { 2204 MVT Simple = VT.getSimpleVT(); 2205 unsigned SimpleSize = Simple.getSizeInBits(); 2206 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2207 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2208 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2209 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2210 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2211 // Compute the high part as N1. 2212 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2213 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2214 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2215 // Compute the low part as N0. 2216 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2217 return CombineTo(N, Lo, Hi); 2218 } 2219 } 2220 2221 return SDValue(); 2222 } 2223 2224 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2225 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2226 if (Res.getNode()) return Res; 2227 2228 EVT VT = N->getValueType(0); 2229 DebugLoc DL = N->getDebugLoc(); 2230 2231 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2232 // plus a shift. 2233 if (VT.isSimple() && !VT.isVector()) { 2234 MVT Simple = VT.getSimpleVT(); 2235 unsigned SimpleSize = Simple.getSizeInBits(); 2236 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2237 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2238 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2239 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2240 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2241 // Compute the high part as N1. 2242 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2243 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2244 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2245 // Compute the low part as N0. 2246 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2247 return CombineTo(N, Lo, Hi); 2248 } 2249 } 2250 2251 return SDValue(); 2252 } 2253 2254 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2255 // (smulo x, 2) -> (saddo x, x) 2256 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2257 if (C2->getAPIntValue() == 2) 2258 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(), 2259 N->getOperand(0), N->getOperand(0)); 2260 2261 return SDValue(); 2262 } 2263 2264 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2265 // (umulo x, 2) -> (uaddo x, x) 2266 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2267 if (C2->getAPIntValue() == 2) 2268 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(), 2269 N->getOperand(0), N->getOperand(0)); 2270 2271 return SDValue(); 2272 } 2273 2274 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2275 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2276 if (Res.getNode()) return Res; 2277 2278 return SDValue(); 2279 } 2280 2281 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2282 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2283 if (Res.getNode()) return Res; 2284 2285 return SDValue(); 2286 } 2287 2288 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2289 /// two operands of the same opcode, try to simplify it. 2290 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2291 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2292 EVT VT = N0.getValueType(); 2293 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2294 2295 // Bail early if none of these transforms apply. 2296 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2297 2298 // For each of OP in AND/OR/XOR: 2299 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2300 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2301 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2302 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2303 // 2304 // do not sink logical op inside of a vector extend, since it may combine 2305 // into a vsetcc. 2306 EVT Op0VT = N0.getOperand(0).getValueType(); 2307 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2308 N0.getOpcode() == ISD::SIGN_EXTEND || 2309 // Avoid infinite looping with PromoteIntBinOp. 2310 (N0.getOpcode() == ISD::ANY_EXTEND && 2311 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2312 (N0.getOpcode() == ISD::TRUNCATE && 2313 (!TLI.isZExtFree(VT, Op0VT) || 2314 !TLI.isTruncateFree(Op0VT, VT)) && 2315 TLI.isTypeLegal(Op0VT))) && 2316 !VT.isVector() && 2317 Op0VT == N1.getOperand(0).getValueType() && 2318 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2319 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2320 N0.getOperand(0).getValueType(), 2321 N0.getOperand(0), N1.getOperand(0)); 2322 AddToWorkList(ORNode.getNode()); 2323 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode); 2324 } 2325 2326 // For each of OP in SHL/SRL/SRA/AND... 2327 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2328 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2329 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2330 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2331 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2332 N0.getOperand(1) == N1.getOperand(1)) { 2333 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2334 N0.getOperand(0).getValueType(), 2335 N0.getOperand(0), N1.getOperand(0)); 2336 AddToWorkList(ORNode.getNode()); 2337 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 2338 ORNode, N0.getOperand(1)); 2339 } 2340 2341 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2342 // Only perform this optimization after type legalization and before 2343 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2344 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2345 // we don't want to undo this promotion. 2346 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2347 // on scalars. 2348 if ((N0.getOpcode() == ISD::BITCAST || N0.getOpcode() == ISD::SCALAR_TO_VECTOR) 2349 && Level == AfterLegalizeTypes) { 2350 SDValue In0 = N0.getOperand(0); 2351 SDValue In1 = N1.getOperand(0); 2352 EVT In0Ty = In0.getValueType(); 2353 EVT In1Ty = In1.getValueType(); 2354 // If both incoming values are integers, and the original types are the same. 2355 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2356 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), In0Ty, In0, In1); 2357 SDValue BC = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, Op); 2358 AddToWorkList(Op.getNode()); 2359 return BC; 2360 } 2361 } 2362 2363 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2364 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2365 // If both shuffles use the same mask, and both shuffle within a single 2366 // vector, then it is worthwhile to move the swizzle after the operation. 2367 // The type-legalizer generates this pattern when loading illegal 2368 // vector types from memory. In many cases this allows additional shuffle 2369 // optimizations. 2370 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 2371 N0.getOperand(1).getOpcode() == ISD::UNDEF && 2372 N1.getOperand(1).getOpcode() == ISD::UNDEF) { 2373 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2374 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2375 2376 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() && 2377 "Inputs to shuffles are not the same type"); 2378 2379 unsigned NumElts = VT.getVectorNumElements(); 2380 2381 // Check that both shuffles use the same mask. The masks are known to be of 2382 // the same length because the result vector type is the same. 2383 bool SameMask = true; 2384 for (unsigned i = 0; i != NumElts; ++i) { 2385 int Idx0 = SVN0->getMaskElt(i); 2386 int Idx1 = SVN1->getMaskElt(i); 2387 if (Idx0 != Idx1) { 2388 SameMask = false; 2389 break; 2390 } 2391 } 2392 2393 if (SameMask) { 2394 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT, 2395 N0.getOperand(0), N1.getOperand(0)); 2396 AddToWorkList(Op.getNode()); 2397 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op, 2398 DAG.getUNDEF(VT), &SVN0->getMask()[0]); 2399 } 2400 } 2401 2402 return SDValue(); 2403 } 2404 2405 SDValue DAGCombiner::visitAND(SDNode *N) { 2406 SDValue N0 = N->getOperand(0); 2407 SDValue N1 = N->getOperand(1); 2408 SDValue LL, LR, RL, RR, CC0, CC1; 2409 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2410 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2411 EVT VT = N1.getValueType(); 2412 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2413 2414 // fold vector ops 2415 if (VT.isVector()) { 2416 SDValue FoldedVOp = SimplifyVBinOp(N); 2417 if (FoldedVOp.getNode()) return FoldedVOp; 2418 } 2419 2420 // fold (and x, undef) -> 0 2421 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2422 return DAG.getConstant(0, VT); 2423 // fold (and c1, c2) -> c1&c2 2424 if (N0C && N1C) 2425 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2426 // canonicalize constant to RHS 2427 if (N0C && !N1C) 2428 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0); 2429 // fold (and x, -1) -> x 2430 if (N1C && N1C->isAllOnesValue()) 2431 return N0; 2432 // if (and x, c) is known to be zero, return 0 2433 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2434 APInt::getAllOnesValue(BitWidth))) 2435 return DAG.getConstant(0, VT); 2436 // reassociate and 2437 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1); 2438 if (RAND.getNode() != 0) 2439 return RAND; 2440 // fold (and (or x, C), D) -> D if (C & D) == D 2441 if (N1C && N0.getOpcode() == ISD::OR) 2442 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2443 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2444 return N1; 2445 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2446 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2447 SDValue N0Op0 = N0.getOperand(0); 2448 APInt Mask = ~N1C->getAPIntValue(); 2449 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2450 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2451 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), 2452 N0.getValueType(), N0Op0); 2453 2454 // Replace uses of the AND with uses of the Zero extend node. 2455 CombineTo(N, Zext); 2456 2457 // We actually want to replace all uses of the any_extend with the 2458 // zero_extend, to avoid duplicating things. This will later cause this 2459 // AND to be folded. 2460 CombineTo(N0.getNode(), Zext); 2461 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2462 } 2463 } 2464 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2465 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2466 // already be zero by virtue of the width of the base type of the load. 2467 // 2468 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2469 // more cases. 2470 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2471 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2472 N0.getOpcode() == ISD::LOAD) { 2473 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2474 N0 : N0.getOperand(0) ); 2475 2476 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2477 // This can be a pure constant or a vector splat, in which case we treat the 2478 // vector as a scalar and use the splat value. 2479 APInt Constant = APInt::getNullValue(1); 2480 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2481 Constant = C->getAPIntValue(); 2482 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2483 APInt SplatValue, SplatUndef; 2484 unsigned SplatBitSize; 2485 bool HasAnyUndefs; 2486 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2487 SplatBitSize, HasAnyUndefs); 2488 if (IsSplat) { 2489 // Undef bits can contribute to a possible optimisation if set, so 2490 // set them. 2491 SplatValue |= SplatUndef; 2492 2493 // The splat value may be something like "0x00FFFFFF", which means 0 for 2494 // the first vector value and FF for the rest, repeating. We need a mask 2495 // that will apply equally to all members of the vector, so AND all the 2496 // lanes of the constant together. 2497 EVT VT = Vector->getValueType(0); 2498 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2499 2500 // If the splat value has been compressed to a bitlength lower 2501 // than the size of the vector lane, we need to re-expand it to 2502 // the lane size. 2503 if (BitWidth > SplatBitSize) 2504 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2505 SplatBitSize < BitWidth; 2506 SplatBitSize = SplatBitSize * 2) 2507 SplatValue |= SplatValue.shl(SplatBitSize); 2508 2509 Constant = APInt::getAllOnesValue(BitWidth); 2510 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2511 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2512 } 2513 } 2514 2515 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2516 // actually legal and isn't going to get expanded, else this is a false 2517 // optimisation. 2518 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2519 Load->getMemoryVT()); 2520 2521 // Resize the constant to the same size as the original memory access before 2522 // extension. If it is still the AllOnesValue then this AND is completely 2523 // unneeded. 2524 Constant = 2525 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2526 2527 bool B; 2528 switch (Load->getExtensionType()) { 2529 default: B = false; break; 2530 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2531 case ISD::ZEXTLOAD: 2532 case ISD::NON_EXTLOAD: B = true; break; 2533 } 2534 2535 if (B && Constant.isAllOnesValue()) { 2536 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2537 // preserve semantics once we get rid of the AND. 2538 SDValue NewLoad(Load, 0); 2539 if (Load->getExtensionType() == ISD::EXTLOAD) { 2540 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2541 Load->getValueType(0), Load->getDebugLoc(), 2542 Load->getChain(), Load->getBasePtr(), 2543 Load->getOffset(), Load->getMemoryVT(), 2544 Load->getMemOperand()); 2545 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2546 if (Load->getNumValues() == 3) { 2547 // PRE/POST_INC loads have 3 values. 2548 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2549 NewLoad.getValue(2) }; 2550 CombineTo(Load, To, 3, true); 2551 } else { 2552 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2553 } 2554 } 2555 2556 // Fold the AND away, taking care not to fold to the old load node if we 2557 // replaced it. 2558 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2559 2560 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2561 } 2562 } 2563 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2564 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2565 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2566 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2567 2568 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2569 LL.getValueType().isInteger()) { 2570 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2571 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2572 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2573 LR.getValueType(), LL, RL); 2574 AddToWorkList(ORNode.getNode()); 2575 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2576 } 2577 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2578 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2579 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(), 2580 LR.getValueType(), LL, RL); 2581 AddToWorkList(ANDNode.getNode()); 2582 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 2583 } 2584 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2585 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2586 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2587 LR.getValueType(), LL, RL); 2588 AddToWorkList(ORNode.getNode()); 2589 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2590 } 2591 } 2592 // canonicalize equivalent to ll == rl 2593 if (LL == RR && LR == RL) { 2594 Op1 = ISD::getSetCCSwappedOperands(Op1); 2595 std::swap(RL, RR); 2596 } 2597 if (LL == RL && LR == RR) { 2598 bool isInteger = LL.getValueType().isInteger(); 2599 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2600 if (Result != ISD::SETCC_INVALID && 2601 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 2602 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 2603 LL, LR, Result); 2604 } 2605 } 2606 2607 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2608 if (N0.getOpcode() == N1.getOpcode()) { 2609 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2610 if (Tmp.getNode()) return Tmp; 2611 } 2612 2613 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2614 // fold (and (sra)) -> (and (srl)) when possible. 2615 if (!VT.isVector() && 2616 SimplifyDemandedBits(SDValue(N, 0))) 2617 return SDValue(N, 0); 2618 2619 // fold (zext_inreg (extload x)) -> (zextload x) 2620 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2621 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2622 EVT MemVT = LN0->getMemoryVT(); 2623 // If we zero all the possible extended bits, then we can turn this into 2624 // a zextload if we are running before legalize or the operation is legal. 2625 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2626 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2627 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2628 ((!LegalOperations && !LN0->isVolatile()) || 2629 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2630 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2631 LN0->getChain(), LN0->getBasePtr(), 2632 LN0->getPointerInfo(), MemVT, 2633 LN0->isVolatile(), LN0->isNonTemporal(), 2634 LN0->getAlignment()); 2635 AddToWorkList(N); 2636 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2637 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2638 } 2639 } 2640 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2641 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2642 N0.hasOneUse()) { 2643 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2644 EVT MemVT = LN0->getMemoryVT(); 2645 // If we zero all the possible extended bits, then we can turn this into 2646 // a zextload if we are running before legalize or the operation is legal. 2647 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2648 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2649 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2650 ((!LegalOperations && !LN0->isVolatile()) || 2651 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2652 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2653 LN0->getChain(), 2654 LN0->getBasePtr(), LN0->getPointerInfo(), 2655 MemVT, 2656 LN0->isVolatile(), LN0->isNonTemporal(), 2657 LN0->getAlignment()); 2658 AddToWorkList(N); 2659 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2660 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2661 } 2662 } 2663 2664 // fold (and (load x), 255) -> (zextload x, i8) 2665 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2666 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2667 if (N1C && (N0.getOpcode() == ISD::LOAD || 2668 (N0.getOpcode() == ISD::ANY_EXTEND && 2669 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2670 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2671 LoadSDNode *LN0 = HasAnyExt 2672 ? cast<LoadSDNode>(N0.getOperand(0)) 2673 : cast<LoadSDNode>(N0); 2674 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2675 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) { 2676 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2677 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2678 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2679 EVT LoadedVT = LN0->getMemoryVT(); 2680 2681 if (ExtVT == LoadedVT && 2682 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2683 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2684 2685 SDValue NewLoad = 2686 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2687 LN0->getChain(), LN0->getBasePtr(), 2688 LN0->getPointerInfo(), 2689 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2690 LN0->getAlignment()); 2691 AddToWorkList(N); 2692 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2693 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2694 } 2695 2696 // Do not change the width of a volatile load. 2697 // Do not generate loads of non-round integer types since these can 2698 // be expensive (and would be wrong if the type is not byte sized). 2699 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2700 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2701 EVT PtrType = LN0->getOperand(1).getValueType(); 2702 2703 unsigned Alignment = LN0->getAlignment(); 2704 SDValue NewPtr = LN0->getBasePtr(); 2705 2706 // For big endian targets, we need to add an offset to the pointer 2707 // to load the correct bytes. For little endian systems, we merely 2708 // need to read fewer bytes from the same pointer. 2709 if (TLI.isBigEndian()) { 2710 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2711 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2712 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2713 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType, 2714 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2715 Alignment = MinAlign(Alignment, PtrOff); 2716 } 2717 2718 AddToWorkList(NewPtr.getNode()); 2719 2720 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2721 SDValue Load = 2722 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2723 LN0->getChain(), NewPtr, 2724 LN0->getPointerInfo(), 2725 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2726 Alignment); 2727 AddToWorkList(N); 2728 CombineTo(LN0, Load, Load.getValue(1)); 2729 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2730 } 2731 } 2732 } 2733 } 2734 2735 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2736 VT.getSizeInBits() <= 64) { 2737 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2738 APInt ADDC = ADDI->getAPIntValue(); 2739 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2740 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2741 // immediate for an add, but it is legal if its top c2 bits are set, 2742 // transform the ADD so the immediate doesn't need to be materialized 2743 // in a register. 2744 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2745 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2746 SRLI->getZExtValue()); 2747 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2748 ADDC |= Mask; 2749 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2750 SDValue NewAdd = 2751 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, 2752 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2753 CombineTo(N0.getNode(), NewAdd); 2754 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2755 } 2756 } 2757 } 2758 } 2759 } 2760 } 2761 2762 2763 return SDValue(); 2764 } 2765 2766 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2767 /// 2768 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2769 bool DemandHighBits) { 2770 if (!LegalOperations) 2771 return SDValue(); 2772 2773 EVT VT = N->getValueType(0); 2774 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2775 return SDValue(); 2776 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2777 return SDValue(); 2778 2779 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2780 bool LookPassAnd0 = false; 2781 bool LookPassAnd1 = false; 2782 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2783 std::swap(N0, N1); 2784 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2785 std::swap(N0, N1); 2786 if (N0.getOpcode() == ISD::AND) { 2787 if (!N0.getNode()->hasOneUse()) 2788 return SDValue(); 2789 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2790 if (!N01C || N01C->getZExtValue() != 0xFF00) 2791 return SDValue(); 2792 N0 = N0.getOperand(0); 2793 LookPassAnd0 = true; 2794 } 2795 2796 if (N1.getOpcode() == ISD::AND) { 2797 if (!N1.getNode()->hasOneUse()) 2798 return SDValue(); 2799 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2800 if (!N11C || N11C->getZExtValue() != 0xFF) 2801 return SDValue(); 2802 N1 = N1.getOperand(0); 2803 LookPassAnd1 = true; 2804 } 2805 2806 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2807 std::swap(N0, N1); 2808 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2809 return SDValue(); 2810 if (!N0.getNode()->hasOneUse() || 2811 !N1.getNode()->hasOneUse()) 2812 return SDValue(); 2813 2814 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2815 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2816 if (!N01C || !N11C) 2817 return SDValue(); 2818 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 2819 return SDValue(); 2820 2821 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 2822 SDValue N00 = N0->getOperand(0); 2823 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 2824 if (!N00.getNode()->hasOneUse()) 2825 return SDValue(); 2826 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 2827 if (!N001C || N001C->getZExtValue() != 0xFF) 2828 return SDValue(); 2829 N00 = N00.getOperand(0); 2830 LookPassAnd0 = true; 2831 } 2832 2833 SDValue N10 = N1->getOperand(0); 2834 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 2835 if (!N10.getNode()->hasOneUse()) 2836 return SDValue(); 2837 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 2838 if (!N101C || N101C->getZExtValue() != 0xFF00) 2839 return SDValue(); 2840 N10 = N10.getOperand(0); 2841 LookPassAnd1 = true; 2842 } 2843 2844 if (N00 != N10) 2845 return SDValue(); 2846 2847 // Make sure everything beyond the low halfword is zero since the SRL 16 2848 // will clear the top bits. 2849 unsigned OpSizeInBits = VT.getSizeInBits(); 2850 if (DemandHighBits && OpSizeInBits > 16 && 2851 (!LookPassAnd0 || !LookPassAnd1) && 2852 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16))) 2853 return SDValue(); 2854 2855 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00); 2856 if (OpSizeInBits > 16) 2857 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res, 2858 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 2859 return Res; 2860 } 2861 2862 /// isBSwapHWordElement - Return true if the specified node is an element 2863 /// that makes up a 32-bit packed halfword byteswap. i.e. 2864 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 2865 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) { 2866 if (!N.getNode()->hasOneUse()) 2867 return false; 2868 2869 unsigned Opc = N.getOpcode(); 2870 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 2871 return false; 2872 2873 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2874 if (!N1C) 2875 return false; 2876 2877 unsigned Num; 2878 switch (N1C->getZExtValue()) { 2879 default: 2880 return false; 2881 case 0xFF: Num = 0; break; 2882 case 0xFF00: Num = 1; break; 2883 case 0xFF0000: Num = 2; break; 2884 case 0xFF000000: Num = 3; break; 2885 } 2886 2887 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 2888 SDValue N0 = N.getOperand(0); 2889 if (Opc == ISD::AND) { 2890 if (Num == 0 || Num == 2) { 2891 // (x >> 8) & 0xff 2892 // (x >> 8) & 0xff0000 2893 if (N0.getOpcode() != ISD::SRL) 2894 return false; 2895 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2896 if (!C || C->getZExtValue() != 8) 2897 return false; 2898 } else { 2899 // (x << 8) & 0xff00 2900 // (x << 8) & 0xff000000 2901 if (N0.getOpcode() != ISD::SHL) 2902 return false; 2903 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2904 if (!C || C->getZExtValue() != 8) 2905 return false; 2906 } 2907 } else if (Opc == ISD::SHL) { 2908 // (x & 0xff) << 8 2909 // (x & 0xff0000) << 8 2910 if (Num != 0 && Num != 2) 2911 return false; 2912 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2913 if (!C || C->getZExtValue() != 8) 2914 return false; 2915 } else { // Opc == ISD::SRL 2916 // (x & 0xff00) >> 8 2917 // (x & 0xff000000) >> 8 2918 if (Num != 1 && Num != 3) 2919 return false; 2920 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2921 if (!C || C->getZExtValue() != 8) 2922 return false; 2923 } 2924 2925 if (Parts[Num]) 2926 return false; 2927 2928 Parts[Num] = N0.getOperand(0).getNode(); 2929 return true; 2930 } 2931 2932 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 2933 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 2934 /// => (rotl (bswap x), 16) 2935 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 2936 if (!LegalOperations) 2937 return SDValue(); 2938 2939 EVT VT = N->getValueType(0); 2940 if (VT != MVT::i32) 2941 return SDValue(); 2942 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2943 return SDValue(); 2944 2945 SmallVector<SDNode*,4> Parts(4, (SDNode*)0); 2946 // Look for either 2947 // (or (or (and), (and)), (or (and), (and))) 2948 // (or (or (or (and), (and)), (and)), (and)) 2949 if (N0.getOpcode() != ISD::OR) 2950 return SDValue(); 2951 SDValue N00 = N0.getOperand(0); 2952 SDValue N01 = N0.getOperand(1); 2953 2954 if (N1.getOpcode() == ISD::OR) { 2955 // (or (or (and), (and)), (or (and), (and))) 2956 SDValue N000 = N00.getOperand(0); 2957 if (!isBSwapHWordElement(N000, Parts)) 2958 return SDValue(); 2959 2960 SDValue N001 = N00.getOperand(1); 2961 if (!isBSwapHWordElement(N001, Parts)) 2962 return SDValue(); 2963 SDValue N010 = N01.getOperand(0); 2964 if (!isBSwapHWordElement(N010, Parts)) 2965 return SDValue(); 2966 SDValue N011 = N01.getOperand(1); 2967 if (!isBSwapHWordElement(N011, Parts)) 2968 return SDValue(); 2969 } else { 2970 // (or (or (or (and), (and)), (and)), (and)) 2971 if (!isBSwapHWordElement(N1, Parts)) 2972 return SDValue(); 2973 if (!isBSwapHWordElement(N01, Parts)) 2974 return SDValue(); 2975 if (N00.getOpcode() != ISD::OR) 2976 return SDValue(); 2977 SDValue N000 = N00.getOperand(0); 2978 if (!isBSwapHWordElement(N000, Parts)) 2979 return SDValue(); 2980 SDValue N001 = N00.getOperand(1); 2981 if (!isBSwapHWordElement(N001, Parts)) 2982 return SDValue(); 2983 } 2984 2985 // Make sure the parts are all coming from the same node. 2986 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 2987 return SDValue(); 2988 2989 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, 2990 SDValue(Parts[0],0)); 2991 2992 // Result of the bswap should be rotated by 16. If it's not legal, than 2993 // do (x << 16) | (x >> 16). 2994 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 2995 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 2996 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt); 2997 else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 2998 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt); 2999 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, 3000 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt), 3001 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt)); 3002 } 3003 3004 SDValue DAGCombiner::visitOR(SDNode *N) { 3005 SDValue N0 = N->getOperand(0); 3006 SDValue N1 = N->getOperand(1); 3007 SDValue LL, LR, RL, RR, CC0, CC1; 3008 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3010 EVT VT = N1.getValueType(); 3011 3012 // fold vector ops 3013 if (VT.isVector()) { 3014 SDValue FoldedVOp = SimplifyVBinOp(N); 3015 if (FoldedVOp.getNode()) return FoldedVOp; 3016 } 3017 3018 // fold (or x, undef) -> -1 3019 if (!LegalOperations && 3020 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3021 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3022 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3023 } 3024 // fold (or c1, c2) -> c1|c2 3025 if (N0C && N1C) 3026 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3027 // canonicalize constant to RHS 3028 if (N0C && !N1C) 3029 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0); 3030 // fold (or x, 0) -> x 3031 if (N1C && N1C->isNullValue()) 3032 return N0; 3033 // fold (or x, -1) -> -1 3034 if (N1C && N1C->isAllOnesValue()) 3035 return N1; 3036 // fold (or x, c) -> c iff (x & ~c) == 0 3037 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3038 return N1; 3039 3040 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3041 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3042 if (BSwap.getNode() != 0) 3043 return BSwap; 3044 BSwap = MatchBSwapHWordLow(N, N0, N1); 3045 if (BSwap.getNode() != 0) 3046 return BSwap; 3047 3048 // reassociate or 3049 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1); 3050 if (ROR.getNode() != 0) 3051 return ROR; 3052 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3053 // iff (c1 & c2) == 0. 3054 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3055 isa<ConstantSDNode>(N0.getOperand(1))) { 3056 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3057 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) 3058 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 3059 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 3060 N0.getOperand(0), N1), 3061 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)); 3062 } 3063 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3064 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3065 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3066 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3067 3068 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3069 LL.getValueType().isInteger()) { 3070 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3071 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3072 if (cast<ConstantSDNode>(LR)->isNullValue() && 3073 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3074 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(), 3075 LR.getValueType(), LL, RL); 3076 AddToWorkList(ORNode.getNode()); 3077 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 3078 } 3079 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3080 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3081 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3082 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3083 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(), 3084 LR.getValueType(), LL, RL); 3085 AddToWorkList(ANDNode.getNode()); 3086 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 3087 } 3088 } 3089 // canonicalize equivalent to ll == rl 3090 if (LL == RR && LR == RL) { 3091 Op1 = ISD::getSetCCSwappedOperands(Op1); 3092 std::swap(RL, RR); 3093 } 3094 if (LL == RL && LR == RR) { 3095 bool isInteger = LL.getValueType().isInteger(); 3096 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3097 if (Result != ISD::SETCC_INVALID && 3098 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 3099 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 3100 LL, LR, Result); 3101 } 3102 } 3103 3104 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3105 if (N0.getOpcode() == N1.getOpcode()) { 3106 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3107 if (Tmp.getNode()) return Tmp; 3108 } 3109 3110 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3111 if (N0.getOpcode() == ISD::AND && 3112 N1.getOpcode() == ISD::AND && 3113 N0.getOperand(1).getOpcode() == ISD::Constant && 3114 N1.getOperand(1).getOpcode() == ISD::Constant && 3115 // Don't increase # computations. 3116 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3117 // We can only do this xform if we know that bits from X that are set in C2 3118 // but not in C1 are already zero. Likewise for Y. 3119 const APInt &LHSMask = 3120 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3121 const APInt &RHSMask = 3122 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3123 3124 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3125 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3126 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 3127 N0.getOperand(0), N1.getOperand(0)); 3128 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X, 3129 DAG.getConstant(LHSMask | RHSMask, VT)); 3130 } 3131 } 3132 3133 // See if this is some rotate idiom. 3134 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc())) 3135 return SDValue(Rot, 0); 3136 3137 // Simplify the operands using demanded-bits information. 3138 if (!VT.isVector() && 3139 SimplifyDemandedBits(SDValue(N, 0))) 3140 return SDValue(N, 0); 3141 3142 return SDValue(); 3143 } 3144 3145 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3146 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3147 if (Op.getOpcode() == ISD::AND) { 3148 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3149 Mask = Op.getOperand(1); 3150 Op = Op.getOperand(0); 3151 } else { 3152 return false; 3153 } 3154 } 3155 3156 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3157 Shift = Op; 3158 return true; 3159 } 3160 3161 return false; 3162 } 3163 3164 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3165 // idioms for rotate, and if the target supports rotation instructions, generate 3166 // a rot[lr]. 3167 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) { 3168 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3169 EVT VT = LHS.getValueType(); 3170 if (!TLI.isTypeLegal(VT)) return 0; 3171 3172 // The target must have at least one rotate flavor. 3173 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3174 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3175 if (!HasROTL && !HasROTR) return 0; 3176 3177 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3178 SDValue LHSShift; // The shift. 3179 SDValue LHSMask; // AND value if any. 3180 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3181 return 0; // Not part of a rotate. 3182 3183 SDValue RHSShift; // The shift. 3184 SDValue RHSMask; // AND value if any. 3185 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3186 return 0; // Not part of a rotate. 3187 3188 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3189 return 0; // Not shifting the same value. 3190 3191 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3192 return 0; // Shifts must disagree. 3193 3194 // Canonicalize shl to left side in a shl/srl pair. 3195 if (RHSShift.getOpcode() == ISD::SHL) { 3196 std::swap(LHS, RHS); 3197 std::swap(LHSShift, RHSShift); 3198 std::swap(LHSMask , RHSMask ); 3199 } 3200 3201 unsigned OpSizeInBits = VT.getSizeInBits(); 3202 SDValue LHSShiftArg = LHSShift.getOperand(0); 3203 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3204 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3205 3206 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3207 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3208 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3209 RHSShiftAmt.getOpcode() == ISD::Constant) { 3210 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3211 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3212 if ((LShVal + RShVal) != OpSizeInBits) 3213 return 0; 3214 3215 SDValue Rot; 3216 if (HasROTL) 3217 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt); 3218 else 3219 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt); 3220 3221 // If there is an AND of either shifted operand, apply it to the result. 3222 if (LHSMask.getNode() || RHSMask.getNode()) { 3223 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3224 3225 if (LHSMask.getNode()) { 3226 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3227 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3228 } 3229 if (RHSMask.getNode()) { 3230 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3231 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3232 } 3233 3234 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3235 } 3236 3237 return Rot.getNode(); 3238 } 3239 3240 // If there is a mask here, and we have a variable shift, we can't be sure 3241 // that we're masking out the right stuff. 3242 if (LHSMask.getNode() || RHSMask.getNode()) 3243 return 0; 3244 3245 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y) 3246 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y)) 3247 if (RHSShiftAmt.getOpcode() == ISD::SUB && 3248 LHSShiftAmt == RHSShiftAmt.getOperand(1)) { 3249 if (ConstantSDNode *SUBC = 3250 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) { 3251 if (SUBC->getAPIntValue() == OpSizeInBits) { 3252 if (HasROTL) 3253 return DAG.getNode(ISD::ROTL, DL, VT, 3254 LHSShiftArg, LHSShiftAmt).getNode(); 3255 else 3256 return DAG.getNode(ISD::ROTR, DL, VT, 3257 LHSShiftArg, RHSShiftAmt).getNode(); 3258 } 3259 } 3260 } 3261 3262 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y) 3263 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y)) 3264 if (LHSShiftAmt.getOpcode() == ISD::SUB && 3265 RHSShiftAmt == LHSShiftAmt.getOperand(1)) { 3266 if (ConstantSDNode *SUBC = 3267 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) { 3268 if (SUBC->getAPIntValue() == OpSizeInBits) { 3269 if (HasROTR) 3270 return DAG.getNode(ISD::ROTR, DL, VT, 3271 LHSShiftArg, RHSShiftAmt).getNode(); 3272 else 3273 return DAG.getNode(ISD::ROTL, DL, VT, 3274 LHSShiftArg, LHSShiftAmt).getNode(); 3275 } 3276 } 3277 } 3278 3279 // Look for sign/zext/any-extended or truncate cases: 3280 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 3281 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 3282 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND 3283 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3284 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 3285 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 3286 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND 3287 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3288 SDValue LExtOp0 = LHSShiftAmt.getOperand(0); 3289 SDValue RExtOp0 = RHSShiftAmt.getOperand(0); 3290 if (RExtOp0.getOpcode() == ISD::SUB && 3291 RExtOp0.getOperand(1) == LExtOp0) { 3292 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3293 // (rotl x, y) 3294 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3295 // (rotr x, (sub 32, y)) 3296 if (ConstantSDNode *SUBC = 3297 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) { 3298 if (SUBC->getAPIntValue() == OpSizeInBits) { 3299 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3300 LHSShiftArg, 3301 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 3302 } 3303 } 3304 } else if (LExtOp0.getOpcode() == ISD::SUB && 3305 RExtOp0 == LExtOp0.getOperand(1)) { 3306 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3307 // (rotr x, y) 3308 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3309 // (rotl x, (sub 32, y)) 3310 if (ConstantSDNode *SUBC = 3311 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) { 3312 if (SUBC->getAPIntValue() == OpSizeInBits) { 3313 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, 3314 LHSShiftArg, 3315 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 3316 } 3317 } 3318 } 3319 } 3320 3321 return 0; 3322 } 3323 3324 SDValue DAGCombiner::visitXOR(SDNode *N) { 3325 SDValue N0 = N->getOperand(0); 3326 SDValue N1 = N->getOperand(1); 3327 SDValue LHS, RHS, CC; 3328 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3329 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3330 EVT VT = N0.getValueType(); 3331 3332 // fold vector ops 3333 if (VT.isVector()) { 3334 SDValue FoldedVOp = SimplifyVBinOp(N); 3335 if (FoldedVOp.getNode()) return FoldedVOp; 3336 } 3337 3338 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3339 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3340 return DAG.getConstant(0, VT); 3341 // fold (xor x, undef) -> undef 3342 if (N0.getOpcode() == ISD::UNDEF) 3343 return N0; 3344 if (N1.getOpcode() == ISD::UNDEF) 3345 return N1; 3346 // fold (xor c1, c2) -> c1^c2 3347 if (N0C && N1C) 3348 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3349 // canonicalize constant to RHS 3350 if (N0C && !N1C) 3351 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 3352 // fold (xor x, 0) -> x 3353 if (N1C && N1C->isNullValue()) 3354 return N0; 3355 // reassociate xor 3356 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1); 3357 if (RXOR.getNode() != 0) 3358 return RXOR; 3359 3360 // fold !(x cc y) -> (x !cc y) 3361 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3362 bool isInt = LHS.getValueType().isInteger(); 3363 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3364 isInt); 3365 3366 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) { 3367 switch (N0.getOpcode()) { 3368 default: 3369 llvm_unreachable("Unhandled SetCC Equivalent!"); 3370 case ISD::SETCC: 3371 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC); 3372 case ISD::SELECT_CC: 3373 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2), 3374 N0.getOperand(3), NotCC); 3375 } 3376 } 3377 } 3378 3379 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3380 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3381 N0.getNode()->hasOneUse() && 3382 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3383 SDValue V = N0.getOperand(0); 3384 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V, 3385 DAG.getConstant(1, V.getValueType())); 3386 AddToWorkList(V.getNode()); 3387 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V); 3388 } 3389 3390 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3391 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3392 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3393 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3394 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3395 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3396 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 3397 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 3398 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3399 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 3400 } 3401 } 3402 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3403 if (N1C && N1C->isAllOnesValue() && 3404 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3405 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3406 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3407 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3408 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 3409 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 3410 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3411 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 3412 } 3413 } 3414 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3415 if (N1C && N0.getOpcode() == ISD::XOR) { 3416 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3417 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3418 if (N00C) 3419 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1), 3420 DAG.getConstant(N1C->getAPIntValue() ^ 3421 N00C->getAPIntValue(), VT)); 3422 if (N01C) 3423 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0), 3424 DAG.getConstant(N1C->getAPIntValue() ^ 3425 N01C->getAPIntValue(), VT)); 3426 } 3427 // fold (xor x, x) -> 0 3428 if (N0 == N1) 3429 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations); 3430 3431 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3432 if (N0.getOpcode() == N1.getOpcode()) { 3433 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3434 if (Tmp.getNode()) return Tmp; 3435 } 3436 3437 // Simplify the expression using non-local knowledge. 3438 if (!VT.isVector() && 3439 SimplifyDemandedBits(SDValue(N, 0))) 3440 return SDValue(N, 0); 3441 3442 return SDValue(); 3443 } 3444 3445 /// visitShiftByConstant - Handle transforms common to the three shifts, when 3446 /// the shift amount is a constant. 3447 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 3448 SDNode *LHS = N->getOperand(0).getNode(); 3449 if (!LHS->hasOneUse()) return SDValue(); 3450 3451 // We want to pull some binops through shifts, so that we have (and (shift)) 3452 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3453 // thing happens with address calculations, so it's important to canonicalize 3454 // it. 3455 bool HighBitSet = false; // Can we transform this if the high bit is set? 3456 3457 switch (LHS->getOpcode()) { 3458 default: return SDValue(); 3459 case ISD::OR: 3460 case ISD::XOR: 3461 HighBitSet = false; // We can only transform sra if the high bit is clear. 3462 break; 3463 case ISD::AND: 3464 HighBitSet = true; // We can only transform sra if the high bit is set. 3465 break; 3466 case ISD::ADD: 3467 if (N->getOpcode() != ISD::SHL) 3468 return SDValue(); // only shl(add) not sr[al](add). 3469 HighBitSet = false; // We can only transform sra if the high bit is clear. 3470 break; 3471 } 3472 3473 // We require the RHS of the binop to be a constant as well. 3474 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3475 if (!BinOpCst) return SDValue(); 3476 3477 // FIXME: disable this unless the input to the binop is a shift by a constant. 3478 // If it is not a shift, it pessimizes some common cases like: 3479 // 3480 // void foo(int *X, int i) { X[i & 1235] = 1; } 3481 // int bar(int *X, int i) { return X[i & 255]; } 3482 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3483 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3484 BinOpLHSVal->getOpcode() != ISD::SRA && 3485 BinOpLHSVal->getOpcode() != ISD::SRL) || 3486 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3487 return SDValue(); 3488 3489 EVT VT = N->getValueType(0); 3490 3491 // If this is a signed shift right, and the high bit is modified by the 3492 // logical operation, do not perform the transformation. The highBitSet 3493 // boolean indicates the value of the high bit of the constant which would 3494 // cause it to be modified for this operation. 3495 if (N->getOpcode() == ISD::SRA) { 3496 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3497 if (BinOpRHSSignSet != HighBitSet) 3498 return SDValue(); 3499 } 3500 3501 // Fold the constants, shifting the binop RHS by the shift amount. 3502 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(), 3503 N->getValueType(0), 3504 LHS->getOperand(1), N->getOperand(1)); 3505 3506 // Create the new shift. 3507 SDValue NewShift = DAG.getNode(N->getOpcode(), 3508 LHS->getOperand(0).getDebugLoc(), 3509 VT, LHS->getOperand(0), N->getOperand(1)); 3510 3511 // Create the new binop. 3512 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS); 3513 } 3514 3515 SDValue DAGCombiner::visitSHL(SDNode *N) { 3516 SDValue N0 = N->getOperand(0); 3517 SDValue N1 = N->getOperand(1); 3518 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3519 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3520 EVT VT = N0.getValueType(); 3521 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3522 3523 // fold (shl c1, c2) -> c1<<c2 3524 if (N0C && N1C) 3525 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3526 // fold (shl 0, x) -> 0 3527 if (N0C && N0C->isNullValue()) 3528 return N0; 3529 // fold (shl x, c >= size(x)) -> undef 3530 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3531 return DAG.getUNDEF(VT); 3532 // fold (shl x, 0) -> x 3533 if (N1C && N1C->isNullValue()) 3534 return N0; 3535 // fold (shl undef, x) -> 0 3536 if (N0.getOpcode() == ISD::UNDEF) 3537 return DAG.getConstant(0, VT); 3538 // if (shl x, c) is known to be zero, return 0 3539 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3540 APInt::getAllOnesValue(OpSizeInBits))) 3541 return DAG.getConstant(0, VT); 3542 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3543 if (N1.getOpcode() == ISD::TRUNCATE && 3544 N1.getOperand(0).getOpcode() == ISD::AND && 3545 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3546 SDValue N101 = N1.getOperand(0).getOperand(1); 3547 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3548 EVT TruncVT = N1.getValueType(); 3549 SDValue N100 = N1.getOperand(0).getOperand(0); 3550 APInt TruncC = N101C->getAPIntValue(); 3551 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3552 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 3553 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT, 3554 DAG.getNode(ISD::TRUNCATE, 3555 N->getDebugLoc(), 3556 TruncVT, N100), 3557 DAG.getConstant(TruncC, TruncVT))); 3558 } 3559 } 3560 3561 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3562 return SDValue(N, 0); 3563 3564 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3565 if (N1C && N0.getOpcode() == ISD::SHL && 3566 N0.getOperand(1).getOpcode() == ISD::Constant) { 3567 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3568 uint64_t c2 = N1C->getZExtValue(); 3569 if (c1 + c2 >= OpSizeInBits) 3570 return DAG.getConstant(0, VT); 3571 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0), 3572 DAG.getConstant(c1 + c2, N1.getValueType())); 3573 } 3574 3575 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3576 // For this to be valid, the second form must not preserve any of the bits 3577 // that are shifted out by the inner shift in the first form. This means 3578 // the outer shift size must be >= the number of bits added by the ext. 3579 // As a corollary, we don't care what kind of ext it is. 3580 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3581 N0.getOpcode() == ISD::ANY_EXTEND || 3582 N0.getOpcode() == ISD::SIGN_EXTEND) && 3583 N0.getOperand(0).getOpcode() == ISD::SHL && 3584 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3585 uint64_t c1 = 3586 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3587 uint64_t c2 = N1C->getZExtValue(); 3588 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3589 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3590 if (c2 >= OpSizeInBits - InnerShiftSize) { 3591 if (c1 + c2 >= OpSizeInBits) 3592 return DAG.getConstant(0, VT); 3593 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT, 3594 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT, 3595 N0.getOperand(0)->getOperand(0)), 3596 DAG.getConstant(c1 + c2, N1.getValueType())); 3597 } 3598 } 3599 3600 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 3601 // (and (srl x, (sub c1, c2), MASK) 3602 // Only fold this if the inner shift has no other uses -- if it does, folding 3603 // this will increase the total number of instructions. 3604 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 3605 N0.getOperand(1).getOpcode() == ISD::Constant) { 3606 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3607 if (c1 < VT.getSizeInBits()) { 3608 uint64_t c2 = N1C->getZExtValue(); 3609 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3610 VT.getSizeInBits() - c1); 3611 SDValue Shift; 3612 if (c2 > c1) { 3613 Mask = Mask.shl(c2-c1); 3614 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0), 3615 DAG.getConstant(c2-c1, N1.getValueType())); 3616 } else { 3617 Mask = Mask.lshr(c1-c2); 3618 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), 3619 DAG.getConstant(c1-c2, N1.getValueType())); 3620 } 3621 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift, 3622 DAG.getConstant(Mask, VT)); 3623 } 3624 } 3625 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 3626 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 3627 SDValue HiBitsMask = 3628 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 3629 VT.getSizeInBits() - 3630 N1C->getZExtValue()), 3631 VT); 3632 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 3633 HiBitsMask); 3634 } 3635 3636 if (N1C) { 3637 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 3638 if (NewSHL.getNode()) 3639 return NewSHL; 3640 } 3641 3642 return SDValue(); 3643 } 3644 3645 SDValue DAGCombiner::visitSRA(SDNode *N) { 3646 SDValue N0 = N->getOperand(0); 3647 SDValue N1 = N->getOperand(1); 3648 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3649 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3650 EVT VT = N0.getValueType(); 3651 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3652 3653 // fold (sra c1, c2) -> (sra c1, c2) 3654 if (N0C && N1C) 3655 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 3656 // fold (sra 0, x) -> 0 3657 if (N0C && N0C->isNullValue()) 3658 return N0; 3659 // fold (sra -1, x) -> -1 3660 if (N0C && N0C->isAllOnesValue()) 3661 return N0; 3662 // fold (sra x, (setge c, size(x))) -> undef 3663 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3664 return DAG.getUNDEF(VT); 3665 // fold (sra x, 0) -> x 3666 if (N1C && N1C->isNullValue()) 3667 return N0; 3668 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 3669 // sext_inreg. 3670 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 3671 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 3672 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 3673 if (VT.isVector()) 3674 ExtVT = EVT::getVectorVT(*DAG.getContext(), 3675 ExtVT, VT.getVectorNumElements()); 3676 if ((!LegalOperations || 3677 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 3678 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 3679 N0.getOperand(0), DAG.getValueType(ExtVT)); 3680 } 3681 3682 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 3683 if (N1C && N0.getOpcode() == ISD::SRA) { 3684 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3685 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 3686 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 3687 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0), 3688 DAG.getConstant(Sum, N1C->getValueType(0))); 3689 } 3690 } 3691 3692 // fold (sra (shl X, m), (sub result_size, n)) 3693 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 3694 // result_size - n != m. 3695 // If truncate is free for the target sext(shl) is likely to result in better 3696 // code. 3697 if (N0.getOpcode() == ISD::SHL) { 3698 // Get the two constanst of the shifts, CN0 = m, CN = n. 3699 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3700 if (N01C && N1C) { 3701 // Determine what the truncate's result bitsize and type would be. 3702 EVT TruncVT = 3703 EVT::getIntegerVT(*DAG.getContext(), 3704 OpSizeInBits - N1C->getZExtValue()); 3705 // Determine the residual right-shift amount. 3706 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 3707 3708 // If the shift is not a no-op (in which case this should be just a sign 3709 // extend already), the truncated to type is legal, sign_extend is legal 3710 // on that type, and the truncate to that type is both legal and free, 3711 // perform the transform. 3712 if ((ShiftAmt > 0) && 3713 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 3714 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 3715 TLI.isTruncateFree(VT, TruncVT)) { 3716 3717 SDValue Amt = DAG.getConstant(ShiftAmt, 3718 getShiftAmountTy(N0.getOperand(0).getValueType())); 3719 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, 3720 N0.getOperand(0), Amt); 3721 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT, 3722 Shift); 3723 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), 3724 N->getValueType(0), Trunc); 3725 } 3726 } 3727 } 3728 3729 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 3730 if (N1.getOpcode() == ISD::TRUNCATE && 3731 N1.getOperand(0).getOpcode() == ISD::AND && 3732 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3733 SDValue N101 = N1.getOperand(0).getOperand(1); 3734 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3735 EVT TruncVT = N1.getValueType(); 3736 SDValue N100 = N1.getOperand(0).getOperand(0); 3737 APInt TruncC = N101C->getAPIntValue(); 3738 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 3739 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 3740 DAG.getNode(ISD::AND, N->getDebugLoc(), 3741 TruncVT, 3742 DAG.getNode(ISD::TRUNCATE, 3743 N->getDebugLoc(), 3744 TruncVT, N100), 3745 DAG.getConstant(TruncC, TruncVT))); 3746 } 3747 } 3748 3749 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2)) 3750 // if c1 is equal to the number of bits the trunc removes 3751 if (N0.getOpcode() == ISD::TRUNCATE && 3752 (N0.getOperand(0).getOpcode() == ISD::SRL || 3753 N0.getOperand(0).getOpcode() == ISD::SRA) && 3754 N0.getOperand(0).hasOneUse() && 3755 N0.getOperand(0).getOperand(1).hasOneUse() && 3756 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 3757 EVT LargeVT = N0.getOperand(0).getValueType(); 3758 ConstantSDNode *LargeShiftAmt = 3759 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1)); 3760 3761 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits == 3762 LargeShiftAmt->getZExtValue()) { 3763 SDValue Amt = 3764 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(), 3765 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType())); 3766 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT, 3767 N0.getOperand(0).getOperand(0), Amt); 3768 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA); 3769 } 3770 } 3771 3772 // Simplify, based on bits shifted out of the LHS. 3773 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3774 return SDValue(N, 0); 3775 3776 3777 // If the sign bit is known to be zero, switch this to a SRL. 3778 if (DAG.SignBitIsZero(N0)) 3779 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1); 3780 3781 if (N1C) { 3782 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 3783 if (NewSRA.getNode()) 3784 return NewSRA; 3785 } 3786 3787 return SDValue(); 3788 } 3789 3790 SDValue DAGCombiner::visitSRL(SDNode *N) { 3791 SDValue N0 = N->getOperand(0); 3792 SDValue N1 = N->getOperand(1); 3793 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3794 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3795 EVT VT = N0.getValueType(); 3796 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3797 3798 // fold (srl c1, c2) -> c1 >>u c2 3799 if (N0C && N1C) 3800 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 3801 // fold (srl 0, x) -> 0 3802 if (N0C && N0C->isNullValue()) 3803 return N0; 3804 // fold (srl x, c >= size(x)) -> undef 3805 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3806 return DAG.getUNDEF(VT); 3807 // fold (srl x, 0) -> x 3808 if (N1C && N1C->isNullValue()) 3809 return N0; 3810 // if (srl x, c) is known to be zero, return 0 3811 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3812 APInt::getAllOnesValue(OpSizeInBits))) 3813 return DAG.getConstant(0, VT); 3814 3815 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 3816 if (N1C && N0.getOpcode() == ISD::SRL && 3817 N0.getOperand(1).getOpcode() == ISD::Constant) { 3818 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3819 uint64_t c2 = N1C->getZExtValue(); 3820 if (c1 + c2 >= OpSizeInBits) 3821 return DAG.getConstant(0, VT); 3822 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), 3823 DAG.getConstant(c1 + c2, N1.getValueType())); 3824 } 3825 3826 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 3827 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 3828 N0.getOperand(0).getOpcode() == ISD::SRL && 3829 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3830 uint64_t c1 = 3831 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3832 uint64_t c2 = N1C->getZExtValue(); 3833 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3834 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 3835 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3836 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 3837 if (c1 + OpSizeInBits == InnerShiftSize) { 3838 if (c1 + c2 >= InnerShiftSize) 3839 return DAG.getConstant(0, VT); 3840 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT, 3841 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT, 3842 N0.getOperand(0)->getOperand(0), 3843 DAG.getConstant(c1 + c2, ShiftCountVT))); 3844 } 3845 } 3846 3847 // fold (srl (shl x, c), c) -> (and x, cst2) 3848 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 3849 N0.getValueSizeInBits() <= 64) { 3850 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 3851 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 3852 DAG.getConstant(~0ULL >> ShAmt, VT)); 3853 } 3854 3855 3856 // fold (srl (anyextend x), c) -> (anyextend (srl x, c)) 3857 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3858 // Shifting in all undef bits? 3859 EVT SmallVT = N0.getOperand(0).getValueType(); 3860 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 3861 return DAG.getUNDEF(VT); 3862 3863 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 3864 uint64_t ShiftAmt = N1C->getZExtValue(); 3865 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT, 3866 N0.getOperand(0), 3867 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 3868 AddToWorkList(SmallShift.getNode()); 3869 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift); 3870 } 3871 } 3872 3873 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 3874 // bit, which is unmodified by sra. 3875 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 3876 if (N0.getOpcode() == ISD::SRA) 3877 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1); 3878 } 3879 3880 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 3881 if (N1C && N0.getOpcode() == ISD::CTLZ && 3882 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 3883 APInt KnownZero, KnownOne; 3884 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 3885 3886 // If any of the input bits are KnownOne, then the input couldn't be all 3887 // zeros, thus the result of the srl will always be zero. 3888 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 3889 3890 // If all of the bits input the to ctlz node are known to be zero, then 3891 // the result of the ctlz is "32" and the result of the shift is one. 3892 APInt UnknownBits = ~KnownZero; 3893 if (UnknownBits == 0) return DAG.getConstant(1, VT); 3894 3895 // Otherwise, check to see if there is exactly one bit input to the ctlz. 3896 if ((UnknownBits & (UnknownBits - 1)) == 0) { 3897 // Okay, we know that only that the single bit specified by UnknownBits 3898 // could be set on input to the CTLZ node. If this bit is set, the SRL 3899 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 3900 // to an SRL/XOR pair, which is likely to simplify more. 3901 unsigned ShAmt = UnknownBits.countTrailingZeros(); 3902 SDValue Op = N0.getOperand(0); 3903 3904 if (ShAmt) { 3905 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op, 3906 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 3907 AddToWorkList(Op.getNode()); 3908 } 3909 3910 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 3911 Op, DAG.getConstant(1, VT)); 3912 } 3913 } 3914 3915 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 3916 if (N1.getOpcode() == ISD::TRUNCATE && 3917 N1.getOperand(0).getOpcode() == ISD::AND && 3918 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3919 SDValue N101 = N1.getOperand(0).getOperand(1); 3920 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3921 EVT TruncVT = N1.getValueType(); 3922 SDValue N100 = N1.getOperand(0).getOperand(0); 3923 APInt TruncC = N101C->getAPIntValue(); 3924 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3925 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 3926 DAG.getNode(ISD::AND, N->getDebugLoc(), 3927 TruncVT, 3928 DAG.getNode(ISD::TRUNCATE, 3929 N->getDebugLoc(), 3930 TruncVT, N100), 3931 DAG.getConstant(TruncC, TruncVT))); 3932 } 3933 } 3934 3935 // fold operands of srl based on knowledge that the low bits are not 3936 // demanded. 3937 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3938 return SDValue(N, 0); 3939 3940 if (N1C) { 3941 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 3942 if (NewSRL.getNode()) 3943 return NewSRL; 3944 } 3945 3946 // Attempt to convert a srl of a load into a narrower zero-extending load. 3947 SDValue NarrowLoad = ReduceLoadWidth(N); 3948 if (NarrowLoad.getNode()) 3949 return NarrowLoad; 3950 3951 // Here is a common situation. We want to optimize: 3952 // 3953 // %a = ... 3954 // %b = and i32 %a, 2 3955 // %c = srl i32 %b, 1 3956 // brcond i32 %c ... 3957 // 3958 // into 3959 // 3960 // %a = ... 3961 // %b = and %a, 2 3962 // %c = setcc eq %b, 0 3963 // brcond %c ... 3964 // 3965 // However when after the source operand of SRL is optimized into AND, the SRL 3966 // itself may not be optimized further. Look for it and add the BRCOND into 3967 // the worklist. 3968 if (N->hasOneUse()) { 3969 SDNode *Use = *N->use_begin(); 3970 if (Use->getOpcode() == ISD::BRCOND) 3971 AddToWorkList(Use); 3972 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 3973 // Also look pass the truncate. 3974 Use = *Use->use_begin(); 3975 if (Use->getOpcode() == ISD::BRCOND) 3976 AddToWorkList(Use); 3977 } 3978 } 3979 3980 return SDValue(); 3981 } 3982 3983 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 3984 SDValue N0 = N->getOperand(0); 3985 EVT VT = N->getValueType(0); 3986 3987 // fold (ctlz c1) -> c2 3988 if (isa<ConstantSDNode>(N0)) 3989 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0); 3990 return SDValue(); 3991 } 3992 3993 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 3994 SDValue N0 = N->getOperand(0); 3995 EVT VT = N->getValueType(0); 3996 3997 // fold (ctlz_zero_undef c1) -> c2 3998 if (isa<ConstantSDNode>(N0)) 3999 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0); 4000 return SDValue(); 4001 } 4002 4003 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4004 SDValue N0 = N->getOperand(0); 4005 EVT VT = N->getValueType(0); 4006 4007 // fold (cttz c1) -> c2 4008 if (isa<ConstantSDNode>(N0)) 4009 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0); 4010 return SDValue(); 4011 } 4012 4013 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4014 SDValue N0 = N->getOperand(0); 4015 EVT VT = N->getValueType(0); 4016 4017 // fold (cttz_zero_undef c1) -> c2 4018 if (isa<ConstantSDNode>(N0)) 4019 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0); 4020 return SDValue(); 4021 } 4022 4023 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4024 SDValue N0 = N->getOperand(0); 4025 EVT VT = N->getValueType(0); 4026 4027 // fold (ctpop c1) -> c2 4028 if (isa<ConstantSDNode>(N0)) 4029 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0); 4030 return SDValue(); 4031 } 4032 4033 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4034 SDValue N0 = N->getOperand(0); 4035 SDValue N1 = N->getOperand(1); 4036 SDValue N2 = N->getOperand(2); 4037 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4038 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4039 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4040 EVT VT = N->getValueType(0); 4041 EVT VT0 = N0.getValueType(); 4042 4043 // fold (select C, X, X) -> X 4044 if (N1 == N2) 4045 return N1; 4046 // fold (select true, X, Y) -> X 4047 if (N0C && !N0C->isNullValue()) 4048 return N1; 4049 // fold (select false, X, Y) -> Y 4050 if (N0C && N0C->isNullValue()) 4051 return N2; 4052 // fold (select C, 1, X) -> (or C, X) 4053 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4054 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 4055 // fold (select C, 0, 1) -> (xor C, 1) 4056 if (VT.isInteger() && 4057 (VT0 == MVT::i1 || 4058 (VT0.isInteger() && 4059 TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) && 4060 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4061 SDValue XORNode; 4062 if (VT == VT0) 4063 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0, 4064 N0, DAG.getConstant(1, VT0)); 4065 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0, 4066 N0, DAG.getConstant(1, VT0)); 4067 AddToWorkList(XORNode.getNode()); 4068 if (VT.bitsGT(VT0)) 4069 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode); 4070 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode); 4071 } 4072 // fold (select C, 0, X) -> (and (not C), X) 4073 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4074 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 4075 AddToWorkList(NOTNode.getNode()); 4076 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2); 4077 } 4078 // fold (select C, X, 1) -> (or (not C), X) 4079 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4080 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 4081 AddToWorkList(NOTNode.getNode()); 4082 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1); 4083 } 4084 // fold (select C, X, 0) -> (and C, X) 4085 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4086 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 4087 // fold (select X, X, Y) -> (or X, Y) 4088 // fold (select X, 1, Y) -> (or X, Y) 4089 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4090 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 4091 // fold (select X, Y, X) -> (and X, Y) 4092 // fold (select X, Y, 0) -> (and X, Y) 4093 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4094 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 4095 4096 // If we can fold this based on the true/false value, do so. 4097 if (SimplifySelectOps(N, N1, N2)) 4098 return SDValue(N, 0); // Don't revisit N. 4099 4100 // fold selects based on a setcc into other things, such as min/max/abs 4101 if (N0.getOpcode() == ISD::SETCC) { 4102 // FIXME: 4103 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4104 // having to say they don't support SELECT_CC on every type the DAG knows 4105 // about, since there is no way to mark an opcode illegal at all value types 4106 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4107 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4108 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, 4109 N0.getOperand(0), N0.getOperand(1), 4110 N1, N2, N0.getOperand(2)); 4111 return SimplifySelect(N->getDebugLoc(), N0, N1, N2); 4112 } 4113 4114 return SDValue(); 4115 } 4116 4117 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4118 SDValue N0 = N->getOperand(0); 4119 SDValue N1 = N->getOperand(1); 4120 SDValue N2 = N->getOperand(2); 4121 SDValue N3 = N->getOperand(3); 4122 SDValue N4 = N->getOperand(4); 4123 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4124 4125 // fold select_cc lhs, rhs, x, x, cc -> x 4126 if (N2 == N3) 4127 return N2; 4128 4129 // Determine if the condition we're dealing with is constant 4130 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 4131 N0, N1, CC, N->getDebugLoc(), false); 4132 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 4133 4134 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 4135 if (!SCCC->isNullValue()) 4136 return N2; // cond always true -> true val 4137 else 4138 return N3; // cond always false -> false val 4139 } 4140 4141 // Fold to a simpler select_cc 4142 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC) 4143 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(), 4144 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4145 SCC.getOperand(2)); 4146 4147 // If we can fold this based on the true/false value, do so. 4148 if (SimplifySelectOps(N, N2, N3)) 4149 return SDValue(N, 0); // Don't revisit N. 4150 4151 // fold select_cc into other things, such as min/max/abs 4152 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC); 4153 } 4154 4155 SDValue DAGCombiner::visitSETCC(SDNode *N) { 4156 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4157 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4158 N->getDebugLoc()); 4159 } 4160 4161 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4162 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4163 // transformation. Returns true if extension are possible and the above 4164 // mentioned transformation is profitable. 4165 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4166 unsigned ExtOpc, 4167 SmallVector<SDNode*, 4> &ExtendNodes, 4168 const TargetLowering &TLI) { 4169 bool HasCopyToRegUses = false; 4170 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4171 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4172 UE = N0.getNode()->use_end(); 4173 UI != UE; ++UI) { 4174 SDNode *User = *UI; 4175 if (User == N) 4176 continue; 4177 if (UI.getUse().getResNo() != N0.getResNo()) 4178 continue; 4179 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4180 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4181 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4182 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4183 // Sign bits will be lost after a zext. 4184 return false; 4185 bool Add = false; 4186 for (unsigned i = 0; i != 2; ++i) { 4187 SDValue UseOp = User->getOperand(i); 4188 if (UseOp == N0) 4189 continue; 4190 if (!isa<ConstantSDNode>(UseOp)) 4191 return false; 4192 Add = true; 4193 } 4194 if (Add) 4195 ExtendNodes.push_back(User); 4196 continue; 4197 } 4198 // If truncates aren't free and there are users we can't 4199 // extend, it isn't worthwhile. 4200 if (!isTruncFree) 4201 return false; 4202 // Remember if this value is live-out. 4203 if (User->getOpcode() == ISD::CopyToReg) 4204 HasCopyToRegUses = true; 4205 } 4206 4207 if (HasCopyToRegUses) { 4208 bool BothLiveOut = false; 4209 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4210 UI != UE; ++UI) { 4211 SDUse &Use = UI.getUse(); 4212 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4213 BothLiveOut = true; 4214 break; 4215 } 4216 } 4217 if (BothLiveOut) 4218 // Both unextended and extended values are live out. There had better be 4219 // a good reason for the transformation. 4220 return ExtendNodes.size(); 4221 } 4222 return true; 4223 } 4224 4225 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs, 4226 SDValue Trunc, SDValue ExtLoad, DebugLoc DL, 4227 ISD::NodeType ExtType) { 4228 // Extend SetCC uses if necessary. 4229 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4230 SDNode *SetCC = SetCCs[i]; 4231 SmallVector<SDValue, 4> Ops; 4232 4233 for (unsigned j = 0; j != 2; ++j) { 4234 SDValue SOp = SetCC->getOperand(j); 4235 if (SOp == Trunc) 4236 Ops.push_back(ExtLoad); 4237 else 4238 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4239 } 4240 4241 Ops.push_back(SetCC->getOperand(2)); 4242 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4243 &Ops[0], Ops.size())); 4244 } 4245 } 4246 4247 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4248 SDValue N0 = N->getOperand(0); 4249 EVT VT = N->getValueType(0); 4250 4251 // fold (sext c1) -> c1 4252 if (isa<ConstantSDNode>(N0)) 4253 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0); 4254 4255 // fold (sext (sext x)) -> (sext x) 4256 // fold (sext (aext x)) -> (sext x) 4257 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4258 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, 4259 N0.getOperand(0)); 4260 4261 if (N0.getOpcode() == ISD::TRUNCATE) { 4262 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4263 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4264 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4265 if (NarrowLoad.getNode()) { 4266 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4267 if (NarrowLoad.getNode() != N0.getNode()) { 4268 CombineTo(N0.getNode(), NarrowLoad); 4269 // CombineTo deleted the truncate, if needed, but not what's under it. 4270 AddToWorkList(oye); 4271 } 4272 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4273 } 4274 4275 // See if the value being truncated is already sign extended. If so, just 4276 // eliminate the trunc/sext pair. 4277 SDValue Op = N0.getOperand(0); 4278 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4279 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4280 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4281 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4282 4283 if (OpBits == DestBits) { 4284 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4285 // bits, it is already ready. 4286 if (NumSignBits > DestBits-MidBits) 4287 return Op; 4288 } else if (OpBits < DestBits) { 4289 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4290 // bits, just sext from i32. 4291 if (NumSignBits > OpBits-MidBits) 4292 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op); 4293 } else { 4294 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4295 // bits, just truncate to i32. 4296 if (NumSignBits > OpBits-MidBits) 4297 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4298 } 4299 4300 // fold (sext (truncate x)) -> (sextinreg x). 4301 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4302 N0.getValueType())) { 4303 if (OpBits < DestBits) 4304 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op); 4305 else if (OpBits > DestBits) 4306 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op); 4307 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op, 4308 DAG.getValueType(N0.getValueType())); 4309 } 4310 } 4311 4312 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4313 // None of the supported targets knows how to perform load and sign extend 4314 // on vectors in one instruction. We only perform this transformation on 4315 // scalars. 4316 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4317 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4318 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4319 bool DoXform = true; 4320 SmallVector<SDNode*, 4> SetCCs; 4321 if (!N0.hasOneUse()) 4322 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4323 if (DoXform) { 4324 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4325 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4326 LN0->getChain(), 4327 LN0->getBasePtr(), LN0->getPointerInfo(), 4328 N0.getValueType(), 4329 LN0->isVolatile(), LN0->isNonTemporal(), 4330 LN0->getAlignment()); 4331 CombineTo(N, ExtLoad); 4332 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4333 N0.getValueType(), ExtLoad); 4334 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4335 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4336 ISD::SIGN_EXTEND); 4337 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4338 } 4339 } 4340 4341 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4342 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4343 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4344 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4345 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4346 EVT MemVT = LN0->getMemoryVT(); 4347 if ((!LegalOperations && !LN0->isVolatile()) || 4348 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4349 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4350 LN0->getChain(), 4351 LN0->getBasePtr(), LN0->getPointerInfo(), 4352 MemVT, 4353 LN0->isVolatile(), LN0->isNonTemporal(), 4354 LN0->getAlignment()); 4355 CombineTo(N, ExtLoad); 4356 CombineTo(N0.getNode(), 4357 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4358 N0.getValueType(), ExtLoad), 4359 ExtLoad.getValue(1)); 4360 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4361 } 4362 } 4363 4364 // fold (sext (and/or/xor (load x), cst)) -> 4365 // (and/or/xor (sextload x), (sext cst)) 4366 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4367 N0.getOpcode() == ISD::XOR) && 4368 isa<LoadSDNode>(N0.getOperand(0)) && 4369 N0.getOperand(1).getOpcode() == ISD::Constant && 4370 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4371 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4372 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4373 if (LN0->getExtensionType() != ISD::ZEXTLOAD) { 4374 bool DoXform = true; 4375 SmallVector<SDNode*, 4> SetCCs; 4376 if (!N0.hasOneUse()) 4377 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4378 SetCCs, TLI); 4379 if (DoXform) { 4380 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT, 4381 LN0->getChain(), LN0->getBasePtr(), 4382 LN0->getPointerInfo(), 4383 LN0->getMemoryVT(), 4384 LN0->isVolatile(), 4385 LN0->isNonTemporal(), 4386 LN0->getAlignment()); 4387 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4388 Mask = Mask.sext(VT.getSizeInBits()); 4389 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 4390 ExtLoad, DAG.getConstant(Mask, VT)); 4391 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4392 N0.getOperand(0).getDebugLoc(), 4393 N0.getOperand(0).getValueType(), ExtLoad); 4394 CombineTo(N, And); 4395 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4396 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4397 ISD::SIGN_EXTEND); 4398 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4399 } 4400 } 4401 } 4402 4403 if (N0.getOpcode() == ISD::SETCC) { 4404 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4405 // Only do this before legalize for now. 4406 if (VT.isVector() && !LegalOperations) { 4407 EVT N0VT = N0.getOperand(0).getValueType(); 4408 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 4409 // of the same size as the compared operands. Only optimize sext(setcc()) 4410 // if this is the case. 4411 EVT SVT = TLI.getSetCCResultType(N0VT); 4412 4413 // We know that the # elements of the results is the same as the 4414 // # elements of the compare (and the # elements of the compare result 4415 // for that matter). Check to see that they are the same size. If so, 4416 // we know that the element size of the sext'd result matches the 4417 // element size of the compare operands. 4418 if (VT.getSizeInBits() == SVT.getSizeInBits()) 4419 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4420 N0.getOperand(1), 4421 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4422 // If the desired elements are smaller or larger than the source 4423 // elements we can use a matching integer vector type and then 4424 // truncate/sign extend 4425 else { 4426 EVT MatchingElementType = 4427 EVT::getIntegerVT(*DAG.getContext(), 4428 N0VT.getScalarType().getSizeInBits()); 4429 EVT MatchingVectorType = 4430 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4431 N0VT.getVectorNumElements()); 4432 4433 if (SVT == MatchingVectorType) { 4434 SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, 4435 N0.getOperand(0), N0.getOperand(1), 4436 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4437 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT); 4438 } 4439 } 4440 } 4441 4442 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc) 4443 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 4444 SDValue NegOne = 4445 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 4446 SDValue SCC = 4447 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4448 NegOne, DAG.getConstant(0, VT), 4449 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4450 if (SCC.getNode()) return SCC; 4451 if (!LegalOperations || 4452 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT))) 4453 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT, 4454 DAG.getSetCC(N->getDebugLoc(), 4455 TLI.getSetCCResultType(VT), 4456 N0.getOperand(0), N0.getOperand(1), 4457 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4458 NegOne, DAG.getConstant(0, VT)); 4459 } 4460 4461 // fold (sext x) -> (zext x) if the sign bit is known zero. 4462 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 4463 DAG.SignBitIsZero(N0)) 4464 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 4465 4466 return SDValue(); 4467 } 4468 4469 // isTruncateOf - If N is a truncate of some other value, return true, record 4470 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 4471 // This function computes KnownZero to avoid a duplicated call to 4472 // ComputeMaskedBits in the caller. 4473 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 4474 APInt &KnownZero) { 4475 APInt KnownOne; 4476 if (N->getOpcode() == ISD::TRUNCATE) { 4477 Op = N->getOperand(0); 4478 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4479 return true; 4480 } 4481 4482 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 4483 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 4484 return false; 4485 4486 SDValue Op0 = N->getOperand(0); 4487 SDValue Op1 = N->getOperand(1); 4488 assert(Op0.getValueType() == Op1.getValueType()); 4489 4490 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 4491 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 4492 if (COp0 && COp0->isNullValue()) 4493 Op = Op1; 4494 else if (COp1 && COp1->isNullValue()) 4495 Op = Op0; 4496 else 4497 return false; 4498 4499 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4500 4501 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 4502 return false; 4503 4504 return true; 4505 } 4506 4507 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 4508 SDValue N0 = N->getOperand(0); 4509 EVT VT = N->getValueType(0); 4510 4511 // fold (zext c1) -> c1 4512 if (isa<ConstantSDNode>(N0)) 4513 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 4514 // fold (zext (zext x)) -> (zext x) 4515 // fold (zext (aext x)) -> (zext x) 4516 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4517 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, 4518 N0.getOperand(0)); 4519 4520 // fold (zext (truncate x)) -> (zext x) or 4521 // (zext (truncate x)) -> (truncate x) 4522 // This is valid when the truncated bits of x are already zero. 4523 // FIXME: We should extend this to work for vectors too. 4524 SDValue Op; 4525 APInt KnownZero; 4526 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 4527 APInt TruncatedBits = 4528 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 4529 APInt(Op.getValueSizeInBits(), 0) : 4530 APInt::getBitsSet(Op.getValueSizeInBits(), 4531 N0.getValueSizeInBits(), 4532 std::min(Op.getValueSizeInBits(), 4533 VT.getSizeInBits())); 4534 if (TruncatedBits == (KnownZero & TruncatedBits)) { 4535 if (VT.bitsGT(Op.getValueType())) 4536 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op); 4537 if (VT.bitsLT(Op.getValueType())) 4538 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4539 4540 return Op; 4541 } 4542 } 4543 4544 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4545 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 4546 if (N0.getOpcode() == ISD::TRUNCATE) { 4547 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4548 if (NarrowLoad.getNode()) { 4549 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4550 if (NarrowLoad.getNode() != N0.getNode()) { 4551 CombineTo(N0.getNode(), NarrowLoad); 4552 // CombineTo deleted the truncate, if needed, but not what's under it. 4553 AddToWorkList(oye); 4554 } 4555 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4556 } 4557 } 4558 4559 // fold (zext (truncate x)) -> (and x, mask) 4560 if (N0.getOpcode() == ISD::TRUNCATE && 4561 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 4562 4563 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4564 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 4565 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4566 if (NarrowLoad.getNode()) { 4567 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4568 if (NarrowLoad.getNode() != N0.getNode()) { 4569 CombineTo(N0.getNode(), NarrowLoad); 4570 // CombineTo deleted the truncate, if needed, but not what's under it. 4571 AddToWorkList(oye); 4572 } 4573 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4574 } 4575 4576 SDValue Op = N0.getOperand(0); 4577 if (Op.getValueType().bitsLT(VT)) { 4578 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op); 4579 AddToWorkList(Op.getNode()); 4580 } else if (Op.getValueType().bitsGT(VT)) { 4581 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4582 AddToWorkList(Op.getNode()); 4583 } 4584 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), 4585 N0.getValueType().getScalarType()); 4586 } 4587 4588 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 4589 // if either of the casts is not free. 4590 if (N0.getOpcode() == ISD::AND && 4591 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4592 N0.getOperand(1).getOpcode() == ISD::Constant && 4593 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4594 N0.getValueType()) || 4595 !TLI.isZExtFree(N0.getValueType(), VT))) { 4596 SDValue X = N0.getOperand(0).getOperand(0); 4597 if (X.getValueType().bitsLT(VT)) { 4598 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X); 4599 } else if (X.getValueType().bitsGT(VT)) { 4600 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 4601 } 4602 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4603 Mask = Mask.zext(VT.getSizeInBits()); 4604 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4605 X, DAG.getConstant(Mask, VT)); 4606 } 4607 4608 // fold (zext (load x)) -> (zext (truncate (zextload x))) 4609 // None of the supported targets knows how to perform load and vector_zext 4610 // on vectors in one instruction. We only perform this transformation on 4611 // scalars. 4612 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4613 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4614 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 4615 bool DoXform = true; 4616 SmallVector<SDNode*, 4> SetCCs; 4617 if (!N0.hasOneUse()) 4618 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 4619 if (DoXform) { 4620 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4621 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 4622 LN0->getChain(), 4623 LN0->getBasePtr(), LN0->getPointerInfo(), 4624 N0.getValueType(), 4625 LN0->isVolatile(), LN0->isNonTemporal(), 4626 LN0->getAlignment()); 4627 CombineTo(N, ExtLoad); 4628 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4629 N0.getValueType(), ExtLoad); 4630 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4631 4632 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4633 ISD::ZERO_EXTEND); 4634 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4635 } 4636 } 4637 4638 // fold (zext (and/or/xor (load x), cst)) -> 4639 // (and/or/xor (zextload x), (zext cst)) 4640 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4641 N0.getOpcode() == ISD::XOR) && 4642 isa<LoadSDNode>(N0.getOperand(0)) && 4643 N0.getOperand(1).getOpcode() == ISD::Constant && 4644 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 4645 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4646 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4647 if (LN0->getExtensionType() != ISD::SEXTLOAD) { 4648 bool DoXform = true; 4649 SmallVector<SDNode*, 4> SetCCs; 4650 if (!N0.hasOneUse()) 4651 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 4652 SetCCs, TLI); 4653 if (DoXform) { 4654 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, 4655 LN0->getChain(), LN0->getBasePtr(), 4656 LN0->getPointerInfo(), 4657 LN0->getMemoryVT(), 4658 LN0->isVolatile(), 4659 LN0->isNonTemporal(), 4660 LN0->getAlignment()); 4661 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4662 Mask = Mask.zext(VT.getSizeInBits()); 4663 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 4664 ExtLoad, DAG.getConstant(Mask, VT)); 4665 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4666 N0.getOperand(0).getDebugLoc(), 4667 N0.getOperand(0).getValueType(), ExtLoad); 4668 CombineTo(N, And); 4669 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4670 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4671 ISD::ZERO_EXTEND); 4672 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4673 } 4674 } 4675 } 4676 4677 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 4678 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 4679 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4680 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4681 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4682 EVT MemVT = LN0->getMemoryVT(); 4683 if ((!LegalOperations && !LN0->isVolatile()) || 4684 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 4685 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 4686 LN0->getChain(), 4687 LN0->getBasePtr(), LN0->getPointerInfo(), 4688 MemVT, 4689 LN0->isVolatile(), LN0->isNonTemporal(), 4690 LN0->getAlignment()); 4691 CombineTo(N, ExtLoad); 4692 CombineTo(N0.getNode(), 4693 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(), 4694 ExtLoad), 4695 ExtLoad.getValue(1)); 4696 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4697 } 4698 } 4699 4700 if (N0.getOpcode() == ISD::SETCC) { 4701 if (!LegalOperations && VT.isVector()) { 4702 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 4703 // Only do this before legalize for now. 4704 EVT N0VT = N0.getOperand(0).getValueType(); 4705 EVT EltVT = VT.getVectorElementType(); 4706 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 4707 DAG.getConstant(1, EltVT)); 4708 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4709 // We know that the # elements of the results is the same as the 4710 // # elements of the compare (and the # elements of the compare result 4711 // for that matter). Check to see that they are the same size. If so, 4712 // we know that the element size of the sext'd result matches the 4713 // element size of the compare operands. 4714 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4715 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4716 N0.getOperand(1), 4717 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4718 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 4719 &OneOps[0], OneOps.size())); 4720 4721 // If the desired elements are smaller or larger than the source 4722 // elements we can use a matching integer vector type and then 4723 // truncate/sign extend 4724 EVT MatchingElementType = 4725 EVT::getIntegerVT(*DAG.getContext(), 4726 N0VT.getScalarType().getSizeInBits()); 4727 EVT MatchingVectorType = 4728 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4729 N0VT.getVectorNumElements()); 4730 SDValue VsetCC = 4731 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0), 4732 N0.getOperand(1), 4733 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4734 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4735 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT), 4736 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 4737 &OneOps[0], OneOps.size())); 4738 } 4739 4740 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 4741 SDValue SCC = 4742 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4743 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 4744 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4745 if (SCC.getNode()) return SCC; 4746 } 4747 4748 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 4749 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 4750 isa<ConstantSDNode>(N0.getOperand(1)) && 4751 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 4752 N0.hasOneUse()) { 4753 SDValue ShAmt = N0.getOperand(1); 4754 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 4755 if (N0.getOpcode() == ISD::SHL) { 4756 SDValue InnerZExt = N0.getOperand(0); 4757 // If the original shl may be shifting out bits, do not perform this 4758 // transformation. 4759 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 4760 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 4761 if (ShAmtVal > KnownZeroBits) 4762 return SDValue(); 4763 } 4764 4765 DebugLoc DL = N->getDebugLoc(); 4766 4767 // Ensure that the shift amount is wide enough for the shifted value. 4768 if (VT.getSizeInBits() >= 256) 4769 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 4770 4771 return DAG.getNode(N0.getOpcode(), DL, VT, 4772 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 4773 ShAmt); 4774 } 4775 4776 return SDValue(); 4777 } 4778 4779 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 4780 SDValue N0 = N->getOperand(0); 4781 EVT VT = N->getValueType(0); 4782 4783 // fold (aext c1) -> c1 4784 if (isa<ConstantSDNode>(N0)) 4785 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0); 4786 // fold (aext (aext x)) -> (aext x) 4787 // fold (aext (zext x)) -> (zext x) 4788 // fold (aext (sext x)) -> (sext x) 4789 if (N0.getOpcode() == ISD::ANY_EXTEND || 4790 N0.getOpcode() == ISD::ZERO_EXTEND || 4791 N0.getOpcode() == ISD::SIGN_EXTEND) 4792 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0)); 4793 4794 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 4795 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 4796 if (N0.getOpcode() == ISD::TRUNCATE) { 4797 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4798 if (NarrowLoad.getNode()) { 4799 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4800 if (NarrowLoad.getNode() != N0.getNode()) { 4801 CombineTo(N0.getNode(), NarrowLoad); 4802 // CombineTo deleted the truncate, if needed, but not what's under it. 4803 AddToWorkList(oye); 4804 } 4805 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4806 } 4807 } 4808 4809 // fold (aext (truncate x)) 4810 if (N0.getOpcode() == ISD::TRUNCATE) { 4811 SDValue TruncOp = N0.getOperand(0); 4812 if (TruncOp.getValueType() == VT) 4813 return TruncOp; // x iff x size == zext size. 4814 if (TruncOp.getValueType().bitsGT(VT)) 4815 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp); 4816 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp); 4817 } 4818 4819 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 4820 // if the trunc is not free. 4821 if (N0.getOpcode() == ISD::AND && 4822 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4823 N0.getOperand(1).getOpcode() == ISD::Constant && 4824 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4825 N0.getValueType())) { 4826 SDValue X = N0.getOperand(0).getOperand(0); 4827 if (X.getValueType().bitsLT(VT)) { 4828 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X); 4829 } else if (X.getValueType().bitsGT(VT)) { 4830 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X); 4831 } 4832 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4833 Mask = Mask.zext(VT.getSizeInBits()); 4834 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4835 X, DAG.getConstant(Mask, VT)); 4836 } 4837 4838 // fold (aext (load x)) -> (aext (truncate (extload x))) 4839 // None of the supported targets knows how to perform load and any_ext 4840 // on vectors in one instruction. We only perform this transformation on 4841 // scalars. 4842 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4843 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4844 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 4845 bool DoXform = true; 4846 SmallVector<SDNode*, 4> SetCCs; 4847 if (!N0.hasOneUse()) 4848 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 4849 if (DoXform) { 4850 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4851 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 4852 LN0->getChain(), 4853 LN0->getBasePtr(), LN0->getPointerInfo(), 4854 N0.getValueType(), 4855 LN0->isVolatile(), LN0->isNonTemporal(), 4856 LN0->getAlignment()); 4857 CombineTo(N, ExtLoad); 4858 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4859 N0.getValueType(), ExtLoad); 4860 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4861 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4862 ISD::ANY_EXTEND); 4863 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4864 } 4865 } 4866 4867 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 4868 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 4869 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 4870 if (N0.getOpcode() == ISD::LOAD && 4871 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4872 N0.hasOneUse()) { 4873 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4874 EVT MemVT = LN0->getMemoryVT(); 4875 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(), 4876 VT, LN0->getChain(), LN0->getBasePtr(), 4877 LN0->getPointerInfo(), MemVT, 4878 LN0->isVolatile(), LN0->isNonTemporal(), 4879 LN0->getAlignment()); 4880 CombineTo(N, ExtLoad); 4881 CombineTo(N0.getNode(), 4882 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4883 N0.getValueType(), ExtLoad), 4884 ExtLoad.getValue(1)); 4885 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4886 } 4887 4888 if (N0.getOpcode() == ISD::SETCC) { 4889 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 4890 // Only do this before legalize for now. 4891 if (VT.isVector() && !LegalOperations) { 4892 EVT N0VT = N0.getOperand(0).getValueType(); 4893 // We know that the # elements of the results is the same as the 4894 // # elements of the compare (and the # elements of the compare result 4895 // for that matter). Check to see that they are the same size. If so, 4896 // we know that the element size of the sext'd result matches the 4897 // element size of the compare operands. 4898 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4899 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4900 N0.getOperand(1), 4901 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4902 // If the desired elements are smaller or larger than the source 4903 // elements we can use a matching integer vector type and then 4904 // truncate/sign extend 4905 else { 4906 EVT MatchingElementType = 4907 EVT::getIntegerVT(*DAG.getContext(), 4908 N0VT.getScalarType().getSizeInBits()); 4909 EVT MatchingVectorType = 4910 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4911 N0VT.getVectorNumElements()); 4912 SDValue VsetCC = 4913 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0), 4914 N0.getOperand(1), 4915 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4916 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT); 4917 } 4918 } 4919 4920 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 4921 SDValue SCC = 4922 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4923 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 4924 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4925 if (SCC.getNode()) 4926 return SCC; 4927 } 4928 4929 return SDValue(); 4930 } 4931 4932 /// GetDemandedBits - See if the specified operand can be simplified with the 4933 /// knowledge that only the bits specified by Mask are used. If so, return the 4934 /// simpler operand, otherwise return a null SDValue. 4935 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 4936 switch (V.getOpcode()) { 4937 default: break; 4938 case ISD::Constant: { 4939 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 4940 assert(CV != 0 && "Const value should be ConstSDNode."); 4941 const APInt &CVal = CV->getAPIntValue(); 4942 APInt NewVal = CVal & Mask; 4943 if (NewVal != CVal) { 4944 return DAG.getConstant(NewVal, V.getValueType()); 4945 } 4946 break; 4947 } 4948 case ISD::OR: 4949 case ISD::XOR: 4950 // If the LHS or RHS don't contribute bits to the or, drop them. 4951 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 4952 return V.getOperand(1); 4953 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 4954 return V.getOperand(0); 4955 break; 4956 case ISD::SRL: 4957 // Only look at single-use SRLs. 4958 if (!V.getNode()->hasOneUse()) 4959 break; 4960 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 4961 // See if we can recursively simplify the LHS. 4962 unsigned Amt = RHSC->getZExtValue(); 4963 4964 // Watch out for shift count overflow though. 4965 if (Amt >= Mask.getBitWidth()) break; 4966 APInt NewMask = Mask << Amt; 4967 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 4968 if (SimplifyLHS.getNode()) 4969 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(), 4970 SimplifyLHS, V.getOperand(1)); 4971 } 4972 } 4973 return SDValue(); 4974 } 4975 4976 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N 4977 /// bits and then truncated to a narrower type and where N is a multiple 4978 /// of number of bits of the narrower type, transform it to a narrower load 4979 /// from address + N / num of bits of new type. If the result is to be 4980 /// extended, also fold the extension to form a extending load. 4981 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 4982 unsigned Opc = N->getOpcode(); 4983 4984 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 4985 SDValue N0 = N->getOperand(0); 4986 EVT VT = N->getValueType(0); 4987 EVT ExtVT = VT; 4988 4989 // This transformation isn't valid for vector loads. 4990 if (VT.isVector()) 4991 return SDValue(); 4992 4993 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 4994 // extended to VT. 4995 if (Opc == ISD::SIGN_EXTEND_INREG) { 4996 ExtType = ISD::SEXTLOAD; 4997 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 4998 } else if (Opc == ISD::SRL) { 4999 // Another special-case: SRL is basically zero-extending a narrower value. 5000 ExtType = ISD::ZEXTLOAD; 5001 N0 = SDValue(N, 0); 5002 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5003 if (!N01) return SDValue(); 5004 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5005 VT.getSizeInBits() - N01->getZExtValue()); 5006 } 5007 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5008 return SDValue(); 5009 5010 unsigned EVTBits = ExtVT.getSizeInBits(); 5011 5012 // Do not generate loads of non-round integer types since these can 5013 // be expensive (and would be wrong if the type is not byte sized). 5014 if (!ExtVT.isRound()) 5015 return SDValue(); 5016 5017 unsigned ShAmt = 0; 5018 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5019 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5020 ShAmt = N01->getZExtValue(); 5021 // Is the shift amount a multiple of size of VT? 5022 if ((ShAmt & (EVTBits-1)) == 0) { 5023 N0 = N0.getOperand(0); 5024 // Is the load width a multiple of size of VT? 5025 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5026 return SDValue(); 5027 } 5028 5029 // At this point, we must have a load or else we can't do the transform. 5030 if (!isa<LoadSDNode>(N0)) return SDValue(); 5031 5032 // If the shift amount is larger than the input type then we're not 5033 // accessing any of the loaded bytes. If the load was a zextload/extload 5034 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5035 // If the load was a sextload then the result is a splat of the sign bit 5036 // of the extended byte. This is not worth optimizing for. 5037 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5038 return SDValue(); 5039 } 5040 } 5041 5042 // If the load is shifted left (and the result isn't shifted back right), 5043 // we can fold the truncate through the shift. 5044 unsigned ShLeftAmt = 0; 5045 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5046 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5047 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5048 ShLeftAmt = N01->getZExtValue(); 5049 N0 = N0.getOperand(0); 5050 } 5051 } 5052 5053 // If we haven't found a load, we can't narrow it. Don't transform one with 5054 // multiple uses, this would require adding a new load. 5055 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() || 5056 // Don't change the width of a volatile load. 5057 cast<LoadSDNode>(N0)->isVolatile()) 5058 return SDValue(); 5059 5060 // Verify that we are actually reducing a load width here. 5061 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits) 5062 return SDValue(); 5063 5064 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5065 EVT PtrType = N0.getOperand(1).getValueType(); 5066 5067 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5068 // It's not possible to generate a constant of extended or untyped type. 5069 return SDValue(); 5070 5071 // For big endian targets, we need to adjust the offset to the pointer to 5072 // load the correct bytes. 5073 if (TLI.isBigEndian()) { 5074 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5075 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5076 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5077 } 5078 5079 uint64_t PtrOff = ShAmt / 8; 5080 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5081 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), 5082 PtrType, LN0->getBasePtr(), 5083 DAG.getConstant(PtrOff, PtrType)); 5084 AddToWorkList(NewPtr.getNode()); 5085 5086 SDValue Load; 5087 if (ExtType == ISD::NON_EXTLOAD) 5088 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr, 5089 LN0->getPointerInfo().getWithOffset(PtrOff), 5090 LN0->isVolatile(), LN0->isNonTemporal(), 5091 LN0->isInvariant(), NewAlign); 5092 else 5093 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr, 5094 LN0->getPointerInfo().getWithOffset(PtrOff), 5095 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5096 NewAlign); 5097 5098 // Replace the old load's chain with the new load's chain. 5099 WorkListRemover DeadNodes(*this); 5100 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5101 5102 // Shift the result left, if we've swallowed a left shift. 5103 SDValue Result = Load; 5104 if (ShLeftAmt != 0) { 5105 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5106 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5107 ShImmTy = VT; 5108 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, 5109 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5110 } 5111 5112 // Return the new loaded value. 5113 return Result; 5114 } 5115 5116 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5117 SDValue N0 = N->getOperand(0); 5118 SDValue N1 = N->getOperand(1); 5119 EVT VT = N->getValueType(0); 5120 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5121 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5122 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5123 5124 // fold (sext_in_reg c1) -> c1 5125 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5126 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1); 5127 5128 // If the input is already sign extended, just drop the extension. 5129 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5130 return N0; 5131 5132 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5133 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5134 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) { 5135 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 5136 N0.getOperand(0), N1); 5137 } 5138 5139 // fold (sext_in_reg (sext x)) -> (sext x) 5140 // fold (sext_in_reg (aext x)) -> (sext x) 5141 // if x is small enough. 5142 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5143 SDValue N00 = N0.getOperand(0); 5144 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5145 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5146 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1); 5147 } 5148 5149 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5150 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5151 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT); 5152 5153 // fold operands of sext_in_reg based on knowledge that the top bits are not 5154 // demanded. 5155 if (SimplifyDemandedBits(SDValue(N, 0))) 5156 return SDValue(N, 0); 5157 5158 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5159 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5160 SDValue NarrowLoad = ReduceLoadWidth(N); 5161 if (NarrowLoad.getNode()) 5162 return NarrowLoad; 5163 5164 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5165 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5166 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5167 if (N0.getOpcode() == ISD::SRL) { 5168 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5169 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5170 // We can turn this into an SRA iff the input to the SRL is already sign 5171 // extended enough. 5172 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5173 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5174 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, 5175 N0.getOperand(0), N0.getOperand(1)); 5176 } 5177 } 5178 5179 // fold (sext_inreg (extload x)) -> (sextload x) 5180 if (ISD::isEXTLoad(N0.getNode()) && 5181 ISD::isUNINDEXEDLoad(N0.getNode()) && 5182 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5183 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5184 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5185 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5186 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 5187 LN0->getChain(), 5188 LN0->getBasePtr(), LN0->getPointerInfo(), 5189 EVT, 5190 LN0->isVolatile(), LN0->isNonTemporal(), 5191 LN0->getAlignment()); 5192 CombineTo(N, ExtLoad); 5193 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5194 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5195 } 5196 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5197 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5198 N0.hasOneUse() && 5199 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5200 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5201 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5202 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5203 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 5204 LN0->getChain(), 5205 LN0->getBasePtr(), LN0->getPointerInfo(), 5206 EVT, 5207 LN0->isVolatile(), LN0->isNonTemporal(), 5208 LN0->getAlignment()); 5209 CombineTo(N, ExtLoad); 5210 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5211 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5212 } 5213 5214 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5215 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5216 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5217 N0.getOperand(1), false); 5218 if (BSwap.getNode() != 0) 5219 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 5220 BSwap, N1); 5221 } 5222 5223 return SDValue(); 5224 } 5225 5226 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5227 SDValue N0 = N->getOperand(0); 5228 EVT VT = N->getValueType(0); 5229 bool isLE = TLI.isLittleEndian(); 5230 5231 // noop truncate 5232 if (N0.getValueType() == N->getValueType(0)) 5233 return N0; 5234 // fold (truncate c1) -> c1 5235 if (isa<ConstantSDNode>(N0)) 5236 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0); 5237 // fold (truncate (truncate x)) -> (truncate x) 5238 if (N0.getOpcode() == ISD::TRUNCATE) 5239 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 5240 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5241 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5242 N0.getOpcode() == ISD::SIGN_EXTEND || 5243 N0.getOpcode() == ISD::ANY_EXTEND) { 5244 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5245 // if the source is smaller than the dest, we still need an extend 5246 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 5247 N0.getOperand(0)); 5248 else if (N0.getOperand(0).getValueType().bitsGT(VT)) 5249 // if the source is larger than the dest, than we just need the truncate 5250 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 5251 else 5252 // if the source and dest are the same type, we can drop both the extend 5253 // and the truncate. 5254 return N0.getOperand(0); 5255 } 5256 5257 // Fold extract-and-trunc into a narrow extract. For example: 5258 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5259 // i32 y = TRUNCATE(i64 x) 5260 // -- becomes -- 5261 // v16i8 b = BITCAST (v2i64 val) 5262 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5263 // 5264 // Note: We only run this optimization after type legalization (which often 5265 // creates this pattern) and before operation legalization after which 5266 // we need to be more careful about the vector instructions that we generate. 5267 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5268 LegalTypes && !LegalOperations && N0->hasOneUse()) { 5269 5270 EVT VecTy = N0.getOperand(0).getValueType(); 5271 EVT ExTy = N0.getValueType(); 5272 EVT TrTy = N->getValueType(0); 5273 5274 unsigned NumElem = VecTy.getVectorNumElements(); 5275 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5276 5277 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5278 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5279 5280 SDValue EltNo = N0->getOperand(1); 5281 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5282 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5283 EVT IndexTy = N0->getOperand(1).getValueType(); 5284 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5285 5286 SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 5287 NVT, N0.getOperand(0)); 5288 5289 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5290 N->getDebugLoc(), TrTy, V, 5291 DAG.getConstant(Index, IndexTy)); 5292 } 5293 } 5294 5295 // See if we can simplify the input to this truncate through knowledge that 5296 // only the low bits are being used. 5297 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5298 // Currently we only perform this optimization on scalars because vectors 5299 // may have different active low bits. 5300 if (!VT.isVector()) { 5301 SDValue Shorter = 5302 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5303 VT.getSizeInBits())); 5304 if (Shorter.getNode()) 5305 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter); 5306 } 5307 // fold (truncate (load x)) -> (smaller load x) 5308 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5309 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5310 SDValue Reduced = ReduceLoadWidth(N); 5311 if (Reduced.getNode()) 5312 return Reduced; 5313 } 5314 5315 // Simplify the operands using demanded-bits information. 5316 if (!VT.isVector() && 5317 SimplifyDemandedBits(SDValue(N, 0))) 5318 return SDValue(N, 0); 5319 5320 return SDValue(); 5321 } 5322 5323 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 5324 SDValue Elt = N->getOperand(i); 5325 if (Elt.getOpcode() != ISD::MERGE_VALUES) 5326 return Elt.getNode(); 5327 return Elt.getOperand(Elt.getResNo()).getNode(); 5328 } 5329 5330 /// CombineConsecutiveLoads - build_pair (load, load) -> load 5331 /// if load locations are consecutive. 5332 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 5333 assert(N->getOpcode() == ISD::BUILD_PAIR); 5334 5335 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 5336 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 5337 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 5338 LD1->getPointerInfo().getAddrSpace() != 5339 LD2->getPointerInfo().getAddrSpace()) 5340 return SDValue(); 5341 EVT LD1VT = LD1->getValueType(0); 5342 5343 if (ISD::isNON_EXTLoad(LD2) && 5344 LD2->hasOneUse() && 5345 // If both are volatile this would reduce the number of volatile loads. 5346 // If one is volatile it might be ok, but play conservative and bail out. 5347 !LD1->isVolatile() && 5348 !LD2->isVolatile() && 5349 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 5350 unsigned Align = LD1->getAlignment(); 5351 unsigned NewAlign = TLI.getTargetData()-> 5352 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5353 5354 if (NewAlign <= Align && 5355 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 5356 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(), 5357 LD1->getBasePtr(), LD1->getPointerInfo(), 5358 false, false, false, Align); 5359 } 5360 5361 return SDValue(); 5362 } 5363 5364 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 5365 SDValue N0 = N->getOperand(0); 5366 EVT VT = N->getValueType(0); 5367 5368 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 5369 // Only do this before legalize, since afterward the target may be depending 5370 // on the bitconvert. 5371 // First check to see if this is all constant. 5372 if (!LegalTypes && 5373 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 5374 VT.isVector()) { 5375 bool isSimple = true; 5376 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) 5377 if (N0.getOperand(i).getOpcode() != ISD::UNDEF && 5378 N0.getOperand(i).getOpcode() != ISD::Constant && 5379 N0.getOperand(i).getOpcode() != ISD::ConstantFP) { 5380 isSimple = false; 5381 break; 5382 } 5383 5384 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 5385 assert(!DestEltVT.isVector() && 5386 "Element type of vector ValueType must not be vector!"); 5387 if (isSimple) 5388 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 5389 } 5390 5391 // If the input is a constant, let getNode fold it. 5392 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 5393 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0); 5394 if (Res.getNode() != N) { 5395 if (!LegalOperations || 5396 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 5397 return Res; 5398 5399 // Folding it resulted in an illegal node, and it's too late to 5400 // do that. Clean up the old node and forego the transformation. 5401 // Ideally this won't happen very often, because instcombine 5402 // and the earlier dagcombine runs (where illegal nodes are 5403 // permitted) should have folded most of them already. 5404 DAG.DeleteNode(Res.getNode()); 5405 } 5406 } 5407 5408 // (conv (conv x, t1), t2) -> (conv x, t2) 5409 if (N0.getOpcode() == ISD::BITCAST) 5410 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, 5411 N0.getOperand(0)); 5412 5413 // fold (conv (load x)) -> (load (conv*)x) 5414 // If the resultant load doesn't need a higher alignment than the original! 5415 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 5416 // Do not change the width of a volatile load. 5417 !cast<LoadSDNode>(N0)->isVolatile() && 5418 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) { 5419 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5420 unsigned Align = TLI.getTargetData()-> 5421 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5422 unsigned OrigAlign = LN0->getAlignment(); 5423 5424 if (Align <= OrigAlign) { 5425 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(), 5426 LN0->getBasePtr(), LN0->getPointerInfo(), 5427 LN0->isVolatile(), LN0->isNonTemporal(), 5428 LN0->isInvariant(), OrigAlign); 5429 AddToWorkList(N); 5430 CombineTo(N0.getNode(), 5431 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5432 N0.getValueType(), Load), 5433 Load.getValue(1)); 5434 return Load; 5435 } 5436 } 5437 5438 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 5439 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 5440 // This often reduces constant pool loads. 5441 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) || 5442 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) && 5443 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) { 5444 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT, 5445 N0.getOperand(0)); 5446 AddToWorkList(NewConv.getNode()); 5447 5448 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5449 if (N0.getOpcode() == ISD::FNEG) 5450 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 5451 NewConv, DAG.getConstant(SignBit, VT)); 5452 assert(N0.getOpcode() == ISD::FABS); 5453 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 5454 NewConv, DAG.getConstant(~SignBit, VT)); 5455 } 5456 5457 // fold (bitconvert (fcopysign cst, x)) -> 5458 // (or (and (bitconvert x), sign), (and cst, (not sign))) 5459 // Note that we don't handle (copysign x, cst) because this can always be 5460 // folded to an fneg or fabs. 5461 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 5462 isa<ConstantFPSDNode>(N0.getOperand(0)) && 5463 VT.isInteger() && !VT.isVector()) { 5464 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 5465 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 5466 if (isTypeLegal(IntXVT)) { 5467 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5468 IntXVT, N0.getOperand(1)); 5469 AddToWorkList(X.getNode()); 5470 5471 // If X has a different width than the result/lhs, sext it or truncate it. 5472 unsigned VTWidth = VT.getSizeInBits(); 5473 if (OrigXWidth < VTWidth) { 5474 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X); 5475 AddToWorkList(X.getNode()); 5476 } else if (OrigXWidth > VTWidth) { 5477 // To get the sign bit in the right place, we have to shift it right 5478 // before truncating. 5479 X = DAG.getNode(ISD::SRL, X.getDebugLoc(), 5480 X.getValueType(), X, 5481 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 5482 AddToWorkList(X.getNode()); 5483 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 5484 AddToWorkList(X.getNode()); 5485 } 5486 5487 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5488 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT, 5489 X, DAG.getConstant(SignBit, VT)); 5490 AddToWorkList(X.getNode()); 5491 5492 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5493 VT, N0.getOperand(0)); 5494 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT, 5495 Cst, DAG.getConstant(~SignBit, VT)); 5496 AddToWorkList(Cst.getNode()); 5497 5498 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst); 5499 } 5500 } 5501 5502 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 5503 if (N0.getOpcode() == ISD::BUILD_PAIR) { 5504 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 5505 if (CombineLD.getNode()) 5506 return CombineLD; 5507 } 5508 5509 return SDValue(); 5510 } 5511 5512 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 5513 EVT VT = N->getValueType(0); 5514 return CombineConsecutiveLoads(N, VT); 5515 } 5516 5517 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 5518 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 5519 /// destination element value type. 5520 SDValue DAGCombiner:: 5521 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 5522 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 5523 5524 // If this is already the right type, we're done. 5525 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 5526 5527 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 5528 unsigned DstBitSize = DstEltVT.getSizeInBits(); 5529 5530 // If this is a conversion of N elements of one type to N elements of another 5531 // type, convert each element. This handles FP<->INT cases. 5532 if (SrcBitSize == DstBitSize) { 5533 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5534 BV->getValueType(0).getVectorNumElements()); 5535 5536 // Due to the FP element handling below calling this routine recursively, 5537 // we can end up with a scalar-to-vector node here. 5538 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 5539 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT, 5540 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(), 5541 DstEltVT, BV->getOperand(0))); 5542 5543 SmallVector<SDValue, 8> Ops; 5544 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5545 SDValue Op = BV->getOperand(i); 5546 // If the vector element type is not legal, the BUILD_VECTOR operands 5547 // are promoted and implicitly truncated. Make that explicit here. 5548 if (Op.getValueType() != SrcEltVT) 5549 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op); 5550 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(), 5551 DstEltVT, Op)); 5552 AddToWorkList(Ops.back().getNode()); 5553 } 5554 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5555 &Ops[0], Ops.size()); 5556 } 5557 5558 // Otherwise, we're growing or shrinking the elements. To avoid having to 5559 // handle annoying details of growing/shrinking FP values, we convert them to 5560 // int first. 5561 if (SrcEltVT.isFloatingPoint()) { 5562 // Convert the input float vector to a int vector where the elements are the 5563 // same sizes. 5564 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 5565 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 5566 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 5567 SrcEltVT = IntVT; 5568 } 5569 5570 // Now we know the input is an integer vector. If the output is a FP type, 5571 // convert to integer first, then to FP of the right size. 5572 if (DstEltVT.isFloatingPoint()) { 5573 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 5574 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 5575 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 5576 5577 // Next, convert to FP elements of the same size. 5578 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 5579 } 5580 5581 // Okay, we know the src/dst types are both integers of differing types. 5582 // Handling growing first. 5583 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 5584 if (SrcBitSize < DstBitSize) { 5585 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 5586 5587 SmallVector<SDValue, 8> Ops; 5588 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 5589 i += NumInputsPerOutput) { 5590 bool isLE = TLI.isLittleEndian(); 5591 APInt NewBits = APInt(DstBitSize, 0); 5592 bool EltIsUndef = true; 5593 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 5594 // Shift the previously computed bits over. 5595 NewBits <<= SrcBitSize; 5596 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 5597 if (Op.getOpcode() == ISD::UNDEF) continue; 5598 EltIsUndef = false; 5599 5600 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 5601 zextOrTrunc(SrcBitSize).zext(DstBitSize); 5602 } 5603 5604 if (EltIsUndef) 5605 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5606 else 5607 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 5608 } 5609 5610 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 5611 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5612 &Ops[0], Ops.size()); 5613 } 5614 5615 // Finally, this must be the case where we are shrinking elements: each input 5616 // turns into multiple outputs. 5617 bool isS2V = ISD::isScalarToVector(BV); 5618 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 5619 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5620 NumOutputsPerInput*BV->getNumOperands()); 5621 SmallVector<SDValue, 8> Ops; 5622 5623 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5624 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 5625 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 5626 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5627 continue; 5628 } 5629 5630 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 5631 getAPIntValue().zextOrTrunc(SrcBitSize); 5632 5633 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 5634 APInt ThisVal = OpVal.trunc(DstBitSize); 5635 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 5636 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 5637 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 5638 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT, 5639 Ops[0]); 5640 OpVal = OpVal.lshr(DstBitSize); 5641 } 5642 5643 // For big endian targets, swap the order of the pieces of each element. 5644 if (TLI.isBigEndian()) 5645 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 5646 } 5647 5648 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5649 &Ops[0], Ops.size()); 5650 } 5651 5652 SDValue DAGCombiner::visitFADD(SDNode *N) { 5653 SDValue N0 = N->getOperand(0); 5654 SDValue N1 = N->getOperand(1); 5655 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5656 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5657 EVT VT = N->getValueType(0); 5658 5659 // fold vector ops 5660 if (VT.isVector()) { 5661 SDValue FoldedVOp = SimplifyVBinOp(N); 5662 if (FoldedVOp.getNode()) return FoldedVOp; 5663 } 5664 5665 // fold (fadd c1, c2) -> c1 + c2 5666 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5667 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1); 5668 // canonicalize constant to RHS 5669 if (N0CFP && !N1CFP) 5670 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0); 5671 // fold (fadd A, 0) -> A 5672 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5673 N1CFP->getValueAPF().isZero()) 5674 return N0; 5675 // fold (fadd A, (fneg B)) -> (fsub A, B) 5676 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5677 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5678 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, 5679 GetNegatedExpression(N1, DAG, LegalOperations)); 5680 // fold (fadd (fneg A), B) -> (fsub B, A) 5681 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5682 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5683 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1, 5684 GetNegatedExpression(N0, DAG, LegalOperations)); 5685 5686 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 5687 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5688 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 5689 isa<ConstantFPSDNode>(N0.getOperand(1))) 5690 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0), 5691 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5692 N0.getOperand(1), N1)); 5693 5694 // In unsafe math mode, we can fold chains of FADD's of the same value 5695 // into multiplications. This transform is not safe in general because 5696 // we are reducing the number of rounding steps. 5697 if (DAG.getTarget().Options.UnsafeFPMath && 5698 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 5699 !N0CFP && !N1CFP) { 5700 if (N0.getOpcode() == ISD::FMUL) { 5701 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 5702 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 5703 5704 // (fadd (fmul c, x), x) -> (fmul c+1, x) 5705 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 5706 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5707 SDValue(CFP00, 0), 5708 DAG.getConstantFP(1.0, VT)); 5709 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5710 N1, NewCFP); 5711 } 5712 5713 // (fadd (fmul x, c), x) -> (fmul c+1, x) 5714 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 5715 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5716 SDValue(CFP01, 0), 5717 DAG.getConstantFP(1.0, VT)); 5718 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5719 N1, NewCFP); 5720 } 5721 5722 // (fadd (fadd x, x), x) -> (fmul 3.0, x) 5723 if (!CFP00 && !CFP01 && N0.getOperand(0) == N0.getOperand(1) && 5724 N0.getOperand(0) == N1) { 5725 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5726 N1, DAG.getConstantFP(3.0, VT)); 5727 } 5728 5729 // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x) 5730 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 5731 N1.getOperand(0) == N1.getOperand(1) && 5732 N0.getOperand(1) == N1.getOperand(0)) { 5733 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5734 SDValue(CFP00, 0), 5735 DAG.getConstantFP(2.0, VT)); 5736 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5737 N0.getOperand(1), NewCFP); 5738 } 5739 5740 // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x) 5741 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 5742 N1.getOperand(0) == N1.getOperand(1) && 5743 N0.getOperand(0) == N1.getOperand(0)) { 5744 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5745 SDValue(CFP01, 0), 5746 DAG.getConstantFP(2.0, VT)); 5747 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5748 N0.getOperand(0), NewCFP); 5749 } 5750 } 5751 5752 if (N1.getOpcode() == ISD::FMUL) { 5753 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 5754 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 5755 5756 // (fadd x, (fmul c, x)) -> (fmul c+1, x) 5757 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 5758 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5759 SDValue(CFP10, 0), 5760 DAG.getConstantFP(1.0, VT)); 5761 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5762 N0, NewCFP); 5763 } 5764 5765 // (fadd x, (fmul x, c)) -> (fmul c+1, x) 5766 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 5767 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5768 SDValue(CFP11, 0), 5769 DAG.getConstantFP(1.0, VT)); 5770 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5771 N0, NewCFP); 5772 } 5773 5774 // (fadd x, (fadd x, x)) -> (fmul 3.0, x) 5775 if (!CFP10 && !CFP11 && N1.getOperand(0) == N1.getOperand(1) && 5776 N1.getOperand(0) == N0) { 5777 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5778 N0, DAG.getConstantFP(3.0, VT)); 5779 } 5780 5781 // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x) 5782 if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD && 5783 N1.getOperand(0) == N1.getOperand(1) && 5784 N0.getOperand(1) == N1.getOperand(0)) { 5785 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5786 SDValue(CFP10, 0), 5787 DAG.getConstantFP(2.0, VT)); 5788 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5789 N0.getOperand(1), NewCFP); 5790 } 5791 5792 // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x) 5793 if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD && 5794 N1.getOperand(0) == N1.getOperand(1) && 5795 N0.getOperand(0) == N1.getOperand(0)) { 5796 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5797 SDValue(CFP11, 0), 5798 DAG.getConstantFP(2.0, VT)); 5799 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5800 N0.getOperand(0), NewCFP); 5801 } 5802 } 5803 5804 // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x) 5805 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 5806 N0.getOperand(0) == N0.getOperand(1) && 5807 N1.getOperand(0) == N1.getOperand(1) && 5808 N0.getOperand(0) == N1.getOperand(0)) { 5809 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5810 N0.getOperand(0), 5811 DAG.getConstantFP(4.0, VT)); 5812 } 5813 } 5814 5815 // FADD -> FMA combines: 5816 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 5817 DAG.getTarget().Options.UnsafeFPMath) && 5818 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) && 5819 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) { 5820 5821 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 5822 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) { 5823 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, 5824 N0.getOperand(0), N0.getOperand(1), N1); 5825 } 5826 5827 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 5828 // Note: Commutes FADD operands. 5829 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) { 5830 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, 5831 N1.getOperand(0), N1.getOperand(1), N0); 5832 } 5833 } 5834 5835 return SDValue(); 5836 } 5837 5838 SDValue DAGCombiner::visitFSUB(SDNode *N) { 5839 SDValue N0 = N->getOperand(0); 5840 SDValue N1 = N->getOperand(1); 5841 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5842 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5843 EVT VT = N->getValueType(0); 5844 DebugLoc dl = N->getDebugLoc(); 5845 5846 // fold vector ops 5847 if (VT.isVector()) { 5848 SDValue FoldedVOp = SimplifyVBinOp(N); 5849 if (FoldedVOp.getNode()) return FoldedVOp; 5850 } 5851 5852 // fold (fsub c1, c2) -> c1-c2 5853 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5854 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1); 5855 // fold (fsub A, 0) -> A 5856 if (DAG.getTarget().Options.UnsafeFPMath && 5857 N1CFP && N1CFP->getValueAPF().isZero()) 5858 return N0; 5859 // fold (fsub 0, B) -> -B 5860 if (DAG.getTarget().Options.UnsafeFPMath && 5861 N0CFP && N0CFP->getValueAPF().isZero()) { 5862 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 5863 return GetNegatedExpression(N1, DAG, LegalOperations); 5864 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 5865 return DAG.getNode(ISD::FNEG, dl, VT, N1); 5866 } 5867 // fold (fsub A, (fneg B)) -> (fadd A, B) 5868 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 5869 return DAG.getNode(ISD::FADD, dl, VT, N0, 5870 GetNegatedExpression(N1, DAG, LegalOperations)); 5871 5872 // If 'unsafe math' is enabled, fold 5873 // (fsub x, x) -> 0.0 & 5874 // (fsub x, (fadd x, y)) -> (fneg y) & 5875 // (fsub x, (fadd y, x)) -> (fneg y) 5876 if (DAG.getTarget().Options.UnsafeFPMath) { 5877 if (N0 == N1) 5878 return DAG.getConstantFP(0.0f, VT); 5879 5880 if (N1.getOpcode() == ISD::FADD) { 5881 SDValue N10 = N1->getOperand(0); 5882 SDValue N11 = N1->getOperand(1); 5883 5884 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 5885 &DAG.getTarget().Options)) 5886 return GetNegatedExpression(N11, DAG, LegalOperations); 5887 else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 5888 &DAG.getTarget().Options)) 5889 return GetNegatedExpression(N10, DAG, LegalOperations); 5890 } 5891 } 5892 5893 // FSUB -> FMA combines: 5894 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 5895 DAG.getTarget().Options.UnsafeFPMath) && 5896 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) && 5897 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) { 5898 5899 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 5900 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) { 5901 return DAG.getNode(ISD::FMA, dl, VT, 5902 N0.getOperand(0), N0.getOperand(1), 5903 DAG.getNode(ISD::FNEG, dl, VT, N1)); 5904 } 5905 5906 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 5907 // Note: Commutes FSUB operands. 5908 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) { 5909 return DAG.getNode(ISD::FMA, dl, VT, 5910 DAG.getNode(ISD::FNEG, dl, VT, 5911 N1.getOperand(0)), 5912 N1.getOperand(1), N0); 5913 } 5914 5915 // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 5916 if (N0.getOpcode() == ISD::FNEG && 5917 N0.getOperand(0).getOpcode() == ISD::FMUL && 5918 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 5919 SDValue N00 = N0.getOperand(0).getOperand(0); 5920 SDValue N01 = N0.getOperand(0).getOperand(1); 5921 return DAG.getNode(ISD::FMA, dl, VT, 5922 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 5923 DAG.getNode(ISD::FNEG, dl, VT, N1)); 5924 } 5925 } 5926 5927 return SDValue(); 5928 } 5929 5930 SDValue DAGCombiner::visitFMUL(SDNode *N) { 5931 SDValue N0 = N->getOperand(0); 5932 SDValue N1 = N->getOperand(1); 5933 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5934 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5935 EVT VT = N->getValueType(0); 5936 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5937 5938 // fold vector ops 5939 if (VT.isVector()) { 5940 SDValue FoldedVOp = SimplifyVBinOp(N); 5941 if (FoldedVOp.getNode()) return FoldedVOp; 5942 } 5943 5944 // fold (fmul c1, c2) -> c1*c2 5945 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5946 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1); 5947 // canonicalize constant to RHS 5948 if (N0CFP && !N1CFP) 5949 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0); 5950 // fold (fmul A, 0) -> 0 5951 if (DAG.getTarget().Options.UnsafeFPMath && 5952 N1CFP && N1CFP->getValueAPF().isZero()) 5953 return N1; 5954 // fold (fmul A, 0) -> 0, vector edition. 5955 if (DAG.getTarget().Options.UnsafeFPMath && 5956 ISD::isBuildVectorAllZeros(N1.getNode())) 5957 return N1; 5958 // fold (fmul A, 1.0) -> A 5959 if (N1CFP && N1CFP->isExactlyValue(1.0)) 5960 return N0; 5961 // fold (fmul X, 2.0) -> (fadd X, X) 5962 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 5963 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0); 5964 // fold (fmul X, -1.0) -> (fneg X) 5965 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 5966 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 5967 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0); 5968 5969 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 5970 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 5971 &DAG.getTarget().Options)) { 5972 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 5973 &DAG.getTarget().Options)) { 5974 // Both can be negated for free, check to see if at least one is cheaper 5975 // negated. 5976 if (LHSNeg == 2 || RHSNeg == 2) 5977 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5978 GetNegatedExpression(N0, DAG, LegalOperations), 5979 GetNegatedExpression(N1, DAG, LegalOperations)); 5980 } 5981 } 5982 5983 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 5984 if (DAG.getTarget().Options.UnsafeFPMath && 5985 N1CFP && N0.getOpcode() == ISD::FMUL && 5986 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 5987 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0), 5988 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5989 N0.getOperand(1), N1)); 5990 5991 return SDValue(); 5992 } 5993 5994 SDValue DAGCombiner::visitFMA(SDNode *N) { 5995 SDValue N0 = N->getOperand(0); 5996 SDValue N1 = N->getOperand(1); 5997 SDValue N2 = N->getOperand(2); 5998 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5999 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6000 EVT VT = N->getValueType(0); 6001 DebugLoc dl = N->getDebugLoc(); 6002 6003 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6004 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2); 6005 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6006 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2); 6007 6008 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6009 if (N0CFP && !N1CFP) 6010 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2); 6011 6012 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6013 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6014 N2.getOpcode() == ISD::FMUL && 6015 N0 == N2.getOperand(0) && 6016 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6017 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6018 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6019 } 6020 6021 6022 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6023 if (DAG.getTarget().Options.UnsafeFPMath && 6024 N0.getOpcode() == ISD::FMUL && N1CFP && 6025 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6026 return DAG.getNode(ISD::FMA, dl, VT, 6027 N0.getOperand(0), 6028 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6029 N2); 6030 } 6031 6032 // (fma x, 1, y) -> (fadd x, y) 6033 // (fma x, -1, y) -> (fadd (fneg x), y) 6034 if (N1CFP) { 6035 if (N1CFP->isExactlyValue(1.0)) 6036 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6037 6038 if (N1CFP->isExactlyValue(-1.0) && 6039 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6040 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6041 AddToWorkList(RHSNeg.getNode()); 6042 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6043 } 6044 } 6045 6046 // (fma x, c, x) -> (fmul x, (c+1)) 6047 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) { 6048 return DAG.getNode(ISD::FMUL, dl, VT, 6049 N0, 6050 DAG.getNode(ISD::FADD, dl, VT, 6051 N1, DAG.getConstantFP(1.0, VT))); 6052 } 6053 6054 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6055 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6056 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 6057 return DAG.getNode(ISD::FMUL, dl, VT, 6058 N0, 6059 DAG.getNode(ISD::FADD, dl, VT, 6060 N1, DAG.getConstantFP(-1.0, VT))); 6061 } 6062 6063 6064 return SDValue(); 6065 } 6066 6067 SDValue DAGCombiner::visitFDIV(SDNode *N) { 6068 SDValue N0 = N->getOperand(0); 6069 SDValue N1 = N->getOperand(1); 6070 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6071 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6072 EVT VT = N->getValueType(0); 6073 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6074 6075 // fold vector ops 6076 if (VT.isVector()) { 6077 SDValue FoldedVOp = SimplifyVBinOp(N); 6078 if (FoldedVOp.getNode()) return FoldedVOp; 6079 } 6080 6081 // fold (fdiv c1, c2) -> c1/c2 6082 if (N0CFP && N1CFP && VT != MVT::ppcf128) 6083 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1); 6084 6085 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6086 if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) { 6087 // Compute the reciprocal 1.0 / c2. 6088 APFloat N1APF = N1CFP->getValueAPF(); 6089 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6090 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6091 // Only do the transform if the reciprocal is a legal fp immediate that 6092 // isn't too nasty (eg NaN, denormal, ...). 6093 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6094 (!LegalOperations || 6095 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6096 // backend)... we should handle this gracefully after Legalize. 6097 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6098 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6099 TLI.isFPImmLegal(Recip, VT))) 6100 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, 6101 DAG.getConstantFP(Recip, VT)); 6102 } 6103 6104 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6105 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6106 &DAG.getTarget().Options)) { 6107 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6108 &DAG.getTarget().Options)) { 6109 // Both can be negated for free, check to see if at least one is cheaper 6110 // negated. 6111 if (LHSNeg == 2 || RHSNeg == 2) 6112 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, 6113 GetNegatedExpression(N0, DAG, LegalOperations), 6114 GetNegatedExpression(N1, DAG, LegalOperations)); 6115 } 6116 } 6117 6118 return SDValue(); 6119 } 6120 6121 SDValue DAGCombiner::visitFREM(SDNode *N) { 6122 SDValue N0 = N->getOperand(0); 6123 SDValue N1 = N->getOperand(1); 6124 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6125 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6126 EVT VT = N->getValueType(0); 6127 6128 // fold (frem c1, c2) -> fmod(c1,c2) 6129 if (N0CFP && N1CFP && VT != MVT::ppcf128) 6130 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1); 6131 6132 return SDValue(); 6133 } 6134 6135 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6136 SDValue N0 = N->getOperand(0); 6137 SDValue N1 = N->getOperand(1); 6138 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6139 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6140 EVT VT = N->getValueType(0); 6141 6142 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold 6143 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1); 6144 6145 if (N1CFP) { 6146 const APFloat& V = N1CFP->getValueAPF(); 6147 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6148 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6149 if (!V.isNegative()) { 6150 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6151 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 6152 } else { 6153 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6154 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, 6155 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0)); 6156 } 6157 } 6158 6159 // copysign(fabs(x), y) -> copysign(x, y) 6160 // copysign(fneg(x), y) -> copysign(x, y) 6161 // copysign(copysign(x,z), y) -> copysign(x, y) 6162 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6163 N0.getOpcode() == ISD::FCOPYSIGN) 6164 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6165 N0.getOperand(0), N1); 6166 6167 // copysign(x, abs(y)) -> abs(x) 6168 if (N1.getOpcode() == ISD::FABS) 6169 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 6170 6171 // copysign(x, copysign(y,z)) -> copysign(x, z) 6172 if (N1.getOpcode() == ISD::FCOPYSIGN) 6173 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6174 N0, N1.getOperand(1)); 6175 6176 // copysign(x, fp_extend(y)) -> copysign(x, y) 6177 // copysign(x, fp_round(y)) -> copysign(x, y) 6178 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6179 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6180 N0, N1.getOperand(0)); 6181 6182 return SDValue(); 6183 } 6184 6185 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6186 SDValue N0 = N->getOperand(0); 6187 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6188 EVT VT = N->getValueType(0); 6189 EVT OpVT = N0.getValueType(); 6190 6191 // fold (sint_to_fp c1) -> c1fp 6192 if (N0C && OpVT != MVT::ppcf128 && 6193 // ...but only if the target supports immediate floating-point values 6194 (!LegalOperations || 6195 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6196 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 6197 6198 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6199 // but UINT_TO_FP is legal on this target, try to convert. 6200 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6201 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6202 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6203 if (DAG.SignBitIsZero(N0)) 6204 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 6205 } 6206 6207 // The next optimizations are desireable only if SELECT_CC can be lowered. 6208 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6209 // having to say they don't support SELECT_CC on every type the DAG knows 6210 // about, since there is no way to mark an opcode illegal at all value types 6211 // (See also visitSELECT) 6212 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6213 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6214 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6215 !VT.isVector() && 6216 (!LegalOperations || 6217 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6218 SDValue Ops[] = 6219 { N0.getOperand(0), N0.getOperand(1), 6220 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6221 N0.getOperand(2) }; 6222 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6223 } 6224 6225 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6226 // (select_cc x, y, 1.0, 0.0,, cc) 6227 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6228 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6229 (!LegalOperations || 6230 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6231 SDValue Ops[] = 6232 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6233 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6234 N0.getOperand(0).getOperand(2) }; 6235 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6236 } 6237 } 6238 6239 return SDValue(); 6240 } 6241 6242 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6243 SDValue N0 = N->getOperand(0); 6244 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6245 EVT VT = N->getValueType(0); 6246 EVT OpVT = N0.getValueType(); 6247 6248 // fold (uint_to_fp c1) -> c1fp 6249 if (N0C && OpVT != MVT::ppcf128 && 6250 // ...but only if the target supports immediate floating-point values 6251 (!LegalOperations || 6252 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6253 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 6254 6255 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 6256 // but SINT_TO_FP is legal on this target, try to convert. 6257 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 6258 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 6259 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 6260 if (DAG.SignBitIsZero(N0)) 6261 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 6262 } 6263 6264 // The next optimizations are desireable only if SELECT_CC can be lowered. 6265 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6266 // having to say they don't support SELECT_CC on every type the DAG knows 6267 // about, since there is no way to mark an opcode illegal at all value types 6268 // (See also visitSELECT) 6269 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6270 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6271 6272 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 6273 (!LegalOperations || 6274 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6275 SDValue Ops[] = 6276 { N0.getOperand(0), N0.getOperand(1), 6277 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 6278 N0.getOperand(2) }; 6279 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6280 } 6281 } 6282 6283 return SDValue(); 6284 } 6285 6286 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 6287 SDValue N0 = N->getOperand(0); 6288 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6289 EVT VT = N->getValueType(0); 6290 6291 // fold (fp_to_sint c1fp) -> c1 6292 if (N0CFP) 6293 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0); 6294 6295 return SDValue(); 6296 } 6297 6298 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 6299 SDValue N0 = N->getOperand(0); 6300 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6301 EVT VT = N->getValueType(0); 6302 6303 // fold (fp_to_uint c1fp) -> c1 6304 if (N0CFP && VT != MVT::ppcf128) 6305 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0); 6306 6307 return SDValue(); 6308 } 6309 6310 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 6311 SDValue N0 = N->getOperand(0); 6312 SDValue N1 = N->getOperand(1); 6313 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6314 EVT VT = N->getValueType(0); 6315 6316 // fold (fp_round c1fp) -> c1fp 6317 if (N0CFP && N0.getValueType() != MVT::ppcf128) 6318 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1); 6319 6320 // fold (fp_round (fp_extend x)) -> x 6321 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 6322 return N0.getOperand(0); 6323 6324 // fold (fp_round (fp_round x)) -> (fp_round x) 6325 if (N0.getOpcode() == ISD::FP_ROUND) { 6326 // This is a value preserving truncation if both round's are. 6327 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 6328 N0.getNode()->getConstantOperandVal(1) == 1; 6329 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0), 6330 DAG.getIntPtrConstant(IsTrunc)); 6331 } 6332 6333 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 6334 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 6335 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT, 6336 N0.getOperand(0), N1); 6337 AddToWorkList(Tmp.getNode()); 6338 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6339 Tmp, N0.getOperand(1)); 6340 } 6341 6342 return SDValue(); 6343 } 6344 6345 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 6346 SDValue N0 = N->getOperand(0); 6347 EVT VT = N->getValueType(0); 6348 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6349 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6350 6351 // fold (fp_round_inreg c1fp) -> c1fp 6352 if (N0CFP && isTypeLegal(EVT)) { 6353 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 6354 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round); 6355 } 6356 6357 return SDValue(); 6358 } 6359 6360 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 6361 SDValue N0 = N->getOperand(0); 6362 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6363 EVT VT = N->getValueType(0); 6364 6365 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 6366 if (N->hasOneUse() && 6367 N->use_begin()->getOpcode() == ISD::FP_ROUND) 6368 return SDValue(); 6369 6370 // fold (fp_extend c1fp) -> c1fp 6371 if (N0CFP && VT != MVT::ppcf128) 6372 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0); 6373 6374 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 6375 // value of X. 6376 if (N0.getOpcode() == ISD::FP_ROUND 6377 && N0.getNode()->getConstantOperandVal(1) == 1) { 6378 SDValue In = N0.getOperand(0); 6379 if (In.getValueType() == VT) return In; 6380 if (VT.bitsLT(In.getValueType())) 6381 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, 6382 In, N0.getOperand(1)); 6383 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In); 6384 } 6385 6386 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 6387 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() && 6388 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6389 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 6390 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6391 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 6392 LN0->getChain(), 6393 LN0->getBasePtr(), LN0->getPointerInfo(), 6394 N0.getValueType(), 6395 LN0->isVolatile(), LN0->isNonTemporal(), 6396 LN0->getAlignment()); 6397 CombineTo(N, ExtLoad); 6398 CombineTo(N0.getNode(), 6399 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), 6400 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 6401 ExtLoad.getValue(1)); 6402 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6403 } 6404 6405 return SDValue(); 6406 } 6407 6408 SDValue DAGCombiner::visitFNEG(SDNode *N) { 6409 SDValue N0 = N->getOperand(0); 6410 EVT VT = N->getValueType(0); 6411 6412 if (VT.isVector() && !LegalOperations) { 6413 // If operand is a BUILD_VECTOR node, see if we can constant fold it. 6414 if (N0.getOpcode() == ISD::BUILD_VECTOR) { 6415 SmallVector<SDValue, 8> Ops; 6416 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6417 SDValue Op = N0.getOperand(i); 6418 if (Op.getOpcode() != ISD::UNDEF && 6419 Op.getOpcode() != ISD::ConstantFP) 6420 break; 6421 EVT EltVT = Op.getValueType(); 6422 SDValue FoldOp = DAG.getNode(ISD::FNEG, N0.getDebugLoc(), EltVT, Op); 6423 if (FoldOp.getOpcode() != ISD::UNDEF && 6424 FoldOp.getOpcode() != ISD::ConstantFP) 6425 break; 6426 Ops.push_back(FoldOp); 6427 AddToWorkList(FoldOp.getNode()); 6428 } 6429 6430 if (Ops.size() == N0.getNumOperands()) 6431 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 6432 VT, &Ops[0], Ops.size()); 6433 } 6434 } 6435 6436 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 6437 &DAG.getTarget().Options)) 6438 return GetNegatedExpression(N0, DAG, LegalOperations); 6439 6440 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 6441 // constant pool values. 6442 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 6443 !VT.isVector() && 6444 N0.getNode()->hasOneUse() && 6445 N0.getOperand(0).getValueType().isInteger()) { 6446 SDValue Int = N0.getOperand(0); 6447 EVT IntVT = Int.getValueType(); 6448 if (IntVT.isInteger() && !IntVT.isVector()) { 6449 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int, 6450 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6451 AddToWorkList(Int.getNode()); 6452 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 6453 VT, Int); 6454 } 6455 } 6456 6457 // (fneg (fmul c, x)) -> (fmul -c, x) 6458 if (N0.getOpcode() == ISD::FMUL) { 6459 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6460 if (CFP1) { 6461 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 6462 N0.getOperand(0), 6463 DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, 6464 N0.getOperand(1))); 6465 } 6466 } 6467 6468 return SDValue(); 6469 } 6470 6471 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 6472 SDValue N0 = N->getOperand(0); 6473 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6474 EVT VT = N->getValueType(0); 6475 6476 // fold (fceil c1) -> fceil(c1) 6477 if (N0CFP && VT != MVT::ppcf128) 6478 return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0); 6479 6480 return SDValue(); 6481 } 6482 6483 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 6484 SDValue N0 = N->getOperand(0); 6485 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6486 EVT VT = N->getValueType(0); 6487 6488 // fold (ftrunc c1) -> ftrunc(c1) 6489 if (N0CFP && VT != MVT::ppcf128) 6490 return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0); 6491 6492 return SDValue(); 6493 } 6494 6495 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 6496 SDValue N0 = N->getOperand(0); 6497 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6498 EVT VT = N->getValueType(0); 6499 6500 // fold (ffloor c1) -> ffloor(c1) 6501 if (N0CFP && VT != MVT::ppcf128) 6502 return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0); 6503 6504 return SDValue(); 6505 } 6506 6507 SDValue DAGCombiner::visitFABS(SDNode *N) { 6508 SDValue N0 = N->getOperand(0); 6509 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6510 EVT VT = N->getValueType(0); 6511 6512 // fold (fabs c1) -> fabs(c1) 6513 if (N0CFP && VT != MVT::ppcf128) 6514 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 6515 // fold (fabs (fabs x)) -> (fabs x) 6516 if (N0.getOpcode() == ISD::FABS) 6517 return N->getOperand(0); 6518 // fold (fabs (fneg x)) -> (fabs x) 6519 // fold (fabs (fcopysign x, y)) -> (fabs x) 6520 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 6521 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0)); 6522 6523 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 6524 // constant pool values. 6525 if (!TLI.isFAbsFree(VT) && 6526 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 6527 N0.getOperand(0).getValueType().isInteger() && 6528 !N0.getOperand(0).getValueType().isVector()) { 6529 SDValue Int = N0.getOperand(0); 6530 EVT IntVT = Int.getValueType(); 6531 if (IntVT.isInteger() && !IntVT.isVector()) { 6532 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int, 6533 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6534 AddToWorkList(Int.getNode()); 6535 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 6536 N->getValueType(0), Int); 6537 } 6538 } 6539 6540 return SDValue(); 6541 } 6542 6543 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 6544 SDValue Chain = N->getOperand(0); 6545 SDValue N1 = N->getOperand(1); 6546 SDValue N2 = N->getOperand(2); 6547 6548 // If N is a constant we could fold this into a fallthrough or unconditional 6549 // branch. However that doesn't happen very often in normal code, because 6550 // Instcombine/SimplifyCFG should have handled the available opportunities. 6551 // If we did this folding here, it would be necessary to update the 6552 // MachineBasicBlock CFG, which is awkward. 6553 6554 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 6555 // on the target. 6556 if (N1.getOpcode() == ISD::SETCC && 6557 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) { 6558 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 6559 Chain, N1.getOperand(2), 6560 N1.getOperand(0), N1.getOperand(1), N2); 6561 } 6562 6563 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 6564 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 6565 (N1.getOperand(0).hasOneUse() && 6566 N1.getOperand(0).getOpcode() == ISD::SRL))) { 6567 SDNode *Trunc = 0; 6568 if (N1.getOpcode() == ISD::TRUNCATE) { 6569 // Look pass the truncate. 6570 Trunc = N1.getNode(); 6571 N1 = N1.getOperand(0); 6572 } 6573 6574 // Match this pattern so that we can generate simpler code: 6575 // 6576 // %a = ... 6577 // %b = and i32 %a, 2 6578 // %c = srl i32 %b, 1 6579 // brcond i32 %c ... 6580 // 6581 // into 6582 // 6583 // %a = ... 6584 // %b = and i32 %a, 2 6585 // %c = setcc eq %b, 0 6586 // brcond %c ... 6587 // 6588 // This applies only when the AND constant value has one bit set and the 6589 // SRL constant is equal to the log2 of the AND constant. The back-end is 6590 // smart enough to convert the result into a TEST/JMP sequence. 6591 SDValue Op0 = N1.getOperand(0); 6592 SDValue Op1 = N1.getOperand(1); 6593 6594 if (Op0.getOpcode() == ISD::AND && 6595 Op1.getOpcode() == ISD::Constant) { 6596 SDValue AndOp1 = Op0.getOperand(1); 6597 6598 if (AndOp1.getOpcode() == ISD::Constant) { 6599 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 6600 6601 if (AndConst.isPowerOf2() && 6602 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 6603 SDValue SetCC = 6604 DAG.getSetCC(N->getDebugLoc(), 6605 TLI.getSetCCResultType(Op0.getValueType()), 6606 Op0, DAG.getConstant(0, Op0.getValueType()), 6607 ISD::SETNE); 6608 6609 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6610 MVT::Other, Chain, SetCC, N2); 6611 // Don't add the new BRCond into the worklist or else SimplifySelectCC 6612 // will convert it back to (X & C1) >> C2. 6613 CombineTo(N, NewBRCond, false); 6614 // Truncate is dead. 6615 if (Trunc) { 6616 removeFromWorkList(Trunc); 6617 DAG.DeleteNode(Trunc); 6618 } 6619 // Replace the uses of SRL with SETCC 6620 WorkListRemover DeadNodes(*this); 6621 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6622 removeFromWorkList(N1.getNode()); 6623 DAG.DeleteNode(N1.getNode()); 6624 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6625 } 6626 } 6627 } 6628 6629 if (Trunc) 6630 // Restore N1 if the above transformation doesn't match. 6631 N1 = N->getOperand(1); 6632 } 6633 6634 // Transform br(xor(x, y)) -> br(x != y) 6635 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 6636 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 6637 SDNode *TheXor = N1.getNode(); 6638 SDValue Op0 = TheXor->getOperand(0); 6639 SDValue Op1 = TheXor->getOperand(1); 6640 if (Op0.getOpcode() == Op1.getOpcode()) { 6641 // Avoid missing important xor optimizations. 6642 SDValue Tmp = visitXOR(TheXor); 6643 if (Tmp.getNode() && Tmp.getNode() != TheXor) { 6644 DEBUG(dbgs() << "\nReplacing.8 "; 6645 TheXor->dump(&DAG); 6646 dbgs() << "\nWith: "; 6647 Tmp.getNode()->dump(&DAG); 6648 dbgs() << '\n'); 6649 WorkListRemover DeadNodes(*this); 6650 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 6651 removeFromWorkList(TheXor); 6652 DAG.DeleteNode(TheXor); 6653 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6654 MVT::Other, Chain, Tmp, N2); 6655 } 6656 } 6657 6658 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 6659 bool Equal = false; 6660 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 6661 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 6662 Op0.getOpcode() == ISD::XOR) { 6663 TheXor = Op0.getNode(); 6664 Equal = true; 6665 } 6666 6667 EVT SetCCVT = N1.getValueType(); 6668 if (LegalTypes) 6669 SetCCVT = TLI.getSetCCResultType(SetCCVT); 6670 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(), 6671 SetCCVT, 6672 Op0, Op1, 6673 Equal ? ISD::SETEQ : ISD::SETNE); 6674 // Replace the uses of XOR with SETCC 6675 WorkListRemover DeadNodes(*this); 6676 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6677 removeFromWorkList(N1.getNode()); 6678 DAG.DeleteNode(N1.getNode()); 6679 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6680 MVT::Other, Chain, SetCC, N2); 6681 } 6682 } 6683 6684 return SDValue(); 6685 } 6686 6687 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 6688 // 6689 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 6690 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 6691 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 6692 6693 // If N is a constant we could fold this into a fallthrough or unconditional 6694 // branch. However that doesn't happen very often in normal code, because 6695 // Instcombine/SimplifyCFG should have handled the available opportunities. 6696 // If we did this folding here, it would be necessary to update the 6697 // MachineBasicBlock CFG, which is awkward. 6698 6699 // Use SimplifySetCC to simplify SETCC's. 6700 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()), 6701 CondLHS, CondRHS, CC->get(), N->getDebugLoc(), 6702 false); 6703 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 6704 6705 // fold to a simpler setcc 6706 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 6707 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 6708 N->getOperand(0), Simp.getOperand(2), 6709 Simp.getOperand(0), Simp.getOperand(1), 6710 N->getOperand(4)); 6711 6712 return SDValue(); 6713 } 6714 6715 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 6716 /// uses N as its base pointer and that N may be folded in the load / store 6717 /// addressing mode. 6718 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 6719 SelectionDAG &DAG, 6720 const TargetLowering &TLI) { 6721 EVT VT; 6722 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 6723 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 6724 return false; 6725 VT = Use->getValueType(0); 6726 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 6727 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 6728 return false; 6729 VT = ST->getValue().getValueType(); 6730 } else 6731 return false; 6732 6733 TargetLowering::AddrMode AM; 6734 if (N->getOpcode() == ISD::ADD) { 6735 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6736 if (Offset) 6737 // [reg +/- imm] 6738 AM.BaseOffs = Offset->getSExtValue(); 6739 else 6740 // [reg +/- reg] 6741 AM.Scale = 1; 6742 } else if (N->getOpcode() == ISD::SUB) { 6743 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6744 if (Offset) 6745 // [reg +/- imm] 6746 AM.BaseOffs = -Offset->getSExtValue(); 6747 else 6748 // [reg +/- reg] 6749 AM.Scale = 1; 6750 } else 6751 return false; 6752 6753 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 6754 } 6755 6756 /// CombineToPreIndexedLoadStore - Try turning a load / store into a 6757 /// pre-indexed load / store when the base pointer is an add or subtract 6758 /// and it has other uses besides the load / store. After the 6759 /// transformation, the new indexed load / store has effectively folded 6760 /// the add / subtract in and all of its other uses are redirected to the 6761 /// new load / store. 6762 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 6763 if (Level < AfterLegalizeDAG) 6764 return false; 6765 6766 bool isLoad = true; 6767 SDValue Ptr; 6768 EVT VT; 6769 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 6770 if (LD->isIndexed()) 6771 return false; 6772 VT = LD->getMemoryVT(); 6773 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 6774 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 6775 return false; 6776 Ptr = LD->getBasePtr(); 6777 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 6778 if (ST->isIndexed()) 6779 return false; 6780 VT = ST->getMemoryVT(); 6781 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 6782 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 6783 return false; 6784 Ptr = ST->getBasePtr(); 6785 isLoad = false; 6786 } else { 6787 return false; 6788 } 6789 6790 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 6791 // out. There is no reason to make this a preinc/predec. 6792 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 6793 Ptr.getNode()->hasOneUse()) 6794 return false; 6795 6796 // Ask the target to do addressing mode selection. 6797 SDValue BasePtr; 6798 SDValue Offset; 6799 ISD::MemIndexedMode AM = ISD::UNINDEXED; 6800 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 6801 return false; 6802 // Don't create a indexed load / store with zero offset. 6803 if (isa<ConstantSDNode>(Offset) && 6804 cast<ConstantSDNode>(Offset)->isNullValue()) 6805 return false; 6806 6807 // Try turning it into a pre-indexed load / store except when: 6808 // 1) The new base ptr is a frame index. 6809 // 2) If N is a store and the new base ptr is either the same as or is a 6810 // predecessor of the value being stored. 6811 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 6812 // that would create a cycle. 6813 // 4) All uses are load / store ops that use it as old base ptr. 6814 6815 // Check #1. Preinc'ing a frame index would require copying the stack pointer 6816 // (plus the implicit offset) to a register to preinc anyway. 6817 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 6818 return false; 6819 6820 // Check #2. 6821 if (!isLoad) { 6822 SDValue Val = cast<StoreSDNode>(N)->getValue(); 6823 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 6824 return false; 6825 } 6826 6827 // Now check for #3 and #4. 6828 bool RealUse = false; 6829 6830 // Caches for hasPredecessorHelper 6831 SmallPtrSet<const SDNode *, 32> Visited; 6832 SmallVector<const SDNode *, 16> Worklist; 6833 6834 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 6835 E = Ptr.getNode()->use_end(); I != E; ++I) { 6836 SDNode *Use = *I; 6837 if (Use == N) 6838 continue; 6839 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 6840 return false; 6841 6842 // If Ptr may be folded in addressing mode of other use, then it's 6843 // not profitable to do this transformation. 6844 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 6845 RealUse = true; 6846 } 6847 6848 if (!RealUse) 6849 return false; 6850 6851 SDValue Result; 6852 if (isLoad) 6853 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 6854 BasePtr, Offset, AM); 6855 else 6856 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 6857 BasePtr, Offset, AM); 6858 ++PreIndexedNodes; 6859 ++NodesCombined; 6860 DEBUG(dbgs() << "\nReplacing.4 "; 6861 N->dump(&DAG); 6862 dbgs() << "\nWith: "; 6863 Result.getNode()->dump(&DAG); 6864 dbgs() << '\n'); 6865 WorkListRemover DeadNodes(*this); 6866 if (isLoad) { 6867 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 6868 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 6869 } else { 6870 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 6871 } 6872 6873 // Finally, since the node is now dead, remove it from the graph. 6874 DAG.DeleteNode(N); 6875 6876 // Replace the uses of Ptr with uses of the updated base value. 6877 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 6878 removeFromWorkList(Ptr.getNode()); 6879 DAG.DeleteNode(Ptr.getNode()); 6880 6881 return true; 6882 } 6883 6884 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a 6885 /// add / sub of the base pointer node into a post-indexed load / store. 6886 /// The transformation folded the add / subtract into the new indexed 6887 /// load / store effectively and all of its uses are redirected to the 6888 /// new load / store. 6889 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 6890 if (Level < AfterLegalizeDAG) 6891 return false; 6892 6893 bool isLoad = true; 6894 SDValue Ptr; 6895 EVT VT; 6896 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 6897 if (LD->isIndexed()) 6898 return false; 6899 VT = LD->getMemoryVT(); 6900 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 6901 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 6902 return false; 6903 Ptr = LD->getBasePtr(); 6904 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 6905 if (ST->isIndexed()) 6906 return false; 6907 VT = ST->getMemoryVT(); 6908 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 6909 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 6910 return false; 6911 Ptr = ST->getBasePtr(); 6912 isLoad = false; 6913 } else { 6914 return false; 6915 } 6916 6917 if (Ptr.getNode()->hasOneUse()) 6918 return false; 6919 6920 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 6921 E = Ptr.getNode()->use_end(); I != E; ++I) { 6922 SDNode *Op = *I; 6923 if (Op == N || 6924 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 6925 continue; 6926 6927 SDValue BasePtr; 6928 SDValue Offset; 6929 ISD::MemIndexedMode AM = ISD::UNINDEXED; 6930 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 6931 // Don't create a indexed load / store with zero offset. 6932 if (isa<ConstantSDNode>(Offset) && 6933 cast<ConstantSDNode>(Offset)->isNullValue()) 6934 continue; 6935 6936 // Try turning it into a post-indexed load / store except when 6937 // 1) All uses are load / store ops that use it as base ptr (and 6938 // it may be folded as addressing mmode). 6939 // 2) Op must be independent of N, i.e. Op is neither a predecessor 6940 // nor a successor of N. Otherwise, if Op is folded that would 6941 // create a cycle. 6942 6943 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 6944 continue; 6945 6946 // Check for #1. 6947 bool TryNext = false; 6948 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 6949 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 6950 SDNode *Use = *II; 6951 if (Use == Ptr.getNode()) 6952 continue; 6953 6954 // If all the uses are load / store addresses, then don't do the 6955 // transformation. 6956 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 6957 bool RealUse = false; 6958 for (SDNode::use_iterator III = Use->use_begin(), 6959 EEE = Use->use_end(); III != EEE; ++III) { 6960 SDNode *UseUse = *III; 6961 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 6962 RealUse = true; 6963 } 6964 6965 if (!RealUse) { 6966 TryNext = true; 6967 break; 6968 } 6969 } 6970 } 6971 6972 if (TryNext) 6973 continue; 6974 6975 // Check for #2 6976 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 6977 SDValue Result = isLoad 6978 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 6979 BasePtr, Offset, AM) 6980 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 6981 BasePtr, Offset, AM); 6982 ++PostIndexedNodes; 6983 ++NodesCombined; 6984 DEBUG(dbgs() << "\nReplacing.5 "; 6985 N->dump(&DAG); 6986 dbgs() << "\nWith: "; 6987 Result.getNode()->dump(&DAG); 6988 dbgs() << '\n'); 6989 WorkListRemover DeadNodes(*this); 6990 if (isLoad) { 6991 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 6992 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 6993 } else { 6994 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 6995 } 6996 6997 // Finally, since the node is now dead, remove it from the graph. 6998 DAG.DeleteNode(N); 6999 7000 // Replace the uses of Use with uses of the updated base value. 7001 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 7002 Result.getValue(isLoad ? 1 : 0)); 7003 removeFromWorkList(Op); 7004 DAG.DeleteNode(Op); 7005 return true; 7006 } 7007 } 7008 } 7009 7010 return false; 7011 } 7012 7013 SDValue DAGCombiner::visitLOAD(SDNode *N) { 7014 LoadSDNode *LD = cast<LoadSDNode>(N); 7015 SDValue Chain = LD->getChain(); 7016 SDValue Ptr = LD->getBasePtr(); 7017 7018 // If load is not volatile and there are no uses of the loaded value (and 7019 // the updated indexed value in case of indexed loads), change uses of the 7020 // chain value into uses of the chain input (i.e. delete the dead load). 7021 if (!LD->isVolatile()) { 7022 if (N->getValueType(1) == MVT::Other) { 7023 // Unindexed loads. 7024 if (!N->hasAnyUseOfValue(0)) { 7025 // It's not safe to use the two value CombineTo variant here. e.g. 7026 // v1, chain2 = load chain1, loc 7027 // v2, chain3 = load chain2, loc 7028 // v3 = add v2, c 7029 // Now we replace use of chain2 with chain1. This makes the second load 7030 // isomorphic to the one we are deleting, and thus makes this load live. 7031 DEBUG(dbgs() << "\nReplacing.6 "; 7032 N->dump(&DAG); 7033 dbgs() << "\nWith chain: "; 7034 Chain.getNode()->dump(&DAG); 7035 dbgs() << "\n"); 7036 WorkListRemover DeadNodes(*this); 7037 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7038 7039 if (N->use_empty()) { 7040 removeFromWorkList(N); 7041 DAG.DeleteNode(N); 7042 } 7043 7044 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7045 } 7046 } else { 7047 // Indexed loads. 7048 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7049 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7050 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7051 DEBUG(dbgs() << "\nReplacing.7 "; 7052 N->dump(&DAG); 7053 dbgs() << "\nWith: "; 7054 Undef.getNode()->dump(&DAG); 7055 dbgs() << " and 2 other values\n"); 7056 WorkListRemover DeadNodes(*this); 7057 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7058 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7059 DAG.getUNDEF(N->getValueType(1))); 7060 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7061 removeFromWorkList(N); 7062 DAG.DeleteNode(N); 7063 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7064 } 7065 } 7066 } 7067 7068 // If this load is directly stored, replace the load value with the stored 7069 // value. 7070 // TODO: Handle store large -> read small portion. 7071 // TODO: Handle TRUNCSTORE/LOADEXT 7072 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7073 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7074 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7075 if (PrevST->getBasePtr() == Ptr && 7076 PrevST->getValue().getValueType() == N->getValueType(0)) 7077 return CombineTo(N, Chain.getOperand(1), Chain); 7078 } 7079 } 7080 7081 // Try to infer better alignment information than the load already has. 7082 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7083 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7084 if (Align > LD->getAlignment()) 7085 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(), 7086 LD->getValueType(0), 7087 Chain, Ptr, LD->getPointerInfo(), 7088 LD->getMemoryVT(), 7089 LD->isVolatile(), LD->isNonTemporal(), Align); 7090 } 7091 } 7092 7093 if (CombinerAA) { 7094 // Walk up chain skipping non-aliasing memory nodes. 7095 SDValue BetterChain = FindBetterChain(N, Chain); 7096 7097 // If there is a better chain. 7098 if (Chain != BetterChain) { 7099 SDValue ReplLoad; 7100 7101 // Replace the chain to void dependency. 7102 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 7103 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(), 7104 BetterChain, Ptr, LD->getPointerInfo(), 7105 LD->isVolatile(), LD->isNonTemporal(), 7106 LD->isInvariant(), LD->getAlignment()); 7107 } else { 7108 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(), 7109 LD->getValueType(0), 7110 BetterChain, Ptr, LD->getPointerInfo(), 7111 LD->getMemoryVT(), 7112 LD->isVolatile(), 7113 LD->isNonTemporal(), 7114 LD->getAlignment()); 7115 } 7116 7117 // Create token factor to keep old chain connected. 7118 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 7119 MVT::Other, Chain, ReplLoad.getValue(1)); 7120 7121 // Make sure the new and old chains are cleaned up. 7122 AddToWorkList(Token.getNode()); 7123 7124 // Replace uses with load result and token factor. Don't add users 7125 // to work list. 7126 return CombineTo(N, ReplLoad.getValue(0), Token, false); 7127 } 7128 } 7129 7130 // Try transforming N to an indexed load. 7131 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7132 return SDValue(N, 0); 7133 7134 return SDValue(); 7135 } 7136 7137 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 7138 /// load is having specific bytes cleared out. If so, return the byte size 7139 /// being masked out and the shift amount. 7140 static std::pair<unsigned, unsigned> 7141 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 7142 std::pair<unsigned, unsigned> Result(0, 0); 7143 7144 // Check for the structure we're looking for. 7145 if (V->getOpcode() != ISD::AND || 7146 !isa<ConstantSDNode>(V->getOperand(1)) || 7147 !ISD::isNormalLoad(V->getOperand(0).getNode())) 7148 return Result; 7149 7150 // Check the chain and pointer. 7151 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 7152 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 7153 7154 // The store should be chained directly to the load or be an operand of a 7155 // tokenfactor. 7156 if (LD == Chain.getNode()) 7157 ; // ok. 7158 else if (Chain->getOpcode() != ISD::TokenFactor) 7159 return Result; // Fail. 7160 else { 7161 bool isOk = false; 7162 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 7163 if (Chain->getOperand(i).getNode() == LD) { 7164 isOk = true; 7165 break; 7166 } 7167 if (!isOk) return Result; 7168 } 7169 7170 // This only handles simple types. 7171 if (V.getValueType() != MVT::i16 && 7172 V.getValueType() != MVT::i32 && 7173 V.getValueType() != MVT::i64) 7174 return Result; 7175 7176 // Check the constant mask. Invert it so that the bits being masked out are 7177 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 7178 // follow the sign bit for uniformity. 7179 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 7180 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask); 7181 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 7182 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask); 7183 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 7184 if (NotMaskLZ == 64) return Result; // All zero mask. 7185 7186 // See if we have a continuous run of bits. If so, we have 0*1+0* 7187 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 7188 return Result; 7189 7190 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 7191 if (V.getValueType() != MVT::i64 && NotMaskLZ) 7192 NotMaskLZ -= 64-V.getValueSizeInBits(); 7193 7194 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 7195 switch (MaskedBytes) { 7196 case 1: 7197 case 2: 7198 case 4: break; 7199 default: return Result; // All one mask, or 5-byte mask. 7200 } 7201 7202 // Verify that the first bit starts at a multiple of mask so that the access 7203 // is aligned the same as the access width. 7204 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 7205 7206 Result.first = MaskedBytes; 7207 Result.second = NotMaskTZ/8; 7208 return Result; 7209 } 7210 7211 7212 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 7213 /// provides a value as specified by MaskInfo. If so, replace the specified 7214 /// store with a narrower store of truncated IVal. 7215 static SDNode * 7216 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 7217 SDValue IVal, StoreSDNode *St, 7218 DAGCombiner *DC) { 7219 unsigned NumBytes = MaskInfo.first; 7220 unsigned ByteShift = MaskInfo.second; 7221 SelectionDAG &DAG = DC->getDAG(); 7222 7223 // Check to see if IVal is all zeros in the part being masked in by the 'or' 7224 // that uses this. If not, this is not a replacement. 7225 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 7226 ByteShift*8, (ByteShift+NumBytes)*8); 7227 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 7228 7229 // Check that it is legal on the target to do this. It is legal if the new 7230 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 7231 // legalization. 7232 MVT VT = MVT::getIntegerVT(NumBytes*8); 7233 if (!DC->isTypeLegal(VT)) 7234 return 0; 7235 7236 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 7237 // shifted by ByteShift and truncated down to NumBytes. 7238 if (ByteShift) 7239 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal, 7240 DAG.getConstant(ByteShift*8, 7241 DC->getShiftAmountTy(IVal.getValueType()))); 7242 7243 // Figure out the offset for the store and the alignment of the access. 7244 unsigned StOffset; 7245 unsigned NewAlign = St->getAlignment(); 7246 7247 if (DAG.getTargetLoweringInfo().isLittleEndian()) 7248 StOffset = ByteShift; 7249 else 7250 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 7251 7252 SDValue Ptr = St->getBasePtr(); 7253 if (StOffset) { 7254 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(), 7255 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 7256 NewAlign = MinAlign(NewAlign, StOffset); 7257 } 7258 7259 // Truncate down to the new size. 7260 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal); 7261 7262 ++OpsNarrowed; 7263 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr, 7264 St->getPointerInfo().getWithOffset(StOffset), 7265 false, false, NewAlign).getNode(); 7266 } 7267 7268 7269 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 7270 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 7271 /// of the loaded bits, try narrowing the load and store if it would end up 7272 /// being a win for performance or code size. 7273 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 7274 StoreSDNode *ST = cast<StoreSDNode>(N); 7275 if (ST->isVolatile()) 7276 return SDValue(); 7277 7278 SDValue Chain = ST->getChain(); 7279 SDValue Value = ST->getValue(); 7280 SDValue Ptr = ST->getBasePtr(); 7281 EVT VT = Value.getValueType(); 7282 7283 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 7284 return SDValue(); 7285 7286 unsigned Opc = Value.getOpcode(); 7287 7288 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 7289 // is a byte mask indicating a consecutive number of bytes, check to see if 7290 // Y is known to provide just those bytes. If so, we try to replace the 7291 // load + replace + store sequence with a single (narrower) store, which makes 7292 // the load dead. 7293 if (Opc == ISD::OR) { 7294 std::pair<unsigned, unsigned> MaskedLoad; 7295 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 7296 if (MaskedLoad.first) 7297 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7298 Value.getOperand(1), ST,this)) 7299 return SDValue(NewST, 0); 7300 7301 // Or is commutative, so try swapping X and Y. 7302 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 7303 if (MaskedLoad.first) 7304 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7305 Value.getOperand(0), ST,this)) 7306 return SDValue(NewST, 0); 7307 } 7308 7309 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 7310 Value.getOperand(1).getOpcode() != ISD::Constant) 7311 return SDValue(); 7312 7313 SDValue N0 = Value.getOperand(0); 7314 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7315 Chain == SDValue(N0.getNode(), 1)) { 7316 LoadSDNode *LD = cast<LoadSDNode>(N0); 7317 if (LD->getBasePtr() != Ptr || 7318 LD->getPointerInfo().getAddrSpace() != 7319 ST->getPointerInfo().getAddrSpace()) 7320 return SDValue(); 7321 7322 // Find the type to narrow it the load / op / store to. 7323 SDValue N1 = Value.getOperand(1); 7324 unsigned BitWidth = N1.getValueSizeInBits(); 7325 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 7326 if (Opc == ISD::AND) 7327 Imm ^= APInt::getAllOnesValue(BitWidth); 7328 if (Imm == 0 || Imm.isAllOnesValue()) 7329 return SDValue(); 7330 unsigned ShAmt = Imm.countTrailingZeros(); 7331 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 7332 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 7333 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7334 while (NewBW < BitWidth && 7335 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 7336 TLI.isNarrowingProfitable(VT, NewVT))) { 7337 NewBW = NextPowerOf2(NewBW); 7338 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7339 } 7340 if (NewBW >= BitWidth) 7341 return SDValue(); 7342 7343 // If the lsb changed does not start at the type bitwidth boundary, 7344 // start at the previous one. 7345 if (ShAmt % NewBW) 7346 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 7347 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW); 7348 if ((Imm & Mask) == Imm) { 7349 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 7350 if (Opc == ISD::AND) 7351 NewImm ^= APInt::getAllOnesValue(NewBW); 7352 uint64_t PtrOff = ShAmt / 8; 7353 // For big endian targets, we need to adjust the offset to the pointer to 7354 // load the correct bytes. 7355 if (TLI.isBigEndian()) 7356 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 7357 7358 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 7359 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 7360 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy)) 7361 return SDValue(); 7362 7363 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(), 7364 Ptr.getValueType(), Ptr, 7365 DAG.getConstant(PtrOff, Ptr.getValueType())); 7366 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(), 7367 LD->getChain(), NewPtr, 7368 LD->getPointerInfo().getWithOffset(PtrOff), 7369 LD->isVolatile(), LD->isNonTemporal(), 7370 LD->isInvariant(), NewAlign); 7371 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD, 7372 DAG.getConstant(NewImm, NewVT)); 7373 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(), 7374 NewVal, NewPtr, 7375 ST->getPointerInfo().getWithOffset(PtrOff), 7376 false, false, NewAlign); 7377 7378 AddToWorkList(NewPtr.getNode()); 7379 AddToWorkList(NewLD.getNode()); 7380 AddToWorkList(NewVal.getNode()); 7381 WorkListRemover DeadNodes(*this); 7382 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 7383 ++OpsNarrowed; 7384 return NewST; 7385 } 7386 } 7387 7388 return SDValue(); 7389 } 7390 7391 /// TransformFPLoadStorePair - For a given floating point load / store pair, 7392 /// if the load value isn't used by any other operations, then consider 7393 /// transforming the pair to integer load / store operations if the target 7394 /// deems the transformation profitable. 7395 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 7396 StoreSDNode *ST = cast<StoreSDNode>(N); 7397 SDValue Chain = ST->getChain(); 7398 SDValue Value = ST->getValue(); 7399 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 7400 Value.hasOneUse() && 7401 Chain == SDValue(Value.getNode(), 1)) { 7402 LoadSDNode *LD = cast<LoadSDNode>(Value); 7403 EVT VT = LD->getMemoryVT(); 7404 if (!VT.isFloatingPoint() || 7405 VT != ST->getMemoryVT() || 7406 LD->isNonTemporal() || 7407 ST->isNonTemporal() || 7408 LD->getPointerInfo().getAddrSpace() != 0 || 7409 ST->getPointerInfo().getAddrSpace() != 0) 7410 return SDValue(); 7411 7412 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7413 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 7414 !TLI.isOperationLegal(ISD::STORE, IntVT) || 7415 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 7416 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 7417 return SDValue(); 7418 7419 unsigned LDAlign = LD->getAlignment(); 7420 unsigned STAlign = ST->getAlignment(); 7421 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 7422 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy); 7423 if (LDAlign < ABIAlign || STAlign < ABIAlign) 7424 return SDValue(); 7425 7426 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(), 7427 LD->getChain(), LD->getBasePtr(), 7428 LD->getPointerInfo(), 7429 false, false, false, LDAlign); 7430 7431 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(), 7432 NewLD, ST->getBasePtr(), 7433 ST->getPointerInfo(), 7434 false, false, STAlign); 7435 7436 AddToWorkList(NewLD.getNode()); 7437 AddToWorkList(NewST.getNode()); 7438 WorkListRemover DeadNodes(*this); 7439 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 7440 ++LdStFP2Int; 7441 return NewST; 7442 } 7443 7444 return SDValue(); 7445 } 7446 7447 SDValue DAGCombiner::visitSTORE(SDNode *N) { 7448 StoreSDNode *ST = cast<StoreSDNode>(N); 7449 SDValue Chain = ST->getChain(); 7450 SDValue Value = ST->getValue(); 7451 SDValue Ptr = ST->getBasePtr(); 7452 7453 // If this is a store of a bit convert, store the input value if the 7454 // resultant store does not need a higher alignment than the original. 7455 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 7456 ST->isUnindexed()) { 7457 unsigned OrigAlign = ST->getAlignment(); 7458 EVT SVT = Value.getOperand(0).getValueType(); 7459 unsigned Align = TLI.getTargetData()-> 7460 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 7461 if (Align <= OrigAlign && 7462 ((!LegalOperations && !ST->isVolatile()) || 7463 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 7464 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0), 7465 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7466 ST->isNonTemporal(), OrigAlign); 7467 } 7468 7469 // Turn 'store undef, Ptr' -> nothing. 7470 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 7471 return Chain; 7472 7473 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 7474 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 7475 // NOTE: If the original store is volatile, this transform must not increase 7476 // the number of stores. For example, on x86-32 an f64 can be stored in one 7477 // processor operation but an i64 (which is not legal) requires two. So the 7478 // transform should not be done in this case. 7479 if (Value.getOpcode() != ISD::TargetConstantFP) { 7480 SDValue Tmp; 7481 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) { 7482 default: llvm_unreachable("Unknown FP type"); 7483 case MVT::f16: // We don't do this for these yet. 7484 case MVT::f80: 7485 case MVT::f128: 7486 case MVT::ppcf128: 7487 break; 7488 case MVT::f32: 7489 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 7490 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 7491 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 7492 bitcastToAPInt().getZExtValue(), MVT::i32); 7493 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 7494 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7495 ST->isNonTemporal(), ST->getAlignment()); 7496 } 7497 break; 7498 case MVT::f64: 7499 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 7500 !ST->isVolatile()) || 7501 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 7502 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 7503 getZExtValue(), MVT::i64); 7504 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 7505 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7506 ST->isNonTemporal(), ST->getAlignment()); 7507 } 7508 7509 if (!ST->isVolatile() && 7510 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 7511 // Many FP stores are not made apparent until after legalize, e.g. for 7512 // argument passing. Since this is so common, custom legalize the 7513 // 64-bit integer store into two 32-bit stores. 7514 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 7515 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 7516 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 7517 if (TLI.isBigEndian()) std::swap(Lo, Hi); 7518 7519 unsigned Alignment = ST->getAlignment(); 7520 bool isVolatile = ST->isVolatile(); 7521 bool isNonTemporal = ST->isNonTemporal(); 7522 7523 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo, 7524 Ptr, ST->getPointerInfo(), 7525 isVolatile, isNonTemporal, 7526 ST->getAlignment()); 7527 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr, 7528 DAG.getConstant(4, Ptr.getValueType())); 7529 Alignment = MinAlign(Alignment, 4U); 7530 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi, 7531 Ptr, ST->getPointerInfo().getWithOffset(4), 7532 isVolatile, isNonTemporal, 7533 Alignment); 7534 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 7535 St0, St1); 7536 } 7537 7538 break; 7539 } 7540 } 7541 } 7542 7543 // Try to infer better alignment information than the store already has. 7544 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 7545 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7546 if (Align > ST->getAlignment()) 7547 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value, 7548 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7549 ST->isVolatile(), ST->isNonTemporal(), Align); 7550 } 7551 } 7552 7553 // Try transforming a pair floating point load / store ops to integer 7554 // load / store ops. 7555 SDValue NewST = TransformFPLoadStorePair(N); 7556 if (NewST.getNode()) 7557 return NewST; 7558 7559 if (CombinerAA) { 7560 // Walk up chain skipping non-aliasing memory nodes. 7561 SDValue BetterChain = FindBetterChain(N, Chain); 7562 7563 // If there is a better chain. 7564 if (Chain != BetterChain) { 7565 SDValue ReplStore; 7566 7567 // Replace the chain to avoid dependency. 7568 if (ST->isTruncatingStore()) { 7569 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr, 7570 ST->getPointerInfo(), 7571 ST->getMemoryVT(), ST->isVolatile(), 7572 ST->isNonTemporal(), ST->getAlignment()); 7573 } else { 7574 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr, 7575 ST->getPointerInfo(), 7576 ST->isVolatile(), ST->isNonTemporal(), 7577 ST->getAlignment()); 7578 } 7579 7580 // Create token to keep both nodes around. 7581 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 7582 MVT::Other, Chain, ReplStore); 7583 7584 // Make sure the new and old chains are cleaned up. 7585 AddToWorkList(Token.getNode()); 7586 7587 // Don't add users to work list. 7588 return CombineTo(N, Token, false); 7589 } 7590 } 7591 7592 // Try transforming N to an indexed store. 7593 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7594 return SDValue(N, 0); 7595 7596 // FIXME: is there such a thing as a truncating indexed store? 7597 if (ST->isTruncatingStore() && ST->isUnindexed() && 7598 Value.getValueType().isInteger()) { 7599 // See if we can simplify the input to this truncstore with knowledge that 7600 // only the low bits are being used. For example: 7601 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 7602 SDValue Shorter = 7603 GetDemandedBits(Value, 7604 APInt::getLowBitsSet( 7605 Value.getValueType().getScalarType().getSizeInBits(), 7606 ST->getMemoryVT().getScalarType().getSizeInBits())); 7607 AddToWorkList(Value.getNode()); 7608 if (Shorter.getNode()) 7609 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter, 7610 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7611 ST->isVolatile(), ST->isNonTemporal(), 7612 ST->getAlignment()); 7613 7614 // Otherwise, see if we can simplify the operation with 7615 // SimplifyDemandedBits, which only works if the value has a single use. 7616 if (SimplifyDemandedBits(Value, 7617 APInt::getLowBitsSet( 7618 Value.getValueType().getScalarType().getSizeInBits(), 7619 ST->getMemoryVT().getScalarType().getSizeInBits()))) 7620 return SDValue(N, 0); 7621 } 7622 7623 // If this is a load followed by a store to the same location, then the store 7624 // is dead/noop. 7625 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 7626 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 7627 ST->isUnindexed() && !ST->isVolatile() && 7628 // There can't be any side effects between the load and store, such as 7629 // a call or store. 7630 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 7631 // The store is dead, remove it. 7632 return Chain; 7633 } 7634 } 7635 7636 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 7637 // truncating store. We can do this even if this is already a truncstore. 7638 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 7639 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 7640 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 7641 ST->getMemoryVT())) { 7642 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0), 7643 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7644 ST->isVolatile(), ST->isNonTemporal(), 7645 ST->getAlignment()); 7646 } 7647 7648 return ReduceLoadOpStoreWidth(N); 7649 } 7650 7651 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 7652 SDValue InVec = N->getOperand(0); 7653 SDValue InVal = N->getOperand(1); 7654 SDValue EltNo = N->getOperand(2); 7655 DebugLoc dl = N->getDebugLoc(); 7656 7657 // If the inserted element is an UNDEF, just use the input vector. 7658 if (InVal.getOpcode() == ISD::UNDEF) 7659 return InVec; 7660 7661 EVT VT = InVec.getValueType(); 7662 7663 // If we can't generate a legal BUILD_VECTOR, exit 7664 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 7665 return SDValue(); 7666 7667 // Check that we know which element is being inserted 7668 if (!isa<ConstantSDNode>(EltNo)) 7669 return SDValue(); 7670 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7671 7672 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 7673 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 7674 // vector elements. 7675 SmallVector<SDValue, 8> Ops; 7676 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 7677 Ops.append(InVec.getNode()->op_begin(), 7678 InVec.getNode()->op_end()); 7679 } else if (InVec.getOpcode() == ISD::UNDEF) { 7680 unsigned NElts = VT.getVectorNumElements(); 7681 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 7682 } else { 7683 return SDValue(); 7684 } 7685 7686 // Insert the element 7687 if (Elt < Ops.size()) { 7688 // All the operands of BUILD_VECTOR must have the same type; 7689 // we enforce that here. 7690 EVT OpVT = Ops[0].getValueType(); 7691 if (InVal.getValueType() != OpVT) 7692 InVal = OpVT.bitsGT(InVal.getValueType()) ? 7693 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 7694 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 7695 Ops[Elt] = InVal; 7696 } 7697 7698 // Return the new vector 7699 return DAG.getNode(ISD::BUILD_VECTOR, dl, 7700 VT, &Ops[0], Ops.size()); 7701 } 7702 7703 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 7704 // (vextract (scalar_to_vector val, 0) -> val 7705 SDValue InVec = N->getOperand(0); 7706 EVT VT = InVec.getValueType(); 7707 EVT NVT = N->getValueType(0); 7708 7709 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7710 // Check if the result type doesn't match the inserted element type. A 7711 // SCALAR_TO_VECTOR may truncate the inserted element and the 7712 // EXTRACT_VECTOR_ELT may widen the extracted vector. 7713 SDValue InOp = InVec.getOperand(0); 7714 if (InOp.getValueType() != NVT) { 7715 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 7716 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT); 7717 } 7718 return InOp; 7719 } 7720 7721 SDValue EltNo = N->getOperand(1); 7722 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 7723 7724 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 7725 // We only perform this optimization before the op legalization phase because 7726 // we may introduce new vector instructions which are not backed by TD patterns. 7727 // For example on AVX, extracting elements from a wide vector without using 7728 // extract_subvector. 7729 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 7730 && ConstEltNo && !LegalOperations) { 7731 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7732 int NumElem = VT.getVectorNumElements(); 7733 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 7734 // Find the new index to extract from. 7735 int OrigElt = SVOp->getMaskElt(Elt); 7736 7737 // Extracting an undef index is undef. 7738 if (OrigElt == -1) 7739 return DAG.getUNDEF(NVT); 7740 7741 // Select the right vector half to extract from. 7742 if (OrigElt < NumElem) { 7743 InVec = InVec->getOperand(0); 7744 } else { 7745 InVec = InVec->getOperand(1); 7746 OrigElt -= NumElem; 7747 } 7748 7749 EVT IndexTy = N->getOperand(1).getValueType(); 7750 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT, 7751 InVec, DAG.getConstant(OrigElt, IndexTy)); 7752 } 7753 7754 // Perform only after legalization to ensure build_vector / vector_shuffle 7755 // optimizations have already been done. 7756 if (!LegalOperations) return SDValue(); 7757 7758 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 7759 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 7760 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 7761 7762 if (ConstEltNo) { 7763 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7764 bool NewLoad = false; 7765 bool BCNumEltsChanged = false; 7766 EVT ExtVT = VT.getVectorElementType(); 7767 EVT LVT = ExtVT; 7768 7769 // If the result of load has to be truncated, then it's not necessarily 7770 // profitable. 7771 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 7772 return SDValue(); 7773 7774 if (InVec.getOpcode() == ISD::BITCAST) { 7775 // Don't duplicate a load with other uses. 7776 if (!InVec.hasOneUse()) 7777 return SDValue(); 7778 7779 EVT BCVT = InVec.getOperand(0).getValueType(); 7780 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 7781 return SDValue(); 7782 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 7783 BCNumEltsChanged = true; 7784 InVec = InVec.getOperand(0); 7785 ExtVT = BCVT.getVectorElementType(); 7786 NewLoad = true; 7787 } 7788 7789 LoadSDNode *LN0 = NULL; 7790 const ShuffleVectorSDNode *SVN = NULL; 7791 if (ISD::isNormalLoad(InVec.getNode())) { 7792 LN0 = cast<LoadSDNode>(InVec); 7793 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 7794 InVec.getOperand(0).getValueType() == ExtVT && 7795 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 7796 // Don't duplicate a load with other uses. 7797 if (!InVec.hasOneUse()) 7798 return SDValue(); 7799 7800 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 7801 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 7802 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 7803 // => 7804 // (load $addr+1*size) 7805 7806 // Don't duplicate a load with other uses. 7807 if (!InVec.hasOneUse()) 7808 return SDValue(); 7809 7810 // If the bit convert changed the number of elements, it is unsafe 7811 // to examine the mask. 7812 if (BCNumEltsChanged) 7813 return SDValue(); 7814 7815 // Select the input vector, guarding against out of range extract vector. 7816 unsigned NumElems = VT.getVectorNumElements(); 7817 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 7818 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 7819 7820 if (InVec.getOpcode() == ISD::BITCAST) { 7821 // Don't duplicate a load with other uses. 7822 if (!InVec.hasOneUse()) 7823 return SDValue(); 7824 7825 InVec = InVec.getOperand(0); 7826 } 7827 if (ISD::isNormalLoad(InVec.getNode())) { 7828 LN0 = cast<LoadSDNode>(InVec); 7829 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 7830 } 7831 } 7832 7833 // Make sure we found a non-volatile load and the extractelement is 7834 // the only use. 7835 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 7836 return SDValue(); 7837 7838 // If Idx was -1 above, Elt is going to be -1, so just return undef. 7839 if (Elt == -1) 7840 return DAG.getUNDEF(LVT); 7841 7842 unsigned Align = LN0->getAlignment(); 7843 if (NewLoad) { 7844 // Check the resultant load doesn't need a higher alignment than the 7845 // original load. 7846 unsigned NewAlign = 7847 TLI.getTargetData() 7848 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 7849 7850 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 7851 return SDValue(); 7852 7853 Align = NewAlign; 7854 } 7855 7856 SDValue NewPtr = LN0->getBasePtr(); 7857 unsigned PtrOff = 0; 7858 7859 if (Elt) { 7860 PtrOff = LVT.getSizeInBits() * Elt / 8; 7861 EVT PtrType = NewPtr.getValueType(); 7862 if (TLI.isBigEndian()) 7863 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 7864 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr, 7865 DAG.getConstant(PtrOff, PtrType)); 7866 } 7867 7868 // The replacement we need to do here is a little tricky: we need to 7869 // replace an extractelement of a load with a load. 7870 // Use ReplaceAllUsesOfValuesWith to do the replacement. 7871 // Note that this replacement assumes that the extractvalue is the only 7872 // use of the load; that's okay because we don't want to perform this 7873 // transformation in other cases anyway. 7874 SDValue Load; 7875 SDValue Chain; 7876 if (NVT.bitsGT(LVT)) { 7877 // If the result type of vextract is wider than the load, then issue an 7878 // extending load instead. 7879 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 7880 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 7881 Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(), 7882 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 7883 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align); 7884 Chain = Load.getValue(1); 7885 } else { 7886 Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr, 7887 LN0->getPointerInfo().getWithOffset(PtrOff), 7888 LN0->isVolatile(), LN0->isNonTemporal(), 7889 LN0->isInvariant(), Align); 7890 Chain = Load.getValue(1); 7891 if (NVT.bitsLT(LVT)) 7892 Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load); 7893 else 7894 Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load); 7895 } 7896 WorkListRemover DeadNodes(*this); 7897 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 7898 SDValue To[] = { Load, Chain }; 7899 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 7900 // Since we're explcitly calling ReplaceAllUses, add the new node to the 7901 // worklist explicitly as well. 7902 AddToWorkList(Load.getNode()); 7903 AddUsersToWorkList(Load.getNode()); // Add users too 7904 // Make sure to revisit this node to clean it up; it will usually be dead. 7905 AddToWorkList(N); 7906 return SDValue(N, 0); 7907 } 7908 7909 return SDValue(); 7910 } 7911 7912 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 7913 unsigned NumInScalars = N->getNumOperands(); 7914 DebugLoc dl = N->getDebugLoc(); 7915 EVT VT = N->getValueType(0); 7916 7917 // A vector built entirely of undefs is undef. 7918 if (ISD::allOperandsUndef(N)) 7919 return DAG.getUNDEF(VT); 7920 7921 // Check to see if this is a BUILD_VECTOR of a bunch of values 7922 // which come from any_extend or zero_extend nodes. If so, we can create 7923 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 7924 // optimizations. We do not handle sign-extend because we can't fill the sign 7925 // using shuffles. 7926 EVT SourceType = MVT::Other; 7927 bool AllAnyExt = true; 7928 7929 for (unsigned i = 0; i != NumInScalars; ++i) { 7930 SDValue In = N->getOperand(i); 7931 // Ignore undef inputs. 7932 if (In.getOpcode() == ISD::UNDEF) continue; 7933 7934 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 7935 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 7936 7937 // Abort if the element is not an extension. 7938 if (!ZeroExt && !AnyExt) { 7939 SourceType = MVT::Other; 7940 break; 7941 } 7942 7943 // The input is a ZeroExt or AnyExt. Check the original type. 7944 EVT InTy = In.getOperand(0).getValueType(); 7945 7946 // Check that all of the widened source types are the same. 7947 if (SourceType == MVT::Other) 7948 // First time. 7949 SourceType = InTy; 7950 else if (InTy != SourceType) { 7951 // Multiple income types. Abort. 7952 SourceType = MVT::Other; 7953 break; 7954 } 7955 7956 // Check if all of the extends are ANY_EXTENDs. 7957 AllAnyExt &= AnyExt; 7958 } 7959 7960 // In order to have valid types, all of the inputs must be extended from the 7961 // same source type and all of the inputs must be any or zero extend. 7962 // Scalar sizes must be a power of two. 7963 EVT OutScalarTy = N->getValueType(0).getScalarType(); 7964 bool ValidTypes = SourceType != MVT::Other && 7965 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 7966 isPowerOf2_32(SourceType.getSizeInBits()); 7967 7968 // We perform this optimization post type-legalization because 7969 // the type-legalizer often scalarizes integer-promoted vectors. 7970 // Performing this optimization before may create bit-casts which 7971 // will be type-legalized to complex code sequences. 7972 // We perform this optimization only before the operation legalizer because we 7973 // may introduce illegal operations. 7974 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 7975 // turn into a single shuffle instruction. 7976 if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) && 7977 ValidTypes) { 7978 bool isLE = TLI.isLittleEndian(); 7979 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 7980 assert(ElemRatio > 1 && "Invalid element size ratio"); 7981 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 7982 DAG.getConstant(0, SourceType); 7983 7984 unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements(); 7985 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 7986 7987 // Populate the new build_vector 7988 for (unsigned i=0; i < N->getNumOperands(); ++i) { 7989 SDValue Cast = N->getOperand(i); 7990 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 7991 Cast.getOpcode() == ISD::ZERO_EXTEND || 7992 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 7993 SDValue In; 7994 if (Cast.getOpcode() == ISD::UNDEF) 7995 In = DAG.getUNDEF(SourceType); 7996 else 7997 In = Cast->getOperand(0); 7998 unsigned Index = isLE ? (i * ElemRatio) : 7999 (i * ElemRatio + (ElemRatio - 1)); 8000 8001 assert(Index < Ops.size() && "Invalid index"); 8002 Ops[Index] = In; 8003 } 8004 8005 // The type of the new BUILD_VECTOR node. 8006 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 8007 assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() && 8008 "Invalid vector size"); 8009 // Check if the new vector type is legal. 8010 if (!isTypeLegal(VecVT)) return SDValue(); 8011 8012 // Make the new BUILD_VECTOR. 8013 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8014 VecVT, &Ops[0], Ops.size()); 8015 8016 // The new BUILD_VECTOR node has the potential to be further optimized. 8017 AddToWorkList(BV.getNode()); 8018 // Bitcast to the desired type. 8019 return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV); 8020 } 8021 8022 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 8023 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 8024 // at most two distinct vectors, turn this into a shuffle node. 8025 8026 // May only combine to shuffle after legalize if shuffle is legal. 8027 if (LegalOperations && 8028 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 8029 return SDValue(); 8030 8031 SDValue VecIn1, VecIn2; 8032 for (unsigned i = 0; i != NumInScalars; ++i) { 8033 // Ignore undef inputs. 8034 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 8035 8036 // If this input is something other than a EXTRACT_VECTOR_ELT with a 8037 // constant index, bail out. 8038 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8039 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 8040 VecIn1 = VecIn2 = SDValue(0, 0); 8041 break; 8042 } 8043 8044 // We allow up to two distinct input vectors. 8045 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 8046 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 8047 continue; 8048 8049 if (VecIn1.getNode() == 0) { 8050 VecIn1 = ExtractedFromVec; 8051 } else if (VecIn2.getNode() == 0) { 8052 VecIn2 = ExtractedFromVec; 8053 } else { 8054 // Too many inputs. 8055 VecIn1 = VecIn2 = SDValue(0, 0); 8056 break; 8057 } 8058 } 8059 8060 // If everything is good, we can make a shuffle operation. 8061 if (VecIn1.getNode()) { 8062 SmallVector<int, 8> Mask; 8063 for (unsigned i = 0; i != NumInScalars; ++i) { 8064 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 8065 Mask.push_back(-1); 8066 continue; 8067 } 8068 8069 // If extracting from the first vector, just use the index directly. 8070 SDValue Extract = N->getOperand(i); 8071 SDValue ExtVal = Extract.getOperand(1); 8072 if (Extract.getOperand(0) == VecIn1) { 8073 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 8074 if (ExtIndex > VT.getVectorNumElements()) 8075 return SDValue(); 8076 8077 Mask.push_back(ExtIndex); 8078 continue; 8079 } 8080 8081 // Otherwise, use InIdx + VecSize 8082 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 8083 Mask.push_back(Idx+NumInScalars); 8084 } 8085 8086 // We can't generate a shuffle node with mismatched input and output types. 8087 // Attempt to transform a single input vector to the correct type. 8088 if ((VT != VecIn1.getValueType())) { 8089 // We don't support shuffeling between TWO values of different types. 8090 if (VecIn2.getNode() != 0) 8091 return SDValue(); 8092 8093 // We only support widening of vectors which are half the size of the 8094 // output registers. For example XMM->YMM widening on X86 with AVX. 8095 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 8096 return SDValue(); 8097 8098 // If the input vector type has a different base type to the output 8099 // vector type, bail out. 8100 if (VecIn1.getValueType().getVectorElementType() != 8101 VT.getVectorElementType()) 8102 return SDValue(); 8103 8104 // Widen the input vector by adding undef values. 8105 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT, 8106 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 8107 } 8108 8109 // If VecIn2 is unused then change it to undef. 8110 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 8111 8112 // Check that we were able to transform all incoming values to the same type. 8113 if (VecIn2.getValueType() != VecIn1.getValueType() || 8114 VecIn1.getValueType() != VT) 8115 return SDValue(); 8116 8117 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 8118 if (!isTypeLegal(VT)) 8119 return SDValue(); 8120 8121 // Return the new VECTOR_SHUFFLE node. 8122 SDValue Ops[2]; 8123 Ops[0] = VecIn1; 8124 Ops[1] = VecIn2; 8125 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]); 8126 } 8127 8128 return SDValue(); 8129 } 8130 8131 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 8132 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 8133 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 8134 // inputs come from at most two distinct vectors, turn this into a shuffle 8135 // node. 8136 8137 // If we only have one input vector, we don't need to do any concatenation. 8138 if (N->getNumOperands() == 1) 8139 return N->getOperand(0); 8140 8141 // Check if all of the operands are undefs. 8142 if (ISD::allOperandsUndef(N)) 8143 return DAG.getUNDEF(N->getValueType(0)); 8144 8145 return SDValue(); 8146 } 8147 8148 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 8149 EVT NVT = N->getValueType(0); 8150 SDValue V = N->getOperand(0); 8151 8152 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 8153 // Handle only simple case where vector being inserted and vector 8154 // being extracted are of same type, and are half size of larger vectors. 8155 EVT BigVT = V->getOperand(0).getValueType(); 8156 EVT SmallVT = V->getOperand(1).getValueType(); 8157 if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 8158 return SDValue(); 8159 8160 // Only handle cases where both indexes are constants with the same type. 8161 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8162 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 8163 8164 if (InsIdx && ExtIdx && 8165 InsIdx->getValueType(0).getSizeInBits() <= 64 && 8166 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 8167 // Combine: 8168 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 8169 // Into: 8170 // indices are equal => V1 8171 // otherwise => (extract_subvec V1, ExtIdx) 8172 if (InsIdx->getZExtValue() == ExtIdx->getZExtValue()) 8173 return V->getOperand(1); 8174 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT, 8175 V->getOperand(0), N->getOperand(1)); 8176 } 8177 } 8178 8179 return SDValue(); 8180 } 8181 8182 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 8183 EVT VT = N->getValueType(0); 8184 unsigned NumElts = VT.getVectorNumElements(); 8185 8186 SDValue N0 = N->getOperand(0); 8187 SDValue N1 = N->getOperand(1); 8188 8189 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 8190 8191 // Canonicalize shuffle undef, undef -> undef 8192 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 8193 return DAG.getUNDEF(VT); 8194 8195 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 8196 8197 // Canonicalize shuffle v, v -> v, undef 8198 if (N0 == N1) { 8199 SmallVector<int, 8> NewMask; 8200 for (unsigned i = 0; i != NumElts; ++i) { 8201 int Idx = SVN->getMaskElt(i); 8202 if (Idx >= (int)NumElts) Idx -= NumElts; 8203 NewMask.push_back(Idx); 8204 } 8205 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT), 8206 &NewMask[0]); 8207 } 8208 8209 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 8210 if (N0.getOpcode() == ISD::UNDEF) { 8211 SmallVector<int, 8> NewMask; 8212 for (unsigned i = 0; i != NumElts; ++i) { 8213 int Idx = SVN->getMaskElt(i); 8214 if (Idx >= 0) { 8215 if (Idx < (int)NumElts) 8216 Idx += NumElts; 8217 else 8218 Idx -= NumElts; 8219 } 8220 NewMask.push_back(Idx); 8221 } 8222 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT), 8223 &NewMask[0]); 8224 } 8225 8226 // Remove references to rhs if it is undef 8227 if (N1.getOpcode() == ISD::UNDEF) { 8228 bool Changed = false; 8229 SmallVector<int, 8> NewMask; 8230 for (unsigned i = 0; i != NumElts; ++i) { 8231 int Idx = SVN->getMaskElt(i); 8232 if (Idx >= (int)NumElts) { 8233 Idx = -1; 8234 Changed = true; 8235 } 8236 NewMask.push_back(Idx); 8237 } 8238 if (Changed) 8239 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]); 8240 } 8241 8242 // If it is a splat, check if the argument vector is another splat or a 8243 // build_vector with all scalar elements the same. 8244 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 8245 SDNode *V = N0.getNode(); 8246 8247 // If this is a bit convert that changes the element type of the vector but 8248 // not the number of vector elements, look through it. Be careful not to 8249 // look though conversions that change things like v4f32 to v2f64. 8250 if (V->getOpcode() == ISD::BITCAST) { 8251 SDValue ConvInput = V->getOperand(0); 8252 if (ConvInput.getValueType().isVector() && 8253 ConvInput.getValueType().getVectorNumElements() == NumElts) 8254 V = ConvInput.getNode(); 8255 } 8256 8257 if (V->getOpcode() == ISD::BUILD_VECTOR) { 8258 assert(V->getNumOperands() == NumElts && 8259 "BUILD_VECTOR has wrong number of operands"); 8260 SDValue Base; 8261 bool AllSame = true; 8262 for (unsigned i = 0; i != NumElts; ++i) { 8263 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 8264 Base = V->getOperand(i); 8265 break; 8266 } 8267 } 8268 // Splat of <u, u, u, u>, return <u, u, u, u> 8269 if (!Base.getNode()) 8270 return N0; 8271 for (unsigned i = 0; i != NumElts; ++i) { 8272 if (V->getOperand(i) != Base) { 8273 AllSame = false; 8274 break; 8275 } 8276 } 8277 // Splat of <x, x, x, x>, return <x, x, x, x> 8278 if (AllSame) 8279 return N0; 8280 } 8281 } 8282 8283 // If this shuffle node is simply a swizzle of another shuffle node, 8284 // and it reverses the swizzle of the previous shuffle then we can 8285 // optimize shuffle(shuffle(x, undef), undef) -> x. 8286 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 8287 N1.getOpcode() == ISD::UNDEF) { 8288 8289 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 8290 8291 // Shuffle nodes can only reverse shuffles with a single non-undef value. 8292 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 8293 return SDValue(); 8294 8295 // The incoming shuffle must be of the same type as the result of the 8296 // current shuffle. 8297 assert(OtherSV->getOperand(0).getValueType() == VT && 8298 "Shuffle types don't match"); 8299 8300 for (unsigned i = 0; i != NumElts; ++i) { 8301 int Idx = SVN->getMaskElt(i); 8302 assert(Idx < (int)NumElts && "Index references undef operand"); 8303 // Next, this index comes from the first value, which is the incoming 8304 // shuffle. Adopt the incoming index. 8305 if (Idx >= 0) 8306 Idx = OtherSV->getMaskElt(Idx); 8307 8308 // The combined shuffle must map each index to itself. 8309 if (Idx >= 0 && (unsigned)Idx != i) 8310 return SDValue(); 8311 } 8312 8313 return OtherSV->getOperand(0); 8314 } 8315 8316 return SDValue(); 8317 } 8318 8319 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) { 8320 if (!TLI.getShouldFoldAtomicFences()) 8321 return SDValue(); 8322 8323 SDValue atomic = N->getOperand(0); 8324 switch (atomic.getOpcode()) { 8325 case ISD::ATOMIC_CMP_SWAP: 8326 case ISD::ATOMIC_SWAP: 8327 case ISD::ATOMIC_LOAD_ADD: 8328 case ISD::ATOMIC_LOAD_SUB: 8329 case ISD::ATOMIC_LOAD_AND: 8330 case ISD::ATOMIC_LOAD_OR: 8331 case ISD::ATOMIC_LOAD_XOR: 8332 case ISD::ATOMIC_LOAD_NAND: 8333 case ISD::ATOMIC_LOAD_MIN: 8334 case ISD::ATOMIC_LOAD_MAX: 8335 case ISD::ATOMIC_LOAD_UMIN: 8336 case ISD::ATOMIC_LOAD_UMAX: 8337 break; 8338 default: 8339 return SDValue(); 8340 } 8341 8342 SDValue fence = atomic.getOperand(0); 8343 if (fence.getOpcode() != ISD::MEMBARRIER) 8344 return SDValue(); 8345 8346 switch (atomic.getOpcode()) { 8347 case ISD::ATOMIC_CMP_SWAP: 8348 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(), 8349 fence.getOperand(0), 8350 atomic.getOperand(1), atomic.getOperand(2), 8351 atomic.getOperand(3)), atomic.getResNo()); 8352 case ISD::ATOMIC_SWAP: 8353 case ISD::ATOMIC_LOAD_ADD: 8354 case ISD::ATOMIC_LOAD_SUB: 8355 case ISD::ATOMIC_LOAD_AND: 8356 case ISD::ATOMIC_LOAD_OR: 8357 case ISD::ATOMIC_LOAD_XOR: 8358 case ISD::ATOMIC_LOAD_NAND: 8359 case ISD::ATOMIC_LOAD_MIN: 8360 case ISD::ATOMIC_LOAD_MAX: 8361 case ISD::ATOMIC_LOAD_UMIN: 8362 case ISD::ATOMIC_LOAD_UMAX: 8363 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(), 8364 fence.getOperand(0), 8365 atomic.getOperand(1), atomic.getOperand(2)), 8366 atomic.getResNo()); 8367 default: 8368 return SDValue(); 8369 } 8370 } 8371 8372 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 8373 /// an AND to a vector_shuffle with the destination vector and a zero vector. 8374 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 8375 /// vector_shuffle V, Zero, <0, 4, 2, 4> 8376 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 8377 EVT VT = N->getValueType(0); 8378 DebugLoc dl = N->getDebugLoc(); 8379 SDValue LHS = N->getOperand(0); 8380 SDValue RHS = N->getOperand(1); 8381 if (N->getOpcode() == ISD::AND) { 8382 if (RHS.getOpcode() == ISD::BITCAST) 8383 RHS = RHS.getOperand(0); 8384 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 8385 SmallVector<int, 8> Indices; 8386 unsigned NumElts = RHS.getNumOperands(); 8387 for (unsigned i = 0; i != NumElts; ++i) { 8388 SDValue Elt = RHS.getOperand(i); 8389 if (!isa<ConstantSDNode>(Elt)) 8390 return SDValue(); 8391 8392 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 8393 Indices.push_back(i); 8394 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 8395 Indices.push_back(NumElts); 8396 else 8397 return SDValue(); 8398 } 8399 8400 // Let's see if the target supports this vector_shuffle. 8401 EVT RVT = RHS.getValueType(); 8402 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 8403 return SDValue(); 8404 8405 // Return the new VECTOR_SHUFFLE node. 8406 EVT EltVT = RVT.getVectorElementType(); 8407 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 8408 DAG.getConstant(0, EltVT)); 8409 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8410 RVT, &ZeroOps[0], ZeroOps.size()); 8411 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 8412 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 8413 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 8414 } 8415 } 8416 8417 return SDValue(); 8418 } 8419 8420 /// SimplifyVBinOp - Visit a binary vector operation, like ADD. 8421 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 8422 // After legalize, the target may be depending on adds and other 8423 // binary ops to provide legal ways to construct constants or other 8424 // things. Simplifying them may result in a loss of legality. 8425 if (LegalOperations) return SDValue(); 8426 8427 assert(N->getValueType(0).isVector() && 8428 "SimplifyVBinOp only works on vectors!"); 8429 8430 SDValue LHS = N->getOperand(0); 8431 SDValue RHS = N->getOperand(1); 8432 SDValue Shuffle = XformToShuffleWithZero(N); 8433 if (Shuffle.getNode()) return Shuffle; 8434 8435 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 8436 // this operation. 8437 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 8438 RHS.getOpcode() == ISD::BUILD_VECTOR) { 8439 SmallVector<SDValue, 8> Ops; 8440 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 8441 SDValue LHSOp = LHS.getOperand(i); 8442 SDValue RHSOp = RHS.getOperand(i); 8443 // If these two elements can't be folded, bail out. 8444 if ((LHSOp.getOpcode() != ISD::UNDEF && 8445 LHSOp.getOpcode() != ISD::Constant && 8446 LHSOp.getOpcode() != ISD::ConstantFP) || 8447 (RHSOp.getOpcode() != ISD::UNDEF && 8448 RHSOp.getOpcode() != ISD::Constant && 8449 RHSOp.getOpcode() != ISD::ConstantFP)) 8450 break; 8451 8452 // Can't fold divide by zero. 8453 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 8454 N->getOpcode() == ISD::FDIV) { 8455 if ((RHSOp.getOpcode() == ISD::Constant && 8456 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 8457 (RHSOp.getOpcode() == ISD::ConstantFP && 8458 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 8459 break; 8460 } 8461 8462 EVT VT = LHSOp.getValueType(); 8463 EVT RVT = RHSOp.getValueType(); 8464 if (RVT != VT) { 8465 // Integer BUILD_VECTOR operands may have types larger than the element 8466 // size (e.g., when the element type is not legal). Prior to type 8467 // legalization, the types may not match between the two BUILD_VECTORS. 8468 // Truncate one of the operands to make them match. 8469 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 8470 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp); 8471 } else { 8472 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp); 8473 VT = RVT; 8474 } 8475 } 8476 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT, 8477 LHSOp, RHSOp); 8478 if (FoldOp.getOpcode() != ISD::UNDEF && 8479 FoldOp.getOpcode() != ISD::Constant && 8480 FoldOp.getOpcode() != ISD::ConstantFP) 8481 break; 8482 Ops.push_back(FoldOp); 8483 AddToWorkList(FoldOp.getNode()); 8484 } 8485 8486 if (Ops.size() == LHS.getNumOperands()) 8487 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8488 LHS.getValueType(), &Ops[0], Ops.size()); 8489 } 8490 8491 return SDValue(); 8492 } 8493 8494 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0, 8495 SDValue N1, SDValue N2){ 8496 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 8497 8498 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 8499 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8500 8501 // If we got a simplified select_cc node back from SimplifySelectCC, then 8502 // break it down into a new SETCC node, and a new SELECT node, and then return 8503 // the SELECT node, since we were called with a SELECT node. 8504 if (SCC.getNode()) { 8505 // Check to see if we got a select_cc back (to turn into setcc/select). 8506 // Otherwise, just return whatever node we got back, like fabs. 8507 if (SCC.getOpcode() == ISD::SELECT_CC) { 8508 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(), 8509 N0.getValueType(), 8510 SCC.getOperand(0), SCC.getOperand(1), 8511 SCC.getOperand(4)); 8512 AddToWorkList(SETCC.getNode()); 8513 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(), 8514 SCC.getOperand(2), SCC.getOperand(3), SETCC); 8515 } 8516 8517 return SCC; 8518 } 8519 return SDValue(); 8520 } 8521 8522 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 8523 /// are the two values being selected between, see if we can simplify the 8524 /// select. Callers of this should assume that TheSelect is deleted if this 8525 /// returns true. As such, they should return the appropriate thing (e.g. the 8526 /// node) back to the top-level of the DAG combiner loop to avoid it being 8527 /// looked at. 8528 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 8529 SDValue RHS) { 8530 8531 // Cannot simplify select with vector condition 8532 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 8533 8534 // If this is a select from two identical things, try to pull the operation 8535 // through the select. 8536 if (LHS.getOpcode() != RHS.getOpcode() || 8537 !LHS.hasOneUse() || !RHS.hasOneUse()) 8538 return false; 8539 8540 // If this is a load and the token chain is identical, replace the select 8541 // of two loads with a load through a select of the address to load from. 8542 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 8543 // constants have been dropped into the constant pool. 8544 if (LHS.getOpcode() == ISD::LOAD) { 8545 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 8546 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 8547 8548 // Token chains must be identical. 8549 if (LHS.getOperand(0) != RHS.getOperand(0) || 8550 // Do not let this transformation reduce the number of volatile loads. 8551 LLD->isVolatile() || RLD->isVolatile() || 8552 // If this is an EXTLOAD, the VT's must match. 8553 LLD->getMemoryVT() != RLD->getMemoryVT() || 8554 // If this is an EXTLOAD, the kind of extension must match. 8555 (LLD->getExtensionType() != RLD->getExtensionType() && 8556 // The only exception is if one of the extensions is anyext. 8557 LLD->getExtensionType() != ISD::EXTLOAD && 8558 RLD->getExtensionType() != ISD::EXTLOAD) || 8559 // FIXME: this discards src value information. This is 8560 // over-conservative. It would be beneficial to be able to remember 8561 // both potential memory locations. Since we are discarding 8562 // src value info, don't do the transformation if the memory 8563 // locations are not in the default address space. 8564 LLD->getPointerInfo().getAddrSpace() != 0 || 8565 RLD->getPointerInfo().getAddrSpace() != 0) 8566 return false; 8567 8568 // Check that the select condition doesn't reach either load. If so, 8569 // folding this will induce a cycle into the DAG. If not, this is safe to 8570 // xform, so create a select of the addresses. 8571 SDValue Addr; 8572 if (TheSelect->getOpcode() == ISD::SELECT) { 8573 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 8574 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 8575 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 8576 return false; 8577 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(), 8578 LLD->getBasePtr().getValueType(), 8579 TheSelect->getOperand(0), LLD->getBasePtr(), 8580 RLD->getBasePtr()); 8581 } else { // Otherwise SELECT_CC 8582 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 8583 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 8584 8585 if ((LLD->hasAnyUseOfValue(1) && 8586 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 8587 (RLD->hasAnyUseOfValue(1) && 8588 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 8589 return false; 8590 8591 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(), 8592 LLD->getBasePtr().getValueType(), 8593 TheSelect->getOperand(0), 8594 TheSelect->getOperand(1), 8595 LLD->getBasePtr(), RLD->getBasePtr(), 8596 TheSelect->getOperand(4)); 8597 } 8598 8599 SDValue Load; 8600 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 8601 Load = DAG.getLoad(TheSelect->getValueType(0), 8602 TheSelect->getDebugLoc(), 8603 // FIXME: Discards pointer info. 8604 LLD->getChain(), Addr, MachinePointerInfo(), 8605 LLD->isVolatile(), LLD->isNonTemporal(), 8606 LLD->isInvariant(), LLD->getAlignment()); 8607 } else { 8608 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 8609 RLD->getExtensionType() : LLD->getExtensionType(), 8610 TheSelect->getDebugLoc(), 8611 TheSelect->getValueType(0), 8612 // FIXME: Discards pointer info. 8613 LLD->getChain(), Addr, MachinePointerInfo(), 8614 LLD->getMemoryVT(), LLD->isVolatile(), 8615 LLD->isNonTemporal(), LLD->getAlignment()); 8616 } 8617 8618 // Users of the select now use the result of the load. 8619 CombineTo(TheSelect, Load); 8620 8621 // Users of the old loads now use the new load's chain. We know the 8622 // old-load value is dead now. 8623 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 8624 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 8625 return true; 8626 } 8627 8628 return false; 8629 } 8630 8631 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 8632 /// where 'cond' is the comparison specified by CC. 8633 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, 8634 SDValue N2, SDValue N3, 8635 ISD::CondCode CC, bool NotExtCompare) { 8636 // (x ? y : y) -> y. 8637 if (N2 == N3) return N2; 8638 8639 EVT VT = N2.getValueType(); 8640 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 8641 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 8642 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 8643 8644 // Determine if the condition we're dealing with is constant 8645 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 8646 N0, N1, CC, DL, false); 8647 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 8648 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 8649 8650 // fold select_cc true, x, y -> x 8651 if (SCCC && !SCCC->isNullValue()) 8652 return N2; 8653 // fold select_cc false, x, y -> y 8654 if (SCCC && SCCC->isNullValue()) 8655 return N3; 8656 8657 // Check to see if we can simplify the select into an fabs node 8658 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 8659 // Allow either -0.0 or 0.0 8660 if (CFP->getValueAPF().isZero()) { 8661 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 8662 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 8663 N0 == N2 && N3.getOpcode() == ISD::FNEG && 8664 N2 == N3.getOperand(0)) 8665 return DAG.getNode(ISD::FABS, DL, VT, N0); 8666 8667 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 8668 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 8669 N0 == N3 && N2.getOpcode() == ISD::FNEG && 8670 N2.getOperand(0) == N3) 8671 return DAG.getNode(ISD::FABS, DL, VT, N3); 8672 } 8673 } 8674 8675 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 8676 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 8677 // in it. This is a win when the constant is not otherwise available because 8678 // it replaces two constant pool loads with one. We only do this if the FP 8679 // type is known to be legal, because if it isn't, then we are before legalize 8680 // types an we want the other legalization to happen first (e.g. to avoid 8681 // messing with soft float) and if the ConstantFP is not legal, because if 8682 // it is legal, we may not need to store the FP constant in a constant pool. 8683 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 8684 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 8685 if (TLI.isTypeLegal(N2.getValueType()) && 8686 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 8687 TargetLowering::Legal) && 8688 // If both constants have multiple uses, then we won't need to do an 8689 // extra load, they are likely around in registers for other users. 8690 (TV->hasOneUse() || FV->hasOneUse())) { 8691 Constant *Elts[] = { 8692 const_cast<ConstantFP*>(FV->getConstantFPValue()), 8693 const_cast<ConstantFP*>(TV->getConstantFPValue()) 8694 }; 8695 Type *FPTy = Elts[0]->getType(); 8696 const TargetData &TD = *TLI.getTargetData(); 8697 8698 // Create a ConstantArray of the two constants. 8699 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 8700 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 8701 TD.getPrefTypeAlignment(FPTy)); 8702 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 8703 8704 // Get the offsets to the 0 and 1 element of the array so that we can 8705 // select between them. 8706 SDValue Zero = DAG.getIntPtrConstant(0); 8707 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 8708 SDValue One = DAG.getIntPtrConstant(EltSize); 8709 8710 SDValue Cond = DAG.getSetCC(DL, 8711 TLI.getSetCCResultType(N0.getValueType()), 8712 N0, N1, CC); 8713 AddToWorkList(Cond.getNode()); 8714 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(), 8715 Cond, One, Zero); 8716 AddToWorkList(CstOffset.getNode()); 8717 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx, 8718 CstOffset); 8719 AddToWorkList(CPIdx.getNode()); 8720 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 8721 MachinePointerInfo::getConstantPool(), false, 8722 false, false, Alignment); 8723 8724 } 8725 } 8726 8727 // Check to see if we can perform the "gzip trick", transforming 8728 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 8729 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 8730 (N1C->isNullValue() || // (a < 0) ? b : 0 8731 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 8732 EVT XType = N0.getValueType(); 8733 EVT AType = N2.getValueType(); 8734 if (XType.bitsGE(AType)) { 8735 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 8736 // single-bit constant. 8737 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 8738 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 8739 ShCtV = XType.getSizeInBits()-ShCtV-1; 8740 SDValue ShCt = DAG.getConstant(ShCtV, 8741 getShiftAmountTy(N0.getValueType())); 8742 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), 8743 XType, N0, ShCt); 8744 AddToWorkList(Shift.getNode()); 8745 8746 if (XType.bitsGT(AType)) { 8747 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 8748 AddToWorkList(Shift.getNode()); 8749 } 8750 8751 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 8752 } 8753 8754 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), 8755 XType, N0, 8756 DAG.getConstant(XType.getSizeInBits()-1, 8757 getShiftAmountTy(N0.getValueType()))); 8758 AddToWorkList(Shift.getNode()); 8759 8760 if (XType.bitsGT(AType)) { 8761 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 8762 AddToWorkList(Shift.getNode()); 8763 } 8764 8765 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 8766 } 8767 } 8768 8769 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 8770 // where y is has a single bit set. 8771 // A plaintext description would be, we can turn the SELECT_CC into an AND 8772 // when the condition can be materialized as an all-ones register. Any 8773 // single bit-test can be materialized as an all-ones register with 8774 // shift-left and shift-right-arith. 8775 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 8776 N0->getValueType(0) == VT && 8777 N1C && N1C->isNullValue() && 8778 N2C && N2C->isNullValue()) { 8779 SDValue AndLHS = N0->getOperand(0); 8780 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8781 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 8782 // Shift the tested bit over the sign bit. 8783 APInt AndMask = ConstAndRHS->getAPIntValue(); 8784 SDValue ShlAmt = 8785 DAG.getConstant(AndMask.countLeadingZeros(), 8786 getShiftAmountTy(AndLHS.getValueType())); 8787 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt); 8788 8789 // Now arithmetic right shift it all the way over, so the result is either 8790 // all-ones, or zero. 8791 SDValue ShrAmt = 8792 DAG.getConstant(AndMask.getBitWidth()-1, 8793 getShiftAmountTy(Shl.getValueType())); 8794 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt); 8795 8796 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 8797 } 8798 } 8799 8800 // fold select C, 16, 0 -> shl C, 4 8801 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 8802 TLI.getBooleanContents(N0.getValueType().isVector()) == 8803 TargetLowering::ZeroOrOneBooleanContent) { 8804 8805 // If the caller doesn't want us to simplify this into a zext of a compare, 8806 // don't do it. 8807 if (NotExtCompare && N2C->getAPIntValue() == 1) 8808 return SDValue(); 8809 8810 // Get a SetCC of the condition 8811 // FIXME: Should probably make sure that setcc is legal if we ever have a 8812 // target where it isn't. 8813 SDValue Temp, SCC; 8814 // cast from setcc result type to select result type 8815 if (LegalTypes) { 8816 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()), 8817 N0, N1, CC); 8818 if (N2.getValueType().bitsLT(SCC.getValueType())) 8819 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType()); 8820 else 8821 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 8822 N2.getValueType(), SCC); 8823 } else { 8824 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC); 8825 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 8826 N2.getValueType(), SCC); 8827 } 8828 8829 AddToWorkList(SCC.getNode()); 8830 AddToWorkList(Temp.getNode()); 8831 8832 if (N2C->getAPIntValue() == 1) 8833 return Temp; 8834 8835 // shl setcc result by log2 n2c 8836 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 8837 DAG.getConstant(N2C->getAPIntValue().logBase2(), 8838 getShiftAmountTy(Temp.getValueType()))); 8839 } 8840 8841 // Check to see if this is the equivalent of setcc 8842 // FIXME: Turn all of these into setcc if setcc if setcc is legal 8843 // otherwise, go ahead with the folds. 8844 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 8845 EVT XType = N0.getValueType(); 8846 if (!LegalOperations || 8847 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) { 8848 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC); 8849 if (Res.getValueType() != VT) 8850 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 8851 return Res; 8852 } 8853 8854 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 8855 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 8856 (!LegalOperations || 8857 TLI.isOperationLegal(ISD::CTLZ, XType))) { 8858 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0); 8859 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 8860 DAG.getConstant(Log2_32(XType.getSizeInBits()), 8861 getShiftAmountTy(Ctlz.getValueType()))); 8862 } 8863 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 8864 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 8865 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(), 8866 XType, DAG.getConstant(0, XType), N0); 8867 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType); 8868 return DAG.getNode(ISD::SRL, DL, XType, 8869 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 8870 DAG.getConstant(XType.getSizeInBits()-1, 8871 getShiftAmountTy(XType))); 8872 } 8873 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 8874 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 8875 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0, 8876 DAG.getConstant(XType.getSizeInBits()-1, 8877 getShiftAmountTy(N0.getValueType()))); 8878 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 8879 } 8880 } 8881 8882 // Check to see if this is an integer abs. 8883 // select_cc setg[te] X, 0, X, -X -> 8884 // select_cc setgt X, -1, X, -X -> 8885 // select_cc setl[te] X, 0, -X, X -> 8886 // select_cc setlt X, 1, -X, X -> 8887 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 8888 if (N1C) { 8889 ConstantSDNode *SubC = NULL; 8890 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 8891 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 8892 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 8893 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 8894 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 8895 (N1C->isOne() && CC == ISD::SETLT)) && 8896 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 8897 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 8898 8899 EVT XType = N0.getValueType(); 8900 if (SubC && SubC->isNullValue() && XType.isInteger()) { 8901 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, 8902 N0, 8903 DAG.getConstant(XType.getSizeInBits()-1, 8904 getShiftAmountTy(N0.getValueType()))); 8905 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), 8906 XType, N0, Shift); 8907 AddToWorkList(Shift.getNode()); 8908 AddToWorkList(Add.getNode()); 8909 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 8910 } 8911 } 8912 8913 return SDValue(); 8914 } 8915 8916 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 8917 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 8918 SDValue N1, ISD::CondCode Cond, 8919 DebugLoc DL, bool foldBooleans) { 8920 TargetLowering::DAGCombinerInfo 8921 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 8922 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 8923 } 8924 8925 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 8926 /// return a DAG expression to select that will generate the same value by 8927 /// multiplying by a magic number. See: 8928 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 8929 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 8930 std::vector<SDNode*> Built; 8931 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 8932 8933 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 8934 ii != ee; ++ii) 8935 AddToWorkList(*ii); 8936 return S; 8937 } 8938 8939 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 8940 /// return a DAG expression to select that will generate the same value by 8941 /// multiplying by a magic number. See: 8942 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 8943 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 8944 std::vector<SDNode*> Built; 8945 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 8946 8947 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 8948 ii != ee; ++ii) 8949 AddToWorkList(*ii); 8950 return S; 8951 } 8952 8953 /// FindBaseOffset - Return true if base is a frame index, which is known not 8954 // to alias with anything but itself. Provides base object and offset as 8955 // results. 8956 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 8957 const GlobalValue *&GV, const void *&CV) { 8958 // Assume it is a primitive operation. 8959 Base = Ptr; Offset = 0; GV = 0; CV = 0; 8960 8961 // If it's an adding a simple constant then integrate the offset. 8962 if (Base.getOpcode() == ISD::ADD) { 8963 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 8964 Base = Base.getOperand(0); 8965 Offset += C->getZExtValue(); 8966 } 8967 } 8968 8969 // Return the underlying GlobalValue, and update the Offset. Return false 8970 // for GlobalAddressSDNode since the same GlobalAddress may be represented 8971 // by multiple nodes with different offsets. 8972 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 8973 GV = G->getGlobal(); 8974 Offset += G->getOffset(); 8975 return false; 8976 } 8977 8978 // Return the underlying Constant value, and update the Offset. Return false 8979 // for ConstantSDNodes since the same constant pool entry may be represented 8980 // by multiple nodes with different offsets. 8981 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 8982 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 8983 : (const void *)C->getConstVal(); 8984 Offset += C->getOffset(); 8985 return false; 8986 } 8987 // If it's any of the following then it can't alias with anything but itself. 8988 return isa<FrameIndexSDNode>(Base); 8989 } 8990 8991 /// isAlias - Return true if there is any possibility that the two addresses 8992 /// overlap. 8993 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, 8994 const Value *SrcValue1, int SrcValueOffset1, 8995 unsigned SrcValueAlign1, 8996 const MDNode *TBAAInfo1, 8997 SDValue Ptr2, int64_t Size2, 8998 const Value *SrcValue2, int SrcValueOffset2, 8999 unsigned SrcValueAlign2, 9000 const MDNode *TBAAInfo2) const { 9001 // If they are the same then they must be aliases. 9002 if (Ptr1 == Ptr2) return true; 9003 9004 // Gather base node and offset information. 9005 SDValue Base1, Base2; 9006 int64_t Offset1, Offset2; 9007 const GlobalValue *GV1, *GV2; 9008 const void *CV1, *CV2; 9009 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 9010 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 9011 9012 // If they have a same base address then check to see if they overlap. 9013 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 9014 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 9015 9016 // It is possible for different frame indices to alias each other, mostly 9017 // when tail call optimization reuses return address slots for arguments. 9018 // To catch this case, look up the actual index of frame indices to compute 9019 // the real alias relationship. 9020 if (isFrameIndex1 && isFrameIndex2) { 9021 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9022 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 9023 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 9024 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 9025 } 9026 9027 // Otherwise, if we know what the bases are, and they aren't identical, then 9028 // we know they cannot alias. 9029 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 9030 return false; 9031 9032 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 9033 // compared to the size and offset of the access, we may be able to prove they 9034 // do not alias. This check is conservative for now to catch cases created by 9035 // splitting vector types. 9036 if ((SrcValueAlign1 == SrcValueAlign2) && 9037 (SrcValueOffset1 != SrcValueOffset2) && 9038 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 9039 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 9040 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 9041 9042 // There is no overlap between these relatively aligned accesses of similar 9043 // size, return no alias. 9044 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 9045 return false; 9046 } 9047 9048 if (CombinerGlobalAA) { 9049 // Use alias analysis information. 9050 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 9051 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 9052 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 9053 AliasAnalysis::AliasResult AAResult = 9054 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1), 9055 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2)); 9056 if (AAResult == AliasAnalysis::NoAlias) 9057 return false; 9058 } 9059 9060 // Otherwise we have to assume they alias. 9061 return true; 9062 } 9063 9064 /// FindAliasInfo - Extracts the relevant alias information from the memory 9065 /// node. Returns true if the operand was a load. 9066 bool DAGCombiner::FindAliasInfo(SDNode *N, 9067 SDValue &Ptr, int64_t &Size, 9068 const Value *&SrcValue, 9069 int &SrcValueOffset, 9070 unsigned &SrcValueAlign, 9071 const MDNode *&TBAAInfo) const { 9072 LSBaseSDNode *LS = cast<LSBaseSDNode>(N); 9073 9074 Ptr = LS->getBasePtr(); 9075 Size = LS->getMemoryVT().getSizeInBits() >> 3; 9076 SrcValue = LS->getSrcValue(); 9077 SrcValueOffset = LS->getSrcValueOffset(); 9078 SrcValueAlign = LS->getOriginalAlignment(); 9079 TBAAInfo = LS->getTBAAInfo(); 9080 return isa<LoadSDNode>(LS); 9081 } 9082 9083 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 9084 /// looking for aliasing nodes and adding them to the Aliases vector. 9085 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 9086 SmallVector<SDValue, 8> &Aliases) { 9087 SmallVector<SDValue, 8> Chains; // List of chains to visit. 9088 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 9089 9090 // Get alias information for node. 9091 SDValue Ptr; 9092 int64_t Size; 9093 const Value *SrcValue; 9094 int SrcValueOffset; 9095 unsigned SrcValueAlign; 9096 const MDNode *SrcTBAAInfo; 9097 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset, 9098 SrcValueAlign, SrcTBAAInfo); 9099 9100 // Starting off. 9101 Chains.push_back(OriginalChain); 9102 unsigned Depth = 0; 9103 9104 // Look at each chain and determine if it is an alias. If so, add it to the 9105 // aliases list. If not, then continue up the chain looking for the next 9106 // candidate. 9107 while (!Chains.empty()) { 9108 SDValue Chain = Chains.back(); 9109 Chains.pop_back(); 9110 9111 // For TokenFactor nodes, look at each operand and only continue up the 9112 // chain until we find two aliases. If we've seen two aliases, assume we'll 9113 // find more and revert to original chain since the xform is unlikely to be 9114 // profitable. 9115 // 9116 // FIXME: The depth check could be made to return the last non-aliasing 9117 // chain we found before we hit a tokenfactor rather than the original 9118 // chain. 9119 if (Depth > 6 || Aliases.size() == 2) { 9120 Aliases.clear(); 9121 Aliases.push_back(OriginalChain); 9122 break; 9123 } 9124 9125 // Don't bother if we've been before. 9126 if (!Visited.insert(Chain.getNode())) 9127 continue; 9128 9129 switch (Chain.getOpcode()) { 9130 case ISD::EntryToken: 9131 // Entry token is ideal chain operand, but handled in FindBetterChain. 9132 break; 9133 9134 case ISD::LOAD: 9135 case ISD::STORE: { 9136 // Get alias information for Chain. 9137 SDValue OpPtr; 9138 int64_t OpSize; 9139 const Value *OpSrcValue; 9140 int OpSrcValueOffset; 9141 unsigned OpSrcValueAlign; 9142 const MDNode *OpSrcTBAAInfo; 9143 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 9144 OpSrcValue, OpSrcValueOffset, 9145 OpSrcValueAlign, 9146 OpSrcTBAAInfo); 9147 9148 // If chain is alias then stop here. 9149 if (!(IsLoad && IsOpLoad) && 9150 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign, 9151 SrcTBAAInfo, 9152 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset, 9153 OpSrcValueAlign, OpSrcTBAAInfo)) { 9154 Aliases.push_back(Chain); 9155 } else { 9156 // Look further up the chain. 9157 Chains.push_back(Chain.getOperand(0)); 9158 ++Depth; 9159 } 9160 break; 9161 } 9162 9163 case ISD::TokenFactor: 9164 // We have to check each of the operands of the token factor for "small" 9165 // token factors, so we queue them up. Adding the operands to the queue 9166 // (stack) in reverse order maintains the original order and increases the 9167 // likelihood that getNode will find a matching token factor (CSE.) 9168 if (Chain.getNumOperands() > 16) { 9169 Aliases.push_back(Chain); 9170 break; 9171 } 9172 for (unsigned n = Chain.getNumOperands(); n;) 9173 Chains.push_back(Chain.getOperand(--n)); 9174 ++Depth; 9175 break; 9176 9177 default: 9178 // For all other instructions we will just have to take what we can get. 9179 Aliases.push_back(Chain); 9180 break; 9181 } 9182 } 9183 } 9184 9185 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 9186 /// for a better chain (aliasing node.) 9187 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 9188 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 9189 9190 // Accumulate all the aliases to this node. 9191 GatherAllAliases(N, OldChain, Aliases); 9192 9193 // If no operands then chain to entry token. 9194 if (Aliases.size() == 0) 9195 return DAG.getEntryNode(); 9196 9197 // If a single operand then chain to it. We don't need to revisit it. 9198 if (Aliases.size() == 1) 9199 return Aliases[0]; 9200 9201 // Construct a custom tailored token factor. 9202 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 9203 &Aliases[0], Aliases.size()); 9204 } 9205 9206 // SelectionDAG::Combine - This is the entry point for the file. 9207 // 9208 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 9209 CodeGenOpt::Level OptLevel) { 9210 /// run - This is the main entry point to this class. 9211 /// 9212 DAGCombiner(*this, AA, OptLevel).Run(Level); 9213 } 9214