DAGCombiner.cpp revision eb9f89287e8ff3daeb9191ecd0cc3241a4f4137d
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//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "dagcombine" 16#include "llvm/CodeGen/SelectionDAG.h" 17#include "llvm/CodeGen/MachineFunction.h" 18#include "llvm/CodeGen/MachineFrameInfo.h" 19#include "llvm/Analysis/AliasAnalysis.h" 20#include "llvm/Target/TargetData.h" 21#include "llvm/Target/TargetFrameInfo.h" 22#include "llvm/Target/TargetLowering.h" 23#include "llvm/Target/TargetMachine.h" 24#include "llvm/Target/TargetOptions.h" 25#include "llvm/ADT/SmallPtrSet.h" 26#include "llvm/ADT/Statistic.h" 27#include "llvm/Support/Compiler.h" 28#include "llvm/Support/CommandLine.h" 29#include "llvm/Support/Debug.h" 30#include "llvm/Support/MathExtras.h" 31#include <algorithm> 32#include <set> 33using namespace llvm; 34 35STATISTIC(NodesCombined , "Number of dag nodes combined"); 36STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 37STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 38 39namespace { 40 static cl::opt<bool> 41 CombinerAA("combiner-alias-analysis", cl::Hidden, 42 cl::desc("Turn on alias analysis during testing")); 43 44 static cl::opt<bool> 45 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 46 cl::desc("Include global information in alias analysis")); 47 48//------------------------------ DAGCombiner ---------------------------------// 49 50 class VISIBILITY_HIDDEN DAGCombiner { 51 SelectionDAG &DAG; 52 TargetLowering &TLI; 53 bool AfterLegalize; 54 bool Fast; 55 56 // Worklist of all of the nodes that need to be simplified. 57 std::vector<SDNode*> WorkList; 58 59 // AA - Used for DAG load/store alias analysis. 60 AliasAnalysis &AA; 61 62 /// AddUsersToWorkList - When an instruction is simplified, add all users of 63 /// the instruction to the work lists because they might get more simplified 64 /// now. 65 /// 66 void AddUsersToWorkList(SDNode *N) { 67 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 68 UI != UE; ++UI) 69 AddToWorkList(*UI); 70 } 71 72 /// visit - call the node-specific routine that knows how to fold each 73 /// particular type of node. 74 SDValue visit(SDNode *N); 75 76 public: 77 /// AddToWorkList - Add to the work list making sure it's instance is at the 78 /// the back (next to be processed.) 79 void AddToWorkList(SDNode *N) { 80 removeFromWorkList(N); 81 WorkList.push_back(N); 82 } 83 84 /// removeFromWorkList - remove all instances of N from the worklist. 85 /// 86 void removeFromWorkList(SDNode *N) { 87 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N), 88 WorkList.end()); 89 } 90 91 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 92 bool AddTo = true); 93 94 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 95 return CombineTo(N, &Res, 1, AddTo); 96 } 97 98 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 99 bool AddTo = true) { 100 SDValue To[] = { Res0, Res1 }; 101 return CombineTo(N, To, 2, AddTo); 102 } 103 104 private: 105 106 /// SimplifyDemandedBits - Check the specified integer node value to see if 107 /// it can be simplified or if things it uses can be simplified by bit 108 /// propagation. If so, return true. 109 bool SimplifyDemandedBits(SDValue Op) { 110 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits()); 111 return SimplifyDemandedBits(Op, Demanded); 112 } 113 114 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 115 116 bool CombineToPreIndexedLoadStore(SDNode *N); 117 bool CombineToPostIndexedLoadStore(SDNode *N); 118 119 120 /// combine - call the node-specific routine that knows how to fold each 121 /// particular type of node. If that doesn't do anything, try the 122 /// target-specific DAG combines. 123 SDValue combine(SDNode *N); 124 125 // Visitation implementation - Implement dag node combining for different 126 // node types. The semantics are as follows: 127 // Return Value: 128 // SDValue.getNode() == 0 - No change was made 129 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 130 // otherwise - N should be replaced by the returned Operand. 131 // 132 SDValue visitTokenFactor(SDNode *N); 133 SDValue visitMERGE_VALUES(SDNode *N); 134 SDValue visitADD(SDNode *N); 135 SDValue visitSUB(SDNode *N); 136 SDValue visitADDC(SDNode *N); 137 SDValue visitADDE(SDNode *N); 138 SDValue visitMUL(SDNode *N); 139 SDValue visitSDIV(SDNode *N); 140 SDValue visitUDIV(SDNode *N); 141 SDValue visitSREM(SDNode *N); 142 SDValue visitUREM(SDNode *N); 143 SDValue visitMULHU(SDNode *N); 144 SDValue visitMULHS(SDNode *N); 145 SDValue visitSMUL_LOHI(SDNode *N); 146 SDValue visitUMUL_LOHI(SDNode *N); 147 SDValue visitSDIVREM(SDNode *N); 148 SDValue visitUDIVREM(SDNode *N); 149 SDValue visitAND(SDNode *N); 150 SDValue visitOR(SDNode *N); 151 SDValue visitXOR(SDNode *N); 152 SDValue SimplifyVBinOp(SDNode *N); 153 SDValue visitSHL(SDNode *N); 154 SDValue visitSRA(SDNode *N); 155 SDValue visitSRL(SDNode *N); 156 SDValue visitCTLZ(SDNode *N); 157 SDValue visitCTTZ(SDNode *N); 158 SDValue visitCTPOP(SDNode *N); 159 SDValue visitSELECT(SDNode *N); 160 SDValue visitSELECT_CC(SDNode *N); 161 SDValue visitSETCC(SDNode *N); 162 SDValue visitSIGN_EXTEND(SDNode *N); 163 SDValue visitZERO_EXTEND(SDNode *N); 164 SDValue visitANY_EXTEND(SDNode *N); 165 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 166 SDValue visitTRUNCATE(SDNode *N); 167 SDValue visitBIT_CONVERT(SDNode *N); 168 SDValue visitBUILD_PAIR(SDNode *N); 169 SDValue visitFADD(SDNode *N); 170 SDValue visitFSUB(SDNode *N); 171 SDValue visitFMUL(SDNode *N); 172 SDValue visitFDIV(SDNode *N); 173 SDValue visitFREM(SDNode *N); 174 SDValue visitFCOPYSIGN(SDNode *N); 175 SDValue visitSINT_TO_FP(SDNode *N); 176 SDValue visitUINT_TO_FP(SDNode *N); 177 SDValue visitFP_TO_SINT(SDNode *N); 178 SDValue visitFP_TO_UINT(SDNode *N); 179 SDValue visitFP_ROUND(SDNode *N); 180 SDValue visitFP_ROUND_INREG(SDNode *N); 181 SDValue visitFP_EXTEND(SDNode *N); 182 SDValue visitFNEG(SDNode *N); 183 SDValue visitFABS(SDNode *N); 184 SDValue visitBRCOND(SDNode *N); 185 SDValue visitBR_CC(SDNode *N); 186 SDValue visitLOAD(SDNode *N); 187 SDValue visitSTORE(SDNode *N); 188 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 189 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 190 SDValue visitBUILD_VECTOR(SDNode *N); 191 SDValue visitCONCAT_VECTORS(SDNode *N); 192 SDValue visitVECTOR_SHUFFLE(SDNode *N); 193 194 SDValue XformToShuffleWithZero(SDNode *N); 195 SDValue ReassociateOps(unsigned Opc, SDValue LHS, SDValue RHS); 196 197 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 198 199 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 200 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 201 SDValue SimplifySelect(SDValue N0, SDValue N1, SDValue N2); 202 SDValue SimplifySelectCC(SDValue N0, SDValue N1, SDValue N2, 203 SDValue N3, ISD::CondCode CC, 204 bool NotExtCompare = false); 205 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1, 206 ISD::CondCode Cond, bool foldBooleans = true); 207 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 208 unsigned HiOp); 209 SDValue CombineConsecutiveLoads(SDNode *N, MVT VT); 210 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT); 211 SDValue BuildSDIV(SDNode *N); 212 SDValue BuildUDIV(SDNode *N); 213 SDNode *MatchRotate(SDValue LHS, SDValue RHS); 214 SDValue ReduceLoadWidth(SDNode *N); 215 216 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 217 218 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 219 /// looking for aliasing nodes and adding them to the Aliases vector. 220 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 221 SmallVector<SDValue, 8> &Aliases); 222 223 /// isAlias - Return true if there is any possibility that the two addresses 224 /// overlap. 225 bool isAlias(SDValue Ptr1, int64_t Size1, 226 const Value *SrcValue1, int SrcValueOffset1, 227 SDValue Ptr2, int64_t Size2, 228 const Value *SrcValue2, int SrcValueOffset2); 229 230 /// FindAliasInfo - Extracts the relevant alias information from the memory 231 /// node. Returns true if the operand was a load. 232 bool FindAliasInfo(SDNode *N, 233 SDValue &Ptr, int64_t &Size, 234 const Value *&SrcValue, int &SrcValueOffset); 235 236 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 237 /// looking for a better chain (aliasing node.) 238 SDValue FindBetterChain(SDNode *N, SDValue Chain); 239 240public: 241 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, bool fast) 242 : DAG(D), 243 TLI(D.getTargetLoweringInfo()), 244 AfterLegalize(false), 245 Fast(fast), 246 AA(A) {} 247 248 /// Run - runs the dag combiner on all nodes in the work list 249 void Run(bool RunningAfterLegalize); 250 }; 251} 252 253 254namespace { 255/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 256/// nodes from the worklist. 257class VISIBILITY_HIDDEN WorkListRemover : 258 public SelectionDAG::DAGUpdateListener { 259 DAGCombiner &DC; 260public: 261 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {} 262 263 virtual void NodeDeleted(SDNode *N, SDNode *E) { 264 DC.removeFromWorkList(N); 265 } 266 267 virtual void NodeUpdated(SDNode *N) { 268 // Ignore updates. 269 } 270}; 271} 272 273//===----------------------------------------------------------------------===// 274// TargetLowering::DAGCombinerInfo implementation 275//===----------------------------------------------------------------------===// 276 277void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 278 ((DAGCombiner*)DC)->AddToWorkList(N); 279} 280 281SDValue TargetLowering::DAGCombinerInfo:: 282CombineTo(SDNode *N, const std::vector<SDValue> &To) { 283 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size()); 284} 285 286SDValue TargetLowering::DAGCombinerInfo:: 287CombineTo(SDNode *N, SDValue Res) { 288 return ((DAGCombiner*)DC)->CombineTo(N, Res); 289} 290 291 292SDValue TargetLowering::DAGCombinerInfo:: 293CombineTo(SDNode *N, SDValue Res0, SDValue Res1) { 294 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1); 295} 296 297 298//===----------------------------------------------------------------------===// 299// Helper Functions 300//===----------------------------------------------------------------------===// 301 302/// isNegatibleForFree - Return 1 if we can compute the negated form of the 303/// specified expression for the same cost as the expression itself, or 2 if we 304/// can compute the negated form more cheaply than the expression itself. 305static char isNegatibleForFree(SDValue Op, bool AfterLegalize, 306 unsigned Depth = 0) { 307 // No compile time optimizations on this type. 308 if (Op.getValueType() == MVT::ppcf128) 309 return 0; 310 311 // fneg is removable even if it has multiple uses. 312 if (Op.getOpcode() == ISD::FNEG) return 2; 313 314 // Don't allow anything with multiple uses. 315 if (!Op.hasOneUse()) return 0; 316 317 // Don't recurse exponentially. 318 if (Depth > 6) return 0; 319 320 switch (Op.getOpcode()) { 321 default: return false; 322 case ISD::ConstantFP: 323 // Don't invert constant FP values after legalize. The negated constant 324 // isn't necessarily legal. 325 return AfterLegalize ? 0 : 1; 326 case ISD::FADD: 327 // FIXME: determine better conditions for this xform. 328 if (!UnsafeFPMath) return 0; 329 330 // -(A+B) -> -A - B 331 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1)) 332 return V; 333 // -(A+B) -> -B - A 334 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1); 335 case ISD::FSUB: 336 // We can't turn -(A-B) into B-A when we honor signed zeros. 337 if (!UnsafeFPMath) return 0; 338 339 // -(A-B) -> B-A 340 return 1; 341 342 case ISD::FMUL: 343 case ISD::FDIV: 344 if (HonorSignDependentRoundingFPMath()) return 0; 345 346 // -(X*Y) -> (-X * Y) or (X*-Y) 347 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1)) 348 return V; 349 350 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1); 351 352 case ISD::FP_EXTEND: 353 case ISD::FP_ROUND: 354 case ISD::FSIN: 355 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1); 356 } 357} 358 359/// GetNegatedExpression - If isNegatibleForFree returns true, this function 360/// returns the newly negated expression. 361static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 362 bool AfterLegalize, unsigned Depth = 0) { 363 // fneg is removable even if it has multiple uses. 364 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 365 366 // Don't allow anything with multiple uses. 367 assert(Op.hasOneUse() && "Unknown reuse!"); 368 369 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 370 switch (Op.getOpcode()) { 371 default: assert(0 && "Unknown code"); 372 case ISD::ConstantFP: { 373 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 374 V.changeSign(); 375 return DAG.getConstantFP(V, Op.getValueType()); 376 } 377 case ISD::FADD: 378 // FIXME: determine better conditions for this xform. 379 assert(UnsafeFPMath); 380 381 // -(A+B) -> -A - B 382 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1)) 383 return DAG.getNode(ISD::FSUB, Op.getValueType(), 384 GetNegatedExpression(Op.getOperand(0), DAG, 385 AfterLegalize, Depth+1), 386 Op.getOperand(1)); 387 // -(A+B) -> -B - A 388 return DAG.getNode(ISD::FSUB, Op.getValueType(), 389 GetNegatedExpression(Op.getOperand(1), DAG, 390 AfterLegalize, Depth+1), 391 Op.getOperand(0)); 392 case ISD::FSUB: 393 // We can't turn -(A-B) into B-A when we honor signed zeros. 394 assert(UnsafeFPMath); 395 396 // -(0-B) -> B 397 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 398 if (N0CFP->getValueAPF().isZero()) 399 return Op.getOperand(1); 400 401 // -(A-B) -> B-A 402 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1), 403 Op.getOperand(0)); 404 405 case ISD::FMUL: 406 case ISD::FDIV: 407 assert(!HonorSignDependentRoundingFPMath()); 408 409 // -(X*Y) -> -X * Y 410 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1)) 411 return DAG.getNode(Op.getOpcode(), Op.getValueType(), 412 GetNegatedExpression(Op.getOperand(0), DAG, 413 AfterLegalize, Depth+1), 414 Op.getOperand(1)); 415 416 // -(X*Y) -> X * -Y 417 return DAG.getNode(Op.getOpcode(), Op.getValueType(), 418 Op.getOperand(0), 419 GetNegatedExpression(Op.getOperand(1), DAG, 420 AfterLegalize, Depth+1)); 421 422 case ISD::FP_EXTEND: 423 case ISD::FSIN: 424 return DAG.getNode(Op.getOpcode(), Op.getValueType(), 425 GetNegatedExpression(Op.getOperand(0), DAG, 426 AfterLegalize, Depth+1)); 427 case ISD::FP_ROUND: 428 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(), 429 GetNegatedExpression(Op.getOperand(0), DAG, 430 AfterLegalize, Depth+1), 431 Op.getOperand(1)); 432 } 433} 434 435 436// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 437// that selects between the values 1 and 0, making it equivalent to a setcc. 438// Also, set the incoming LHS, RHS, and CC references to the appropriate 439// nodes based on the type of node we are checking. This simplifies life a 440// bit for the callers. 441static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 442 SDValue &CC) { 443 if (N.getOpcode() == ISD::SETCC) { 444 LHS = N.getOperand(0); 445 RHS = N.getOperand(1); 446 CC = N.getOperand(2); 447 return true; 448 } 449 if (N.getOpcode() == ISD::SELECT_CC && 450 N.getOperand(2).getOpcode() == ISD::Constant && 451 N.getOperand(3).getOpcode() == ISD::Constant && 452 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 453 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 454 LHS = N.getOperand(0); 455 RHS = N.getOperand(1); 456 CC = N.getOperand(4); 457 return true; 458 } 459 return false; 460} 461 462// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 463// one use. If this is true, it allows the users to invert the operation for 464// free when it is profitable to do so. 465static bool isOneUseSetCC(SDValue N) { 466 SDValue N0, N1, N2; 467 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 468 return true; 469 return false; 470} 471 472SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDValue N0, SDValue N1){ 473 MVT VT = N0.getValueType(); 474 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use 475 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 476 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) { 477 if (isa<ConstantSDNode>(N1)) { 478 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1); 479 AddToWorkList(OpNode.getNode()); 480 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0)); 481 } else if (N0.hasOneUse()) { 482 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1); 483 AddToWorkList(OpNode.getNode()); 484 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1)); 485 } 486 } 487 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use 488 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 489 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) { 490 if (isa<ConstantSDNode>(N0)) { 491 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0); 492 AddToWorkList(OpNode.getNode()); 493 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0)); 494 } else if (N1.hasOneUse()) { 495 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0); 496 AddToWorkList(OpNode.getNode()); 497 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1)); 498 } 499 } 500 return SDValue(); 501} 502 503SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 504 bool AddTo) { 505 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 506 ++NodesCombined; 507 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG)); 508 DOUT << "\nWith: "; DEBUG(To[0].getNode()->dump(&DAG)); 509 DOUT << " and " << NumTo-1 << " other values\n"; 510 WorkListRemover DeadNodes(*this); 511 DAG.ReplaceAllUsesWith(N, To, &DeadNodes); 512 513 if (AddTo) { 514 // Push the new nodes and any users onto the worklist 515 for (unsigned i = 0, e = NumTo; i != e; ++i) { 516 AddToWorkList(To[i].getNode()); 517 AddUsersToWorkList(To[i].getNode()); 518 } 519 } 520 521 // Nodes can be reintroduced into the worklist. Make sure we do not 522 // process a node that has been replaced. 523 removeFromWorkList(N); 524 525 // Finally, since the node is now dead, remove it from the graph. 526 DAG.DeleteNode(N); 527 return SDValue(N, 0); 528} 529 530/// SimplifyDemandedBits - Check the specified integer node value to see if 531/// it can be simplified or if things it uses can be simplified by bit 532/// propagation. If so, return true. 533bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 534 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize); 535 APInt KnownZero, KnownOne; 536 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 537 return false; 538 539 // Revisit the node. 540 AddToWorkList(Op.getNode()); 541 542 // Replace the old value with the new one. 543 ++NodesCombined; 544 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.getNode()->dump(&DAG)); 545 DOUT << "\nWith: "; DEBUG(TLO.New.getNode()->dump(&DAG)); 546 DOUT << '\n'; 547 548 // Replace all uses. If any nodes become isomorphic to other nodes and 549 // are deleted, make sure to remove them from our worklist. 550 WorkListRemover DeadNodes(*this); 551 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes); 552 553 // Push the new node and any (possibly new) users onto the worklist. 554 AddToWorkList(TLO.New.getNode()); 555 AddUsersToWorkList(TLO.New.getNode()); 556 557 // Finally, if the node is now dead, remove it from the graph. The node 558 // may not be dead if the replacement process recursively simplified to 559 // something else needing this node. 560 if (TLO.Old.getNode()->use_empty()) { 561 removeFromWorkList(TLO.Old.getNode()); 562 563 // If the operands of this node are only used by the node, they will now 564 // be dead. Make sure to visit them first to delete dead nodes early. 565 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 566 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 567 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 568 569 DAG.DeleteNode(TLO.Old.getNode()); 570 } 571 return true; 572} 573 574//===----------------------------------------------------------------------===// 575// Main DAG Combiner implementation 576//===----------------------------------------------------------------------===// 577 578void DAGCombiner::Run(bool RunningAfterLegalize) { 579 // set the instance variable, so that the various visit routines may use it. 580 AfterLegalize = RunningAfterLegalize; 581 582 // Add all the dag nodes to the worklist. 583 WorkList.reserve(DAG.allnodes_size()); 584 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 585 E = DAG.allnodes_end(); I != E; ++I) 586 WorkList.push_back(I); 587 588 // Create a dummy node (which is not added to allnodes), that adds a reference 589 // to the root node, preventing it from being deleted, and tracking any 590 // changes of the root. 591 HandleSDNode Dummy(DAG.getRoot()); 592 593 // The root of the dag may dangle to deleted nodes until the dag combiner is 594 // done. Set it to null to avoid confusion. 595 DAG.setRoot(SDValue()); 596 597 // while the worklist isn't empty, inspect the node on the end of it and 598 // try and combine it. 599 while (!WorkList.empty()) { 600 SDNode *N = WorkList.back(); 601 WorkList.pop_back(); 602 603 // If N has no uses, it is dead. Make sure to revisit all N's operands once 604 // N is deleted from the DAG, since they too may now be dead or may have a 605 // reduced number of uses, allowing other xforms. 606 if (N->use_empty() && N != &Dummy) { 607 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 608 AddToWorkList(N->getOperand(i).getNode()); 609 610 DAG.DeleteNode(N); 611 continue; 612 } 613 614 SDValue RV = combine(N); 615 616 if (RV.getNode() == 0) 617 continue; 618 619 ++NodesCombined; 620 621 // If we get back the same node we passed in, rather than a new node or 622 // zero, we know that the node must have defined multiple values and 623 // CombineTo was used. Since CombineTo takes care of the worklist 624 // mechanics for us, we have no work to do in this case. 625 if (RV.getNode() == N) 626 continue; 627 628 assert(N->getOpcode() != ISD::DELETED_NODE && 629 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 630 "Node was deleted but visit returned new node!"); 631 632 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG)); 633 DOUT << "\nWith: "; DEBUG(RV.getNode()->dump(&DAG)); 634 DOUT << '\n'; 635 WorkListRemover DeadNodes(*this); 636 if (N->getNumValues() == RV.getNode()->getNumValues()) 637 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes); 638 else { 639 assert(N->getValueType(0) == RV.getValueType() && 640 N->getNumValues() == 1 && "Type mismatch"); 641 SDValue OpV = RV; 642 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes); 643 } 644 645 // Push the new node and any users onto the worklist 646 AddToWorkList(RV.getNode()); 647 AddUsersToWorkList(RV.getNode()); 648 649 // Add any uses of the old node to the worklist in case this node is the 650 // last one that uses them. They may become dead after this node is 651 // deleted. 652 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 653 AddToWorkList(N->getOperand(i).getNode()); 654 655 // Nodes can be reintroduced into the worklist. Make sure we do not 656 // process a node that has been replaced. 657 removeFromWorkList(N); 658 659 // Finally, since the node is now dead, remove it from the graph. 660 DAG.DeleteNode(N); 661 } 662 663 // If the root changed (e.g. it was a dead load, update the root). 664 DAG.setRoot(Dummy.getValue()); 665} 666 667SDValue DAGCombiner::visit(SDNode *N) { 668 switch(N->getOpcode()) { 669 default: break; 670 case ISD::TokenFactor: return visitTokenFactor(N); 671 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 672 case ISD::ADD: return visitADD(N); 673 case ISD::SUB: return visitSUB(N); 674 case ISD::ADDC: return visitADDC(N); 675 case ISD::ADDE: return visitADDE(N); 676 case ISD::MUL: return visitMUL(N); 677 case ISD::SDIV: return visitSDIV(N); 678 case ISD::UDIV: return visitUDIV(N); 679 case ISD::SREM: return visitSREM(N); 680 case ISD::UREM: return visitUREM(N); 681 case ISD::MULHU: return visitMULHU(N); 682 case ISD::MULHS: return visitMULHS(N); 683 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 684 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 685 case ISD::SDIVREM: return visitSDIVREM(N); 686 case ISD::UDIVREM: return visitUDIVREM(N); 687 case ISD::AND: return visitAND(N); 688 case ISD::OR: return visitOR(N); 689 case ISD::XOR: return visitXOR(N); 690 case ISD::SHL: return visitSHL(N); 691 case ISD::SRA: return visitSRA(N); 692 case ISD::SRL: return visitSRL(N); 693 case ISD::CTLZ: return visitCTLZ(N); 694 case ISD::CTTZ: return visitCTTZ(N); 695 case ISD::CTPOP: return visitCTPOP(N); 696 case ISD::SELECT: return visitSELECT(N); 697 case ISD::SELECT_CC: return visitSELECT_CC(N); 698 case ISD::SETCC: return visitSETCC(N); 699 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 700 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 701 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 702 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 703 case ISD::TRUNCATE: return visitTRUNCATE(N); 704 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N); 705 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 706 case ISD::FADD: return visitFADD(N); 707 case ISD::FSUB: return visitFSUB(N); 708 case ISD::FMUL: return visitFMUL(N); 709 case ISD::FDIV: return visitFDIV(N); 710 case ISD::FREM: return visitFREM(N); 711 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 712 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 713 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 714 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 715 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 716 case ISD::FP_ROUND: return visitFP_ROUND(N); 717 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 718 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 719 case ISD::FNEG: return visitFNEG(N); 720 case ISD::FABS: return visitFABS(N); 721 case ISD::BRCOND: return visitBRCOND(N); 722 case ISD::BR_CC: return visitBR_CC(N); 723 case ISD::LOAD: return visitLOAD(N); 724 case ISD::STORE: return visitSTORE(N); 725 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 726 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 727 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 728 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 729 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 730 } 731 return SDValue(); 732} 733 734SDValue DAGCombiner::combine(SDNode *N) { 735 736 SDValue RV = visit(N); 737 738 // If nothing happened, try a target-specific DAG combine. 739 if (RV.getNode() == 0) { 740 assert(N->getOpcode() != ISD::DELETED_NODE && 741 "Node was deleted but visit returned NULL!"); 742 743 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 744 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 745 746 // Expose the DAG combiner to the target combiner impls. 747 TargetLowering::DAGCombinerInfo 748 DagCombineInfo(DAG, !AfterLegalize, false, this); 749 750 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 751 } 752 } 753 754 // If N is a commutative binary node, try commuting it to enable more 755 // sdisel CSE. 756 if (RV.getNode() == 0 && 757 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 758 N->getNumValues() == 1) { 759 SDValue N0 = N->getOperand(0); 760 SDValue N1 = N->getOperand(1); 761 // Constant operands are canonicalized to RHS. 762 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 763 SDValue Ops[] = { N1, N0 }; 764 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 765 Ops, 2); 766 if (CSENode) 767 return SDValue(CSENode, 0); 768 } 769 } 770 771 return RV; 772} 773 774/// getInputChainForNode - Given a node, return its input chain if it has one, 775/// otherwise return a null sd operand. 776static SDValue getInputChainForNode(SDNode *N) { 777 if (unsigned NumOps = N->getNumOperands()) { 778 if (N->getOperand(0).getValueType() == MVT::Other) 779 return N->getOperand(0); 780 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 781 return N->getOperand(NumOps-1); 782 for (unsigned i = 1; i < NumOps-1; ++i) 783 if (N->getOperand(i).getValueType() == MVT::Other) 784 return N->getOperand(i); 785 } 786 return SDValue(0, 0); 787} 788 789SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 790 // If N has two operands, where one has an input chain equal to the other, 791 // the 'other' chain is redundant. 792 if (N->getNumOperands() == 2) { 793 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 794 return N->getOperand(0); 795 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 796 return N->getOperand(1); 797 } 798 799 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 800 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 801 SmallPtrSet<SDNode*, 16> SeenOps; 802 bool Changed = false; // If we should replace this token factor. 803 804 // Start out with this token factor. 805 TFs.push_back(N); 806 807 // Iterate through token factors. The TFs grows when new token factors are 808 // encountered. 809 for (unsigned i = 0; i < TFs.size(); ++i) { 810 SDNode *TF = TFs[i]; 811 812 // Check each of the operands. 813 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 814 SDValue Op = TF->getOperand(i); 815 816 switch (Op.getOpcode()) { 817 case ISD::EntryToken: 818 // Entry tokens don't need to be added to the list. They are 819 // rededundant. 820 Changed = true; 821 break; 822 823 case ISD::TokenFactor: 824 if ((CombinerAA || Op.hasOneUse()) && 825 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 826 // Queue up for processing. 827 TFs.push_back(Op.getNode()); 828 // Clean up in case the token factor is removed. 829 AddToWorkList(Op.getNode()); 830 Changed = true; 831 break; 832 } 833 // Fall thru 834 835 default: 836 // Only add if it isn't already in the list. 837 if (SeenOps.insert(Op.getNode())) 838 Ops.push_back(Op); 839 else 840 Changed = true; 841 break; 842 } 843 } 844 } 845 846 SDValue Result; 847 848 // If we've change things around then replace token factor. 849 if (Changed) { 850 if (Ops.empty()) { 851 // The entry token is the only possible outcome. 852 Result = DAG.getEntryNode(); 853 } else { 854 // New and improved token factor. 855 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size()); 856 } 857 858 // Don't add users to work list. 859 return CombineTo(N, Result, false); 860 } 861 862 return Result; 863} 864 865/// MERGE_VALUES can always be eliminated. 866SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 867 WorkListRemover DeadNodes(*this); 868 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 869 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i), 870 &DeadNodes); 871 removeFromWorkList(N); 872 DAG.DeleteNode(N); 873 return SDValue(N, 0); // Return N so it doesn't get rechecked! 874} 875 876 877static 878SDValue combineShlAddConstant(SDValue N0, SDValue N1, SelectionDAG &DAG) { 879 MVT VT = N0.getValueType(); 880 SDValue N00 = N0.getOperand(0); 881 SDValue N01 = N0.getOperand(1); 882 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 883 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 884 isa<ConstantSDNode>(N00.getOperand(1))) { 885 N0 = DAG.getNode(ISD::ADD, VT, 886 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01), 887 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01)); 888 return DAG.getNode(ISD::ADD, VT, N0, N1); 889 } 890 return SDValue(); 891} 892 893static 894SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 895 SelectionDAG &DAG) { 896 MVT VT = N->getValueType(0); 897 unsigned Opc = N->getOpcode(); 898 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC; 899 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1); 900 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2); 901 ISD::CondCode CC = ISD::SETCC_INVALID; 902 if (isSlctCC) 903 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get(); 904 else { 905 SDValue CCOp = Slct.getOperand(0); 906 if (CCOp.getOpcode() == ISD::SETCC) 907 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get(); 908 } 909 910 bool DoXform = false; 911 bool InvCC = false; 912 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) && 913 "Bad input!"); 914 if (LHS.getOpcode() == ISD::Constant && 915 cast<ConstantSDNode>(LHS)->isNullValue()) 916 DoXform = true; 917 else if (CC != ISD::SETCC_INVALID && 918 RHS.getOpcode() == ISD::Constant && 919 cast<ConstantSDNode>(RHS)->isNullValue()) { 920 std::swap(LHS, RHS); 921 SDValue Op0 = Slct.getOperand(0); 922 bool isInt = (isSlctCC ? Op0.getValueType() : 923 Op0.getOperand(0).getValueType()).isInteger(); 924 CC = ISD::getSetCCInverse(CC, isInt); 925 DoXform = true; 926 InvCC = true; 927 } 928 929 if (DoXform) { 930 SDValue Result = DAG.getNode(Opc, VT, OtherOp, RHS); 931 if (isSlctCC) 932 return DAG.getSelectCC(OtherOp, Result, 933 Slct.getOperand(0), Slct.getOperand(1), CC); 934 SDValue CCOp = Slct.getOperand(0); 935 if (InvCC) 936 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0), 937 CCOp.getOperand(1), CC); 938 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result); 939 } 940 return SDValue(); 941} 942 943SDValue DAGCombiner::visitADD(SDNode *N) { 944 SDValue N0 = N->getOperand(0); 945 SDValue N1 = N->getOperand(1); 946 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 947 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 948 MVT VT = N0.getValueType(); 949 950 // fold vector ops 951 if (VT.isVector()) { 952 SDValue FoldedVOp = SimplifyVBinOp(N); 953 if (FoldedVOp.getNode()) return FoldedVOp; 954 } 955 956 // fold (add x, undef) -> undef 957 if (N0.getOpcode() == ISD::UNDEF) 958 return N0; 959 if (N1.getOpcode() == ISD::UNDEF) 960 return N1; 961 // fold (add c1, c2) -> c1+c2 962 if (N0C && N1C) 963 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT); 964 // canonicalize constant to RHS 965 if (N0C && !N1C) 966 return DAG.getNode(ISD::ADD, VT, N1, N0); 967 // fold (add x, 0) -> x 968 if (N1C && N1C->isNullValue()) 969 return N0; 970 // fold ((c1-A)+c2) -> (c1+c2)-A 971 if (N1C && N0.getOpcode() == ISD::SUB) 972 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 973 return DAG.getNode(ISD::SUB, VT, 974 DAG.getConstant(N1C->getAPIntValue()+ 975 N0C->getAPIntValue(), VT), 976 N0.getOperand(1)); 977 // reassociate add 978 SDValue RADD = ReassociateOps(ISD::ADD, N0, N1); 979 if (RADD.getNode() != 0) 980 return RADD; 981 // fold ((0-A) + B) -> B-A 982 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 983 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 984 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1)); 985 // fold (A + (0-B)) -> A-B 986 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 987 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 988 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1)); 989 // fold (A+(B-A)) -> B 990 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 991 return N1.getOperand(0); 992 993 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 994 return SDValue(N, 0); 995 996 // fold (a+b) -> (a|b) iff a and b share no bits. 997 if (VT.isInteger() && !VT.isVector()) { 998 APInt LHSZero, LHSOne; 999 APInt RHSZero, RHSOne; 1000 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()); 1001 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne); 1002 if (LHSZero.getBoolValue()) { 1003 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne); 1004 1005 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1006 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1007 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) || 1008 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask)) 1009 return DAG.getNode(ISD::OR, VT, N0, N1); 1010 } 1011 } 1012 1013 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1014 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1015 SDValue Result = combineShlAddConstant(N0, N1, DAG); 1016 if (Result.getNode()) return Result; 1017 } 1018 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1019 SDValue Result = combineShlAddConstant(N1, N0, DAG); 1020 if (Result.getNode()) return Result; 1021 } 1022 1023 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 1024 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) { 1025 SDValue Result = combineSelectAndUse(N, N0, N1, DAG); 1026 if (Result.getNode()) return Result; 1027 } 1028 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) { 1029 SDValue Result = combineSelectAndUse(N, N1, N0, DAG); 1030 if (Result.getNode()) return Result; 1031 } 1032 1033 return SDValue(); 1034} 1035 1036SDValue DAGCombiner::visitADDC(SDNode *N) { 1037 SDValue N0 = N->getOperand(0); 1038 SDValue N1 = N->getOperand(1); 1039 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1040 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1041 MVT VT = N0.getValueType(); 1042 1043 // If the flag result is dead, turn this into an ADD. 1044 if (N->hasNUsesOfValue(0, 1)) 1045 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0), 1046 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag)); 1047 1048 // canonicalize constant to RHS. 1049 if (N0C && !N1C) 1050 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0); 1051 1052 // fold (addc x, 0) -> x + no carry out 1053 if (N1C && N1C->isNullValue()) 1054 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag)); 1055 1056 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1057 APInt LHSZero, LHSOne; 1058 APInt RHSZero, RHSOne; 1059 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()); 1060 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne); 1061 if (LHSZero.getBoolValue()) { 1062 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne); 1063 1064 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1065 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1066 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) || 1067 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask)) 1068 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1), 1069 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag)); 1070 } 1071 1072 return SDValue(); 1073} 1074 1075SDValue DAGCombiner::visitADDE(SDNode *N) { 1076 SDValue N0 = N->getOperand(0); 1077 SDValue N1 = N->getOperand(1); 1078 SDValue CarryIn = N->getOperand(2); 1079 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1080 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1081 //MVT VT = N0.getValueType(); 1082 1083 // canonicalize constant to RHS 1084 if (N0C && !N1C) 1085 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn); 1086 1087 // fold (adde x, y, false) -> (addc x, y) 1088 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1089 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0); 1090 1091 return SDValue(); 1092} 1093 1094 1095 1096SDValue DAGCombiner::visitSUB(SDNode *N) { 1097 SDValue N0 = N->getOperand(0); 1098 SDValue N1 = N->getOperand(1); 1099 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1100 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1101 MVT VT = N0.getValueType(); 1102 1103 // fold vector ops 1104 if (VT.isVector()) { 1105 SDValue FoldedVOp = SimplifyVBinOp(N); 1106 if (FoldedVOp.getNode()) return FoldedVOp; 1107 } 1108 1109 // fold (sub x, x) -> 0 1110 if (N0 == N1) 1111 return DAG.getConstant(0, N->getValueType(0)); 1112 // fold (sub c1, c2) -> c1-c2 1113 if (N0C && N1C) 1114 return DAG.getNode(ISD::SUB, VT, N0, N1); 1115 // fold (sub x, c) -> (add x, -c) 1116 if (N1C) 1117 return DAG.getNode(ISD::ADD, VT, N0, 1118 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1119 // fold (A+B)-A -> B 1120 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1121 return N0.getOperand(1); 1122 // fold (A+B)-B -> A 1123 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1124 return N0.getOperand(0); 1125 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 1126 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) { 1127 SDValue Result = combineSelectAndUse(N, N1, N0, DAG); 1128 if (Result.getNode()) return Result; 1129 } 1130 // If either operand of a sub is undef, the result is undef 1131 if (N0.getOpcode() == ISD::UNDEF) 1132 return N0; 1133 if (N1.getOpcode() == ISD::UNDEF) 1134 return N1; 1135 1136 return SDValue(); 1137} 1138 1139SDValue DAGCombiner::visitMUL(SDNode *N) { 1140 SDValue N0 = N->getOperand(0); 1141 SDValue N1 = N->getOperand(1); 1142 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1143 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1144 MVT VT = N0.getValueType(); 1145 1146 // fold vector ops 1147 if (VT.isVector()) { 1148 SDValue FoldedVOp = SimplifyVBinOp(N); 1149 if (FoldedVOp.getNode()) return FoldedVOp; 1150 } 1151 1152 // fold (mul x, undef) -> 0 1153 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1154 return DAG.getConstant(0, VT); 1155 // fold (mul c1, c2) -> c1*c2 1156 if (N0C && N1C) 1157 return DAG.getNode(ISD::MUL, VT, N0, N1); 1158 // canonicalize constant to RHS 1159 if (N0C && !N1C) 1160 return DAG.getNode(ISD::MUL, VT, N1, N0); 1161 // fold (mul x, 0) -> 0 1162 if (N1C && N1C->isNullValue()) 1163 return N1; 1164 // fold (mul x, -1) -> 0-x 1165 if (N1C && N1C->isAllOnesValue()) 1166 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0); 1167 // fold (mul x, (1 << c)) -> x << c 1168 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1169 return DAG.getNode(ISD::SHL, VT, N0, 1170 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1171 TLI.getShiftAmountTy())); 1172 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1173 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) { 1174 // FIXME: If the input is something that is easily negated (e.g. a 1175 // single-use add), we should put the negate there. 1176 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), 1177 DAG.getNode(ISD::SHL, VT, N0, 1178 DAG.getConstant(Log2_64(-N1C->getSignExtended()), 1179 TLI.getShiftAmountTy()))); 1180 } 1181 1182 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1183 if (N1C && N0.getOpcode() == ISD::SHL && 1184 isa<ConstantSDNode>(N0.getOperand(1))) { 1185 SDValue C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1)); 1186 AddToWorkList(C3.getNode()); 1187 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3); 1188 } 1189 1190 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1191 // use. 1192 { 1193 SDValue Sh(0,0), Y(0,0); 1194 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1195 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) && 1196 N0.getNode()->hasOneUse()) { 1197 Sh = N0; Y = N1; 1198 } else if (N1.getOpcode() == ISD::SHL && 1199 isa<ConstantSDNode>(N1.getOperand(1)) && N1.getNode()->hasOneUse()) { 1200 Sh = N1; Y = N0; 1201 } 1202 if (Sh.getNode()) { 1203 SDValue Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y); 1204 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1)); 1205 } 1206 } 1207 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1208 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1209 isa<ConstantSDNode>(N0.getOperand(1))) { 1210 return DAG.getNode(ISD::ADD, VT, 1211 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1), 1212 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1)); 1213 } 1214 1215 // reassociate mul 1216 SDValue RMUL = ReassociateOps(ISD::MUL, N0, N1); 1217 if (RMUL.getNode() != 0) 1218 return RMUL; 1219 1220 return SDValue(); 1221} 1222 1223SDValue DAGCombiner::visitSDIV(SDNode *N) { 1224 SDValue N0 = N->getOperand(0); 1225 SDValue N1 = N->getOperand(1); 1226 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1227 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1228 MVT VT = N->getValueType(0); 1229 1230 // fold vector ops 1231 if (VT.isVector()) { 1232 SDValue FoldedVOp = SimplifyVBinOp(N); 1233 if (FoldedVOp.getNode()) return FoldedVOp; 1234 } 1235 1236 // fold (sdiv c1, c2) -> c1/c2 1237 if (N0C && N1C && !N1C->isNullValue()) 1238 return DAG.getNode(ISD::SDIV, VT, N0, N1); 1239 // fold (sdiv X, 1) -> X 1240 if (N1C && N1C->getSignExtended() == 1LL) 1241 return N0; 1242 // fold (sdiv X, -1) -> 0-X 1243 if (N1C && N1C->isAllOnesValue()) 1244 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0); 1245 // If we know the sign bits of both operands are zero, strength reduce to a 1246 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1247 if (!VT.isVector()) { 1248 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1249 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1); 1250 } 1251 // fold (sdiv X, pow2) -> simple ops after legalize 1252 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() && 1253 (isPowerOf2_64(N1C->getSignExtended()) || 1254 isPowerOf2_64(-N1C->getSignExtended()))) { 1255 // If dividing by powers of two is cheap, then don't perform the following 1256 // fold. 1257 if (TLI.isPow2DivCheap()) 1258 return SDValue(); 1259 int64_t pow2 = N1C->getSignExtended(); 1260 int64_t abs2 = pow2 > 0 ? pow2 : -pow2; 1261 unsigned lg2 = Log2_64(abs2); 1262 // Splat the sign bit into the register 1263 SDValue SGN = DAG.getNode(ISD::SRA, VT, N0, 1264 DAG.getConstant(VT.getSizeInBits()-1, 1265 TLI.getShiftAmountTy())); 1266 AddToWorkList(SGN.getNode()); 1267 // Add (N0 < 0) ? abs2 - 1 : 0; 1268 SDValue SRL = DAG.getNode(ISD::SRL, VT, SGN, 1269 DAG.getConstant(VT.getSizeInBits()-lg2, 1270 TLI.getShiftAmountTy())); 1271 SDValue ADD = DAG.getNode(ISD::ADD, VT, N0, SRL); 1272 AddToWorkList(SRL.getNode()); 1273 AddToWorkList(ADD.getNode()); // Divide by pow2 1274 SDValue SRA = DAG.getNode(ISD::SRA, VT, ADD, 1275 DAG.getConstant(lg2, TLI.getShiftAmountTy())); 1276 // If we're dividing by a positive value, we're done. Otherwise, we must 1277 // negate the result. 1278 if (pow2 > 0) 1279 return SRA; 1280 AddToWorkList(SRA.getNode()); 1281 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA); 1282 } 1283 // if integer divide is expensive and we satisfy the requirements, emit an 1284 // alternate sequence. 1285 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) && 1286 !TLI.isIntDivCheap()) { 1287 SDValue Op = BuildSDIV(N); 1288 if (Op.getNode()) return Op; 1289 } 1290 1291 // undef / X -> 0 1292 if (N0.getOpcode() == ISD::UNDEF) 1293 return DAG.getConstant(0, VT); 1294 // X / undef -> undef 1295 if (N1.getOpcode() == ISD::UNDEF) 1296 return N1; 1297 1298 return SDValue(); 1299} 1300 1301SDValue DAGCombiner::visitUDIV(SDNode *N) { 1302 SDValue N0 = N->getOperand(0); 1303 SDValue N1 = N->getOperand(1); 1304 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1306 MVT VT = N->getValueType(0); 1307 1308 // fold vector ops 1309 if (VT.isVector()) { 1310 SDValue FoldedVOp = SimplifyVBinOp(N); 1311 if (FoldedVOp.getNode()) return FoldedVOp; 1312 } 1313 1314 // fold (udiv c1, c2) -> c1/c2 1315 if (N0C && N1C && !N1C->isNullValue()) 1316 return DAG.getNode(ISD::UDIV, VT, N0, N1); 1317 // fold (udiv x, (1 << c)) -> x >>u c 1318 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1319 return DAG.getNode(ISD::SRL, VT, N0, 1320 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1321 TLI.getShiftAmountTy())); 1322 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 1323 if (N1.getOpcode() == ISD::SHL) { 1324 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 1325 if (SHC->getAPIntValue().isPowerOf2()) { 1326 MVT ADDVT = N1.getOperand(1).getValueType(); 1327 SDValue Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1), 1328 DAG.getConstant(SHC->getAPIntValue() 1329 .logBase2(), 1330 ADDVT)); 1331 AddToWorkList(Add.getNode()); 1332 return DAG.getNode(ISD::SRL, VT, N0, Add); 1333 } 1334 } 1335 } 1336 // fold (udiv x, c) -> alternate 1337 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1338 SDValue Op = BuildUDIV(N); 1339 if (Op.getNode()) return Op; 1340 } 1341 1342 // undef / X -> 0 1343 if (N0.getOpcode() == ISD::UNDEF) 1344 return DAG.getConstant(0, VT); 1345 // X / undef -> undef 1346 if (N1.getOpcode() == ISD::UNDEF) 1347 return N1; 1348 1349 return SDValue(); 1350} 1351 1352SDValue DAGCombiner::visitSREM(SDNode *N) { 1353 SDValue N0 = N->getOperand(0); 1354 SDValue N1 = N->getOperand(1); 1355 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1356 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1357 MVT VT = N->getValueType(0); 1358 1359 // fold (srem c1, c2) -> c1%c2 1360 if (N0C && N1C && !N1C->isNullValue()) 1361 return DAG.getNode(ISD::SREM, VT, N0, N1); 1362 // If we know the sign bits of both operands are zero, strength reduce to a 1363 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 1364 if (!VT.isVector()) { 1365 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1366 return DAG.getNode(ISD::UREM, VT, N0, N1); 1367 } 1368 1369 // If X/C can be simplified by the division-by-constant logic, lower 1370 // X%C to the equivalent of X-X/C*C. 1371 if (N1C && !N1C->isNullValue()) { 1372 SDValue Div = DAG.getNode(ISD::SDIV, VT, N0, N1); 1373 AddToWorkList(Div.getNode()); 1374 SDValue OptimizedDiv = combine(Div.getNode()); 1375 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 1376 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1); 1377 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul); 1378 AddToWorkList(Mul.getNode()); 1379 return Sub; 1380 } 1381 } 1382 1383 // undef % X -> 0 1384 if (N0.getOpcode() == ISD::UNDEF) 1385 return DAG.getConstant(0, VT); 1386 // X % undef -> undef 1387 if (N1.getOpcode() == ISD::UNDEF) 1388 return N1; 1389 1390 return SDValue(); 1391} 1392 1393SDValue DAGCombiner::visitUREM(SDNode *N) { 1394 SDValue N0 = N->getOperand(0); 1395 SDValue N1 = N->getOperand(1); 1396 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1397 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1398 MVT VT = N->getValueType(0); 1399 1400 // fold (urem c1, c2) -> c1%c2 1401 if (N0C && N1C && !N1C->isNullValue()) 1402 return DAG.getNode(ISD::UREM, VT, N0, N1); 1403 // fold (urem x, pow2) -> (and x, pow2-1) 1404 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 1405 return DAG.getNode(ISD::AND, VT, N0, 1406 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 1407 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 1408 if (N1.getOpcode() == ISD::SHL) { 1409 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 1410 if (SHC->getAPIntValue().isPowerOf2()) { 1411 SDValue Add = 1412 DAG.getNode(ISD::ADD, VT, N1, 1413 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 1414 VT)); 1415 AddToWorkList(Add.getNode()); 1416 return DAG.getNode(ISD::AND, VT, N0, Add); 1417 } 1418 } 1419 } 1420 1421 // If X/C can be simplified by the division-by-constant logic, lower 1422 // X%C to the equivalent of X-X/C*C. 1423 if (N1C && !N1C->isNullValue()) { 1424 SDValue Div = DAG.getNode(ISD::UDIV, VT, N0, N1); 1425 SDValue OptimizedDiv = combine(Div.getNode()); 1426 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 1427 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1); 1428 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul); 1429 AddToWorkList(Mul.getNode()); 1430 return Sub; 1431 } 1432 } 1433 1434 // undef % X -> 0 1435 if (N0.getOpcode() == ISD::UNDEF) 1436 return DAG.getConstant(0, VT); 1437 // X % undef -> undef 1438 if (N1.getOpcode() == ISD::UNDEF) 1439 return N1; 1440 1441 return SDValue(); 1442} 1443 1444SDValue DAGCombiner::visitMULHS(SDNode *N) { 1445 SDValue N0 = N->getOperand(0); 1446 SDValue N1 = N->getOperand(1); 1447 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1448 MVT VT = N->getValueType(0); 1449 1450 // fold (mulhs x, 0) -> 0 1451 if (N1C && N1C->isNullValue()) 1452 return N1; 1453 // fold (mulhs x, 1) -> (sra x, size(x)-1) 1454 if (N1C && N1C->getAPIntValue() == 1) 1455 return DAG.getNode(ISD::SRA, N0.getValueType(), N0, 1456 DAG.getConstant(N0.getValueType().getSizeInBits()-1, 1457 TLI.getShiftAmountTy())); 1458 // fold (mulhs x, undef) -> 0 1459 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1460 return DAG.getConstant(0, VT); 1461 1462 return SDValue(); 1463} 1464 1465SDValue DAGCombiner::visitMULHU(SDNode *N) { 1466 SDValue N0 = N->getOperand(0); 1467 SDValue N1 = N->getOperand(1); 1468 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1469 MVT VT = N->getValueType(0); 1470 1471 // fold (mulhu x, 0) -> 0 1472 if (N1C && N1C->isNullValue()) 1473 return N1; 1474 // fold (mulhu x, 1) -> 0 1475 if (N1C && N1C->getAPIntValue() == 1) 1476 return DAG.getConstant(0, N0.getValueType()); 1477 // fold (mulhu x, undef) -> 0 1478 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1479 return DAG.getConstant(0, VT); 1480 1481 return SDValue(); 1482} 1483 1484/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 1485/// compute two values. LoOp and HiOp give the opcodes for the two computations 1486/// that are being performed. Return true if a simplification was made. 1487/// 1488SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 1489 unsigned HiOp) { 1490 // If the high half is not needed, just compute the low half. 1491 bool HiExists = N->hasAnyUseOfValue(1); 1492 if (!HiExists && 1493 (!AfterLegalize || 1494 TLI.isOperationLegal(LoOp, N->getValueType(0)))) { 1495 SDValue Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(), 1496 N->getNumOperands()); 1497 return CombineTo(N, Res, Res); 1498 } 1499 1500 // If the low half is not needed, just compute the high half. 1501 bool LoExists = N->hasAnyUseOfValue(0); 1502 if (!LoExists && 1503 (!AfterLegalize || 1504 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 1505 SDValue Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(), 1506 N->getNumOperands()); 1507 return CombineTo(N, Res, Res); 1508 } 1509 1510 // If both halves are used, return as it is. 1511 if (LoExists && HiExists) 1512 return SDValue(); 1513 1514 // If the two computed results can be simplified separately, separate them. 1515 if (LoExists) { 1516 SDValue Lo = DAG.getNode(LoOp, N->getValueType(0), 1517 N->op_begin(), N->getNumOperands()); 1518 AddToWorkList(Lo.getNode()); 1519 SDValue LoOpt = combine(Lo.getNode()); 1520 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 1521 (!AfterLegalize || 1522 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 1523 return CombineTo(N, LoOpt, LoOpt); 1524 } 1525 1526 if (HiExists) { 1527 SDValue Hi = DAG.getNode(HiOp, N->getValueType(1), 1528 N->op_begin(), N->getNumOperands()); 1529 AddToWorkList(Hi.getNode()); 1530 SDValue HiOpt = combine(Hi.getNode()); 1531 if (HiOpt.getNode() && HiOpt != Hi && 1532 (!AfterLegalize || 1533 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 1534 return CombineTo(N, HiOpt, HiOpt); 1535 } 1536 return SDValue(); 1537} 1538 1539SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 1540 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 1541 if (Res.getNode()) return Res; 1542 1543 return SDValue(); 1544} 1545 1546SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 1547 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 1548 if (Res.getNode()) return Res; 1549 1550 return SDValue(); 1551} 1552 1553SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 1554 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 1555 if (Res.getNode()) return Res; 1556 1557 return SDValue(); 1558} 1559 1560SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 1561 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 1562 if (Res.getNode()) return Res; 1563 1564 return SDValue(); 1565} 1566 1567/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 1568/// two operands of the same opcode, try to simplify it. 1569SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 1570 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 1571 MVT VT = N0.getValueType(); 1572 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 1573 1574 // For each of OP in AND/OR/XOR: 1575 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 1576 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 1577 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 1578 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) 1579 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND|| 1580 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) && 1581 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) { 1582 SDValue ORNode = DAG.getNode(N->getOpcode(), 1583 N0.getOperand(0).getValueType(), 1584 N0.getOperand(0), N1.getOperand(0)); 1585 AddToWorkList(ORNode.getNode()); 1586 return DAG.getNode(N0.getOpcode(), VT, ORNode); 1587 } 1588 1589 // For each of OP in SHL/SRL/SRA/AND... 1590 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 1591 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 1592 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 1593 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 1594 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 1595 N0.getOperand(1) == N1.getOperand(1)) { 1596 SDValue ORNode = DAG.getNode(N->getOpcode(), 1597 N0.getOperand(0).getValueType(), 1598 N0.getOperand(0), N1.getOperand(0)); 1599 AddToWorkList(ORNode.getNode()); 1600 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1)); 1601 } 1602 1603 return SDValue(); 1604} 1605 1606SDValue DAGCombiner::visitAND(SDNode *N) { 1607 SDValue N0 = N->getOperand(0); 1608 SDValue N1 = N->getOperand(1); 1609 SDValue LL, LR, RL, RR, CC0, CC1; 1610 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1611 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1612 MVT VT = N1.getValueType(); 1613 unsigned BitWidth = VT.getSizeInBits(); 1614 1615 // fold vector ops 1616 if (VT.isVector()) { 1617 SDValue FoldedVOp = SimplifyVBinOp(N); 1618 if (FoldedVOp.getNode()) return FoldedVOp; 1619 } 1620 1621 // fold (and x, undef) -> 0 1622 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1623 return DAG.getConstant(0, VT); 1624 // fold (and c1, c2) -> c1&c2 1625 if (N0C && N1C) 1626 return DAG.getNode(ISD::AND, VT, N0, N1); 1627 // canonicalize constant to RHS 1628 if (N0C && !N1C) 1629 return DAG.getNode(ISD::AND, VT, N1, N0); 1630 // fold (and x, -1) -> x 1631 if (N1C && N1C->isAllOnesValue()) 1632 return N0; 1633 // if (and x, c) is known to be zero, return 0 1634 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 1635 APInt::getAllOnesValue(BitWidth))) 1636 return DAG.getConstant(0, VT); 1637 // reassociate and 1638 SDValue RAND = ReassociateOps(ISD::AND, N0, N1); 1639 if (RAND.getNode() != 0) 1640 return RAND; 1641 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF 1642 if (N1C && N0.getOpcode() == ISD::OR) 1643 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 1644 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 1645 return N1; 1646 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 1647 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 1648 SDValue N0Op0 = N0.getOperand(0); 1649 APInt Mask = ~N1C->getAPIntValue(); 1650 Mask.trunc(N0Op0.getValueSizeInBits()); 1651 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 1652 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(), 1653 N0Op0); 1654 1655 // Replace uses of the AND with uses of the Zero extend node. 1656 CombineTo(N, Zext); 1657 1658 // We actually want to replace all uses of the any_extend with the 1659 // zero_extend, to avoid duplicating things. This will later cause this 1660 // AND to be folded. 1661 CombineTo(N0.getNode(), Zext); 1662 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1663 } 1664 } 1665 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 1666 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 1667 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 1668 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 1669 1670 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 1671 LL.getValueType().isInteger()) { 1672 // fold (X == 0) & (Y == 0) -> (X|Y == 0) 1673 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 1674 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL); 1675 AddToWorkList(ORNode.getNode()); 1676 return DAG.getSetCC(VT, ORNode, LR, Op1); 1677 } 1678 // fold (X == -1) & (Y == -1) -> (X&Y == -1) 1679 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 1680 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL); 1681 AddToWorkList(ANDNode.getNode()); 1682 return DAG.getSetCC(VT, ANDNode, LR, Op1); 1683 } 1684 // fold (X > -1) & (Y > -1) -> (X|Y > -1) 1685 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 1686 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL); 1687 AddToWorkList(ORNode.getNode()); 1688 return DAG.getSetCC(VT, ORNode, LR, Op1); 1689 } 1690 } 1691 // canonicalize equivalent to ll == rl 1692 if (LL == RR && LR == RL) { 1693 Op1 = ISD::getSetCCSwappedOperands(Op1); 1694 std::swap(RL, RR); 1695 } 1696 if (LL == RL && LR == RR) { 1697 bool isInteger = LL.getValueType().isInteger(); 1698 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 1699 if (Result != ISD::SETCC_INVALID) 1700 return DAG.getSetCC(N0.getValueType(), LL, LR, Result); 1701 } 1702 } 1703 1704 // Simplify: and (op x...), (op y...) -> (op (and x, y)) 1705 if (N0.getOpcode() == N1.getOpcode()) { 1706 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 1707 if (Tmp.getNode()) return Tmp; 1708 } 1709 1710 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 1711 // fold (and (sra)) -> (and (srl)) when possible. 1712 if (!VT.isVector() && 1713 SimplifyDemandedBits(SDValue(N, 0))) 1714 return SDValue(N, 0); 1715 // fold (zext_inreg (extload x)) -> (zextload x) 1716 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 1717 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 1718 MVT EVT = LN0->getMemoryVT(); 1719 // If we zero all the possible extended bits, then we can turn this into 1720 // a zextload if we are running before legalize or the operation is legal. 1721 unsigned BitWidth = N1.getValueSizeInBits(); 1722 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 1723 BitWidth - EVT.getSizeInBits())) && 1724 ((!AfterLegalize && !LN0->isVolatile()) || 1725 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) { 1726 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), 1727 LN0->getBasePtr(), LN0->getSrcValue(), 1728 LN0->getSrcValueOffset(), EVT, 1729 LN0->isVolatile(), 1730 LN0->getAlignment()); 1731 AddToWorkList(N); 1732 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 1733 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1734 } 1735 } 1736 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 1737 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 1738 N0.hasOneUse()) { 1739 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 1740 MVT EVT = LN0->getMemoryVT(); 1741 // If we zero all the possible extended bits, then we can turn this into 1742 // a zextload if we are running before legalize or the operation is legal. 1743 unsigned BitWidth = N1.getValueSizeInBits(); 1744 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 1745 BitWidth - EVT.getSizeInBits())) && 1746 ((!AfterLegalize && !LN0->isVolatile()) || 1747 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) { 1748 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), 1749 LN0->getBasePtr(), LN0->getSrcValue(), 1750 LN0->getSrcValueOffset(), EVT, 1751 LN0->isVolatile(), 1752 LN0->getAlignment()); 1753 AddToWorkList(N); 1754 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 1755 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1756 } 1757 } 1758 1759 // fold (and (load x), 255) -> (zextload x, i8) 1760 // fold (and (extload x, i16), 255) -> (zextload x, i8) 1761 if (N1C && N0.getOpcode() == ISD::LOAD) { 1762 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 1763 if (LN0->getExtensionType() != ISD::SEXTLOAD && 1764 LN0->isUnindexed() && N0.hasOneUse() && 1765 // Do not change the width of a volatile load. 1766 !LN0->isVolatile()) { 1767 MVT EVT = MVT::Other; 1768 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 1769 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())) 1770 EVT = MVT::getIntegerVT(ActiveBits); 1771 1772 MVT LoadedVT = LN0->getMemoryVT(); 1773 // Do not generate loads of non-round integer types since these can 1774 // be expensive (and would be wrong if the type is not byte sized). 1775 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() && 1776 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) { 1777 MVT PtrType = N0.getOperand(1).getValueType(); 1778 // For big endian targets, we need to add an offset to the pointer to 1779 // load the correct bytes. For little endian systems, we merely need to 1780 // read fewer bytes from the same pointer. 1781 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8; 1782 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8; 1783 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 1784 unsigned Alignment = LN0->getAlignment(); 1785 SDValue NewPtr = LN0->getBasePtr(); 1786 if (TLI.isBigEndian()) { 1787 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr, 1788 DAG.getConstant(PtrOff, PtrType)); 1789 Alignment = MinAlign(Alignment, PtrOff); 1790 } 1791 AddToWorkList(NewPtr.getNode()); 1792 SDValue Load = 1793 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr, 1794 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT, 1795 LN0->isVolatile(), Alignment); 1796 AddToWorkList(N); 1797 CombineTo(N0.getNode(), Load, Load.getValue(1)); 1798 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1799 } 1800 } 1801 } 1802 1803 return SDValue(); 1804} 1805 1806SDValue DAGCombiner::visitOR(SDNode *N) { 1807 SDValue N0 = N->getOperand(0); 1808 SDValue N1 = N->getOperand(1); 1809 SDValue LL, LR, RL, RR, CC0, CC1; 1810 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1811 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1812 MVT VT = N1.getValueType(); 1813 1814 // fold vector ops 1815 if (VT.isVector()) { 1816 SDValue FoldedVOp = SimplifyVBinOp(N); 1817 if (FoldedVOp.getNode()) return FoldedVOp; 1818 } 1819 1820 // fold (or x, undef) -> -1 1821 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1822 return DAG.getConstant(~0ULL, VT); 1823 // fold (or c1, c2) -> c1|c2 1824 if (N0C && N1C) 1825 return DAG.getNode(ISD::OR, VT, N0, N1); 1826 // canonicalize constant to RHS 1827 if (N0C && !N1C) 1828 return DAG.getNode(ISD::OR, VT, N1, N0); 1829 // fold (or x, 0) -> x 1830 if (N1C && N1C->isNullValue()) 1831 return N0; 1832 // fold (or x, -1) -> -1 1833 if (N1C && N1C->isAllOnesValue()) 1834 return N1; 1835 // fold (or x, c) -> c iff (x & ~c) == 0 1836 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 1837 return N1; 1838 // reassociate or 1839 SDValue ROR = ReassociateOps(ISD::OR, N0, N1); 1840 if (ROR.getNode() != 0) 1841 return ROR; 1842 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 1843 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 1844 isa<ConstantSDNode>(N0.getOperand(1))) { 1845 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 1846 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0), 1847 N1), 1848 DAG.getConstant(N1C->getAPIntValue() | 1849 C1->getAPIntValue(), VT)); 1850 } 1851 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 1852 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 1853 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 1854 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 1855 1856 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 1857 LL.getValueType().isInteger()) { 1858 // fold (X != 0) | (Y != 0) -> (X|Y != 0) 1859 // fold (X < 0) | (Y < 0) -> (X|Y < 0) 1860 if (cast<ConstantSDNode>(LR)->isNullValue() && 1861 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 1862 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL); 1863 AddToWorkList(ORNode.getNode()); 1864 return DAG.getSetCC(VT, ORNode, LR, Op1); 1865 } 1866 // fold (X != -1) | (Y != -1) -> (X&Y != -1) 1867 // fold (X > -1) | (Y > -1) -> (X&Y > -1) 1868 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 1869 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 1870 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL); 1871 AddToWorkList(ANDNode.getNode()); 1872 return DAG.getSetCC(VT, ANDNode, LR, Op1); 1873 } 1874 } 1875 // canonicalize equivalent to ll == rl 1876 if (LL == RR && LR == RL) { 1877 Op1 = ISD::getSetCCSwappedOperands(Op1); 1878 std::swap(RL, RR); 1879 } 1880 if (LL == RL && LR == RR) { 1881 bool isInteger = LL.getValueType().isInteger(); 1882 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 1883 if (Result != ISD::SETCC_INVALID) 1884 return DAG.getSetCC(N0.getValueType(), LL, LR, Result); 1885 } 1886 } 1887 1888 // Simplify: or (op x...), (op y...) -> (op (or x, y)) 1889 if (N0.getOpcode() == N1.getOpcode()) { 1890 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 1891 if (Tmp.getNode()) return Tmp; 1892 } 1893 1894 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible. 1895 if (N0.getOpcode() == ISD::AND && 1896 N1.getOpcode() == ISD::AND && 1897 N0.getOperand(1).getOpcode() == ISD::Constant && 1898 N1.getOperand(1).getOpcode() == ISD::Constant && 1899 // Don't increase # computations. 1900 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 1901 // We can only do this xform if we know that bits from X that are set in C2 1902 // but not in C1 are already zero. Likewise for Y. 1903 const APInt &LHSMask = 1904 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1905 const APInt &RHSMask = 1906 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 1907 1908 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 1909 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 1910 SDValue X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0)); 1911 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT)); 1912 } 1913 } 1914 1915 1916 // See if this is some rotate idiom. 1917 if (SDNode *Rot = MatchRotate(N0, N1)) 1918 return SDValue(Rot, 0); 1919 1920 return SDValue(); 1921} 1922 1923 1924/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 1925static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 1926 if (Op.getOpcode() == ISD::AND) { 1927 if (isa<ConstantSDNode>(Op.getOperand(1))) { 1928 Mask = Op.getOperand(1); 1929 Op = Op.getOperand(0); 1930 } else { 1931 return false; 1932 } 1933 } 1934 1935 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 1936 Shift = Op; 1937 return true; 1938 } 1939 return false; 1940} 1941 1942 1943// MatchRotate - Handle an 'or' of two operands. If this is one of the many 1944// idioms for rotate, and if the target supports rotation instructions, generate 1945// a rot[lr]. 1946SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS) { 1947 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 1948 MVT VT = LHS.getValueType(); 1949 if (!TLI.isTypeLegal(VT)) return 0; 1950 1951 // The target must have at least one rotate flavor. 1952 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT); 1953 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT); 1954 if (!HasROTL && !HasROTR) return 0; 1955 1956 // Match "(X shl/srl V1) & V2" where V2 may not be present. 1957 SDValue LHSShift; // The shift. 1958 SDValue LHSMask; // AND value if any. 1959 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 1960 return 0; // Not part of a rotate. 1961 1962 SDValue RHSShift; // The shift. 1963 SDValue RHSMask; // AND value if any. 1964 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 1965 return 0; // Not part of a rotate. 1966 1967 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 1968 return 0; // Not shifting the same value. 1969 1970 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 1971 return 0; // Shifts must disagree. 1972 1973 // Canonicalize shl to left side in a shl/srl pair. 1974 if (RHSShift.getOpcode() == ISD::SHL) { 1975 std::swap(LHS, RHS); 1976 std::swap(LHSShift, RHSShift); 1977 std::swap(LHSMask , RHSMask ); 1978 } 1979 1980 unsigned OpSizeInBits = VT.getSizeInBits(); 1981 SDValue LHSShiftArg = LHSShift.getOperand(0); 1982 SDValue LHSShiftAmt = LHSShift.getOperand(1); 1983 SDValue RHSShiftAmt = RHSShift.getOperand(1); 1984 1985 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 1986 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 1987 if (LHSShiftAmt.getOpcode() == ISD::Constant && 1988 RHSShiftAmt.getOpcode() == ISD::Constant) { 1989 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue(); 1990 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue(); 1991 if ((LShVal + RShVal) != OpSizeInBits) 1992 return 0; 1993 1994 SDValue Rot; 1995 if (HasROTL) 1996 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt); 1997 else 1998 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt); 1999 2000 // If there is an AND of either shifted operand, apply it to the result. 2001 if (LHSMask.getNode() || RHSMask.getNode()) { 2002 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 2003 2004 if (LHSMask.getNode()) { 2005 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 2006 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 2007 } 2008 if (RHSMask.getNode()) { 2009 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 2010 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 2011 } 2012 2013 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT)); 2014 } 2015 2016 return Rot.getNode(); 2017 } 2018 2019 // If there is a mask here, and we have a variable shift, we can't be sure 2020 // that we're masking out the right stuff. 2021 if (LHSMask.getNode() || RHSMask.getNode()) 2022 return 0; 2023 2024 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y) 2025 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y)) 2026 if (RHSShiftAmt.getOpcode() == ISD::SUB && 2027 LHSShiftAmt == RHSShiftAmt.getOperand(1)) { 2028 if (ConstantSDNode *SUBC = 2029 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) { 2030 if (SUBC->getAPIntValue() == OpSizeInBits) { 2031 if (HasROTL) 2032 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode(); 2033 else 2034 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode(); 2035 } 2036 } 2037 } 2038 2039 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y) 2040 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y)) 2041 if (LHSShiftAmt.getOpcode() == ISD::SUB && 2042 RHSShiftAmt == LHSShiftAmt.getOperand(1)) { 2043 if (ConstantSDNode *SUBC = 2044 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) { 2045 if (SUBC->getAPIntValue() == OpSizeInBits) { 2046 if (HasROTL) 2047 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode(); 2048 else 2049 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode(); 2050 } 2051 } 2052 } 2053 2054 // Look for sign/zext/any-extended cases: 2055 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 2056 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 2057 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) && 2058 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 2059 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 2060 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) { 2061 SDValue LExtOp0 = LHSShiftAmt.getOperand(0); 2062 SDValue RExtOp0 = RHSShiftAmt.getOperand(0); 2063 if (RExtOp0.getOpcode() == ISD::SUB && 2064 RExtOp0.getOperand(1) == LExtOp0) { 2065 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 2066 // (rotr x, y) 2067 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 2068 // (rotl x, (sub 32, y)) 2069 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) { 2070 if (SUBC->getAPIntValue() == OpSizeInBits) { 2071 if (HasROTL) 2072 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode(); 2073 else 2074 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode(); 2075 } 2076 } 2077 } else if (LExtOp0.getOpcode() == ISD::SUB && 2078 RExtOp0 == LExtOp0.getOperand(1)) { 2079 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) -> 2080 // (rotl x, y) 2081 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) -> 2082 // (rotr x, (sub 32, y)) 2083 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) { 2084 if (SUBC->getAPIntValue() == OpSizeInBits) { 2085 if (HasROTL) 2086 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).getNode(); 2087 else 2088 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode(); 2089 } 2090 } 2091 } 2092 } 2093 2094 return 0; 2095} 2096 2097 2098SDValue DAGCombiner::visitXOR(SDNode *N) { 2099 SDValue N0 = N->getOperand(0); 2100 SDValue N1 = N->getOperand(1); 2101 SDValue LHS, RHS, CC; 2102 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2103 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2104 MVT VT = N0.getValueType(); 2105 2106 // fold vector ops 2107 if (VT.isVector()) { 2108 SDValue FoldedVOp = SimplifyVBinOp(N); 2109 if (FoldedVOp.getNode()) return FoldedVOp; 2110 } 2111 2112 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 2113 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 2114 return DAG.getConstant(0, VT); 2115 // fold (xor x, undef) -> undef 2116 if (N0.getOpcode() == ISD::UNDEF) 2117 return N0; 2118 if (N1.getOpcode() == ISD::UNDEF) 2119 return N1; 2120 // fold (xor c1, c2) -> c1^c2 2121 if (N0C && N1C) 2122 return DAG.getNode(ISD::XOR, VT, N0, N1); 2123 // canonicalize constant to RHS 2124 if (N0C && !N1C) 2125 return DAG.getNode(ISD::XOR, VT, N1, N0); 2126 // fold (xor x, 0) -> x 2127 if (N1C && N1C->isNullValue()) 2128 return N0; 2129 // reassociate xor 2130 SDValue RXOR = ReassociateOps(ISD::XOR, N0, N1); 2131 if (RXOR.getNode() != 0) 2132 return RXOR; 2133 // fold !(x cc y) -> (x !cc y) 2134 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 2135 bool isInt = LHS.getValueType().isInteger(); 2136 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 2137 isInt); 2138 if (N0.getOpcode() == ISD::SETCC) 2139 return DAG.getSetCC(VT, LHS, RHS, NotCC); 2140 if (N0.getOpcode() == ISD::SELECT_CC) 2141 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC); 2142 assert(0 && "Unhandled SetCC Equivalent!"); 2143 abort(); 2144 } 2145 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 2146 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 2147 N0.getNode()->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 2148 SDValue V = N0.getOperand(0); 2149 V = DAG.getNode(ISD::XOR, V.getValueType(), V, 2150 DAG.getConstant(1, V.getValueType())); 2151 AddToWorkList(V.getNode()); 2152 return DAG.getNode(ISD::ZERO_EXTEND, VT, V); 2153 } 2154 2155 // fold !(x or y) -> (!x and !y) iff x or y are setcc 2156 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 2157 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 2158 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 2159 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 2160 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 2161 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS 2162 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS 2163 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 2164 return DAG.getNode(NewOpcode, VT, LHS, RHS); 2165 } 2166 } 2167 // fold !(x or y) -> (!x and !y) iff x or y are constants 2168 if (N1C && N1C->isAllOnesValue() && 2169 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 2170 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 2171 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 2172 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 2173 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS 2174 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS 2175 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 2176 return DAG.getNode(NewOpcode, VT, LHS, RHS); 2177 } 2178 } 2179 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2) 2180 if (N1C && N0.getOpcode() == ISD::XOR) { 2181 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 2182 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2183 if (N00C) 2184 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1), 2185 DAG.getConstant(N1C->getAPIntValue()^ 2186 N00C->getAPIntValue(), VT)); 2187 if (N01C) 2188 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0), 2189 DAG.getConstant(N1C->getAPIntValue()^ 2190 N01C->getAPIntValue(), VT)); 2191 } 2192 // fold (xor x, x) -> 0 2193 if (N0 == N1) { 2194 if (!VT.isVector()) { 2195 return DAG.getConstant(0, VT); 2196 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) { 2197 // Produce a vector of zeros. 2198 SDValue El = DAG.getConstant(0, VT.getVectorElementType()); 2199 std::vector<SDValue> Ops(VT.getVectorNumElements(), El); 2200 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()); 2201 } 2202 } 2203 2204 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 2205 if (N0.getOpcode() == N1.getOpcode()) { 2206 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2207 if (Tmp.getNode()) return Tmp; 2208 } 2209 2210 // Simplify the expression using non-local knowledge. 2211 if (!VT.isVector() && 2212 SimplifyDemandedBits(SDValue(N, 0))) 2213 return SDValue(N, 0); 2214 2215 return SDValue(); 2216} 2217 2218/// visitShiftByConstant - Handle transforms common to the three shifts, when 2219/// the shift amount is a constant. 2220SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 2221 SDNode *LHS = N->getOperand(0).getNode(); 2222 if (!LHS->hasOneUse()) return SDValue(); 2223 2224 // We want to pull some binops through shifts, so that we have (and (shift)) 2225 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 2226 // thing happens with address calculations, so it's important to canonicalize 2227 // it. 2228 bool HighBitSet = false; // Can we transform this if the high bit is set? 2229 2230 switch (LHS->getOpcode()) { 2231 default: return SDValue(); 2232 case ISD::OR: 2233 case ISD::XOR: 2234 HighBitSet = false; // We can only transform sra if the high bit is clear. 2235 break; 2236 case ISD::AND: 2237 HighBitSet = true; // We can only transform sra if the high bit is set. 2238 break; 2239 case ISD::ADD: 2240 if (N->getOpcode() != ISD::SHL) 2241 return SDValue(); // only shl(add) not sr[al](add). 2242 HighBitSet = false; // We can only transform sra if the high bit is clear. 2243 break; 2244 } 2245 2246 // We require the RHS of the binop to be a constant as well. 2247 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 2248 if (!BinOpCst) return SDValue(); 2249 2250 2251 // FIXME: disable this for unless the input to the binop is a shift by a 2252 // constant. If it is not a shift, it pessimizes some common cases like: 2253 // 2254 //void foo(int *X, int i) { X[i & 1235] = 1; } 2255 //int bar(int *X, int i) { return X[i & 255]; } 2256 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 2257 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 2258 BinOpLHSVal->getOpcode() != ISD::SRA && 2259 BinOpLHSVal->getOpcode() != ISD::SRL) || 2260 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 2261 return SDValue(); 2262 2263 MVT VT = N->getValueType(0); 2264 2265 // If this is a signed shift right, and the high bit is modified 2266 // by the logical operation, do not perform the transformation. 2267 // The highBitSet boolean indicates the value of the high bit of 2268 // the constant which would cause it to be modified for this 2269 // operation. 2270 if (N->getOpcode() == ISD::SRA) { 2271 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 2272 if (BinOpRHSSignSet != HighBitSet) 2273 return SDValue(); 2274 } 2275 2276 // Fold the constants, shifting the binop RHS by the shift amount. 2277 SDValue NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0), 2278 LHS->getOperand(1), N->getOperand(1)); 2279 2280 // Create the new shift. 2281 SDValue NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0), 2282 N->getOperand(1)); 2283 2284 // Create the new binop. 2285 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS); 2286} 2287 2288 2289SDValue DAGCombiner::visitSHL(SDNode *N) { 2290 SDValue N0 = N->getOperand(0); 2291 SDValue N1 = N->getOperand(1); 2292 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2293 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2294 MVT VT = N0.getValueType(); 2295 unsigned OpSizeInBits = VT.getSizeInBits(); 2296 2297 // fold (shl c1, c2) -> c1<<c2 2298 if (N0C && N1C) 2299 return DAG.getNode(ISD::SHL, VT, N0, N1); 2300 // fold (shl 0, x) -> 0 2301 if (N0C && N0C->isNullValue()) 2302 return N0; 2303 // fold (shl x, c >= size(x)) -> undef 2304 if (N1C && N1C->getValue() >= OpSizeInBits) 2305 return DAG.getNode(ISD::UNDEF, VT); 2306 // fold (shl x, 0) -> x 2307 if (N1C && N1C->isNullValue()) 2308 return N0; 2309 // if (shl x, c) is known to be zero, return 0 2310 if (DAG.MaskedValueIsZero(SDValue(N, 0), 2311 APInt::getAllOnesValue(VT.getSizeInBits()))) 2312 return DAG.getConstant(0, VT); 2313 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), c)) 2314 // iff (trunc c) == c 2315 if (N1.getOpcode() == ISD::TRUNCATE && 2316 N1.getOperand(0).getOpcode() == ISD::AND) { 2317 SDValue N101 = N1.getOperand(0).getOperand(1); 2318 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101); 2319 if (N101C) { 2320 MVT TruncVT = N1.getValueType(); 2321 unsigned TruncBitSize = TruncVT.getSizeInBits(); 2322 APInt ShAmt = N101C->getAPIntValue(); 2323 if (ShAmt.trunc(TruncBitSize).getZExtValue() == N101C->getValue()) { 2324 SDValue N100 = N1.getOperand(0).getOperand(0); 2325 return DAG.getNode(ISD::SHL, VT, N0, 2326 DAG.getNode(ISD::AND, TruncVT, 2327 DAG.getNode(ISD::TRUNCATE, TruncVT, N100), 2328 DAG.getConstant(N101C->getValue(), TruncVT))); 2329 } 2330 } 2331 } 2332 2333 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 2334 return SDValue(N, 0); 2335 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2) 2336 if (N1C && N0.getOpcode() == ISD::SHL && 2337 N0.getOperand(1).getOpcode() == ISD::Constant) { 2338 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue(); 2339 uint64_t c2 = N1C->getValue(); 2340 if (c1 + c2 > OpSizeInBits) 2341 return DAG.getConstant(0, VT); 2342 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0), 2343 DAG.getConstant(c1 + c2, N1.getValueType())); 2344 } 2345 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or 2346 // (srl (and x, -1 << c1), c1-c2) 2347 if (N1C && N0.getOpcode() == ISD::SRL && 2348 N0.getOperand(1).getOpcode() == ISD::Constant) { 2349 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue(); 2350 uint64_t c2 = N1C->getValue(); 2351 SDValue Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0), 2352 DAG.getConstant(~0ULL << c1, VT)); 2353 if (c2 > c1) 2354 return DAG.getNode(ISD::SHL, VT, Mask, 2355 DAG.getConstant(c2-c1, N1.getValueType())); 2356 else 2357 return DAG.getNode(ISD::SRL, VT, Mask, 2358 DAG.getConstant(c1-c2, N1.getValueType())); 2359 } 2360 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1) 2361 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) 2362 return DAG.getNode(ISD::AND, VT, N0.getOperand(0), 2363 DAG.getConstant(~0ULL << N1C->getValue(), VT)); 2364 2365 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDValue(); 2366} 2367 2368SDValue DAGCombiner::visitSRA(SDNode *N) { 2369 SDValue N0 = N->getOperand(0); 2370 SDValue N1 = N->getOperand(1); 2371 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2372 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2373 MVT VT = N0.getValueType(); 2374 2375 // fold (sra c1, c2) -> c1>>c2 2376 if (N0C && N1C) 2377 return DAG.getNode(ISD::SRA, VT, N0, N1); 2378 // fold (sra 0, x) -> 0 2379 if (N0C && N0C->isNullValue()) 2380 return N0; 2381 // fold (sra -1, x) -> -1 2382 if (N0C && N0C->isAllOnesValue()) 2383 return N0; 2384 // fold (sra x, c >= size(x)) -> undef 2385 if (N1C && N1C->getValue() >= VT.getSizeInBits()) 2386 return DAG.getNode(ISD::UNDEF, VT); 2387 // fold (sra x, 0) -> x 2388 if (N1C && N1C->isNullValue()) 2389 return N0; 2390 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 2391 // sext_inreg. 2392 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 2393 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue(); 2394 MVT EVT = MVT::getIntegerVT(LowBits); 2395 if (EVT.isSimple() && // TODO: remove when apint codegen support lands. 2396 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))) 2397 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), 2398 DAG.getValueType(EVT)); 2399 } 2400 2401 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2) 2402 if (N1C && N0.getOpcode() == ISD::SRA) { 2403 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2404 unsigned Sum = N1C->getValue() + C1->getValue(); 2405 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1; 2406 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), 2407 DAG.getConstant(Sum, N1C->getValueType(0))); 2408 } 2409 } 2410 2411 // fold sra (shl X, m), result_size - n 2412 // -> (sign_extend (trunc (shl X, result_size - n - m))) for 2413 // result_size - n != m. 2414 // If truncate is free for the target sext(shl) is likely to result in better 2415 // code. 2416 if (N0.getOpcode() == ISD::SHL) { 2417 // Get the two constanst of the shifts, CN0 = m, CN = n. 2418 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2419 if (N01C && N1C) { 2420 // Determine what the truncate's result bitsize and type would be. 2421 unsigned VTValSize = VT.getSizeInBits(); 2422 MVT TruncVT = 2423 MVT::getIntegerVT(VTValSize - N1C->getValue()); 2424 // Determine the residual right-shift amount. 2425 unsigned ShiftAmt = N1C->getValue() - N01C->getValue(); 2426 2427 // If the shift is not a no-op (in which case this should be just a sign 2428 // extend already), the truncated to type is legal, sign_extend is legal 2429 // on that type, and the the truncate to that type is both legal and free, 2430 // perform the transform. 2431 if (ShiftAmt && 2432 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) && 2433 TLI.isOperationLegal(ISD::TRUNCATE, VT) && 2434 TLI.isTruncateFree(VT, TruncVT)) { 2435 2436 SDValue Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy()); 2437 SDValue Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt); 2438 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift); 2439 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc); 2440 } 2441 } 2442 } 2443 2444 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), c)) 2445 // iff (trunc c) == c 2446 if (N1.getOpcode() == ISD::TRUNCATE && 2447 N1.getOperand(0).getOpcode() == ISD::AND) { 2448 SDValue N101 = N1.getOperand(0).getOperand(1); 2449 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101); 2450 if (N101C) { 2451 MVT TruncVT = N1.getValueType(); 2452 unsigned TruncBitSize = TruncVT.getSizeInBits(); 2453 APInt ShAmt = N101C->getAPIntValue(); 2454 if (ShAmt.trunc(TruncBitSize).getZExtValue() == N101C->getValue()) { 2455 SDValue N100 = N1.getOperand(0).getOperand(0); 2456 return DAG.getNode(ISD::SRA, VT, N0, 2457 DAG.getNode(ISD::AND, TruncVT, 2458 DAG.getNode(ISD::TRUNCATE, TruncVT, N100), 2459 DAG.getConstant(N101C->getValue(), TruncVT))); 2460 } 2461 } 2462 } 2463 2464 // Simplify, based on bits shifted out of the LHS. 2465 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 2466 return SDValue(N, 0); 2467 2468 2469 // If the sign bit is known to be zero, switch this to a SRL. 2470 if (DAG.SignBitIsZero(N0)) 2471 return DAG.getNode(ISD::SRL, VT, N0, N1); 2472 2473 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDValue(); 2474} 2475 2476SDValue DAGCombiner::visitSRL(SDNode *N) { 2477 SDValue N0 = N->getOperand(0); 2478 SDValue N1 = N->getOperand(1); 2479 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2481 MVT VT = N0.getValueType(); 2482 unsigned OpSizeInBits = VT.getSizeInBits(); 2483 2484 // fold (srl c1, c2) -> c1 >>u c2 2485 if (N0C && N1C) 2486 return DAG.getNode(ISD::SRL, VT, N0, N1); 2487 // fold (srl 0, x) -> 0 2488 if (N0C && N0C->isNullValue()) 2489 return N0; 2490 // fold (srl x, c >= size(x)) -> undef 2491 if (N1C && N1C->getValue() >= OpSizeInBits) 2492 return DAG.getNode(ISD::UNDEF, VT); 2493 // fold (srl x, 0) -> x 2494 if (N1C && N1C->isNullValue()) 2495 return N0; 2496 // if (srl x, c) is known to be zero, return 0 2497 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2498 APInt::getAllOnesValue(OpSizeInBits))) 2499 return DAG.getConstant(0, VT); 2500 2501 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2) 2502 if (N1C && N0.getOpcode() == ISD::SRL && 2503 N0.getOperand(1).getOpcode() == ISD::Constant) { 2504 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue(); 2505 uint64_t c2 = N1C->getValue(); 2506 if (c1 + c2 > OpSizeInBits) 2507 return DAG.getConstant(0, VT); 2508 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), 2509 DAG.getConstant(c1 + c2, N1.getValueType())); 2510 } 2511 2512 // fold (srl (anyextend x), c) -> (anyextend (srl x, c)) 2513 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2514 // Shifting in all undef bits? 2515 MVT SmallVT = N0.getOperand(0).getValueType(); 2516 if (N1C->getValue() >= SmallVT.getSizeInBits()) 2517 return DAG.getNode(ISD::UNDEF, VT); 2518 2519 SDValue SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1); 2520 AddToWorkList(SmallShift.getNode()); 2521 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift); 2522 } 2523 2524 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 2525 // bit, which is unmodified by sra. 2526 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) { 2527 if (N0.getOpcode() == ISD::SRA) 2528 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1); 2529 } 2530 2531 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 2532 if (N1C && N0.getOpcode() == ISD::CTLZ && 2533 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 2534 APInt KnownZero, KnownOne; 2535 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()); 2536 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne); 2537 2538 // If any of the input bits are KnownOne, then the input couldn't be all 2539 // zeros, thus the result of the srl will always be zero. 2540 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 2541 2542 // If all of the bits input the to ctlz node are known to be zero, then 2543 // the result of the ctlz is "32" and the result of the shift is one. 2544 APInt UnknownBits = ~KnownZero & Mask; 2545 if (UnknownBits == 0) return DAG.getConstant(1, VT); 2546 2547 // Otherwise, check to see if there is exactly one bit input to the ctlz. 2548 if ((UnknownBits & (UnknownBits-1)) == 0) { 2549 // Okay, we know that only that the single bit specified by UnknownBits 2550 // could be set on input to the CTLZ node. If this bit is set, the SRL 2551 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 2552 // to an SRL,XOR pair, which is likely to simplify more. 2553 unsigned ShAmt = UnknownBits.countTrailingZeros(); 2554 SDValue Op = N0.getOperand(0); 2555 if (ShAmt) { 2556 Op = DAG.getNode(ISD::SRL, VT, Op, 2557 DAG.getConstant(ShAmt, TLI.getShiftAmountTy())); 2558 AddToWorkList(Op.getNode()); 2559 } 2560 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT)); 2561 } 2562 } 2563 2564 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), c)) 2565 // iff (trunc c) == c 2566 if (N1.getOpcode() == ISD::TRUNCATE && 2567 N1.getOperand(0).getOpcode() == ISD::AND) { 2568 SDValue N101 = N1.getOperand(0).getOperand(1); 2569 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101); 2570 if (N101C) { 2571 MVT TruncVT = N1.getValueType(); 2572 unsigned TruncBitSize = TruncVT.getSizeInBits(); 2573 APInt ShAmt = N101C->getAPIntValue(); 2574 if (ShAmt.trunc(TruncBitSize).getZExtValue() == N101C->getValue()) { 2575 SDValue N100 = N1.getOperand(0).getOperand(0); 2576 return DAG.getNode(ISD::SRL, VT, N0, 2577 DAG.getNode(ISD::AND, TruncVT, 2578 DAG.getNode(ISD::TRUNCATE, TruncVT, N100), 2579 DAG.getConstant(N101C->getValue(), TruncVT))); 2580 } 2581 } 2582 } 2583 2584 // fold operands of srl based on knowledge that the low bits are not 2585 // demanded. 2586 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 2587 return SDValue(N, 0); 2588 2589 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDValue(); 2590} 2591 2592SDValue DAGCombiner::visitCTLZ(SDNode *N) { 2593 SDValue N0 = N->getOperand(0); 2594 MVT VT = N->getValueType(0); 2595 2596 // fold (ctlz c1) -> c2 2597 if (isa<ConstantSDNode>(N0)) 2598 return DAG.getNode(ISD::CTLZ, VT, N0); 2599 return SDValue(); 2600} 2601 2602SDValue DAGCombiner::visitCTTZ(SDNode *N) { 2603 SDValue N0 = N->getOperand(0); 2604 MVT VT = N->getValueType(0); 2605 2606 // fold (cttz c1) -> c2 2607 if (isa<ConstantSDNode>(N0)) 2608 return DAG.getNode(ISD::CTTZ, VT, N0); 2609 return SDValue(); 2610} 2611 2612SDValue DAGCombiner::visitCTPOP(SDNode *N) { 2613 SDValue N0 = N->getOperand(0); 2614 MVT VT = N->getValueType(0); 2615 2616 // fold (ctpop c1) -> c2 2617 if (isa<ConstantSDNode>(N0)) 2618 return DAG.getNode(ISD::CTPOP, VT, N0); 2619 return SDValue(); 2620} 2621 2622SDValue DAGCombiner::visitSELECT(SDNode *N) { 2623 SDValue N0 = N->getOperand(0); 2624 SDValue N1 = N->getOperand(1); 2625 SDValue N2 = N->getOperand(2); 2626 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2627 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2628 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 2629 MVT VT = N->getValueType(0); 2630 MVT VT0 = N0.getValueType(); 2631 2632 // fold select C, X, X -> X 2633 if (N1 == N2) 2634 return N1; 2635 // fold select true, X, Y -> X 2636 if (N0C && !N0C->isNullValue()) 2637 return N1; 2638 // fold select false, X, Y -> Y 2639 if (N0C && N0C->isNullValue()) 2640 return N2; 2641 // fold select C, 1, X -> C | X 2642 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 2643 return DAG.getNode(ISD::OR, VT, N0, N2); 2644 // fold select C, 0, 1 -> ~C 2645 if (VT.isInteger() && VT0.isInteger() && 2646 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 2647 SDValue XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0)); 2648 if (VT == VT0) 2649 return XORNode; 2650 AddToWorkList(XORNode.getNode()); 2651 if (VT.bitsGT(VT0)) 2652 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode); 2653 return DAG.getNode(ISD::TRUNCATE, VT, XORNode); 2654 } 2655 // fold select C, 0, X -> ~C & X 2656 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 2657 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT)); 2658 AddToWorkList(XORNode.getNode()); 2659 return DAG.getNode(ISD::AND, VT, XORNode, N2); 2660 } 2661 // fold select C, X, 1 -> ~C | X 2662 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 2663 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT)); 2664 AddToWorkList(XORNode.getNode()); 2665 return DAG.getNode(ISD::OR, VT, XORNode, N1); 2666 } 2667 // fold select C, X, 0 -> C & X 2668 // FIXME: this should check for C type == X type, not i1? 2669 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 2670 return DAG.getNode(ISD::AND, VT, N0, N1); 2671 // fold X ? X : Y --> X ? 1 : Y --> X | Y 2672 if (VT == MVT::i1 && N0 == N1) 2673 return DAG.getNode(ISD::OR, VT, N0, N2); 2674 // fold X ? Y : X --> X ? Y : 0 --> X & Y 2675 if (VT == MVT::i1 && N0 == N2) 2676 return DAG.getNode(ISD::AND, VT, N0, N1); 2677 2678 // If we can fold this based on the true/false value, do so. 2679 if (SimplifySelectOps(N, N1, N2)) 2680 return SDValue(N, 0); // Don't revisit N. 2681 2682 // fold selects based on a setcc into other things, such as min/max/abs 2683 if (N0.getOpcode() == ISD::SETCC) { 2684 // FIXME: 2685 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 2686 // having to say they don't support SELECT_CC on every type the DAG knows 2687 // about, since there is no way to mark an opcode illegal at all value types 2688 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other)) 2689 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1), 2690 N1, N2, N0.getOperand(2)); 2691 else 2692 return SimplifySelect(N0, N1, N2); 2693 } 2694 return SDValue(); 2695} 2696 2697SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 2698 SDValue N0 = N->getOperand(0); 2699 SDValue N1 = N->getOperand(1); 2700 SDValue N2 = N->getOperand(2); 2701 SDValue N3 = N->getOperand(3); 2702 SDValue N4 = N->getOperand(4); 2703 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 2704 2705 // fold select_cc lhs, rhs, x, x, cc -> x 2706 if (N2 == N3) 2707 return N2; 2708 2709 // Determine if the condition we're dealing with is constant 2710 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false); 2711 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 2712 2713 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 2714 if (!SCCC->isNullValue()) 2715 return N2; // cond always true -> true val 2716 else 2717 return N3; // cond always false -> false val 2718 } 2719 2720 // Fold to a simpler select_cc 2721 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC) 2722 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(), 2723 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 2724 SCC.getOperand(2)); 2725 2726 // If we can fold this based on the true/false value, do so. 2727 if (SimplifySelectOps(N, N2, N3)) 2728 return SDValue(N, 0); // Don't revisit N. 2729 2730 // fold select_cc into other things, such as min/max/abs 2731 return SimplifySelectCC(N0, N1, N2, N3, CC); 2732} 2733 2734SDValue DAGCombiner::visitSETCC(SDNode *N) { 2735 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 2736 cast<CondCodeSDNode>(N->getOperand(2))->get()); 2737} 2738 2739// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 2740// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))" 2741// transformation. Returns true if extension are possible and the above 2742// mentioned transformation is profitable. 2743static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 2744 unsigned ExtOpc, 2745 SmallVector<SDNode*, 4> &ExtendNodes, 2746 TargetLowering &TLI) { 2747 bool HasCopyToRegUses = false; 2748 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 2749 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), UE = N0.getNode()->use_end(); 2750 UI != UE; ++UI) { 2751 SDNode *User = *UI; 2752 if (User == N) 2753 continue; 2754 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 2755 if (User->getOpcode() == ISD::SETCC) { 2756 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 2757 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 2758 // Sign bits will be lost after a zext. 2759 return false; 2760 bool Add = false; 2761 for (unsigned i = 0; i != 2; ++i) { 2762 SDValue UseOp = User->getOperand(i); 2763 if (UseOp == N0) 2764 continue; 2765 if (!isa<ConstantSDNode>(UseOp)) 2766 return false; 2767 Add = true; 2768 } 2769 if (Add) 2770 ExtendNodes.push_back(User); 2771 } else { 2772 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 2773 SDValue UseOp = User->getOperand(i); 2774 if (UseOp == N0) { 2775 // If truncate from extended type to original load type is free 2776 // on this target, then it's ok to extend a CopyToReg. 2777 if (isTruncFree && User->getOpcode() == ISD::CopyToReg) 2778 HasCopyToRegUses = true; 2779 else 2780 return false; 2781 } 2782 } 2783 } 2784 } 2785 2786 if (HasCopyToRegUses) { 2787 bool BothLiveOut = false; 2788 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 2789 UI != UE; ++UI) { 2790 SDNode *User = *UI; 2791 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 2792 SDValue UseOp = User->getOperand(i); 2793 if (UseOp.getNode() == N && UseOp.getResNo() == 0) { 2794 BothLiveOut = true; 2795 break; 2796 } 2797 } 2798 } 2799 if (BothLiveOut) 2800 // Both unextended and extended values are live out. There had better be 2801 // good a reason for the transformation. 2802 return ExtendNodes.size(); 2803 } 2804 return true; 2805} 2806 2807SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 2808 SDValue N0 = N->getOperand(0); 2809 MVT VT = N->getValueType(0); 2810 2811 // fold (sext c1) -> c1 2812 if (isa<ConstantSDNode>(N0)) 2813 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0); 2814 2815 // fold (sext (sext x)) -> (sext x) 2816 // fold (sext (aext x)) -> (sext x) 2817 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 2818 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0)); 2819 2820 if (N0.getOpcode() == ISD::TRUNCATE) { 2821 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 2822 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 2823 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 2824 if (NarrowLoad.getNode()) { 2825 if (NarrowLoad.getNode() != N0.getNode()) 2826 CombineTo(N0.getNode(), NarrowLoad); 2827 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad); 2828 } 2829 2830 // See if the value being truncated is already sign extended. If so, just 2831 // eliminate the trunc/sext pair. 2832 SDValue Op = N0.getOperand(0); 2833 unsigned OpBits = Op.getValueType().getSizeInBits(); 2834 unsigned MidBits = N0.getValueType().getSizeInBits(); 2835 unsigned DestBits = VT.getSizeInBits(); 2836 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 2837 2838 if (OpBits == DestBits) { 2839 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 2840 // bits, it is already ready. 2841 if (NumSignBits > DestBits-MidBits) 2842 return Op; 2843 } else if (OpBits < DestBits) { 2844 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 2845 // bits, just sext from i32. 2846 if (NumSignBits > OpBits-MidBits) 2847 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op); 2848 } else { 2849 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 2850 // bits, just truncate to i32. 2851 if (NumSignBits > OpBits-MidBits) 2852 return DAG.getNode(ISD::TRUNCATE, VT, Op); 2853 } 2854 2855 // fold (sext (truncate x)) -> (sextinreg x). 2856 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 2857 N0.getValueType())) { 2858 if (Op.getValueType().bitsLT(VT)) 2859 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op); 2860 else if (Op.getValueType().bitsGT(VT)) 2861 Op = DAG.getNode(ISD::TRUNCATE, VT, Op); 2862 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op, 2863 DAG.getValueType(N0.getValueType())); 2864 } 2865 } 2866 2867 // fold (sext (load x)) -> (sext (truncate (sextload x))) 2868 if (ISD::isNON_EXTLoad(N0.getNode()) && 2869 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) || 2870 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) { 2871 bool DoXform = true; 2872 SmallVector<SDNode*, 4> SetCCs; 2873 if (!N0.hasOneUse()) 2874 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 2875 if (DoXform) { 2876 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2877 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(), 2878 LN0->getBasePtr(), LN0->getSrcValue(), 2879 LN0->getSrcValueOffset(), 2880 N0.getValueType(), 2881 LN0->isVolatile(), 2882 LN0->getAlignment()); 2883 CombineTo(N, ExtLoad); 2884 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad); 2885 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 2886 // Extend SetCC uses if necessary. 2887 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 2888 SDNode *SetCC = SetCCs[i]; 2889 SmallVector<SDValue, 4> Ops; 2890 for (unsigned j = 0; j != 2; ++j) { 2891 SDValue SOp = SetCC->getOperand(j); 2892 if (SOp == Trunc) 2893 Ops.push_back(ExtLoad); 2894 else 2895 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp)); 2896 } 2897 Ops.push_back(SetCC->getOperand(2)); 2898 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0), 2899 &Ops[0], Ops.size())); 2900 } 2901 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2902 } 2903 } 2904 2905 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 2906 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 2907 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 2908 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 2909 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2910 MVT EVT = LN0->getMemoryVT(); 2911 if ((!AfterLegalize && !LN0->isVolatile()) || 2912 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) { 2913 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(), 2914 LN0->getBasePtr(), LN0->getSrcValue(), 2915 LN0->getSrcValueOffset(), EVT, 2916 LN0->isVolatile(), 2917 LN0->getAlignment()); 2918 CombineTo(N, ExtLoad); 2919 CombineTo(N0.getNode(), DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad), 2920 ExtLoad.getValue(1)); 2921 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2922 } 2923 } 2924 2925 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc 2926 if (N0.getOpcode() == ISD::SETCC) { 2927 SDValue SCC = 2928 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), 2929 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT), 2930 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 2931 if (SCC.getNode()) return SCC; 2932 } 2933 2934 // fold (sext x) -> (zext x) if the sign bit is known zero. 2935 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 2936 DAG.SignBitIsZero(N0)) 2937 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0); 2938 2939 return SDValue(); 2940} 2941 2942SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 2943 SDValue N0 = N->getOperand(0); 2944 MVT VT = N->getValueType(0); 2945 2946 // fold (zext c1) -> c1 2947 if (isa<ConstantSDNode>(N0)) 2948 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0); 2949 // fold (zext (zext x)) -> (zext x) 2950 // fold (zext (aext x)) -> (zext x) 2951 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 2952 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0)); 2953 2954 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 2955 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 2956 if (N0.getOpcode() == ISD::TRUNCATE) { 2957 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 2958 if (NarrowLoad.getNode()) { 2959 if (NarrowLoad.getNode() != N0.getNode()) 2960 CombineTo(N0.getNode(), NarrowLoad); 2961 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad); 2962 } 2963 } 2964 2965 // fold (zext (truncate x)) -> (and x, mask) 2966 if (N0.getOpcode() == ISD::TRUNCATE && 2967 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) { 2968 SDValue Op = N0.getOperand(0); 2969 if (Op.getValueType().bitsLT(VT)) { 2970 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op); 2971 } else if (Op.getValueType().bitsGT(VT)) { 2972 Op = DAG.getNode(ISD::TRUNCATE, VT, Op); 2973 } 2974 return DAG.getZeroExtendInReg(Op, N0.getValueType()); 2975 } 2976 2977 // fold (zext (and (trunc x), cst)) -> (and x, cst). 2978 if (N0.getOpcode() == ISD::AND && 2979 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 2980 N0.getOperand(1).getOpcode() == ISD::Constant) { 2981 SDValue X = N0.getOperand(0).getOperand(0); 2982 if (X.getValueType().bitsLT(VT)) { 2983 X = DAG.getNode(ISD::ANY_EXTEND, VT, X); 2984 } else if (X.getValueType().bitsGT(VT)) { 2985 X = DAG.getNode(ISD::TRUNCATE, VT, X); 2986 } 2987 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 2988 Mask.zext(VT.getSizeInBits()); 2989 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT)); 2990 } 2991 2992 // fold (zext (load x)) -> (zext (truncate (zextload x))) 2993 if (ISD::isNON_EXTLoad(N0.getNode()) && 2994 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) || 2995 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 2996 bool DoXform = true; 2997 SmallVector<SDNode*, 4> SetCCs; 2998 if (!N0.hasOneUse()) 2999 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 3000 if (DoXform) { 3001 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3002 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), 3003 LN0->getBasePtr(), LN0->getSrcValue(), 3004 LN0->getSrcValueOffset(), 3005 N0.getValueType(), 3006 LN0->isVolatile(), 3007 LN0->getAlignment()); 3008 CombineTo(N, ExtLoad); 3009 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad); 3010 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 3011 // Extend SetCC uses if necessary. 3012 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 3013 SDNode *SetCC = SetCCs[i]; 3014 SmallVector<SDValue, 4> Ops; 3015 for (unsigned j = 0; j != 2; ++j) { 3016 SDValue SOp = SetCC->getOperand(j); 3017 if (SOp == Trunc) 3018 Ops.push_back(ExtLoad); 3019 else 3020 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp)); 3021 } 3022 Ops.push_back(SetCC->getOperand(2)); 3023 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0), 3024 &Ops[0], Ops.size())); 3025 } 3026 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3027 } 3028 } 3029 3030 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 3031 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 3032 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 3033 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 3034 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3035 MVT EVT = LN0->getMemoryVT(); 3036 if ((!AfterLegalize && !LN0->isVolatile()) || 3037 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) { 3038 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), 3039 LN0->getBasePtr(), LN0->getSrcValue(), 3040 LN0->getSrcValueOffset(), EVT, 3041 LN0->isVolatile(), 3042 LN0->getAlignment()); 3043 CombineTo(N, ExtLoad); 3044 CombineTo(N0.getNode(), DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad), 3045 ExtLoad.getValue(1)); 3046 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3047 } 3048 } 3049 3050 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 3051 if (N0.getOpcode() == ISD::SETCC) { 3052 SDValue SCC = 3053 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), 3054 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 3055 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 3056 if (SCC.getNode()) return SCC; 3057 } 3058 3059 return SDValue(); 3060} 3061 3062SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 3063 SDValue N0 = N->getOperand(0); 3064 MVT VT = N->getValueType(0); 3065 3066 // fold (aext c1) -> c1 3067 if (isa<ConstantSDNode>(N0)) 3068 return DAG.getNode(ISD::ANY_EXTEND, VT, N0); 3069 // fold (aext (aext x)) -> (aext x) 3070 // fold (aext (zext x)) -> (zext x) 3071 // fold (aext (sext x)) -> (sext x) 3072 if (N0.getOpcode() == ISD::ANY_EXTEND || 3073 N0.getOpcode() == ISD::ZERO_EXTEND || 3074 N0.getOpcode() == ISD::SIGN_EXTEND) 3075 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0)); 3076 3077 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 3078 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 3079 if (N0.getOpcode() == ISD::TRUNCATE) { 3080 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 3081 if (NarrowLoad.getNode()) { 3082 if (NarrowLoad.getNode() != N0.getNode()) 3083 CombineTo(N0.getNode(), NarrowLoad); 3084 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad); 3085 } 3086 } 3087 3088 // fold (aext (truncate x)) 3089 if (N0.getOpcode() == ISD::TRUNCATE) { 3090 SDValue TruncOp = N0.getOperand(0); 3091 if (TruncOp.getValueType() == VT) 3092 return TruncOp; // x iff x size == zext size. 3093 if (TruncOp.getValueType().bitsGT(VT)) 3094 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp); 3095 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp); 3096 } 3097 3098 // fold (aext (and (trunc x), cst)) -> (and x, cst). 3099 if (N0.getOpcode() == ISD::AND && 3100 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 3101 N0.getOperand(1).getOpcode() == ISD::Constant) { 3102 SDValue X = N0.getOperand(0).getOperand(0); 3103 if (X.getValueType().bitsLT(VT)) { 3104 X = DAG.getNode(ISD::ANY_EXTEND, VT, X); 3105 } else if (X.getValueType().bitsGT(VT)) { 3106 X = DAG.getNode(ISD::TRUNCATE, VT, X); 3107 } 3108 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3109 Mask.zext(VT.getSizeInBits()); 3110 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT)); 3111 } 3112 3113 // fold (aext (load x)) -> (aext (truncate (extload x))) 3114 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() && 3115 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) || 3116 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) { 3117 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3118 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(), 3119 LN0->getBasePtr(), LN0->getSrcValue(), 3120 LN0->getSrcValueOffset(), 3121 N0.getValueType(), 3122 LN0->isVolatile(), 3123 LN0->getAlignment()); 3124 CombineTo(N, ExtLoad); 3125 // Redirect any chain users to the new load. 3126 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), 3127 SDValue(ExtLoad.getNode(), 1)); 3128 // If any node needs the original loaded value, recompute it. 3129 if (!LN0->use_empty()) 3130 CombineTo(LN0, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad), 3131 ExtLoad.getValue(1)); 3132 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3133 } 3134 3135 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 3136 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 3137 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 3138 if (N0.getOpcode() == ISD::LOAD && 3139 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3140 N0.hasOneUse()) { 3141 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3142 MVT EVT = LN0->getMemoryVT(); 3143 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT, 3144 LN0->getChain(), LN0->getBasePtr(), 3145 LN0->getSrcValue(), 3146 LN0->getSrcValueOffset(), EVT, 3147 LN0->isVolatile(), 3148 LN0->getAlignment()); 3149 CombineTo(N, ExtLoad); 3150 CombineTo(N0.getNode(), 3151 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad), 3152 ExtLoad.getValue(1)); 3153 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3154 } 3155 3156 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 3157 if (N0.getOpcode() == ISD::SETCC) { 3158 SDValue SCC = 3159 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), 3160 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 3161 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 3162 if (SCC.getNode()) 3163 return SCC; 3164 } 3165 3166 return SDValue(); 3167} 3168 3169/// GetDemandedBits - See if the specified operand can be simplified with the 3170/// knowledge that only the bits specified by Mask are used. If so, return the 3171/// simpler operand, otherwise return a null SDValue. 3172SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 3173 switch (V.getOpcode()) { 3174 default: break; 3175 case ISD::OR: 3176 case ISD::XOR: 3177 // If the LHS or RHS don't contribute bits to the or, drop them. 3178 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 3179 return V.getOperand(1); 3180 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 3181 return V.getOperand(0); 3182 break; 3183 case ISD::SRL: 3184 // Only look at single-use SRLs. 3185 if (!V.getNode()->hasOneUse()) 3186 break; 3187 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 3188 // See if we can recursively simplify the LHS. 3189 unsigned Amt = RHSC->getValue(); 3190 APInt NewMask = Mask << Amt; 3191 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 3192 if (SimplifyLHS.getNode()) { 3193 return DAG.getNode(ISD::SRL, V.getValueType(), 3194 SimplifyLHS, V.getOperand(1)); 3195 } 3196 } 3197 } 3198 return SDValue(); 3199} 3200 3201/// ReduceLoadWidth - If the result of a wider load is shifted to right of N 3202/// bits and then truncated to a narrower type and where N is a multiple 3203/// of number of bits of the narrower type, transform it to a narrower load 3204/// from address + N / num of bits of new type. If the result is to be 3205/// extended, also fold the extension to form a extending load. 3206SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 3207 unsigned Opc = N->getOpcode(); 3208 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 3209 SDValue N0 = N->getOperand(0); 3210 MVT VT = N->getValueType(0); 3211 MVT EVT = N->getValueType(0); 3212 3213 // This transformation isn't valid for vector loads. 3214 if (VT.isVector()) 3215 return SDValue(); 3216 3217 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then 3218 // extended to VT. 3219 if (Opc == ISD::SIGN_EXTEND_INREG) { 3220 ExtType = ISD::SEXTLOAD; 3221 EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 3222 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) 3223 return SDValue(); 3224 } 3225 3226 unsigned EVTBits = EVT.getSizeInBits(); 3227 unsigned ShAmt = 0; 3228 bool CombineSRL = false; 3229 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3230 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3231 ShAmt = N01->getValue(); 3232 // Is the shift amount a multiple of size of VT? 3233 if ((ShAmt & (EVTBits-1)) == 0) { 3234 N0 = N0.getOperand(0); 3235 if (N0.getValueType().getSizeInBits() <= EVTBits) 3236 return SDValue(); 3237 CombineSRL = true; 3238 } 3239 } 3240 } 3241 3242 // Do not generate loads of non-round integer types since these can 3243 // be expensive (and would be wrong if the type is not byte sized). 3244 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && VT.isRound() && 3245 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits && 3246 // Do not change the width of a volatile load. 3247 !cast<LoadSDNode>(N0)->isVolatile()) { 3248 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3249 MVT PtrType = N0.getOperand(1).getValueType(); 3250 // For big endian targets, we need to adjust the offset to the pointer to 3251 // load the correct bytes. 3252 if (TLI.isBigEndian()) { 3253 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 3254 unsigned EVTStoreBits = EVT.getStoreSizeInBits(); 3255 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 3256 } 3257 uint64_t PtrOff = ShAmt / 8; 3258 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 3259 SDValue NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(), 3260 DAG.getConstant(PtrOff, PtrType)); 3261 AddToWorkList(NewPtr.getNode()); 3262 SDValue Load = (ExtType == ISD::NON_EXTLOAD) 3263 ? DAG.getLoad(VT, LN0->getChain(), NewPtr, 3264 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff, 3265 LN0->isVolatile(), NewAlign) 3266 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr, 3267 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff, 3268 EVT, LN0->isVolatile(), NewAlign); 3269 AddToWorkList(N); 3270 if (CombineSRL) { 3271 WorkListRemover DeadNodes(*this); 3272 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1), 3273 &DeadNodes); 3274 CombineTo(N->getOperand(0).getNode(), Load); 3275 } else 3276 CombineTo(N0.getNode(), Load, Load.getValue(1)); 3277 if (ShAmt) { 3278 if (Opc == ISD::SIGN_EXTEND_INREG) 3279 return DAG.getNode(Opc, VT, Load, N->getOperand(1)); 3280 else 3281 return DAG.getNode(Opc, VT, Load); 3282 } 3283 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3284 } 3285 3286 return SDValue(); 3287} 3288 3289 3290SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 3291 SDValue N0 = N->getOperand(0); 3292 SDValue N1 = N->getOperand(1); 3293 MVT VT = N->getValueType(0); 3294 MVT EVT = cast<VTSDNode>(N1)->getVT(); 3295 unsigned VTBits = VT.getSizeInBits(); 3296 unsigned EVTBits = EVT.getSizeInBits(); 3297 3298 // fold (sext_in_reg c1) -> c1 3299 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 3300 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1); 3301 3302 // If the input is already sign extended, just drop the extension. 3303 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1) 3304 return N0; 3305 3306 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 3307 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 3308 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) { 3309 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1); 3310 } 3311 3312 // fold (sext_in_reg (sext x)) -> (sext x) 3313 // fold (sext_in_reg (aext x)) -> (sext x) 3314 // if x is small enough. 3315 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 3316 SDValue N00 = N0.getOperand(0); 3317 if (N00.getValueType().getSizeInBits() < EVTBits) 3318 return DAG.getNode(ISD::SIGN_EXTEND, VT, N00, N1); 3319 } 3320 3321 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 3322 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 3323 return DAG.getZeroExtendInReg(N0, EVT); 3324 3325 // fold operands of sext_in_reg based on knowledge that the top bits are not 3326 // demanded. 3327 if (SimplifyDemandedBits(SDValue(N, 0))) 3328 return SDValue(N, 0); 3329 3330 // fold (sext_in_reg (load x)) -> (smaller sextload x) 3331 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 3332 SDValue NarrowLoad = ReduceLoadWidth(N); 3333 if (NarrowLoad.getNode()) 3334 return NarrowLoad; 3335 3336 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24 3337 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible. 3338 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 3339 if (N0.getOpcode() == ISD::SRL) { 3340 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3341 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) { 3342 // We can turn this into an SRA iff the input to the SRL is already sign 3343 // extended enough. 3344 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 3345 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits) 3346 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1)); 3347 } 3348 } 3349 3350 // fold (sext_inreg (extload x)) -> (sextload x) 3351 if (ISD::isEXTLoad(N0.getNode()) && 3352 ISD::isUNINDEXEDLoad(N0.getNode()) && 3353 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 3354 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) || 3355 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) { 3356 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3357 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(), 3358 LN0->getBasePtr(), LN0->getSrcValue(), 3359 LN0->getSrcValueOffset(), EVT, 3360 LN0->isVolatile(), 3361 LN0->getAlignment()); 3362 CombineTo(N, ExtLoad); 3363 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3364 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3365 } 3366 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 3367 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3368 N0.hasOneUse() && 3369 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 3370 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) || 3371 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) { 3372 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3373 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(), 3374 LN0->getBasePtr(), LN0->getSrcValue(), 3375 LN0->getSrcValueOffset(), EVT, 3376 LN0->isVolatile(), 3377 LN0->getAlignment()); 3378 CombineTo(N, ExtLoad); 3379 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3380 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3381 } 3382 return SDValue(); 3383} 3384 3385SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 3386 SDValue N0 = N->getOperand(0); 3387 MVT VT = N->getValueType(0); 3388 3389 // noop truncate 3390 if (N0.getValueType() == N->getValueType(0)) 3391 return N0; 3392 // fold (truncate c1) -> c1 3393 if (isa<ConstantSDNode>(N0)) 3394 return DAG.getNode(ISD::TRUNCATE, VT, N0); 3395 // fold (truncate (truncate x)) -> (truncate x) 3396 if (N0.getOpcode() == ISD::TRUNCATE) 3397 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0)); 3398 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 3399 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND|| 3400 N0.getOpcode() == ISD::ANY_EXTEND) { 3401 if (N0.getOperand(0).getValueType().bitsLT(VT)) 3402 // if the source is smaller than the dest, we still need an extend 3403 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0)); 3404 else if (N0.getOperand(0).getValueType().bitsGT(VT)) 3405 // if the source is larger than the dest, than we just need the truncate 3406 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0)); 3407 else 3408 // if the source and dest are the same type, we can drop both the extend 3409 // and the truncate 3410 return N0.getOperand(0); 3411 } 3412 3413 // See if we can simplify the input to this truncate through knowledge that 3414 // only the low bits are being used. For example "trunc (or (shl x, 8), y)" 3415 // -> trunc y 3416 SDValue Shorter = 3417 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 3418 VT.getSizeInBits())); 3419 if (Shorter.getNode()) 3420 return DAG.getNode(ISD::TRUNCATE, VT, Shorter); 3421 3422 // fold (truncate (load x)) -> (smaller load x) 3423 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 3424 return ReduceLoadWidth(N); 3425} 3426 3427static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 3428 SDValue Elt = N->getOperand(i); 3429 if (Elt.getOpcode() != ISD::MERGE_VALUES) 3430 return Elt.getNode(); 3431 return Elt.getOperand(Elt.getResNo()).getNode(); 3432} 3433 3434/// CombineConsecutiveLoads - build_pair (load, load) -> load 3435/// if load locations are consecutive. 3436SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) { 3437 assert(N->getOpcode() == ISD::BUILD_PAIR); 3438 3439 SDNode *LD1 = getBuildPairElt(N, 0); 3440 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse()) 3441 return SDValue(); 3442 MVT LD1VT = LD1->getValueType(0); 3443 SDNode *LD2 = getBuildPairElt(N, 1); 3444 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3445 if (ISD::isNON_EXTLoad(LD2) && 3446 LD2->hasOneUse() && 3447 // If both are volatile this would reduce the number of volatile loads. 3448 // If one is volatile it might be ok, but play conservative and bail out. 3449 !cast<LoadSDNode>(LD1)->isVolatile() && 3450 !cast<LoadSDNode>(LD2)->isVolatile() && 3451 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) { 3452 LoadSDNode *LD = cast<LoadSDNode>(LD1); 3453 unsigned Align = LD->getAlignment(); 3454 unsigned NewAlign = TLI.getTargetMachine().getTargetData()-> 3455 getABITypeAlignment(VT.getTypeForMVT()); 3456 if (NewAlign <= Align && 3457 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) 3458 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), 3459 LD->getSrcValue(), LD->getSrcValueOffset(), 3460 false, Align); 3461 } 3462 return SDValue(); 3463} 3464 3465SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) { 3466 SDValue N0 = N->getOperand(0); 3467 MVT VT = N->getValueType(0); 3468 3469 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 3470 // Only do this before legalize, since afterward the target may be depending 3471 // on the bitconvert. 3472 // First check to see if this is all constant. 3473 if (!AfterLegalize && 3474 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 3475 VT.isVector()) { 3476 bool isSimple = true; 3477 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) 3478 if (N0.getOperand(i).getOpcode() != ISD::UNDEF && 3479 N0.getOperand(i).getOpcode() != ISD::Constant && 3480 N0.getOperand(i).getOpcode() != ISD::ConstantFP) { 3481 isSimple = false; 3482 break; 3483 } 3484 3485 MVT DestEltVT = N->getValueType(0).getVectorElementType(); 3486 assert(!DestEltVT.isVector() && 3487 "Element type of vector ValueType must not be vector!"); 3488 if (isSimple) { 3489 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT); 3490 } 3491 } 3492 3493 // If the input is a constant, let Val fold it. 3494 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 3495 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0); 3496 if (Res.getNode() != N) return Res; 3497 } 3498 3499 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2) 3500 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0)); 3501 3502 // fold (conv (load x)) -> (load (conv*)x) 3503 // If the resultant load doesn't need a higher alignment than the original! 3504 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 3505 // Do not change the width of a volatile load. 3506 !cast<LoadSDNode>(N0)->isVolatile() && 3507 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) { 3508 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3509 unsigned Align = TLI.getTargetMachine().getTargetData()-> 3510 getABITypeAlignment(VT.getTypeForMVT()); 3511 unsigned OrigAlign = LN0->getAlignment(); 3512 if (Align <= OrigAlign) { 3513 SDValue Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(), 3514 LN0->getSrcValue(), LN0->getSrcValueOffset(), 3515 LN0->isVolatile(), OrigAlign); 3516 AddToWorkList(N); 3517 CombineTo(N0.getNode(), DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load), 3518 Load.getValue(1)); 3519 return Load; 3520 } 3521 } 3522 3523 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit) 3524 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit) 3525 // This often reduces constant pool loads. 3526 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) && 3527 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) { 3528 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0)); 3529 AddToWorkList(NewConv.getNode()); 3530 3531 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 3532 if (N0.getOpcode() == ISD::FNEG) 3533 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT)); 3534 assert(N0.getOpcode() == ISD::FABS); 3535 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT)); 3536 } 3537 3538 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign' 3539 // Note that we don't handle copysign(x,cst) because this can always be folded 3540 // to an fneg or fabs. 3541 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 3542 isa<ConstantFPSDNode>(N0.getOperand(0)) && 3543 VT.isInteger() && !VT.isVector()) { 3544 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 3545 SDValue X = DAG.getNode(ISD::BIT_CONVERT, 3546 MVT::getIntegerVT(OrigXWidth), 3547 N0.getOperand(1)); 3548 AddToWorkList(X.getNode()); 3549 3550 // If X has a different width than the result/lhs, sext it or truncate it. 3551 unsigned VTWidth = VT.getSizeInBits(); 3552 if (OrigXWidth < VTWidth) { 3553 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X); 3554 AddToWorkList(X.getNode()); 3555 } else if (OrigXWidth > VTWidth) { 3556 // To get the sign bit in the right place, we have to shift it right 3557 // before truncating. 3558 X = DAG.getNode(ISD::SRL, X.getValueType(), X, 3559 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 3560 AddToWorkList(X.getNode()); 3561 X = DAG.getNode(ISD::TRUNCATE, VT, X); 3562 AddToWorkList(X.getNode()); 3563 } 3564 3565 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 3566 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT)); 3567 AddToWorkList(X.getNode()); 3568 3569 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0)); 3570 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT)); 3571 AddToWorkList(Cst.getNode()); 3572 3573 return DAG.getNode(ISD::OR, VT, X, Cst); 3574 } 3575 3576 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 3577 if (N0.getOpcode() == ISD::BUILD_PAIR) { 3578 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 3579 if (CombineLD.getNode()) 3580 return CombineLD; 3581 } 3582 3583 return SDValue(); 3584} 3585 3586SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 3587 MVT VT = N->getValueType(0); 3588 return CombineConsecutiveLoads(N, VT); 3589} 3590 3591/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector 3592/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 3593/// destination element value type. 3594SDValue DAGCombiner:: 3595ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) { 3596 MVT SrcEltVT = BV->getOperand(0).getValueType(); 3597 3598 // If this is already the right type, we're done. 3599 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 3600 3601 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 3602 unsigned DstBitSize = DstEltVT.getSizeInBits(); 3603 3604 // If this is a conversion of N elements of one type to N elements of another 3605 // type, convert each element. This handles FP<->INT cases. 3606 if (SrcBitSize == DstBitSize) { 3607 SmallVector<SDValue, 8> Ops; 3608 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 3609 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i))); 3610 AddToWorkList(Ops.back().getNode()); 3611 } 3612 MVT VT = MVT::getVectorVT(DstEltVT, 3613 BV->getValueType(0).getVectorNumElements()); 3614 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()); 3615 } 3616 3617 // Otherwise, we're growing or shrinking the elements. To avoid having to 3618 // handle annoying details of growing/shrinking FP values, we convert them to 3619 // int first. 3620 if (SrcEltVT.isFloatingPoint()) { 3621 // Convert the input float vector to a int vector where the elements are the 3622 // same sizes. 3623 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 3624 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits()); 3625 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode(); 3626 SrcEltVT = IntVT; 3627 } 3628 3629 // Now we know the input is an integer vector. If the output is a FP type, 3630 // convert to integer first, then to FP of the right size. 3631 if (DstEltVT.isFloatingPoint()) { 3632 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 3633 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits()); 3634 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode(); 3635 3636 // Next, convert to FP elements of the same size. 3637 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT); 3638 } 3639 3640 // Okay, we know the src/dst types are both integers of differing types. 3641 // Handling growing first. 3642 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 3643 if (SrcBitSize < DstBitSize) { 3644 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 3645 3646 SmallVector<SDValue, 8> Ops; 3647 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 3648 i += NumInputsPerOutput) { 3649 bool isLE = TLI.isLittleEndian(); 3650 APInt NewBits = APInt(DstBitSize, 0); 3651 bool EltIsUndef = true; 3652 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 3653 // Shift the previously computed bits over. 3654 NewBits <<= SrcBitSize; 3655 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 3656 if (Op.getOpcode() == ISD::UNDEF) continue; 3657 EltIsUndef = false; 3658 3659 NewBits |= 3660 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize); 3661 } 3662 3663 if (EltIsUndef) 3664 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT)); 3665 else 3666 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 3667 } 3668 3669 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size()); 3670 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()); 3671 } 3672 3673 // Finally, this must be the case where we are shrinking elements: each input 3674 // turns into multiple outputs. 3675 bool isS2V = ISD::isScalarToVector(BV); 3676 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 3677 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands()); 3678 SmallVector<SDValue, 8> Ops; 3679 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 3680 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 3681 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 3682 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT)); 3683 continue; 3684 } 3685 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue(); 3686 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 3687 APInt ThisVal = APInt(OpVal).trunc(DstBitSize); 3688 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 3689 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal) 3690 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 3691 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]); 3692 OpVal = OpVal.lshr(DstBitSize); 3693 } 3694 3695 // For big endian targets, swap the order of the pieces of each element. 3696 if (TLI.isBigEndian()) 3697 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 3698 } 3699 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()); 3700} 3701 3702 3703 3704SDValue DAGCombiner::visitFADD(SDNode *N) { 3705 SDValue N0 = N->getOperand(0); 3706 SDValue N1 = N->getOperand(1); 3707 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3708 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3709 MVT VT = N->getValueType(0); 3710 3711 // fold vector ops 3712 if (VT.isVector()) { 3713 SDValue FoldedVOp = SimplifyVBinOp(N); 3714 if (FoldedVOp.getNode()) return FoldedVOp; 3715 } 3716 3717 // fold (fadd c1, c2) -> c1+c2 3718 if (N0CFP && N1CFP && VT != MVT::ppcf128) 3719 return DAG.getNode(ISD::FADD, VT, N0, N1); 3720 // canonicalize constant to RHS 3721 if (N0CFP && !N1CFP) 3722 return DAG.getNode(ISD::FADD, VT, N1, N0); 3723 // fold (A + (-B)) -> A-B 3724 if (isNegatibleForFree(N1, AfterLegalize) == 2) 3725 return DAG.getNode(ISD::FSUB, VT, N0, 3726 GetNegatedExpression(N1, DAG, AfterLegalize)); 3727 // fold ((-A) + B) -> B-A 3728 if (isNegatibleForFree(N0, AfterLegalize) == 2) 3729 return DAG.getNode(ISD::FSUB, VT, N1, 3730 GetNegatedExpression(N0, DAG, AfterLegalize)); 3731 3732 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 3733 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD && 3734 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 3735 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0), 3736 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1)); 3737 3738 return SDValue(); 3739} 3740 3741SDValue DAGCombiner::visitFSUB(SDNode *N) { 3742 SDValue N0 = N->getOperand(0); 3743 SDValue N1 = N->getOperand(1); 3744 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3745 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3746 MVT VT = N->getValueType(0); 3747 3748 // fold vector ops 3749 if (VT.isVector()) { 3750 SDValue FoldedVOp = SimplifyVBinOp(N); 3751 if (FoldedVOp.getNode()) return FoldedVOp; 3752 } 3753 3754 // fold (fsub c1, c2) -> c1-c2 3755 if (N0CFP && N1CFP && VT != MVT::ppcf128) 3756 return DAG.getNode(ISD::FSUB, VT, N0, N1); 3757 // fold (0-B) -> -B 3758 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) { 3759 if (isNegatibleForFree(N1, AfterLegalize)) 3760 return GetNegatedExpression(N1, DAG, AfterLegalize); 3761 return DAG.getNode(ISD::FNEG, VT, N1); 3762 } 3763 // fold (A-(-B)) -> A+B 3764 if (isNegatibleForFree(N1, AfterLegalize)) 3765 return DAG.getNode(ISD::FADD, VT, N0, 3766 GetNegatedExpression(N1, DAG, AfterLegalize)); 3767 3768 return SDValue(); 3769} 3770 3771SDValue DAGCombiner::visitFMUL(SDNode *N) { 3772 SDValue N0 = N->getOperand(0); 3773 SDValue N1 = N->getOperand(1); 3774 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3775 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3776 MVT VT = N->getValueType(0); 3777 3778 // fold vector ops 3779 if (VT.isVector()) { 3780 SDValue FoldedVOp = SimplifyVBinOp(N); 3781 if (FoldedVOp.getNode()) return FoldedVOp; 3782 } 3783 3784 // fold (fmul c1, c2) -> c1*c2 3785 if (N0CFP && N1CFP && VT != MVT::ppcf128) 3786 return DAG.getNode(ISD::FMUL, VT, N0, N1); 3787 // canonicalize constant to RHS 3788 if (N0CFP && !N1CFP) 3789 return DAG.getNode(ISD::FMUL, VT, N1, N0); 3790 // fold (fmul X, 2.0) -> (fadd X, X) 3791 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 3792 return DAG.getNode(ISD::FADD, VT, N0, N0); 3793 // fold (fmul X, -1.0) -> (fneg X) 3794 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 3795 return DAG.getNode(ISD::FNEG, VT, N0); 3796 3797 // -X * -Y -> X*Y 3798 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) { 3799 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) { 3800 // Both can be negated for free, check to see if at least one is cheaper 3801 // negated. 3802 if (LHSNeg == 2 || RHSNeg == 2) 3803 return DAG.getNode(ISD::FMUL, VT, 3804 GetNegatedExpression(N0, DAG, AfterLegalize), 3805 GetNegatedExpression(N1, DAG, AfterLegalize)); 3806 } 3807 } 3808 3809 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 3810 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL && 3811 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 3812 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0), 3813 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1)); 3814 3815 return SDValue(); 3816} 3817 3818SDValue DAGCombiner::visitFDIV(SDNode *N) { 3819 SDValue N0 = N->getOperand(0); 3820 SDValue N1 = N->getOperand(1); 3821 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3822 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3823 MVT VT = N->getValueType(0); 3824 3825 // fold vector ops 3826 if (VT.isVector()) { 3827 SDValue FoldedVOp = SimplifyVBinOp(N); 3828 if (FoldedVOp.getNode()) return FoldedVOp; 3829 } 3830 3831 // fold (fdiv c1, c2) -> c1/c2 3832 if (N0CFP && N1CFP && VT != MVT::ppcf128) 3833 return DAG.getNode(ISD::FDIV, VT, N0, N1); 3834 3835 3836 // -X / -Y -> X*Y 3837 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) { 3838 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) { 3839 // Both can be negated for free, check to see if at least one is cheaper 3840 // negated. 3841 if (LHSNeg == 2 || RHSNeg == 2) 3842 return DAG.getNode(ISD::FDIV, VT, 3843 GetNegatedExpression(N0, DAG, AfterLegalize), 3844 GetNegatedExpression(N1, DAG, AfterLegalize)); 3845 } 3846 } 3847 3848 return SDValue(); 3849} 3850 3851SDValue DAGCombiner::visitFREM(SDNode *N) { 3852 SDValue N0 = N->getOperand(0); 3853 SDValue N1 = N->getOperand(1); 3854 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3855 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3856 MVT VT = N->getValueType(0); 3857 3858 // fold (frem c1, c2) -> fmod(c1,c2) 3859 if (N0CFP && N1CFP && VT != MVT::ppcf128) 3860 return DAG.getNode(ISD::FREM, VT, N0, N1); 3861 3862 return SDValue(); 3863} 3864 3865SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 3866 SDValue N0 = N->getOperand(0); 3867 SDValue N1 = N->getOperand(1); 3868 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3869 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3870 MVT VT = N->getValueType(0); 3871 3872 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold 3873 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1); 3874 3875 if (N1CFP) { 3876 const APFloat& V = N1CFP->getValueAPF(); 3877 // copysign(x, c1) -> fabs(x) iff ispos(c1) 3878 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 3879 if (!V.isNegative()) 3880 return DAG.getNode(ISD::FABS, VT, N0); 3881 else 3882 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0)); 3883 } 3884 3885 // copysign(fabs(x), y) -> copysign(x, y) 3886 // copysign(fneg(x), y) -> copysign(x, y) 3887 // copysign(copysign(x,z), y) -> copysign(x, y) 3888 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 3889 N0.getOpcode() == ISD::FCOPYSIGN) 3890 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1); 3891 3892 // copysign(x, abs(y)) -> abs(x) 3893 if (N1.getOpcode() == ISD::FABS) 3894 return DAG.getNode(ISD::FABS, VT, N0); 3895 3896 // copysign(x, copysign(y,z)) -> copysign(x, z) 3897 if (N1.getOpcode() == ISD::FCOPYSIGN) 3898 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1)); 3899 3900 // copysign(x, fp_extend(y)) -> copysign(x, y) 3901 // copysign(x, fp_round(y)) -> copysign(x, y) 3902 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 3903 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0)); 3904 3905 return SDValue(); 3906} 3907 3908 3909 3910SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 3911 SDValue N0 = N->getOperand(0); 3912 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3913 MVT VT = N->getValueType(0); 3914 MVT OpVT = N0.getValueType(); 3915 3916 // fold (sint_to_fp c1) -> c1fp 3917 if (N0C && OpVT != MVT::ppcf128) 3918 return DAG.getNode(ISD::SINT_TO_FP, VT, N0); 3919 3920 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 3921 // but UINT_TO_FP is legal on this target, try to convert. 3922 if (!TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT) && 3923 TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT)) { 3924 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 3925 if (DAG.SignBitIsZero(N0)) 3926 return DAG.getNode(ISD::UINT_TO_FP, VT, N0); 3927 } 3928 3929 3930 return SDValue(); 3931} 3932 3933SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 3934 SDValue N0 = N->getOperand(0); 3935 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3936 MVT VT = N->getValueType(0); 3937 MVT OpVT = N0.getValueType(); 3938 3939 // fold (uint_to_fp c1) -> c1fp 3940 if (N0C && OpVT != MVT::ppcf128) 3941 return DAG.getNode(ISD::UINT_TO_FP, VT, N0); 3942 3943 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 3944 // but SINT_TO_FP is legal on this target, try to convert. 3945 if (!TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT) && 3946 TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT)) { 3947 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 3948 if (DAG.SignBitIsZero(N0)) 3949 return DAG.getNode(ISD::SINT_TO_FP, VT, N0); 3950 } 3951 3952 return SDValue(); 3953} 3954 3955SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 3956 SDValue N0 = N->getOperand(0); 3957 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3958 MVT VT = N->getValueType(0); 3959 3960 // fold (fp_to_sint c1fp) -> c1 3961 if (N0CFP) 3962 return DAG.getNode(ISD::FP_TO_SINT, VT, N0); 3963 return SDValue(); 3964} 3965 3966SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 3967 SDValue N0 = N->getOperand(0); 3968 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3969 MVT VT = N->getValueType(0); 3970 3971 // fold (fp_to_uint c1fp) -> c1 3972 if (N0CFP && VT != MVT::ppcf128) 3973 return DAG.getNode(ISD::FP_TO_UINT, VT, N0); 3974 return SDValue(); 3975} 3976 3977SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 3978 SDValue N0 = N->getOperand(0); 3979 SDValue N1 = N->getOperand(1); 3980 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 3981 MVT VT = N->getValueType(0); 3982 3983 // fold (fp_round c1fp) -> c1fp 3984 if (N0CFP && N0.getValueType() != MVT::ppcf128) 3985 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1); 3986 3987 // fold (fp_round (fp_extend x)) -> x 3988 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 3989 return N0.getOperand(0); 3990 3991 // fold (fp_round (fp_round x)) -> (fp_round x) 3992 if (N0.getOpcode() == ISD::FP_ROUND) { 3993 // This is a value preserving truncation if both round's are. 3994 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 3995 N0.getNode()->getConstantOperandVal(1) == 1; 3996 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), 3997 DAG.getIntPtrConstant(IsTrunc)); 3998 } 3999 4000 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 4001 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 4002 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1); 4003 AddToWorkList(Tmp.getNode()); 4004 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1)); 4005 } 4006 4007 return SDValue(); 4008} 4009 4010SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 4011 SDValue N0 = N->getOperand(0); 4012 MVT VT = N->getValueType(0); 4013 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 4014 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4015 4016 // fold (fp_round_inreg c1fp) -> c1fp 4017 if (N0CFP) { 4018 SDValue Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT); 4019 return DAG.getNode(ISD::FP_EXTEND, VT, Round); 4020 } 4021 return SDValue(); 4022} 4023 4024SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 4025 SDValue N0 = N->getOperand(0); 4026 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4027 MVT VT = N->getValueType(0); 4028 4029 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 4030 if (N->hasOneUse() && 4031 N->use_begin().getUse().getSDValue().getOpcode() == ISD::FP_ROUND) 4032 return SDValue(); 4033 4034 // fold (fp_extend c1fp) -> c1fp 4035 if (N0CFP && VT != MVT::ppcf128) 4036 return DAG.getNode(ISD::FP_EXTEND, VT, N0); 4037 4038 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 4039 // value of X. 4040 if (N0.getOpcode() == ISD::FP_ROUND && N0.getNode()->getConstantOperandVal(1) == 1){ 4041 SDValue In = N0.getOperand(0); 4042 if (In.getValueType() == VT) return In; 4043 if (VT.bitsLT(In.getValueType())) 4044 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1)); 4045 return DAG.getNode(ISD::FP_EXTEND, VT, In); 4046 } 4047 4048 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 4049 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() && 4050 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) || 4051 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) { 4052 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4053 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(), 4054 LN0->getBasePtr(), LN0->getSrcValue(), 4055 LN0->getSrcValueOffset(), 4056 N0.getValueType(), 4057 LN0->isVolatile(), 4058 LN0->getAlignment()); 4059 CombineTo(N, ExtLoad); 4060 CombineTo(N0.getNode(), DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad, 4061 DAG.getIntPtrConstant(1)), 4062 ExtLoad.getValue(1)); 4063 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4064 } 4065 4066 return SDValue(); 4067} 4068 4069SDValue DAGCombiner::visitFNEG(SDNode *N) { 4070 SDValue N0 = N->getOperand(0); 4071 4072 if (isNegatibleForFree(N0, AfterLegalize)) 4073 return GetNegatedExpression(N0, DAG, AfterLegalize); 4074 4075 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 4076 // constant pool values. 4077 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() && 4078 N0.getOperand(0).getValueType().isInteger() && 4079 !N0.getOperand(0).getValueType().isVector()) { 4080 SDValue Int = N0.getOperand(0); 4081 MVT IntVT = Int.getValueType(); 4082 if (IntVT.isInteger() && !IntVT.isVector()) { 4083 Int = DAG.getNode(ISD::XOR, IntVT, Int, 4084 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT)); 4085 AddToWorkList(Int.getNode()); 4086 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int); 4087 } 4088 } 4089 4090 return SDValue(); 4091} 4092 4093SDValue DAGCombiner::visitFABS(SDNode *N) { 4094 SDValue N0 = N->getOperand(0); 4095 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4096 MVT VT = N->getValueType(0); 4097 4098 // fold (fabs c1) -> fabs(c1) 4099 if (N0CFP && VT != MVT::ppcf128) 4100 return DAG.getNode(ISD::FABS, VT, N0); 4101 // fold (fabs (fabs x)) -> (fabs x) 4102 if (N0.getOpcode() == ISD::FABS) 4103 return N->getOperand(0); 4104 // fold (fabs (fneg x)) -> (fabs x) 4105 // fold (fabs (fcopysign x, y)) -> (fabs x) 4106 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 4107 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0)); 4108 4109 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 4110 // constant pool values. 4111 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() && 4112 N0.getOperand(0).getValueType().isInteger() && 4113 !N0.getOperand(0).getValueType().isVector()) { 4114 SDValue Int = N0.getOperand(0); 4115 MVT IntVT = Int.getValueType(); 4116 if (IntVT.isInteger() && !IntVT.isVector()) { 4117 Int = DAG.getNode(ISD::AND, IntVT, Int, 4118 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT)); 4119 AddToWorkList(Int.getNode()); 4120 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int); 4121 } 4122 } 4123 4124 return SDValue(); 4125} 4126 4127SDValue DAGCombiner::visitBRCOND(SDNode *N) { 4128 SDValue Chain = N->getOperand(0); 4129 SDValue N1 = N->getOperand(1); 4130 SDValue N2 = N->getOperand(2); 4131 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4132 4133 // never taken branch, fold to chain 4134 if (N1C && N1C->isNullValue()) 4135 return Chain; 4136 // unconditional branch 4137 if (N1C && N1C->getAPIntValue() == 1) 4138 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2); 4139 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 4140 // on the target. 4141 if (N1.getOpcode() == ISD::SETCC && 4142 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) { 4143 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2), 4144 N1.getOperand(0), N1.getOperand(1), N2); 4145 } 4146 return SDValue(); 4147} 4148 4149// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 4150// 4151SDValue DAGCombiner::visitBR_CC(SDNode *N) { 4152 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 4153 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 4154 4155 // Use SimplifySetCC to simplify SETCC's. 4156 SDValue Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false); 4157 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 4158 4159 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.getNode()); 4160 4161 // fold br_cc true, dest -> br dest (unconditional branch) 4162 if (SCCC && !SCCC->isNullValue()) 4163 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0), 4164 N->getOperand(4)); 4165 // fold br_cc false, dest -> unconditional fall through 4166 if (SCCC && SCCC->isNullValue()) 4167 return N->getOperand(0); 4168 4169 // fold to a simpler setcc 4170 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 4171 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0), 4172 Simp.getOperand(2), Simp.getOperand(0), 4173 Simp.getOperand(1), N->getOperand(4)); 4174 return SDValue(); 4175} 4176 4177 4178/// CombineToPreIndexedLoadStore - Try turning a load / store into a 4179/// pre-indexed load / store when the base pointer is an add or subtract 4180/// and it has other uses besides the load / store. After the 4181/// transformation, the new indexed load / store has effectively folded 4182/// the add / subtract in and all of its other uses are redirected to the 4183/// new load / store. 4184bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 4185 if (!AfterLegalize) 4186 return false; 4187 4188 bool isLoad = true; 4189 SDValue Ptr; 4190 MVT VT; 4191 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 4192 if (LD->isIndexed()) 4193 return false; 4194 VT = LD->getMemoryVT(); 4195 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 4196 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 4197 return false; 4198 Ptr = LD->getBasePtr(); 4199 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 4200 if (ST->isIndexed()) 4201 return false; 4202 VT = ST->getMemoryVT(); 4203 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 4204 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 4205 return false; 4206 Ptr = ST->getBasePtr(); 4207 isLoad = false; 4208 } else 4209 return false; 4210 4211 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 4212 // out. There is no reason to make this a preinc/predec. 4213 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 4214 Ptr.getNode()->hasOneUse()) 4215 return false; 4216 4217 // Ask the target to do addressing mode selection. 4218 SDValue BasePtr; 4219 SDValue Offset; 4220 ISD::MemIndexedMode AM = ISD::UNINDEXED; 4221 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 4222 return false; 4223 // Don't create a indexed load / store with zero offset. 4224 if (isa<ConstantSDNode>(Offset) && 4225 cast<ConstantSDNode>(Offset)->isNullValue()) 4226 return false; 4227 4228 // Try turning it into a pre-indexed load / store except when: 4229 // 1) The new base ptr is a frame index. 4230 // 2) If N is a store and the new base ptr is either the same as or is a 4231 // predecessor of the value being stored. 4232 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 4233 // that would create a cycle. 4234 // 4) All uses are load / store ops that use it as old base ptr. 4235 4236 // Check #1. Preinc'ing a frame index would require copying the stack pointer 4237 // (plus the implicit offset) to a register to preinc anyway. 4238 if (isa<FrameIndexSDNode>(BasePtr)) 4239 return false; 4240 4241 // Check #2. 4242 if (!isLoad) { 4243 SDValue Val = cast<StoreSDNode>(N)->getValue(); 4244 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 4245 return false; 4246 } 4247 4248 // Now check for #3 and #4. 4249 bool RealUse = false; 4250 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 4251 E = Ptr.getNode()->use_end(); I != E; ++I) { 4252 SDNode *Use = *I; 4253 if (Use == N) 4254 continue; 4255 if (Use->isPredecessorOf(N)) 4256 return false; 4257 4258 if (!((Use->getOpcode() == ISD::LOAD && 4259 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) || 4260 (Use->getOpcode() == ISD::STORE && 4261 cast<StoreSDNode>(Use)->getBasePtr() == Ptr))) 4262 RealUse = true; 4263 } 4264 if (!RealUse) 4265 return false; 4266 4267 SDValue Result; 4268 if (isLoad) 4269 Result = DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM); 4270 else 4271 Result = DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM); 4272 ++PreIndexedNodes; 4273 ++NodesCombined; 4274 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG)); 4275 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG)); 4276 DOUT << '\n'; 4277 WorkListRemover DeadNodes(*this); 4278 if (isLoad) { 4279 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0), 4280 &DeadNodes); 4281 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2), 4282 &DeadNodes); 4283 } else { 4284 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1), 4285 &DeadNodes); 4286 } 4287 4288 // Finally, since the node is now dead, remove it from the graph. 4289 DAG.DeleteNode(N); 4290 4291 // Replace the uses of Ptr with uses of the updated base value. 4292 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0), 4293 &DeadNodes); 4294 removeFromWorkList(Ptr.getNode()); 4295 DAG.DeleteNode(Ptr.getNode()); 4296 4297 return true; 4298} 4299 4300/// CombineToPostIndexedLoadStore - Try to combine a load / store with a 4301/// add / sub of the base pointer node into a post-indexed load / store. 4302/// The transformation folded the add / subtract into the new indexed 4303/// load / store effectively and all of its uses are redirected to the 4304/// new load / store. 4305bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 4306 if (!AfterLegalize) 4307 return false; 4308 4309 bool isLoad = true; 4310 SDValue Ptr; 4311 MVT VT; 4312 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 4313 if (LD->isIndexed()) 4314 return false; 4315 VT = LD->getMemoryVT(); 4316 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 4317 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 4318 return false; 4319 Ptr = LD->getBasePtr(); 4320 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 4321 if (ST->isIndexed()) 4322 return false; 4323 VT = ST->getMemoryVT(); 4324 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 4325 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 4326 return false; 4327 Ptr = ST->getBasePtr(); 4328 isLoad = false; 4329 } else 4330 return false; 4331 4332 if (Ptr.getNode()->hasOneUse()) 4333 return false; 4334 4335 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 4336 E = Ptr.getNode()->use_end(); I != E; ++I) { 4337 SDNode *Op = *I; 4338 if (Op == N || 4339 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 4340 continue; 4341 4342 SDValue BasePtr; 4343 SDValue Offset; 4344 ISD::MemIndexedMode AM = ISD::UNINDEXED; 4345 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 4346 if (Ptr == Offset) 4347 std::swap(BasePtr, Offset); 4348 if (Ptr != BasePtr) 4349 continue; 4350 // Don't create a indexed load / store with zero offset. 4351 if (isa<ConstantSDNode>(Offset) && 4352 cast<ConstantSDNode>(Offset)->isNullValue()) 4353 continue; 4354 4355 // Try turning it into a post-indexed load / store except when 4356 // 1) All uses are load / store ops that use it as base ptr. 4357 // 2) Op must be independent of N, i.e. Op is neither a predecessor 4358 // nor a successor of N. Otherwise, if Op is folded that would 4359 // create a cycle. 4360 4361 // Check for #1. 4362 bool TryNext = false; 4363 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 4364 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 4365 SDNode *Use = *II; 4366 if (Use == Ptr.getNode()) 4367 continue; 4368 4369 // If all the uses are load / store addresses, then don't do the 4370 // transformation. 4371 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 4372 bool RealUse = false; 4373 for (SDNode::use_iterator III = Use->use_begin(), 4374 EEE = Use->use_end(); III != EEE; ++III) { 4375 SDNode *UseUse = *III; 4376 if (!((UseUse->getOpcode() == ISD::LOAD && 4377 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) || 4378 (UseUse->getOpcode() == ISD::STORE && 4379 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use))) 4380 RealUse = true; 4381 } 4382 4383 if (!RealUse) { 4384 TryNext = true; 4385 break; 4386 } 4387 } 4388 } 4389 if (TryNext) 4390 continue; 4391 4392 // Check for #2 4393 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 4394 SDValue Result = isLoad 4395 ? DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM) 4396 : DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM); 4397 ++PostIndexedNodes; 4398 ++NodesCombined; 4399 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG)); 4400 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG)); 4401 DOUT << '\n'; 4402 WorkListRemover DeadNodes(*this); 4403 if (isLoad) { 4404 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0), 4405 &DeadNodes); 4406 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2), 4407 &DeadNodes); 4408 } else { 4409 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1), 4410 &DeadNodes); 4411 } 4412 4413 // Finally, since the node is now dead, remove it from the graph. 4414 DAG.DeleteNode(N); 4415 4416 // Replace the uses of Use with uses of the updated base value. 4417 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 4418 Result.getValue(isLoad ? 1 : 0), 4419 &DeadNodes); 4420 removeFromWorkList(Op); 4421 DAG.DeleteNode(Op); 4422 return true; 4423 } 4424 } 4425 } 4426 return false; 4427} 4428 4429/// InferAlignment - If we can infer some alignment information from this 4430/// pointer, return it. 4431static unsigned InferAlignment(SDValue Ptr, SelectionDAG &DAG) { 4432 // If this is a direct reference to a stack slot, use information about the 4433 // stack slot's alignment. 4434 int FrameIdx = 1 << 31; 4435 int64_t FrameOffset = 0; 4436 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 4437 FrameIdx = FI->getIndex(); 4438 } else if (Ptr.getOpcode() == ISD::ADD && 4439 isa<ConstantSDNode>(Ptr.getOperand(1)) && 4440 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4441 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4442 FrameOffset = Ptr.getConstantOperandVal(1); 4443 } 4444 4445 if (FrameIdx != (1 << 31)) { 4446 // FIXME: Handle FI+CST. 4447 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo(); 4448 if (MFI.isFixedObjectIndex(FrameIdx)) { 4449 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset; 4450 4451 // The alignment of the frame index can be determined from its offset from 4452 // the incoming frame position. If the frame object is at offset 32 and 4453 // the stack is guaranteed to be 16-byte aligned, then we know that the 4454 // object is 16-byte aligned. 4455 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment(); 4456 unsigned Align = MinAlign(ObjectOffset, StackAlign); 4457 4458 // Finally, the frame object itself may have a known alignment. Factor 4459 // the alignment + offset into a new alignment. For example, if we know 4460 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a 4461 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte 4462 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc. 4463 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 4464 FrameOffset); 4465 return std::max(Align, FIInfoAlign); 4466 } 4467 } 4468 4469 return 0; 4470} 4471 4472SDValue DAGCombiner::visitLOAD(SDNode *N) { 4473 LoadSDNode *LD = cast<LoadSDNode>(N); 4474 SDValue Chain = LD->getChain(); 4475 SDValue Ptr = LD->getBasePtr(); 4476 4477 // Try to infer better alignment information than the load already has. 4478 if (!Fast && LD->isUnindexed()) { 4479 if (unsigned Align = InferAlignment(Ptr, DAG)) { 4480 if (Align > LD->getAlignment()) 4481 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0), 4482 Chain, Ptr, LD->getSrcValue(), 4483 LD->getSrcValueOffset(), LD->getMemoryVT(), 4484 LD->isVolatile(), Align); 4485 } 4486 } 4487 4488 4489 // If load is not volatile and there are no uses of the loaded value (and 4490 // the updated indexed value in case of indexed loads), change uses of the 4491 // chain value into uses of the chain input (i.e. delete the dead load). 4492 if (!LD->isVolatile()) { 4493 if (N->getValueType(1) == MVT::Other) { 4494 // Unindexed loads. 4495 if (N->hasNUsesOfValue(0, 0)) { 4496 // It's not safe to use the two value CombineTo variant here. e.g. 4497 // v1, chain2 = load chain1, loc 4498 // v2, chain3 = load chain2, loc 4499 // v3 = add v2, c 4500 // Now we replace use of chain2 with chain1. This makes the second load 4501 // isomorphic to the one we are deleting, and thus makes this load live. 4502 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG)); 4503 DOUT << "\nWith chain: "; DEBUG(Chain.getNode()->dump(&DAG)); 4504 DOUT << "\n"; 4505 WorkListRemover DeadNodes(*this); 4506 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes); 4507 if (N->use_empty()) { 4508 removeFromWorkList(N); 4509 DAG.DeleteNode(N); 4510 } 4511 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4512 } 4513 } else { 4514 // Indexed loads. 4515 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 4516 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) { 4517 SDValue Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0)); 4518 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG)); 4519 DOUT << "\nWith: "; DEBUG(Undef.getNode()->dump(&DAG)); 4520 DOUT << " and 2 other values\n"; 4521 WorkListRemover DeadNodes(*this); 4522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes); 4523 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 4524 DAG.getNode(ISD::UNDEF, N->getValueType(1)), 4525 &DeadNodes); 4526 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes); 4527 removeFromWorkList(N); 4528 DAG.DeleteNode(N); 4529 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4530 } 4531 } 4532 } 4533 4534 // If this load is directly stored, replace the load value with the stored 4535 // value. 4536 // TODO: Handle store large -> read small portion. 4537 // TODO: Handle TRUNCSTORE/LOADEXT 4538 if (LD->getExtensionType() == ISD::NON_EXTLOAD && 4539 !LD->isVolatile()) { 4540 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 4541 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 4542 if (PrevST->getBasePtr() == Ptr && 4543 PrevST->getValue().getValueType() == N->getValueType(0)) 4544 return CombineTo(N, Chain.getOperand(1), Chain); 4545 } 4546 } 4547 4548 if (CombinerAA) { 4549 // Walk up chain skipping non-aliasing memory nodes. 4550 SDValue BetterChain = FindBetterChain(N, Chain); 4551 4552 // If there is a better chain. 4553 if (Chain != BetterChain) { 4554 SDValue ReplLoad; 4555 4556 // Replace the chain to void dependency. 4557 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 4558 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr, 4559 LD->getSrcValue(), LD->getSrcValueOffset(), 4560 LD->isVolatile(), LD->getAlignment()); 4561 } else { 4562 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), 4563 LD->getValueType(0), 4564 BetterChain, Ptr, LD->getSrcValue(), 4565 LD->getSrcValueOffset(), 4566 LD->getMemoryVT(), 4567 LD->isVolatile(), 4568 LD->getAlignment()); 4569 } 4570 4571 // Create token factor to keep old chain connected. 4572 SDValue Token = DAG.getNode(ISD::TokenFactor, MVT::Other, 4573 Chain, ReplLoad.getValue(1)); 4574 4575 // Replace uses with load result and token factor. Don't add users 4576 // to work list. 4577 return CombineTo(N, ReplLoad.getValue(0), Token, false); 4578 } 4579 } 4580 4581 // Try transforming N to an indexed load. 4582 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 4583 return SDValue(N, 0); 4584 4585 return SDValue(); 4586} 4587 4588 4589SDValue DAGCombiner::visitSTORE(SDNode *N) { 4590 StoreSDNode *ST = cast<StoreSDNode>(N); 4591 SDValue Chain = ST->getChain(); 4592 SDValue Value = ST->getValue(); 4593 SDValue Ptr = ST->getBasePtr(); 4594 4595 // Try to infer better alignment information than the store already has. 4596 if (!Fast && ST->isUnindexed()) { 4597 if (unsigned Align = InferAlignment(Ptr, DAG)) { 4598 if (Align > ST->getAlignment()) 4599 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(), 4600 ST->getSrcValueOffset(), ST->getMemoryVT(), 4601 ST->isVolatile(), Align); 4602 } 4603 } 4604 4605 // If this is a store of a bit convert, store the input value if the 4606 // resultant store does not need a higher alignment than the original. 4607 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() && 4608 ST->isUnindexed()) { 4609 unsigned Align = ST->getAlignment(); 4610 MVT SVT = Value.getOperand(0).getValueType(); 4611 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()-> 4612 getABITypeAlignment(SVT.getTypeForMVT()); 4613 if (Align <= OrigAlign && 4614 ((!AfterLegalize && !ST->isVolatile()) || 4615 TLI.isOperationLegal(ISD::STORE, SVT))) 4616 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(), 4617 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign); 4618 } 4619 4620 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 4621 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 4622 // NOTE: If the original store is volatile, this transform must not increase 4623 // the number of stores. For example, on x86-32 an f64 can be stored in one 4624 // processor operation but an i64 (which is not legal) requires two. So the 4625 // transform should not be done in this case. 4626 if (Value.getOpcode() != ISD::TargetConstantFP) { 4627 SDValue Tmp; 4628 switch (CFP->getValueType(0).getSimpleVT()) { 4629 default: assert(0 && "Unknown FP type"); 4630 case MVT::f80: // We don't do this for these yet. 4631 case MVT::f128: 4632 case MVT::ppcf128: 4633 break; 4634 case MVT::f32: 4635 if ((!AfterLegalize && !ST->isVolatile()) || 4636 TLI.isOperationLegal(ISD::STORE, MVT::i32)) { 4637 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 4638 convertToAPInt().getZExtValue(), MVT::i32); 4639 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(), 4640 ST->getSrcValueOffset(), ST->isVolatile(), 4641 ST->getAlignment()); 4642 } 4643 break; 4644 case MVT::f64: 4645 if ((!AfterLegalize && !ST->isVolatile()) || 4646 TLI.isOperationLegal(ISD::STORE, MVT::i64)) { 4647 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt(). 4648 getZExtValue(), MVT::i64); 4649 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(), 4650 ST->getSrcValueOffset(), ST->isVolatile(), 4651 ST->getAlignment()); 4652 } else if (!ST->isVolatile() && 4653 TLI.isOperationLegal(ISD::STORE, MVT::i32)) { 4654 // Many FP stores are not made apparent until after legalize, e.g. for 4655 // argument passing. Since this is so common, custom legalize the 4656 // 64-bit integer store into two 32-bit stores. 4657 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue(); 4658 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 4659 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 4660 if (TLI.isBigEndian()) std::swap(Lo, Hi); 4661 4662 int SVOffset = ST->getSrcValueOffset(); 4663 unsigned Alignment = ST->getAlignment(); 4664 bool isVolatile = ST->isVolatile(); 4665 4666 SDValue St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(), 4667 ST->getSrcValueOffset(), 4668 isVolatile, ST->getAlignment()); 4669 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr, 4670 DAG.getConstant(4, Ptr.getValueType())); 4671 SVOffset += 4; 4672 Alignment = MinAlign(Alignment, 4U); 4673 SDValue St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(), 4674 SVOffset, isVolatile, Alignment); 4675 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1); 4676 } 4677 break; 4678 } 4679 } 4680 } 4681 4682 if (CombinerAA) { 4683 // Walk up chain skipping non-aliasing memory nodes. 4684 SDValue BetterChain = FindBetterChain(N, Chain); 4685 4686 // If there is a better chain. 4687 if (Chain != BetterChain) { 4688 // Replace the chain to avoid dependency. 4689 SDValue ReplStore; 4690 if (ST->isTruncatingStore()) { 4691 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr, 4692 ST->getSrcValue(),ST->getSrcValueOffset(), 4693 ST->getMemoryVT(), 4694 ST->isVolatile(), ST->getAlignment()); 4695 } else { 4696 ReplStore = DAG.getStore(BetterChain, Value, Ptr, 4697 ST->getSrcValue(), ST->getSrcValueOffset(), 4698 ST->isVolatile(), ST->getAlignment()); 4699 } 4700 4701 // Create token to keep both nodes around. 4702 SDValue Token = 4703 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore); 4704 4705 // Don't add users to work list. 4706 return CombineTo(N, Token, false); 4707 } 4708 } 4709 4710 // Try transforming N to an indexed store. 4711 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 4712 return SDValue(N, 0); 4713 4714 // FIXME: is there such a thing as a truncating indexed store? 4715 if (ST->isTruncatingStore() && ST->isUnindexed() && 4716 Value.getValueType().isInteger()) { 4717 // See if we can simplify the input to this truncstore with knowledge that 4718 // only the low bits are being used. For example: 4719 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 4720 SDValue Shorter = 4721 GetDemandedBits(Value, 4722 APInt::getLowBitsSet(Value.getValueSizeInBits(), 4723 ST->getMemoryVT().getSizeInBits())); 4724 AddToWorkList(Value.getNode()); 4725 if (Shorter.getNode()) 4726 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(), 4727 ST->getSrcValueOffset(), ST->getMemoryVT(), 4728 ST->isVolatile(), ST->getAlignment()); 4729 4730 // Otherwise, see if we can simplify the operation with 4731 // SimplifyDemandedBits, which only works if the value has a single use. 4732 if (SimplifyDemandedBits(Value, 4733 APInt::getLowBitsSet( 4734 Value.getValueSizeInBits(), 4735 ST->getMemoryVT().getSizeInBits()))) 4736 return SDValue(N, 0); 4737 } 4738 4739 // If this is a load followed by a store to the same location, then the store 4740 // is dead/noop. 4741 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 4742 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 4743 ST->isUnindexed() && !ST->isVolatile() && 4744 // There can't be any side effects between the load and store, such as 4745 // a call or store. 4746 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 4747 // The store is dead, remove it. 4748 return Chain; 4749 } 4750 } 4751 4752 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 4753 // truncating store. We can do this even if this is already a truncstore. 4754 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 4755 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 4756 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 4757 ST->getMemoryVT())) { 4758 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(), 4759 ST->getSrcValueOffset(), ST->getMemoryVT(), 4760 ST->isVolatile(), ST->getAlignment()); 4761 } 4762 4763 return SDValue(); 4764} 4765 4766SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 4767 SDValue InVec = N->getOperand(0); 4768 SDValue InVal = N->getOperand(1); 4769 SDValue EltNo = N->getOperand(2); 4770 4771 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new 4772 // vector with the inserted element. 4773 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) { 4774 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue(); 4775 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(), InVec.getNode()->op_end()); 4776 if (Elt < Ops.size()) 4777 Ops[Elt] = InVal; 4778 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(), 4779 &Ops[0], Ops.size()); 4780 } 4781 4782 return SDValue(); 4783} 4784 4785SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 4786 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 4787 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 4788 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 4789 4790 // Perform only after legalization to ensure build_vector / vector_shuffle 4791 // optimizations have already been done. 4792 if (!AfterLegalize) return SDValue(); 4793 4794 SDValue InVec = N->getOperand(0); 4795 SDValue EltNo = N->getOperand(1); 4796 4797 if (isa<ConstantSDNode>(EltNo)) { 4798 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue(); 4799 bool NewLoad = false; 4800 MVT VT = InVec.getValueType(); 4801 MVT EVT = VT.getVectorElementType(); 4802 MVT LVT = EVT; 4803 if (InVec.getOpcode() == ISD::BIT_CONVERT) { 4804 MVT BCVT = InVec.getOperand(0).getValueType(); 4805 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType())) 4806 return SDValue(); 4807 InVec = InVec.getOperand(0); 4808 EVT = BCVT.getVectorElementType(); 4809 NewLoad = true; 4810 } 4811 4812 LoadSDNode *LN0 = NULL; 4813 if (ISD::isNormalLoad(InVec.getNode())) 4814 LN0 = cast<LoadSDNode>(InVec); 4815 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 4816 InVec.getOperand(0).getValueType() == EVT && 4817 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 4818 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 4819 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 4820 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 4821 // => 4822 // (load $addr+1*size) 4823 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2). 4824 getOperand(Elt))->getValue(); 4825 unsigned NumElems = InVec.getOperand(2).getNumOperands(); 4826 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 4827 if (InVec.getOpcode() == ISD::BIT_CONVERT) 4828 InVec = InVec.getOperand(0); 4829 if (ISD::isNormalLoad(InVec.getNode())) { 4830 LN0 = cast<LoadSDNode>(InVec); 4831 Elt = (Idx < NumElems) ? Idx : Idx - NumElems; 4832 } 4833 } 4834 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile()) 4835 return SDValue(); 4836 4837 unsigned Align = LN0->getAlignment(); 4838 if (NewLoad) { 4839 // Check the resultant load doesn't need a higher alignment than the 4840 // original load. 4841 unsigned NewAlign = TLI.getTargetMachine().getTargetData()-> 4842 getABITypeAlignment(LVT.getTypeForMVT()); 4843 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT)) 4844 return SDValue(); 4845 Align = NewAlign; 4846 } 4847 4848 SDValue NewPtr = LN0->getBasePtr(); 4849 if (Elt) { 4850 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8; 4851 MVT PtrType = NewPtr.getValueType(); 4852 if (TLI.isBigEndian()) 4853 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 4854 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr, 4855 DAG.getConstant(PtrOff, PtrType)); 4856 } 4857 return DAG.getLoad(LVT, LN0->getChain(), NewPtr, 4858 LN0->getSrcValue(), LN0->getSrcValueOffset(), 4859 LN0->isVolatile(), Align); 4860 } 4861 return SDValue(); 4862} 4863 4864 4865SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 4866 unsigned NumInScalars = N->getNumOperands(); 4867 MVT VT = N->getValueType(0); 4868 unsigned NumElts = VT.getVectorNumElements(); 4869 MVT EltType = VT.getVectorElementType(); 4870 4871 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 4872 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 4873 // at most two distinct vectors, turn this into a shuffle node. 4874 SDValue VecIn1, VecIn2; 4875 for (unsigned i = 0; i != NumInScalars; ++i) { 4876 // Ignore undef inputs. 4877 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 4878 4879 // If this input is something other than a EXTRACT_VECTOR_ELT with a 4880 // constant index, bail out. 4881 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4882 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 4883 VecIn1 = VecIn2 = SDValue(0, 0); 4884 break; 4885 } 4886 4887 // If the input vector type disagrees with the result of the build_vector, 4888 // we can't make a shuffle. 4889 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 4890 if (ExtractedFromVec.getValueType() != VT) { 4891 VecIn1 = VecIn2 = SDValue(0, 0); 4892 break; 4893 } 4894 4895 // Otherwise, remember this. We allow up to two distinct input vectors. 4896 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 4897 continue; 4898 4899 if (VecIn1.getNode() == 0) { 4900 VecIn1 = ExtractedFromVec; 4901 } else if (VecIn2.getNode() == 0) { 4902 VecIn2 = ExtractedFromVec; 4903 } else { 4904 // Too many inputs. 4905 VecIn1 = VecIn2 = SDValue(0, 0); 4906 break; 4907 } 4908 } 4909 4910 // If everything is good, we can make a shuffle operation. 4911 if (VecIn1.getNode()) { 4912 SmallVector<SDValue, 8> BuildVecIndices; 4913 for (unsigned i = 0; i != NumInScalars; ++i) { 4914 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 4915 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy())); 4916 continue; 4917 } 4918 4919 SDValue Extract = N->getOperand(i); 4920 4921 // If extracting from the first vector, just use the index directly. 4922 if (Extract.getOperand(0) == VecIn1) { 4923 BuildVecIndices.push_back(Extract.getOperand(1)); 4924 continue; 4925 } 4926 4927 // Otherwise, use InIdx + VecSize 4928 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue(); 4929 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars)); 4930 } 4931 4932 // Add count and size info. 4933 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts); 4934 4935 // Return the new VECTOR_SHUFFLE node. 4936 SDValue Ops[5]; 4937 Ops[0] = VecIn1; 4938 if (VecIn2.getNode()) { 4939 Ops[1] = VecIn2; 4940 } else { 4941 // Use an undef build_vector as input for the second operand. 4942 std::vector<SDValue> UnOps(NumInScalars, 4943 DAG.getNode(ISD::UNDEF, 4944 EltType)); 4945 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT, 4946 &UnOps[0], UnOps.size()); 4947 AddToWorkList(Ops[1].getNode()); 4948 } 4949 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT, 4950 &BuildVecIndices[0], BuildVecIndices.size()); 4951 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3); 4952 } 4953 4954 return SDValue(); 4955} 4956 4957SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 4958 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 4959 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 4960 // inputs come from at most two distinct vectors, turn this into a shuffle 4961 // node. 4962 4963 // If we only have one input vector, we don't need to do any concatenation. 4964 if (N->getNumOperands() == 1) { 4965 return N->getOperand(0); 4966 } 4967 4968 return SDValue(); 4969} 4970 4971SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 4972 SDValue ShufMask = N->getOperand(2); 4973 unsigned NumElts = ShufMask.getNumOperands(); 4974 4975 // If the shuffle mask is an identity operation on the LHS, return the LHS. 4976 bool isIdentity = true; 4977 for (unsigned i = 0; i != NumElts; ++i) { 4978 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF && 4979 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) { 4980 isIdentity = false; 4981 break; 4982 } 4983 } 4984 if (isIdentity) return N->getOperand(0); 4985 4986 // If the shuffle mask is an identity operation on the RHS, return the RHS. 4987 isIdentity = true; 4988 for (unsigned i = 0; i != NumElts; ++i) { 4989 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF && 4990 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) { 4991 isIdentity = false; 4992 break; 4993 } 4994 } 4995 if (isIdentity) return N->getOperand(1); 4996 4997 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not 4998 // needed at all. 4999 bool isUnary = true; 5000 bool isSplat = true; 5001 int VecNum = -1; 5002 unsigned BaseIdx = 0; 5003 for (unsigned i = 0; i != NumElts; ++i) 5004 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) { 5005 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue(); 5006 int V = (Idx < NumElts) ? 0 : 1; 5007 if (VecNum == -1) { 5008 VecNum = V; 5009 BaseIdx = Idx; 5010 } else { 5011 if (BaseIdx != Idx) 5012 isSplat = false; 5013 if (VecNum != V) { 5014 isUnary = false; 5015 break; 5016 } 5017 } 5018 } 5019 5020 SDValue N0 = N->getOperand(0); 5021 SDValue N1 = N->getOperand(1); 5022 // Normalize unary shuffle so the RHS is undef. 5023 if (isUnary && VecNum == 1) 5024 std::swap(N0, N1); 5025 5026 // If it is a splat, check if the argument vector is a build_vector with 5027 // all scalar elements the same. 5028 if (isSplat) { 5029 SDNode *V = N0.getNode(); 5030 5031 // If this is a bit convert that changes the element type of the vector but 5032 // not the number of vector elements, look through it. Be careful not to 5033 // look though conversions that change things like v4f32 to v2f64. 5034 if (V->getOpcode() == ISD::BIT_CONVERT) { 5035 SDValue ConvInput = V->getOperand(0); 5036 if (ConvInput.getValueType().isVector() && 5037 ConvInput.getValueType().getVectorNumElements() == NumElts) 5038 V = ConvInput.getNode(); 5039 } 5040 5041 if (V->getOpcode() == ISD::BUILD_VECTOR) { 5042 unsigned NumElems = V->getNumOperands(); 5043 if (NumElems > BaseIdx) { 5044 SDValue Base; 5045 bool AllSame = true; 5046 for (unsigned i = 0; i != NumElems; ++i) { 5047 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 5048 Base = V->getOperand(i); 5049 break; 5050 } 5051 } 5052 // Splat of <u, u, u, u>, return <u, u, u, u> 5053 if (!Base.getNode()) 5054 return N0; 5055 for (unsigned i = 0; i != NumElems; ++i) { 5056 if (V->getOperand(i) != Base) { 5057 AllSame = false; 5058 break; 5059 } 5060 } 5061 // Splat of <x, x, x, x>, return <x, x, x, x> 5062 if (AllSame) 5063 return N0; 5064 } 5065 } 5066 } 5067 5068 // If it is a unary or the LHS and the RHS are the same node, turn the RHS 5069 // into an undef. 5070 if (isUnary || N0 == N1) { 5071 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the 5072 // first operand. 5073 SmallVector<SDValue, 8> MappedOps; 5074 for (unsigned i = 0; i != NumElts; ++i) { 5075 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF || 5076 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) { 5077 MappedOps.push_back(ShufMask.getOperand(i)); 5078 } else { 5079 unsigned NewIdx = 5080 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts; 5081 MappedOps.push_back(DAG.getConstant(NewIdx, 5082 ShufMask.getOperand(i).getValueType())); 5083 } 5084 } 5085 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(), 5086 &MappedOps[0], MappedOps.size()); 5087 AddToWorkList(ShufMask.getNode()); 5088 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0), 5089 N0, 5090 DAG.getNode(ISD::UNDEF, N->getValueType(0)), 5091 ShufMask); 5092 } 5093 5094 return SDValue(); 5095} 5096 5097/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 5098/// an AND to a vector_shuffle with the destination vector and a zero vector. 5099/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 5100/// vector_shuffle V, Zero, <0, 4, 2, 4> 5101SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 5102 SDValue LHS = N->getOperand(0); 5103 SDValue RHS = N->getOperand(1); 5104 if (N->getOpcode() == ISD::AND) { 5105 if (RHS.getOpcode() == ISD::BIT_CONVERT) 5106 RHS = RHS.getOperand(0); 5107 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 5108 std::vector<SDValue> IdxOps; 5109 unsigned NumOps = RHS.getNumOperands(); 5110 unsigned NumElts = NumOps; 5111 MVT EVT = RHS.getValueType().getVectorElementType(); 5112 for (unsigned i = 0; i != NumElts; ++i) { 5113 SDValue Elt = RHS.getOperand(i); 5114 if (!isa<ConstantSDNode>(Elt)) 5115 return SDValue(); 5116 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 5117 IdxOps.push_back(DAG.getConstant(i, EVT)); 5118 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 5119 IdxOps.push_back(DAG.getConstant(NumElts, EVT)); 5120 else 5121 return SDValue(); 5122 } 5123 5124 // Let's see if the target supports this vector_shuffle. 5125 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG)) 5126 return SDValue(); 5127 5128 // Return the new VECTOR_SHUFFLE node. 5129 MVT VT = MVT::getVectorVT(EVT, NumElts); 5130 std::vector<SDValue> Ops; 5131 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS); 5132 Ops.push_back(LHS); 5133 AddToWorkList(LHS.getNode()); 5134 std::vector<SDValue> ZeroOps(NumElts, DAG.getConstant(0, EVT)); 5135 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT, 5136 &ZeroOps[0], ZeroOps.size())); 5137 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT, 5138 &IdxOps[0], IdxOps.size())); 5139 SDValue Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, 5140 &Ops[0], Ops.size()); 5141 if (VT != N->getValueType(0)) 5142 Result = DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Result); 5143 return Result; 5144 } 5145 } 5146 return SDValue(); 5147} 5148 5149/// SimplifyVBinOp - Visit a binary vector operation, like ADD. 5150SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 5151 // After legalize, the target may be depending on adds and other 5152 // binary ops to provide legal ways to construct constants or other 5153 // things. Simplifying them may result in a loss of legality. 5154 if (AfterLegalize) return SDValue(); 5155 5156 MVT VT = N->getValueType(0); 5157 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!"); 5158 5159 MVT EltType = VT.getVectorElementType(); 5160 SDValue LHS = N->getOperand(0); 5161 SDValue RHS = N->getOperand(1); 5162 SDValue Shuffle = XformToShuffleWithZero(N); 5163 if (Shuffle.getNode()) return Shuffle; 5164 5165 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 5166 // this operation. 5167 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 5168 RHS.getOpcode() == ISD::BUILD_VECTOR) { 5169 SmallVector<SDValue, 8> Ops; 5170 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 5171 SDValue LHSOp = LHS.getOperand(i); 5172 SDValue RHSOp = RHS.getOperand(i); 5173 // If these two elements can't be folded, bail out. 5174 if ((LHSOp.getOpcode() != ISD::UNDEF && 5175 LHSOp.getOpcode() != ISD::Constant && 5176 LHSOp.getOpcode() != ISD::ConstantFP) || 5177 (RHSOp.getOpcode() != ISD::UNDEF && 5178 RHSOp.getOpcode() != ISD::Constant && 5179 RHSOp.getOpcode() != ISD::ConstantFP)) 5180 break; 5181 // Can't fold divide by zero. 5182 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 5183 N->getOpcode() == ISD::FDIV) { 5184 if ((RHSOp.getOpcode() == ISD::Constant && 5185 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 5186 (RHSOp.getOpcode() == ISD::ConstantFP && 5187 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 5188 break; 5189 } 5190 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp)); 5191 AddToWorkList(Ops.back().getNode()); 5192 assert((Ops.back().getOpcode() == ISD::UNDEF || 5193 Ops.back().getOpcode() == ISD::Constant || 5194 Ops.back().getOpcode() == ISD::ConstantFP) && 5195 "Scalar binop didn't fold!"); 5196 } 5197 5198 if (Ops.size() == LHS.getNumOperands()) { 5199 MVT VT = LHS.getValueType(); 5200 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()); 5201 } 5202 } 5203 5204 return SDValue(); 5205} 5206 5207SDValue DAGCombiner::SimplifySelect(SDValue N0, SDValue N1, SDValue N2){ 5208 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 5209 5210 SDValue SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2, 5211 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5212 // If we got a simplified select_cc node back from SimplifySelectCC, then 5213 // break it down into a new SETCC node, and a new SELECT node, and then return 5214 // the SELECT node, since we were called with a SELECT node. 5215 if (SCC.getNode()) { 5216 // Check to see if we got a select_cc back (to turn into setcc/select). 5217 // Otherwise, just return whatever node we got back, like fabs. 5218 if (SCC.getOpcode() == ISD::SELECT_CC) { 5219 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(), 5220 SCC.getOperand(0), SCC.getOperand(1), 5221 SCC.getOperand(4)); 5222 AddToWorkList(SETCC.getNode()); 5223 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2), 5224 SCC.getOperand(3), SETCC); 5225 } 5226 return SCC; 5227 } 5228 return SDValue(); 5229} 5230 5231/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 5232/// are the two values being selected between, see if we can simplify the 5233/// select. Callers of this should assume that TheSelect is deleted if this 5234/// returns true. As such, they should return the appropriate thing (e.g. the 5235/// node) back to the top-level of the DAG combiner loop to avoid it being 5236/// looked at. 5237/// 5238bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 5239 SDValue RHS) { 5240 5241 // If this is a select from two identical things, try to pull the operation 5242 // through the select. 5243 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){ 5244 // If this is a load and the token chain is identical, replace the select 5245 // of two loads with a load through a select of the address to load from. 5246 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 5247 // constants have been dropped into the constant pool. 5248 if (LHS.getOpcode() == ISD::LOAD && 5249 // Do not let this transformation reduce the number of volatile loads. 5250 !cast<LoadSDNode>(LHS)->isVolatile() && 5251 !cast<LoadSDNode>(RHS)->isVolatile() && 5252 // Token chains must be identical. 5253 LHS.getOperand(0) == RHS.getOperand(0)) { 5254 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 5255 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 5256 5257 // If this is an EXTLOAD, the VT's must match. 5258 if (LLD->getMemoryVT() == RLD->getMemoryVT()) { 5259 // FIXME: this conflates two src values, discarding one. This is not 5260 // the right thing to do, but nothing uses srcvalues now. When they do, 5261 // turn SrcValue into a list of locations. 5262 SDValue Addr; 5263 if (TheSelect->getOpcode() == ISD::SELECT) { 5264 // Check that the condition doesn't reach either load. If so, folding 5265 // this will induce a cycle into the DAG. 5266 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) && 5267 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) { 5268 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(), 5269 TheSelect->getOperand(0), LLD->getBasePtr(), 5270 RLD->getBasePtr()); 5271 } 5272 } else { 5273 // Check that the condition doesn't reach either load. If so, folding 5274 // this will induce a cycle into the DAG. 5275 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) && 5276 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) && 5277 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()) && 5278 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())) { 5279 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(), 5280 TheSelect->getOperand(0), 5281 TheSelect->getOperand(1), 5282 LLD->getBasePtr(), RLD->getBasePtr(), 5283 TheSelect->getOperand(4)); 5284 } 5285 } 5286 5287 if (Addr.getNode()) { 5288 SDValue Load; 5289 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) 5290 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(), 5291 Addr,LLD->getSrcValue(), 5292 LLD->getSrcValueOffset(), 5293 LLD->isVolatile(), 5294 LLD->getAlignment()); 5295 else { 5296 Load = DAG.getExtLoad(LLD->getExtensionType(), 5297 TheSelect->getValueType(0), 5298 LLD->getChain(), Addr, LLD->getSrcValue(), 5299 LLD->getSrcValueOffset(), 5300 LLD->getMemoryVT(), 5301 LLD->isVolatile(), 5302 LLD->getAlignment()); 5303 } 5304 // Users of the select now use the result of the load. 5305 CombineTo(TheSelect, Load); 5306 5307 // Users of the old loads now use the new load's chain. We know the 5308 // old-load value is dead now. 5309 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 5310 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 5311 return true; 5312 } 5313 } 5314 } 5315 } 5316 5317 return false; 5318} 5319 5320SDValue DAGCombiner::SimplifySelectCC(SDValue N0, SDValue N1, 5321 SDValue N2, SDValue N3, 5322 ISD::CondCode CC, bool NotExtCompare) { 5323 5324 MVT VT = N2.getValueType(); 5325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 5326 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 5327 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 5328 5329 // Determine if the condition we're dealing with is constant 5330 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false); 5331 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 5332 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 5333 5334 // fold select_cc true, x, y -> x 5335 if (SCCC && !SCCC->isNullValue()) 5336 return N2; 5337 // fold select_cc false, x, y -> y 5338 if (SCCC && SCCC->isNullValue()) 5339 return N3; 5340 5341 // Check to see if we can simplify the select into an fabs node 5342 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 5343 // Allow either -0.0 or 0.0 5344 if (CFP->getValueAPF().isZero()) { 5345 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 5346 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 5347 N0 == N2 && N3.getOpcode() == ISD::FNEG && 5348 N2 == N3.getOperand(0)) 5349 return DAG.getNode(ISD::FABS, VT, N0); 5350 5351 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 5352 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 5353 N0 == N3 && N2.getOpcode() == ISD::FNEG && 5354 N2.getOperand(0) == N3) 5355 return DAG.getNode(ISD::FABS, VT, N3); 5356 } 5357 } 5358 5359 // Check to see if we can perform the "gzip trick", transforming 5360 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 5361 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 5362 N0.getValueType().isInteger() && 5363 N2.getValueType().isInteger() && 5364 (N1C->isNullValue() || // (a < 0) ? b : 0 5365 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 5366 MVT XType = N0.getValueType(); 5367 MVT AType = N2.getValueType(); 5368 if (XType.bitsGE(AType)) { 5369 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 5370 // single-bit constant. 5371 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 5372 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 5373 ShCtV = XType.getSizeInBits()-ShCtV-1; 5374 SDValue ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy()); 5375 SDValue Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt); 5376 AddToWorkList(Shift.getNode()); 5377 if (XType.bitsGT(AType)) { 5378 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift); 5379 AddToWorkList(Shift.getNode()); 5380 } 5381 return DAG.getNode(ISD::AND, AType, Shift, N2); 5382 } 5383 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0, 5384 DAG.getConstant(XType.getSizeInBits()-1, 5385 TLI.getShiftAmountTy())); 5386 AddToWorkList(Shift.getNode()); 5387 if (XType.bitsGT(AType)) { 5388 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift); 5389 AddToWorkList(Shift.getNode()); 5390 } 5391 return DAG.getNode(ISD::AND, AType, Shift, N2); 5392 } 5393 } 5394 5395 // fold select C, 16, 0 -> shl C, 4 5396 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 5397 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) { 5398 5399 // If the caller doesn't want us to simplify this into a zext of a compare, 5400 // don't do it. 5401 if (NotExtCompare && N2C->getAPIntValue() == 1) 5402 return SDValue(); 5403 5404 // Get a SetCC of the condition 5405 // FIXME: Should probably make sure that setcc is legal if we ever have a 5406 // target where it isn't. 5407 SDValue Temp, SCC; 5408 // cast from setcc result type to select result type 5409 if (AfterLegalize) { 5410 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC); 5411 if (N2.getValueType().bitsLT(SCC.getValueType())) 5412 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType()); 5413 else 5414 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC); 5415 } else { 5416 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC); 5417 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC); 5418 } 5419 AddToWorkList(SCC.getNode()); 5420 AddToWorkList(Temp.getNode()); 5421 5422 if (N2C->getAPIntValue() == 1) 5423 return Temp; 5424 // shl setcc result by log2 n2c 5425 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp, 5426 DAG.getConstant(N2C->getAPIntValue().logBase2(), 5427 TLI.getShiftAmountTy())); 5428 } 5429 5430 // Check to see if this is the equivalent of setcc 5431 // FIXME: Turn all of these into setcc if setcc if setcc is legal 5432 // otherwise, go ahead with the folds. 5433 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 5434 MVT XType = N0.getValueType(); 5435 if (!AfterLegalize || 5436 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) { 5437 SDValue Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC); 5438 if (Res.getValueType() != VT) 5439 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res); 5440 return Res; 5441 } 5442 5443 // seteq X, 0 -> srl (ctlz X, log2(size(X))) 5444 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 5445 (!AfterLegalize || 5446 TLI.isOperationLegal(ISD::CTLZ, XType))) { 5447 SDValue Ctlz = DAG.getNode(ISD::CTLZ, XType, N0); 5448 return DAG.getNode(ISD::SRL, XType, Ctlz, 5449 DAG.getConstant(Log2_32(XType.getSizeInBits()), 5450 TLI.getShiftAmountTy())); 5451 } 5452 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1) 5453 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 5454 SDValue NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType), 5455 N0); 5456 SDValue NotN0 = DAG.getNode(ISD::XOR, XType, N0, 5457 DAG.getConstant(~0ULL, XType)); 5458 return DAG.getNode(ISD::SRL, XType, 5459 DAG.getNode(ISD::AND, XType, NegN0, NotN0), 5460 DAG.getConstant(XType.getSizeInBits()-1, 5461 TLI.getShiftAmountTy())); 5462 } 5463 // setgt X, -1 -> xor (srl (X, size(X)-1), 1) 5464 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 5465 SDValue Sign = DAG.getNode(ISD::SRL, XType, N0, 5466 DAG.getConstant(XType.getSizeInBits()-1, 5467 TLI.getShiftAmountTy())); 5468 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType)); 5469 } 5470 } 5471 5472 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X -> 5473 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5474 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) && 5475 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) && 5476 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) { 5477 MVT XType = N0.getValueType(); 5478 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0, 5479 DAG.getConstant(XType.getSizeInBits()-1, 5480 TLI.getShiftAmountTy())); 5481 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift); 5482 AddToWorkList(Shift.getNode()); 5483 AddToWorkList(Add.getNode()); 5484 return DAG.getNode(ISD::XOR, XType, Add, Shift); 5485 } 5486 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X -> 5487 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5488 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT && 5489 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) { 5490 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) { 5491 MVT XType = N0.getValueType(); 5492 if (SubC->isNullValue() && XType.isInteger()) { 5493 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0, 5494 DAG.getConstant(XType.getSizeInBits()-1, 5495 TLI.getShiftAmountTy())); 5496 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift); 5497 AddToWorkList(Shift.getNode()); 5498 AddToWorkList(Add.getNode()); 5499 return DAG.getNode(ISD::XOR, XType, Add, Shift); 5500 } 5501 } 5502 } 5503 5504 return SDValue(); 5505} 5506 5507/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 5508SDValue DAGCombiner::SimplifySetCC(MVT VT, SDValue N0, 5509 SDValue N1, ISD::CondCode Cond, 5510 bool foldBooleans) { 5511 TargetLowering::DAGCombinerInfo 5512 DagCombineInfo(DAG, !AfterLegalize, false, this); 5513 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo); 5514} 5515 5516/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 5517/// return a DAG expression to select that will generate the same value by 5518/// multiplying by a magic number. See: 5519/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 5520SDValue DAGCombiner::BuildSDIV(SDNode *N) { 5521 std::vector<SDNode*> Built; 5522 SDValue S = TLI.BuildSDIV(N, DAG, &Built); 5523 5524 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 5525 ii != ee; ++ii) 5526 AddToWorkList(*ii); 5527 return S; 5528} 5529 5530/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 5531/// return a DAG expression to select that will generate the same value by 5532/// multiplying by a magic number. See: 5533/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 5534SDValue DAGCombiner::BuildUDIV(SDNode *N) { 5535 std::vector<SDNode*> Built; 5536 SDValue S = TLI.BuildUDIV(N, DAG, &Built); 5537 5538 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 5539 ii != ee; ++ii) 5540 AddToWorkList(*ii); 5541 return S; 5542} 5543 5544/// FindBaseOffset - Return true if base is known not to alias with anything 5545/// but itself. Provides base object and offset as results. 5546static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset) { 5547 // Assume it is a primitive operation. 5548 Base = Ptr; Offset = 0; 5549 5550 // If it's an adding a simple constant then integrate the offset. 5551 if (Base.getOpcode() == ISD::ADD) { 5552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 5553 Base = Base.getOperand(0); 5554 Offset += C->getValue(); 5555 } 5556 } 5557 5558 // If it's any of the following then it can't alias with anything but itself. 5559 return isa<FrameIndexSDNode>(Base) || 5560 isa<ConstantPoolSDNode>(Base) || 5561 isa<GlobalAddressSDNode>(Base); 5562} 5563 5564/// isAlias - Return true if there is any possibility that the two addresses 5565/// overlap. 5566bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, 5567 const Value *SrcValue1, int SrcValueOffset1, 5568 SDValue Ptr2, int64_t Size2, 5569 const Value *SrcValue2, int SrcValueOffset2) 5570{ 5571 // If they are the same then they must be aliases. 5572 if (Ptr1 == Ptr2) return true; 5573 5574 // Gather base node and offset information. 5575 SDValue Base1, Base2; 5576 int64_t Offset1, Offset2; 5577 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1); 5578 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2); 5579 5580 // If they have a same base address then... 5581 if (Base1 == Base2) { 5582 // Check to see if the addresses overlap. 5583 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 5584 } 5585 5586 // If we know both bases then they can't alias. 5587 if (KnownBase1 && KnownBase2) return false; 5588 5589 if (CombinerGlobalAA) { 5590 // Use alias analysis information. 5591 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 5592 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 5593 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 5594 AliasAnalysis::AliasResult AAResult = 5595 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2); 5596 if (AAResult == AliasAnalysis::NoAlias) 5597 return false; 5598 } 5599 5600 // Otherwise we have to assume they alias. 5601 return true; 5602} 5603 5604/// FindAliasInfo - Extracts the relevant alias information from the memory 5605/// node. Returns true if the operand was a load. 5606bool DAGCombiner::FindAliasInfo(SDNode *N, 5607 SDValue &Ptr, int64_t &Size, 5608 const Value *&SrcValue, int &SrcValueOffset) { 5609 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 5610 Ptr = LD->getBasePtr(); 5611 Size = LD->getMemoryVT().getSizeInBits() >> 3; 5612 SrcValue = LD->getSrcValue(); 5613 SrcValueOffset = LD->getSrcValueOffset(); 5614 return true; 5615 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 5616 Ptr = ST->getBasePtr(); 5617 Size = ST->getMemoryVT().getSizeInBits() >> 3; 5618 SrcValue = ST->getSrcValue(); 5619 SrcValueOffset = ST->getSrcValueOffset(); 5620 } else { 5621 assert(0 && "FindAliasInfo expected a memory operand"); 5622 } 5623 5624 return false; 5625} 5626 5627/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 5628/// looking for aliasing nodes and adding them to the Aliases vector. 5629void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 5630 SmallVector<SDValue, 8> &Aliases) { 5631 SmallVector<SDValue, 8> Chains; // List of chains to visit. 5632 std::set<SDNode *> Visited; // Visited node set. 5633 5634 // Get alias information for node. 5635 SDValue Ptr; 5636 int64_t Size; 5637 const Value *SrcValue; 5638 int SrcValueOffset; 5639 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset); 5640 5641 // Starting off. 5642 Chains.push_back(OriginalChain); 5643 5644 // Look at each chain and determine if it is an alias. If so, add it to the 5645 // aliases list. If not, then continue up the chain looking for the next 5646 // candidate. 5647 while (!Chains.empty()) { 5648 SDValue Chain = Chains.back(); 5649 Chains.pop_back(); 5650 5651 // Don't bother if we've been before. 5652 if (Visited.find(Chain.getNode()) != Visited.end()) continue; 5653 Visited.insert(Chain.getNode()); 5654 5655 switch (Chain.getOpcode()) { 5656 case ISD::EntryToken: 5657 // Entry token is ideal chain operand, but handled in FindBetterChain. 5658 break; 5659 5660 case ISD::LOAD: 5661 case ISD::STORE: { 5662 // Get alias information for Chain. 5663 SDValue OpPtr; 5664 int64_t OpSize; 5665 const Value *OpSrcValue; 5666 int OpSrcValueOffset; 5667 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 5668 OpSrcValue, OpSrcValueOffset); 5669 5670 // If chain is alias then stop here. 5671 if (!(IsLoad && IsOpLoad) && 5672 isAlias(Ptr, Size, SrcValue, SrcValueOffset, 5673 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) { 5674 Aliases.push_back(Chain); 5675 } else { 5676 // Look further up the chain. 5677 Chains.push_back(Chain.getOperand(0)); 5678 // Clean up old chain. 5679 AddToWorkList(Chain.getNode()); 5680 } 5681 break; 5682 } 5683 5684 case ISD::TokenFactor: 5685 // We have to check each of the operands of the token factor, so we queue 5686 // then up. Adding the operands to the queue (stack) in reverse order 5687 // maintains the original order and increases the likelihood that getNode 5688 // will find a matching token factor (CSE.) 5689 for (unsigned n = Chain.getNumOperands(); n;) 5690 Chains.push_back(Chain.getOperand(--n)); 5691 // Eliminate the token factor if we can. 5692 AddToWorkList(Chain.getNode()); 5693 break; 5694 5695 default: 5696 // For all other instructions we will just have to take what we can get. 5697 Aliases.push_back(Chain); 5698 break; 5699 } 5700 } 5701} 5702 5703/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 5704/// for a better chain (aliasing node.) 5705SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 5706 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 5707 5708 // Accumulate all the aliases to this node. 5709 GatherAllAliases(N, OldChain, Aliases); 5710 5711 if (Aliases.size() == 0) { 5712 // If no operands then chain to entry token. 5713 return DAG.getEntryNode(); 5714 } else if (Aliases.size() == 1) { 5715 // If a single operand then chain to it. We don't need to revisit it. 5716 return Aliases[0]; 5717 } 5718 5719 // Construct a custom tailored token factor. 5720 SDValue NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, 5721 &Aliases[0], Aliases.size()); 5722 5723 // Make sure the old chain gets cleaned up. 5724 if (NewChain != OldChain) AddToWorkList(OldChain.getNode()); 5725 5726 return NewChain; 5727} 5728 5729// SelectionDAG::Combine - This is the entry point for the file. 5730// 5731void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA, 5732 bool Fast) { 5733 /// run - This is the main entry point to this class. 5734 /// 5735 DAGCombiner(*this, AA, Fast).Run(RunningAfterLegalize); 5736} 5737