1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #define DEBUG_TYPE "dagcombine" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/DerivedTypes.h" 22 #include "llvm/LLVMContext.h" 23 #include "llvm/CodeGen/MachineFunction.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Target/TargetLowering.h" 28 #include "llvm/Target/TargetMachine.h" 29 #include "llvm/Target/TargetOptions.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> 38 using namespace llvm; 39 40 STATISTIC(NodesCombined , "Number of dag nodes combined"); 41 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 42 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 43 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 44 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 45 46 namespace { 47 static cl::opt<bool> 48 CombinerAA("combiner-alias-analysis", cl::Hidden, 49 cl::desc("Turn on alias analysis during testing")); 50 51 static cl::opt<bool> 52 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 53 cl::desc("Include global information in alias analysis")); 54 55 //------------------------------ DAGCombiner ---------------------------------// 56 57 class DAGCombiner { 58 SelectionDAG &DAG; 59 const TargetLowering &TLI; 60 CombineLevel Level; 61 CodeGenOpt::Level OptLevel; 62 bool LegalOperations; 63 bool LegalTypes; 64 65 // Worklist of all of the nodes that need to be simplified. 66 // 67 // This has the semantics that when adding to the worklist, 68 // the item added must be next to be processed. It should 69 // also only appear once. The naive approach to this takes 70 // linear time. 71 // 72 // To reduce the insert/remove time to logarithmic, we use 73 // a set and a vector to maintain our worklist. 74 // 75 // The set contains the items on the worklist, but does not 76 // maintain the order they should be visited. 77 // 78 // The vector maintains the order nodes should be visited, but may 79 // contain duplicate or removed nodes. When choosing a node to 80 // visit, we pop off the order stack until we find an item that is 81 // also in the contents set. All operations are O(log N). 82 SmallPtrSet<SDNode*, 64> WorkListContents; 83 SmallVector<SDNode*, 64> WorkListOrder; 84 85 // AA - Used for DAG load/store alias analysis. 86 AliasAnalysis &AA; 87 88 /// AddUsersToWorkList - When an instruction is simplified, add all users of 89 /// the instruction to the work lists because they might get more simplified 90 /// now. 91 /// 92 void AddUsersToWorkList(SDNode *N) { 93 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 94 UI != UE; ++UI) 95 AddToWorkList(*UI); 96 } 97 98 /// visit - call the node-specific routine that knows how to fold each 99 /// particular type of node. 100 SDValue visit(SDNode *N); 101 102 public: 103 /// AddToWorkList - Add to the work list making sure its instance is at the 104 /// back (next to be processed.) 105 void AddToWorkList(SDNode *N) { 106 WorkListContents.insert(N); 107 WorkListOrder.push_back(N); 108 } 109 110 /// removeFromWorkList - remove all instances of N from the worklist. 111 /// 112 void removeFromWorkList(SDNode *N) { 113 WorkListContents.erase(N); 114 } 115 116 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 117 bool AddTo = true); 118 119 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 120 return CombineTo(N, &Res, 1, AddTo); 121 } 122 123 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 124 bool AddTo = true) { 125 SDValue To[] = { Res0, Res1 }; 126 return CombineTo(N, To, 2, AddTo); 127 } 128 129 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 130 131 private: 132 133 /// SimplifyDemandedBits - Check the specified integer node value to see if 134 /// it can be simplified or if things it uses can be simplified by bit 135 /// propagation. If so, return true. 136 bool SimplifyDemandedBits(SDValue Op) { 137 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 138 APInt Demanded = APInt::getAllOnesValue(BitWidth); 139 return SimplifyDemandedBits(Op, Demanded); 140 } 141 142 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 143 144 bool CombineToPreIndexedLoadStore(SDNode *N); 145 bool CombineToPostIndexedLoadStore(SDNode *N); 146 147 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 148 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 149 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 150 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 151 SDValue PromoteIntBinOp(SDValue Op); 152 SDValue PromoteIntShiftOp(SDValue Op); 153 SDValue PromoteExtend(SDValue Op); 154 bool PromoteLoad(SDValue Op); 155 156 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs, 157 SDValue Trunc, SDValue ExtLoad, DebugLoc DL, 158 ISD::NodeType ExtType); 159 160 /// combine - call the node-specific routine that knows how to fold each 161 /// particular type of node. If that doesn't do anything, try the 162 /// target-specific DAG combines. 163 SDValue combine(SDNode *N); 164 165 // Visitation implementation - Implement dag node combining for different 166 // node types. The semantics are as follows: 167 // Return Value: 168 // SDValue.getNode() == 0 - No change was made 169 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 170 // otherwise - N should be replaced by the returned Operand. 171 // 172 SDValue visitTokenFactor(SDNode *N); 173 SDValue visitMERGE_VALUES(SDNode *N); 174 SDValue visitADD(SDNode *N); 175 SDValue visitSUB(SDNode *N); 176 SDValue visitADDC(SDNode *N); 177 SDValue visitSUBC(SDNode *N); 178 SDValue visitADDE(SDNode *N); 179 SDValue visitSUBE(SDNode *N); 180 SDValue visitMUL(SDNode *N); 181 SDValue visitSDIV(SDNode *N); 182 SDValue visitUDIV(SDNode *N); 183 SDValue visitSREM(SDNode *N); 184 SDValue visitUREM(SDNode *N); 185 SDValue visitMULHU(SDNode *N); 186 SDValue visitMULHS(SDNode *N); 187 SDValue visitSMUL_LOHI(SDNode *N); 188 SDValue visitUMUL_LOHI(SDNode *N); 189 SDValue visitSMULO(SDNode *N); 190 SDValue visitUMULO(SDNode *N); 191 SDValue visitSDIVREM(SDNode *N); 192 SDValue visitUDIVREM(SDNode *N); 193 SDValue visitAND(SDNode *N); 194 SDValue visitOR(SDNode *N); 195 SDValue visitXOR(SDNode *N); 196 SDValue SimplifyVBinOp(SDNode *N); 197 SDValue visitSHL(SDNode *N); 198 SDValue visitSRA(SDNode *N); 199 SDValue visitSRL(SDNode *N); 200 SDValue visitCTLZ(SDNode *N); 201 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 202 SDValue visitCTTZ(SDNode *N); 203 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 204 SDValue visitCTPOP(SDNode *N); 205 SDValue visitSELECT(SDNode *N); 206 SDValue visitSELECT_CC(SDNode *N); 207 SDValue visitSETCC(SDNode *N); 208 SDValue visitSIGN_EXTEND(SDNode *N); 209 SDValue visitZERO_EXTEND(SDNode *N); 210 SDValue visitANY_EXTEND(SDNode *N); 211 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 212 SDValue visitTRUNCATE(SDNode *N); 213 SDValue visitBITCAST(SDNode *N); 214 SDValue visitBUILD_PAIR(SDNode *N); 215 SDValue visitFADD(SDNode *N); 216 SDValue visitFSUB(SDNode *N); 217 SDValue visitFMUL(SDNode *N); 218 SDValue visitFMA(SDNode *N); 219 SDValue visitFDIV(SDNode *N); 220 SDValue visitFREM(SDNode *N); 221 SDValue visitFCOPYSIGN(SDNode *N); 222 SDValue visitSINT_TO_FP(SDNode *N); 223 SDValue visitUINT_TO_FP(SDNode *N); 224 SDValue visitFP_TO_SINT(SDNode *N); 225 SDValue visitFP_TO_UINT(SDNode *N); 226 SDValue visitFP_ROUND(SDNode *N); 227 SDValue visitFP_ROUND_INREG(SDNode *N); 228 SDValue visitFP_EXTEND(SDNode *N); 229 SDValue visitFNEG(SDNode *N); 230 SDValue visitFABS(SDNode *N); 231 SDValue visitFCEIL(SDNode *N); 232 SDValue visitFTRUNC(SDNode *N); 233 SDValue visitFFLOOR(SDNode *N); 234 SDValue visitBRCOND(SDNode *N); 235 SDValue visitBR_CC(SDNode *N); 236 SDValue visitLOAD(SDNode *N); 237 SDValue visitSTORE(SDNode *N); 238 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 239 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 240 SDValue visitBUILD_VECTOR(SDNode *N); 241 SDValue visitCONCAT_VECTORS(SDNode *N); 242 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 243 SDValue visitVECTOR_SHUFFLE(SDNode *N); 244 SDValue visitMEMBARRIER(SDNode *N); 245 246 SDValue XformToShuffleWithZero(SDNode *N); 247 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS); 248 249 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 250 251 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 252 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 253 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2); 254 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2, 255 SDValue N3, ISD::CondCode CC, 256 bool NotExtCompare = false); 257 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 258 DebugLoc DL, bool foldBooleans = true); 259 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 260 unsigned HiOp); 261 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 262 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 263 SDValue BuildSDIV(SDNode *N); 264 SDValue BuildUDIV(SDNode *N); 265 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 266 bool DemandHighBits = true); 267 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 268 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL); 269 SDValue ReduceLoadWidth(SDNode *N); 270 SDValue ReduceLoadOpStoreWidth(SDNode *N); 271 SDValue TransformFPLoadStorePair(SDNode *N); 272 273 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 274 275 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 276 /// looking for aliasing nodes and adding them to the Aliases vector. 277 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 278 SmallVector<SDValue, 8> &Aliases); 279 280 /// isAlias - Return true if there is any possibility that the two addresses 281 /// overlap. 282 bool isAlias(SDValue Ptr1, int64_t Size1, 283 const Value *SrcValue1, int SrcValueOffset1, 284 unsigned SrcValueAlign1, 285 const MDNode *TBAAInfo1, 286 SDValue Ptr2, int64_t Size2, 287 const Value *SrcValue2, int SrcValueOffset2, 288 unsigned SrcValueAlign2, 289 const MDNode *TBAAInfo2) const; 290 291 /// FindAliasInfo - Extracts the relevant alias information from the memory 292 /// node. Returns true if the operand was a load. 293 bool FindAliasInfo(SDNode *N, 294 SDValue &Ptr, int64_t &Size, 295 const Value *&SrcValue, int &SrcValueOffset, 296 unsigned &SrcValueAlignment, 297 const MDNode *&TBAAInfo) const; 298 299 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 300 /// looking for a better chain (aliasing node.) 301 SDValue FindBetterChain(SDNode *N, SDValue Chain); 302 303 public: 304 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 305 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 306 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {} 307 308 /// Run - runs the dag combiner on all nodes in the work list 309 void Run(CombineLevel AtLevel); 310 311 SelectionDAG &getDAG() const { return DAG; } 312 313 /// getShiftAmountTy - Returns a type large enough to hold any valid 314 /// shift amount - before type legalization these can be huge. 315 EVT getShiftAmountTy(EVT LHSTy) { 316 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy(); 317 } 318 319 /// isTypeLegal - This method returns true if we are running before type 320 /// legalization or if the specified VT is legal. 321 bool isTypeLegal(const EVT &VT) { 322 if (!LegalTypes) return true; 323 return TLI.isTypeLegal(VT); 324 } 325 }; 326 } 327 328 329 namespace { 330 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 331 /// nodes from the worklist. 332 class WorkListRemover : public SelectionDAG::DAGUpdateListener { 333 DAGCombiner &DC; 334 public: 335 explicit WorkListRemover(DAGCombiner &dc) 336 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 337 338 virtual void NodeDeleted(SDNode *N, SDNode *E) { 339 DC.removeFromWorkList(N); 340 } 341 }; 342 } 343 344 //===----------------------------------------------------------------------===// 345 // TargetLowering::DAGCombinerInfo implementation 346 //===----------------------------------------------------------------------===// 347 348 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 349 ((DAGCombiner*)DC)->AddToWorkList(N); 350 } 351 352 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 353 ((DAGCombiner*)DC)->removeFromWorkList(N); 354 } 355 356 SDValue TargetLowering::DAGCombinerInfo:: 357 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 358 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 359 } 360 361 SDValue TargetLowering::DAGCombinerInfo:: 362 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 363 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 364 } 365 366 367 SDValue TargetLowering::DAGCombinerInfo:: 368 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 369 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 370 } 371 372 void TargetLowering::DAGCombinerInfo:: 373 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 374 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 375 } 376 377 //===----------------------------------------------------------------------===// 378 // Helper Functions 379 //===----------------------------------------------------------------------===// 380 381 /// isNegatibleForFree - Return 1 if we can compute the negated form of the 382 /// specified expression for the same cost as the expression itself, or 2 if we 383 /// can compute the negated form more cheaply than the expression itself. 384 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 385 const TargetLowering &TLI, 386 const TargetOptions *Options, 387 unsigned Depth = 0) { 388 // No compile time optimizations on this type. 389 if (Op.getValueType() == MVT::ppcf128) 390 return 0; 391 392 // fneg is removable even if it has multiple uses. 393 if (Op.getOpcode() == ISD::FNEG) return 2; 394 395 // Don't allow anything with multiple uses. 396 if (!Op.hasOneUse()) return 0; 397 398 // Don't recurse exponentially. 399 if (Depth > 6) return 0; 400 401 switch (Op.getOpcode()) { 402 default: return false; 403 case ISD::ConstantFP: 404 // Don't invert constant FP values after legalize. The negated constant 405 // isn't necessarily legal. 406 return LegalOperations ? 0 : 1; 407 case ISD::FADD: 408 // FIXME: determine better conditions for this xform. 409 if (!Options->UnsafeFPMath) return 0; 410 411 // After operation legalization, it might not be legal to create new FSUBs. 412 if (LegalOperations && 413 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 414 return 0; 415 416 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B) 417 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 418 Options, Depth + 1)) 419 return V; 420 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 421 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 422 Depth + 1); 423 case ISD::FSUB: 424 // We can't turn -(A-B) into B-A when we honor signed zeros. 425 if (!Options->UnsafeFPMath) return 0; 426 427 // fold (fneg (fsub A, B)) -> (fsub B, A) 428 return 1; 429 430 case ISD::FMUL: 431 case ISD::FDIV: 432 if (Options->HonorSignDependentRoundingFPMath()) return 0; 433 434 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 435 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 436 Options, Depth + 1)) 437 return V; 438 439 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 440 Depth + 1); 441 442 case ISD::FP_EXTEND: 443 case ISD::FP_ROUND: 444 case ISD::FSIN: 445 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 446 Depth + 1); 447 } 448 } 449 450 /// GetNegatedExpression - If isNegatibleForFree returns true, this function 451 /// returns the newly negated expression. 452 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 453 bool LegalOperations, unsigned Depth = 0) { 454 // fneg is removable even if it has multiple uses. 455 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 456 457 // Don't allow anything with multiple uses. 458 assert(Op.hasOneUse() && "Unknown reuse!"); 459 460 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 461 switch (Op.getOpcode()) { 462 default: llvm_unreachable("Unknown code"); 463 case ISD::ConstantFP: { 464 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 465 V.changeSign(); 466 return DAG.getConstantFP(V, Op.getValueType()); 467 } 468 case ISD::FADD: 469 // FIXME: determine better conditions for this xform. 470 assert(DAG.getTarget().Options.UnsafeFPMath); 471 472 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 473 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 474 DAG.getTargetLoweringInfo(), 475 &DAG.getTarget().Options, Depth+1)) 476 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 477 GetNegatedExpression(Op.getOperand(0), DAG, 478 LegalOperations, Depth+1), 479 Op.getOperand(1)); 480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 481 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 482 GetNegatedExpression(Op.getOperand(1), DAG, 483 LegalOperations, Depth+1), 484 Op.getOperand(0)); 485 case ISD::FSUB: 486 // We can't turn -(A-B) into B-A when we honor signed zeros. 487 assert(DAG.getTarget().Options.UnsafeFPMath); 488 489 // fold (fneg (fsub 0, B)) -> B 490 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 491 if (N0CFP->getValueAPF().isZero()) 492 return Op.getOperand(1); 493 494 // fold (fneg (fsub A, B)) -> (fsub B, A) 495 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 496 Op.getOperand(1), Op.getOperand(0)); 497 498 case ISD::FMUL: 499 case ISD::FDIV: 500 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 501 502 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 503 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 504 DAG.getTargetLoweringInfo(), 505 &DAG.getTarget().Options, Depth+1)) 506 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 507 GetNegatedExpression(Op.getOperand(0), DAG, 508 LegalOperations, Depth+1), 509 Op.getOperand(1)); 510 511 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 512 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 513 Op.getOperand(0), 514 GetNegatedExpression(Op.getOperand(1), DAG, 515 LegalOperations, Depth+1)); 516 517 case ISD::FP_EXTEND: 518 case ISD::FSIN: 519 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 520 GetNegatedExpression(Op.getOperand(0), DAG, 521 LegalOperations, Depth+1)); 522 case ISD::FP_ROUND: 523 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(), 524 GetNegatedExpression(Op.getOperand(0), DAG, 525 LegalOperations, Depth+1), 526 Op.getOperand(1)); 527 } 528 } 529 530 531 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 532 // that selects between the values 1 and 0, making it equivalent to a setcc. 533 // Also, set the incoming LHS, RHS, and CC references to the appropriate 534 // nodes based on the type of node we are checking. This simplifies life a 535 // bit for the callers. 536 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 537 SDValue &CC) { 538 if (N.getOpcode() == ISD::SETCC) { 539 LHS = N.getOperand(0); 540 RHS = N.getOperand(1); 541 CC = N.getOperand(2); 542 return true; 543 } 544 if (N.getOpcode() == ISD::SELECT_CC && 545 N.getOperand(2).getOpcode() == ISD::Constant && 546 N.getOperand(3).getOpcode() == ISD::Constant && 547 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 548 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 549 LHS = N.getOperand(0); 550 RHS = N.getOperand(1); 551 CC = N.getOperand(4); 552 return true; 553 } 554 return false; 555 } 556 557 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 558 // one use. If this is true, it allows the users to invert the operation for 559 // free when it is profitable to do so. 560 static bool isOneUseSetCC(SDValue N) { 561 SDValue N0, N1, N2; 562 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 563 return true; 564 return false; 565 } 566 567 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL, 568 SDValue N0, SDValue N1) { 569 EVT VT = N0.getValueType(); 570 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) { 571 if (isa<ConstantSDNode>(N1)) { 572 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 573 SDValue OpNode = 574 DAG.FoldConstantArithmetic(Opc, VT, 575 cast<ConstantSDNode>(N0.getOperand(1)), 576 cast<ConstantSDNode>(N1)); 577 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 578 } 579 if (N0.hasOneUse()) { 580 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use 581 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 582 N0.getOperand(0), N1); 583 AddToWorkList(OpNode.getNode()); 584 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 585 } 586 } 587 588 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) { 589 if (isa<ConstantSDNode>(N0)) { 590 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 591 SDValue OpNode = 592 DAG.FoldConstantArithmetic(Opc, VT, 593 cast<ConstantSDNode>(N1.getOperand(1)), 594 cast<ConstantSDNode>(N0)); 595 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 596 } 597 if (N1.hasOneUse()) { 598 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use 599 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 600 N1.getOperand(0), N0); 601 AddToWorkList(OpNode.getNode()); 602 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 603 } 604 } 605 606 return SDValue(); 607 } 608 609 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 610 bool AddTo) { 611 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 612 ++NodesCombined; 613 DEBUG(dbgs() << "\nReplacing.1 "; 614 N->dump(&DAG); 615 dbgs() << "\nWith: "; 616 To[0].getNode()->dump(&DAG); 617 dbgs() << " and " << NumTo-1 << " other values\n"; 618 for (unsigned i = 0, e = NumTo; i != e; ++i) 619 assert((!To[i].getNode() || 620 N->getValueType(i) == To[i].getValueType()) && 621 "Cannot combine value to value of different type!")); 622 WorkListRemover DeadNodes(*this); 623 DAG.ReplaceAllUsesWith(N, To); 624 if (AddTo) { 625 // Push the new nodes and any users onto the worklist 626 for (unsigned i = 0, e = NumTo; i != e; ++i) { 627 if (To[i].getNode()) { 628 AddToWorkList(To[i].getNode()); 629 AddUsersToWorkList(To[i].getNode()); 630 } 631 } 632 } 633 634 // Finally, if the node is now dead, remove it from the graph. The node 635 // may not be dead if the replacement process recursively simplified to 636 // something else needing this node. 637 if (N->use_empty()) { 638 // Nodes can be reintroduced into the worklist. Make sure we do not 639 // process a node that has been replaced. 640 removeFromWorkList(N); 641 642 // Finally, since the node is now dead, remove it from the graph. 643 DAG.DeleteNode(N); 644 } 645 return SDValue(N, 0); 646 } 647 648 void DAGCombiner:: 649 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 650 // Replace all uses. If any nodes become isomorphic to other nodes and 651 // are deleted, make sure to remove them from our worklist. 652 WorkListRemover DeadNodes(*this); 653 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 654 655 // Push the new node and any (possibly new) users onto the worklist. 656 AddToWorkList(TLO.New.getNode()); 657 AddUsersToWorkList(TLO.New.getNode()); 658 659 // Finally, if the node is now dead, remove it from the graph. The node 660 // may not be dead if the replacement process recursively simplified to 661 // something else needing this node. 662 if (TLO.Old.getNode()->use_empty()) { 663 removeFromWorkList(TLO.Old.getNode()); 664 665 // If the operands of this node are only used by the node, they will now 666 // be dead. Make sure to visit them first to delete dead nodes early. 667 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 668 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 669 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 670 671 DAG.DeleteNode(TLO.Old.getNode()); 672 } 673 } 674 675 /// SimplifyDemandedBits - Check the specified integer node value to see if 676 /// it can be simplified or if things it uses can be simplified by bit 677 /// propagation. If so, return true. 678 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 679 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 680 APInt KnownZero, KnownOne; 681 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 682 return false; 683 684 // Revisit the node. 685 AddToWorkList(Op.getNode()); 686 687 // Replace the old value with the new one. 688 ++NodesCombined; 689 DEBUG(dbgs() << "\nReplacing.2 "; 690 TLO.Old.getNode()->dump(&DAG); 691 dbgs() << "\nWith: "; 692 TLO.New.getNode()->dump(&DAG); 693 dbgs() << '\n'); 694 695 CommitTargetLoweringOpt(TLO); 696 return true; 697 } 698 699 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 700 DebugLoc dl = Load->getDebugLoc(); 701 EVT VT = Load->getValueType(0); 702 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 703 704 DEBUG(dbgs() << "\nReplacing.9 "; 705 Load->dump(&DAG); 706 dbgs() << "\nWith: "; 707 Trunc.getNode()->dump(&DAG); 708 dbgs() << '\n'); 709 WorkListRemover DeadNodes(*this); 710 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 711 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 712 removeFromWorkList(Load); 713 DAG.DeleteNode(Load); 714 AddToWorkList(Trunc.getNode()); 715 } 716 717 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 718 Replace = false; 719 DebugLoc dl = Op.getDebugLoc(); 720 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 721 EVT MemVT = LD->getMemoryVT(); 722 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 723 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 724 : ISD::EXTLOAD) 725 : LD->getExtensionType(); 726 Replace = true; 727 return DAG.getExtLoad(ExtType, dl, PVT, 728 LD->getChain(), LD->getBasePtr(), 729 LD->getPointerInfo(), 730 MemVT, LD->isVolatile(), 731 LD->isNonTemporal(), LD->getAlignment()); 732 } 733 734 unsigned Opc = Op.getOpcode(); 735 switch (Opc) { 736 default: break; 737 case ISD::AssertSext: 738 return DAG.getNode(ISD::AssertSext, dl, PVT, 739 SExtPromoteOperand(Op.getOperand(0), PVT), 740 Op.getOperand(1)); 741 case ISD::AssertZext: 742 return DAG.getNode(ISD::AssertZext, dl, PVT, 743 ZExtPromoteOperand(Op.getOperand(0), PVT), 744 Op.getOperand(1)); 745 case ISD::Constant: { 746 unsigned ExtOpc = 747 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 748 return DAG.getNode(ExtOpc, dl, PVT, Op); 749 } 750 } 751 752 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 753 return SDValue(); 754 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 755 } 756 757 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 758 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 759 return SDValue(); 760 EVT OldVT = Op.getValueType(); 761 DebugLoc dl = Op.getDebugLoc(); 762 bool Replace = false; 763 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 764 if (NewOp.getNode() == 0) 765 return SDValue(); 766 AddToWorkList(NewOp.getNode()); 767 768 if (Replace) 769 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 770 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 771 DAG.getValueType(OldVT)); 772 } 773 774 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 775 EVT OldVT = Op.getValueType(); 776 DebugLoc dl = Op.getDebugLoc(); 777 bool Replace = false; 778 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 779 if (NewOp.getNode() == 0) 780 return SDValue(); 781 AddToWorkList(NewOp.getNode()); 782 783 if (Replace) 784 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 785 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 786 } 787 788 /// PromoteIntBinOp - Promote the specified integer binary operation if the 789 /// target indicates it is beneficial. e.g. On x86, it's usually better to 790 /// promote i16 operations to i32 since i16 instructions are longer. 791 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 792 if (!LegalOperations) 793 return SDValue(); 794 795 EVT VT = Op.getValueType(); 796 if (VT.isVector() || !VT.isInteger()) 797 return SDValue(); 798 799 // If operation type is 'undesirable', e.g. i16 on x86, consider 800 // promoting it. 801 unsigned Opc = Op.getOpcode(); 802 if (TLI.isTypeDesirableForOp(Opc, VT)) 803 return SDValue(); 804 805 EVT PVT = VT; 806 // Consult target whether it is a good idea to promote this operation and 807 // what's the right type to promote it to. 808 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 809 assert(PVT != VT && "Don't know what type to promote to!"); 810 811 bool Replace0 = false; 812 SDValue N0 = Op.getOperand(0); 813 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 814 if (NN0.getNode() == 0) 815 return SDValue(); 816 817 bool Replace1 = false; 818 SDValue N1 = Op.getOperand(1); 819 SDValue NN1; 820 if (N0 == N1) 821 NN1 = NN0; 822 else { 823 NN1 = PromoteOperand(N1, PVT, Replace1); 824 if (NN1.getNode() == 0) 825 return SDValue(); 826 } 827 828 AddToWorkList(NN0.getNode()); 829 if (NN1.getNode()) 830 AddToWorkList(NN1.getNode()); 831 832 if (Replace0) 833 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 834 if (Replace1) 835 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 836 837 DEBUG(dbgs() << "\nPromoting "; 838 Op.getNode()->dump(&DAG)); 839 DebugLoc dl = Op.getDebugLoc(); 840 return DAG.getNode(ISD::TRUNCATE, dl, VT, 841 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 842 } 843 return SDValue(); 844 } 845 846 /// PromoteIntShiftOp - Promote the specified integer shift operation if the 847 /// target indicates it is beneficial. e.g. On x86, it's usually better to 848 /// promote i16 operations to i32 since i16 instructions are longer. 849 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 850 if (!LegalOperations) 851 return SDValue(); 852 853 EVT VT = Op.getValueType(); 854 if (VT.isVector() || !VT.isInteger()) 855 return SDValue(); 856 857 // If operation type is 'undesirable', e.g. i16 on x86, consider 858 // promoting it. 859 unsigned Opc = Op.getOpcode(); 860 if (TLI.isTypeDesirableForOp(Opc, VT)) 861 return SDValue(); 862 863 EVT PVT = VT; 864 // Consult target whether it is a good idea to promote this operation and 865 // what's the right type to promote it to. 866 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 867 assert(PVT != VT && "Don't know what type to promote to!"); 868 869 bool Replace = false; 870 SDValue N0 = Op.getOperand(0); 871 if (Opc == ISD::SRA) 872 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 873 else if (Opc == ISD::SRL) 874 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 875 else 876 N0 = PromoteOperand(N0, PVT, Replace); 877 if (N0.getNode() == 0) 878 return SDValue(); 879 880 AddToWorkList(N0.getNode()); 881 if (Replace) 882 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 883 884 DEBUG(dbgs() << "\nPromoting "; 885 Op.getNode()->dump(&DAG)); 886 DebugLoc dl = Op.getDebugLoc(); 887 return DAG.getNode(ISD::TRUNCATE, dl, VT, 888 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 889 } 890 return SDValue(); 891 } 892 893 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 894 if (!LegalOperations) 895 return SDValue(); 896 897 EVT VT = Op.getValueType(); 898 if (VT.isVector() || !VT.isInteger()) 899 return SDValue(); 900 901 // If operation type is 'undesirable', e.g. i16 on x86, consider 902 // promoting it. 903 unsigned Opc = Op.getOpcode(); 904 if (TLI.isTypeDesirableForOp(Opc, VT)) 905 return SDValue(); 906 907 EVT PVT = VT; 908 // Consult target whether it is a good idea to promote this operation and 909 // what's the right type to promote it to. 910 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 911 assert(PVT != VT && "Don't know what type to promote to!"); 912 // fold (aext (aext x)) -> (aext x) 913 // fold (aext (zext x)) -> (zext x) 914 // fold (aext (sext x)) -> (sext x) 915 DEBUG(dbgs() << "\nPromoting "; 916 Op.getNode()->dump(&DAG)); 917 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0)); 918 } 919 return SDValue(); 920 } 921 922 bool DAGCombiner::PromoteLoad(SDValue Op) { 923 if (!LegalOperations) 924 return false; 925 926 EVT VT = Op.getValueType(); 927 if (VT.isVector() || !VT.isInteger()) 928 return false; 929 930 // If operation type is 'undesirable', e.g. i16 on x86, consider 931 // promoting it. 932 unsigned Opc = Op.getOpcode(); 933 if (TLI.isTypeDesirableForOp(Opc, VT)) 934 return false; 935 936 EVT PVT = VT; 937 // Consult target whether it is a good idea to promote this operation and 938 // what's the right type to promote it to. 939 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 940 assert(PVT != VT && "Don't know what type to promote to!"); 941 942 DebugLoc dl = Op.getDebugLoc(); 943 SDNode *N = Op.getNode(); 944 LoadSDNode *LD = cast<LoadSDNode>(N); 945 EVT MemVT = LD->getMemoryVT(); 946 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 947 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 948 : ISD::EXTLOAD) 949 : LD->getExtensionType(); 950 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 951 LD->getChain(), LD->getBasePtr(), 952 LD->getPointerInfo(), 953 MemVT, LD->isVolatile(), 954 LD->isNonTemporal(), LD->getAlignment()); 955 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 956 957 DEBUG(dbgs() << "\nPromoting "; 958 N->dump(&DAG); 959 dbgs() << "\nTo: "; 960 Result.getNode()->dump(&DAG); 961 dbgs() << '\n'); 962 WorkListRemover DeadNodes(*this); 963 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 964 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 965 removeFromWorkList(N); 966 DAG.DeleteNode(N); 967 AddToWorkList(Result.getNode()); 968 return true; 969 } 970 return false; 971 } 972 973 974 //===----------------------------------------------------------------------===// 975 // Main DAG Combiner implementation 976 //===----------------------------------------------------------------------===// 977 978 void DAGCombiner::Run(CombineLevel AtLevel) { 979 // set the instance variables, so that the various visit routines may use it. 980 Level = AtLevel; 981 LegalOperations = Level >= AfterLegalizeVectorOps; 982 LegalTypes = Level >= AfterLegalizeTypes; 983 984 // Add all the dag nodes to the worklist. 985 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 986 E = DAG.allnodes_end(); I != E; ++I) 987 AddToWorkList(I); 988 989 // Create a dummy node (which is not added to allnodes), that adds a reference 990 // to the root node, preventing it from being deleted, and tracking any 991 // changes of the root. 992 HandleSDNode Dummy(DAG.getRoot()); 993 994 // The root of the dag may dangle to deleted nodes until the dag combiner is 995 // done. Set it to null to avoid confusion. 996 DAG.setRoot(SDValue()); 997 998 // while the worklist isn't empty, find a node and 999 // try and combine it. 1000 while (!WorkListContents.empty()) { 1001 SDNode *N; 1002 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates. 1003 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1004 // worklist *should* contain, and check the node we want to visit is should 1005 // actually be visited. 1006 do { 1007 N = WorkListOrder.pop_back_val(); 1008 } while (!WorkListContents.erase(N)); 1009 1010 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1011 // N is deleted from the DAG, since they too may now be dead or may have a 1012 // reduced number of uses, allowing other xforms. 1013 if (N->use_empty() && N != &Dummy) { 1014 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1015 AddToWorkList(N->getOperand(i).getNode()); 1016 1017 DAG.DeleteNode(N); 1018 continue; 1019 } 1020 1021 SDValue RV = combine(N); 1022 1023 if (RV.getNode() == 0) 1024 continue; 1025 1026 ++NodesCombined; 1027 1028 // If we get back the same node we passed in, rather than a new node or 1029 // zero, we know that the node must have defined multiple values and 1030 // CombineTo was used. Since CombineTo takes care of the worklist 1031 // mechanics for us, we have no work to do in this case. 1032 if (RV.getNode() == N) 1033 continue; 1034 1035 assert(N->getOpcode() != ISD::DELETED_NODE && 1036 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1037 "Node was deleted but visit returned new node!"); 1038 1039 DEBUG(dbgs() << "\nReplacing.3 "; 1040 N->dump(&DAG); 1041 dbgs() << "\nWith: "; 1042 RV.getNode()->dump(&DAG); 1043 dbgs() << '\n'); 1044 1045 // Transfer debug value. 1046 DAG.TransferDbgValues(SDValue(N, 0), RV); 1047 WorkListRemover DeadNodes(*this); 1048 if (N->getNumValues() == RV.getNode()->getNumValues()) 1049 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1050 else { 1051 assert(N->getValueType(0) == RV.getValueType() && 1052 N->getNumValues() == 1 && "Type mismatch"); 1053 SDValue OpV = RV; 1054 DAG.ReplaceAllUsesWith(N, &OpV); 1055 } 1056 1057 // Push the new node and any users onto the worklist 1058 AddToWorkList(RV.getNode()); 1059 AddUsersToWorkList(RV.getNode()); 1060 1061 // Add any uses of the old node to the worklist in case this node is the 1062 // last one that uses them. They may become dead after this node is 1063 // deleted. 1064 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1065 AddToWorkList(N->getOperand(i).getNode()); 1066 1067 // Finally, if the node is now dead, remove it from the graph. The node 1068 // may not be dead if the replacement process recursively simplified to 1069 // something else needing this node. 1070 if (N->use_empty()) { 1071 // Nodes can be reintroduced into the worklist. Make sure we do not 1072 // process a node that has been replaced. 1073 removeFromWorkList(N); 1074 1075 // Finally, since the node is now dead, remove it from the graph. 1076 DAG.DeleteNode(N); 1077 } 1078 } 1079 1080 // If the root changed (e.g. it was a dead load, update the root). 1081 DAG.setRoot(Dummy.getValue()); 1082 DAG.RemoveDeadNodes(); 1083 } 1084 1085 SDValue DAGCombiner::visit(SDNode *N) { 1086 switch (N->getOpcode()) { 1087 default: break; 1088 case ISD::TokenFactor: return visitTokenFactor(N); 1089 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1090 case ISD::ADD: return visitADD(N); 1091 case ISD::SUB: return visitSUB(N); 1092 case ISD::ADDC: return visitADDC(N); 1093 case ISD::SUBC: return visitSUBC(N); 1094 case ISD::ADDE: return visitADDE(N); 1095 case ISD::SUBE: return visitSUBE(N); 1096 case ISD::MUL: return visitMUL(N); 1097 case ISD::SDIV: return visitSDIV(N); 1098 case ISD::UDIV: return visitUDIV(N); 1099 case ISD::SREM: return visitSREM(N); 1100 case ISD::UREM: return visitUREM(N); 1101 case ISD::MULHU: return visitMULHU(N); 1102 case ISD::MULHS: return visitMULHS(N); 1103 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1104 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1105 case ISD::SMULO: return visitSMULO(N); 1106 case ISD::UMULO: return visitUMULO(N); 1107 case ISD::SDIVREM: return visitSDIVREM(N); 1108 case ISD::UDIVREM: return visitUDIVREM(N); 1109 case ISD::AND: return visitAND(N); 1110 case ISD::OR: return visitOR(N); 1111 case ISD::XOR: return visitXOR(N); 1112 case ISD::SHL: return visitSHL(N); 1113 case ISD::SRA: return visitSRA(N); 1114 case ISD::SRL: return visitSRL(N); 1115 case ISD::CTLZ: return visitCTLZ(N); 1116 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1117 case ISD::CTTZ: return visitCTTZ(N); 1118 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1119 case ISD::CTPOP: return visitCTPOP(N); 1120 case ISD::SELECT: return visitSELECT(N); 1121 case ISD::SELECT_CC: return visitSELECT_CC(N); 1122 case ISD::SETCC: return visitSETCC(N); 1123 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1124 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1125 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1126 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1127 case ISD::TRUNCATE: return visitTRUNCATE(N); 1128 case ISD::BITCAST: return visitBITCAST(N); 1129 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1130 case ISD::FADD: return visitFADD(N); 1131 case ISD::FSUB: return visitFSUB(N); 1132 case ISD::FMUL: return visitFMUL(N); 1133 case ISD::FMA: return visitFMA(N); 1134 case ISD::FDIV: return visitFDIV(N); 1135 case ISD::FREM: return visitFREM(N); 1136 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1137 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1138 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1139 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1140 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1141 case ISD::FP_ROUND: return visitFP_ROUND(N); 1142 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1143 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1144 case ISD::FNEG: return visitFNEG(N); 1145 case ISD::FABS: return visitFABS(N); 1146 case ISD::FFLOOR: return visitFFLOOR(N); 1147 case ISD::FCEIL: return visitFCEIL(N); 1148 case ISD::FTRUNC: return visitFTRUNC(N); 1149 case ISD::BRCOND: return visitBRCOND(N); 1150 case ISD::BR_CC: return visitBR_CC(N); 1151 case ISD::LOAD: return visitLOAD(N); 1152 case ISD::STORE: return visitSTORE(N); 1153 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1154 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1155 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1156 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1157 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1158 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1159 case ISD::MEMBARRIER: return visitMEMBARRIER(N); 1160 } 1161 return SDValue(); 1162 } 1163 1164 SDValue DAGCombiner::combine(SDNode *N) { 1165 SDValue RV = visit(N); 1166 1167 // If nothing happened, try a target-specific DAG combine. 1168 if (RV.getNode() == 0) { 1169 assert(N->getOpcode() != ISD::DELETED_NODE && 1170 "Node was deleted but visit returned NULL!"); 1171 1172 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1173 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1174 1175 // Expose the DAG combiner to the target combiner impls. 1176 TargetLowering::DAGCombinerInfo 1177 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 1178 1179 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1180 } 1181 } 1182 1183 // If nothing happened still, try promoting the operation. 1184 if (RV.getNode() == 0) { 1185 switch (N->getOpcode()) { 1186 default: break; 1187 case ISD::ADD: 1188 case ISD::SUB: 1189 case ISD::MUL: 1190 case ISD::AND: 1191 case ISD::OR: 1192 case ISD::XOR: 1193 RV = PromoteIntBinOp(SDValue(N, 0)); 1194 break; 1195 case ISD::SHL: 1196 case ISD::SRA: 1197 case ISD::SRL: 1198 RV = PromoteIntShiftOp(SDValue(N, 0)); 1199 break; 1200 case ISD::SIGN_EXTEND: 1201 case ISD::ZERO_EXTEND: 1202 case ISD::ANY_EXTEND: 1203 RV = PromoteExtend(SDValue(N, 0)); 1204 break; 1205 case ISD::LOAD: 1206 if (PromoteLoad(SDValue(N, 0))) 1207 RV = SDValue(N, 0); 1208 break; 1209 } 1210 } 1211 1212 // If N is a commutative binary node, try commuting it to enable more 1213 // sdisel CSE. 1214 if (RV.getNode() == 0 && 1215 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1216 N->getNumValues() == 1) { 1217 SDValue N0 = N->getOperand(0); 1218 SDValue N1 = N->getOperand(1); 1219 1220 // Constant operands are canonicalized to RHS. 1221 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1222 SDValue Ops[] = { N1, N0 }; 1223 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1224 Ops, 2); 1225 if (CSENode) 1226 return SDValue(CSENode, 0); 1227 } 1228 } 1229 1230 return RV; 1231 } 1232 1233 /// getInputChainForNode - Given a node, return its input chain if it has one, 1234 /// otherwise return a null sd operand. 1235 static SDValue getInputChainForNode(SDNode *N) { 1236 if (unsigned NumOps = N->getNumOperands()) { 1237 if (N->getOperand(0).getValueType() == MVT::Other) 1238 return N->getOperand(0); 1239 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1240 return N->getOperand(NumOps-1); 1241 for (unsigned i = 1; i < NumOps-1; ++i) 1242 if (N->getOperand(i).getValueType() == MVT::Other) 1243 return N->getOperand(i); 1244 } 1245 return SDValue(); 1246 } 1247 1248 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1249 // If N has two operands, where one has an input chain equal to the other, 1250 // the 'other' chain is redundant. 1251 if (N->getNumOperands() == 2) { 1252 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1253 return N->getOperand(0); 1254 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1255 return N->getOperand(1); 1256 } 1257 1258 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1259 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1260 SmallPtrSet<SDNode*, 16> SeenOps; 1261 bool Changed = false; // If we should replace this token factor. 1262 1263 // Start out with this token factor. 1264 TFs.push_back(N); 1265 1266 // Iterate through token factors. The TFs grows when new token factors are 1267 // encountered. 1268 for (unsigned i = 0; i < TFs.size(); ++i) { 1269 SDNode *TF = TFs[i]; 1270 1271 // Check each of the operands. 1272 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1273 SDValue Op = TF->getOperand(i); 1274 1275 switch (Op.getOpcode()) { 1276 case ISD::EntryToken: 1277 // Entry tokens don't need to be added to the list. They are 1278 // rededundant. 1279 Changed = true; 1280 break; 1281 1282 case ISD::TokenFactor: 1283 if (Op.hasOneUse() && 1284 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1285 // Queue up for processing. 1286 TFs.push_back(Op.getNode()); 1287 // Clean up in case the token factor is removed. 1288 AddToWorkList(Op.getNode()); 1289 Changed = true; 1290 break; 1291 } 1292 // Fall thru 1293 1294 default: 1295 // Only add if it isn't already in the list. 1296 if (SeenOps.insert(Op.getNode())) 1297 Ops.push_back(Op); 1298 else 1299 Changed = true; 1300 break; 1301 } 1302 } 1303 } 1304 1305 SDValue Result; 1306 1307 // If we've change things around then replace token factor. 1308 if (Changed) { 1309 if (Ops.empty()) { 1310 // The entry token is the only possible outcome. 1311 Result = DAG.getEntryNode(); 1312 } else { 1313 // New and improved token factor. 1314 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 1315 MVT::Other, &Ops[0], Ops.size()); 1316 } 1317 1318 // Don't add users to work list. 1319 return CombineTo(N, Result, false); 1320 } 1321 1322 return Result; 1323 } 1324 1325 /// MERGE_VALUES can always be eliminated. 1326 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1327 WorkListRemover DeadNodes(*this); 1328 // Replacing results may cause a different MERGE_VALUES to suddenly 1329 // be CSE'd with N, and carry its uses with it. Iterate until no 1330 // uses remain, to ensure that the node can be safely deleted. 1331 // First add the users of this node to the work list so that they 1332 // can be tried again once they have new operands. 1333 AddUsersToWorkList(N); 1334 do { 1335 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1336 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1337 } while (!N->use_empty()); 1338 removeFromWorkList(N); 1339 DAG.DeleteNode(N); 1340 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1341 } 1342 1343 static 1344 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1, 1345 SelectionDAG &DAG) { 1346 EVT VT = N0.getValueType(); 1347 SDValue N00 = N0.getOperand(0); 1348 SDValue N01 = N0.getOperand(1); 1349 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1350 1351 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1352 isa<ConstantSDNode>(N00.getOperand(1))) { 1353 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1354 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, 1355 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT, 1356 N00.getOperand(0), N01), 1357 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT, 1358 N00.getOperand(1), N01)); 1359 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1360 } 1361 1362 return SDValue(); 1363 } 1364 1365 SDValue DAGCombiner::visitADD(SDNode *N) { 1366 SDValue N0 = N->getOperand(0); 1367 SDValue N1 = N->getOperand(1); 1368 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1370 EVT VT = N0.getValueType(); 1371 1372 // fold vector ops 1373 if (VT.isVector()) { 1374 SDValue FoldedVOp = SimplifyVBinOp(N); 1375 if (FoldedVOp.getNode()) return FoldedVOp; 1376 } 1377 1378 // fold (add x, undef) -> undef 1379 if (N0.getOpcode() == ISD::UNDEF) 1380 return N0; 1381 if (N1.getOpcode() == ISD::UNDEF) 1382 return N1; 1383 // fold (add c1, c2) -> c1+c2 1384 if (N0C && N1C) 1385 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1386 // canonicalize constant to RHS 1387 if (N0C && !N1C) 1388 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0); 1389 // fold (add x, 0) -> x 1390 if (N1C && N1C->isNullValue()) 1391 return N0; 1392 // fold (add Sym, c) -> Sym+c 1393 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1394 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1395 GA->getOpcode() == ISD::GlobalAddress) 1396 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT, 1397 GA->getOffset() + 1398 (uint64_t)N1C->getSExtValue()); 1399 // fold ((c1-A)+c2) -> (c1+c2)-A 1400 if (N1C && N0.getOpcode() == ISD::SUB) 1401 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1402 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1403 DAG.getConstant(N1C->getAPIntValue()+ 1404 N0C->getAPIntValue(), VT), 1405 N0.getOperand(1)); 1406 // reassociate add 1407 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1); 1408 if (RADD.getNode() != 0) 1409 return RADD; 1410 // fold ((0-A) + B) -> B-A 1411 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1412 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1413 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1)); 1414 // fold (A + (0-B)) -> A-B 1415 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1416 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1417 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1)); 1418 // fold (A+(B-A)) -> B 1419 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1420 return N1.getOperand(0); 1421 // fold ((B-A)+A) -> B 1422 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1423 return N0.getOperand(0); 1424 // fold (A+(B-(A+C))) to (B-C) 1425 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1426 N0 == N1.getOperand(1).getOperand(0)) 1427 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1428 N1.getOperand(1).getOperand(1)); 1429 // fold (A+(B-(C+A))) to (B-C) 1430 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1431 N0 == N1.getOperand(1).getOperand(1)) 1432 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1433 N1.getOperand(1).getOperand(0)); 1434 // fold (A+((B-A)+or-C)) to (B+or-C) 1435 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1436 N1.getOperand(0).getOpcode() == ISD::SUB && 1437 N0 == N1.getOperand(0).getOperand(1)) 1438 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT, 1439 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1440 1441 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1442 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1443 SDValue N00 = N0.getOperand(0); 1444 SDValue N01 = N0.getOperand(1); 1445 SDValue N10 = N1.getOperand(0); 1446 SDValue N11 = N1.getOperand(1); 1447 1448 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1449 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1450 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10), 1451 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11)); 1452 } 1453 1454 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1455 return SDValue(N, 0); 1456 1457 // fold (a+b) -> (a|b) iff a and b share no bits. 1458 if (VT.isInteger() && !VT.isVector()) { 1459 APInt LHSZero, LHSOne; 1460 APInt RHSZero, RHSOne; 1461 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1462 1463 if (LHSZero.getBoolValue()) { 1464 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1465 1466 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1467 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1468 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1469 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1); 1470 } 1471 } 1472 1473 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1474 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1475 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG); 1476 if (Result.getNode()) return Result; 1477 } 1478 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1479 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG); 1480 if (Result.getNode()) return Result; 1481 } 1482 1483 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1484 if (N1.getOpcode() == ISD::SHL && 1485 N1.getOperand(0).getOpcode() == ISD::SUB) 1486 if (ConstantSDNode *C = 1487 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1488 if (C->getAPIntValue() == 0) 1489 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, 1490 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1491 N1.getOperand(0).getOperand(1), 1492 N1.getOperand(1))); 1493 if (N0.getOpcode() == ISD::SHL && 1494 N0.getOperand(0).getOpcode() == ISD::SUB) 1495 if (ConstantSDNode *C = 1496 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1497 if (C->getAPIntValue() == 0) 1498 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, 1499 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1500 N0.getOperand(0).getOperand(1), 1501 N0.getOperand(1))); 1502 1503 if (N1.getOpcode() == ISD::AND) { 1504 SDValue AndOp0 = N1.getOperand(0); 1505 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1506 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1507 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1508 1509 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1510 // and similar xforms where the inner op is either ~0 or 0. 1511 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1512 DebugLoc DL = N->getDebugLoc(); 1513 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1514 } 1515 } 1516 1517 // add (sext i1), X -> sub X, (zext i1) 1518 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1519 N0.getOperand(0).getValueType() == MVT::i1 && 1520 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1521 DebugLoc DL = N->getDebugLoc(); 1522 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1523 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1524 } 1525 1526 return SDValue(); 1527 } 1528 1529 SDValue DAGCombiner::visitADDC(SDNode *N) { 1530 SDValue N0 = N->getOperand(0); 1531 SDValue N1 = N->getOperand(1); 1532 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1533 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1534 EVT VT = N0.getValueType(); 1535 1536 // If the flag result is dead, turn this into an ADD. 1537 if (!N->hasAnyUseOfValue(1)) 1538 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1), 1539 DAG.getNode(ISD::CARRY_FALSE, 1540 N->getDebugLoc(), MVT::Glue)); 1541 1542 // canonicalize constant to RHS. 1543 if (N0C && !N1C) 1544 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0); 1545 1546 // fold (addc x, 0) -> x + no carry out 1547 if (N1C && N1C->isNullValue()) 1548 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1549 N->getDebugLoc(), MVT::Glue)); 1550 1551 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1552 APInt LHSZero, LHSOne; 1553 APInt RHSZero, RHSOne; 1554 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1555 1556 if (LHSZero.getBoolValue()) { 1557 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1558 1559 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1560 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1561 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1562 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1), 1563 DAG.getNode(ISD::CARRY_FALSE, 1564 N->getDebugLoc(), MVT::Glue)); 1565 } 1566 1567 return SDValue(); 1568 } 1569 1570 SDValue DAGCombiner::visitADDE(SDNode *N) { 1571 SDValue N0 = N->getOperand(0); 1572 SDValue N1 = N->getOperand(1); 1573 SDValue CarryIn = N->getOperand(2); 1574 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1575 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1576 1577 // canonicalize constant to RHS 1578 if (N0C && !N1C) 1579 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), 1580 N1, N0, CarryIn); 1581 1582 // fold (adde x, y, false) -> (addc x, y) 1583 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1584 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1); 1585 1586 return SDValue(); 1587 } 1588 1589 // Since it may not be valid to emit a fold to zero for vector initializers 1590 // check if we can before folding. 1591 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT, 1592 SelectionDAG &DAG, bool LegalOperations) { 1593 if (!VT.isVector()) { 1594 return DAG.getConstant(0, VT); 1595 } 1596 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) { 1597 // Produce a vector of zeros. 1598 SDValue El = DAG.getConstant(0, VT.getVectorElementType()); 1599 std::vector<SDValue> Ops(VT.getVectorNumElements(), El); 1600 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 1601 &Ops[0], Ops.size()); 1602 } 1603 return SDValue(); 1604 } 1605 1606 SDValue DAGCombiner::visitSUB(SDNode *N) { 1607 SDValue N0 = N->getOperand(0); 1608 SDValue N1 = N->getOperand(1); 1609 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1610 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1611 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 : 1612 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1613 EVT VT = N0.getValueType(); 1614 1615 // fold vector ops 1616 if (VT.isVector()) { 1617 SDValue FoldedVOp = SimplifyVBinOp(N); 1618 if (FoldedVOp.getNode()) return FoldedVOp; 1619 } 1620 1621 // fold (sub x, x) -> 0 1622 // FIXME: Refactor this and xor and other similar operations together. 1623 if (N0 == N1) 1624 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations); 1625 // fold (sub c1, c2) -> c1-c2 1626 if (N0C && N1C) 1627 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1628 // fold (sub x, c) -> (add x, -c) 1629 if (N1C) 1630 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, 1631 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1632 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1633 if (N0C && N0C->isAllOnesValue()) 1634 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 1635 // fold A-(A-B) -> B 1636 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1637 return N1.getOperand(1); 1638 // fold (A+B)-A -> B 1639 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1640 return N0.getOperand(1); 1641 // fold (A+B)-B -> A 1642 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1643 return N0.getOperand(0); 1644 // fold C2-(A+C1) -> (C2-C1)-A 1645 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1646 SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT); 1647 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC, 1648 N1.getOperand(0)); 1649 } 1650 // fold ((A+(B+or-C))-B) -> A+or-C 1651 if (N0.getOpcode() == ISD::ADD && 1652 (N0.getOperand(1).getOpcode() == ISD::SUB || 1653 N0.getOperand(1).getOpcode() == ISD::ADD) && 1654 N0.getOperand(1).getOperand(0) == N1) 1655 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT, 1656 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1657 // fold ((A+(C+B))-B) -> A+C 1658 if (N0.getOpcode() == ISD::ADD && 1659 N0.getOperand(1).getOpcode() == ISD::ADD && 1660 N0.getOperand(1).getOperand(1) == N1) 1661 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1662 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1663 // fold ((A-(B-C))-C) -> A-B 1664 if (N0.getOpcode() == ISD::SUB && 1665 N0.getOperand(1).getOpcode() == ISD::SUB && 1666 N0.getOperand(1).getOperand(1) == N1) 1667 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1668 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1669 1670 // If either operand of a sub is undef, the result is undef 1671 if (N0.getOpcode() == ISD::UNDEF) 1672 return N0; 1673 if (N1.getOpcode() == ISD::UNDEF) 1674 return N1; 1675 1676 // If the relocation model supports it, consider symbol offsets. 1677 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1678 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1679 // fold (sub Sym, c) -> Sym-c 1680 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1681 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT, 1682 GA->getOffset() - 1683 (uint64_t)N1C->getSExtValue()); 1684 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1685 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1686 if (GA->getGlobal() == GB->getGlobal()) 1687 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1688 VT); 1689 } 1690 1691 return SDValue(); 1692 } 1693 1694 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1695 SDValue N0 = N->getOperand(0); 1696 SDValue N1 = N->getOperand(1); 1697 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1698 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1699 EVT VT = N0.getValueType(); 1700 1701 // If the flag result is dead, turn this into an SUB. 1702 if (!N->hasAnyUseOfValue(1)) 1703 return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1), 1704 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1705 MVT::Glue)); 1706 1707 // fold (subc x, x) -> 0 + no borrow 1708 if (N0 == N1) 1709 return CombineTo(N, DAG.getConstant(0, VT), 1710 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1711 MVT::Glue)); 1712 1713 // fold (subc x, 0) -> x + no borrow 1714 if (N1C && N1C->isNullValue()) 1715 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1716 MVT::Glue)); 1717 1718 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1719 if (N0C && N0C->isAllOnesValue()) 1720 return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0), 1721 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1722 MVT::Glue)); 1723 1724 return SDValue(); 1725 } 1726 1727 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1728 SDValue N0 = N->getOperand(0); 1729 SDValue N1 = N->getOperand(1); 1730 SDValue CarryIn = N->getOperand(2); 1731 1732 // fold (sube x, y, false) -> (subc x, y) 1733 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1734 return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1); 1735 1736 return SDValue(); 1737 } 1738 1739 SDValue DAGCombiner::visitMUL(SDNode *N) { 1740 SDValue N0 = N->getOperand(0); 1741 SDValue N1 = N->getOperand(1); 1742 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1743 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1744 EVT VT = N0.getValueType(); 1745 1746 // fold vector ops 1747 if (VT.isVector()) { 1748 SDValue FoldedVOp = SimplifyVBinOp(N); 1749 if (FoldedVOp.getNode()) return FoldedVOp; 1750 } 1751 1752 // fold (mul x, undef) -> 0 1753 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1754 return DAG.getConstant(0, VT); 1755 // fold (mul c1, c2) -> c1*c2 1756 if (N0C && N1C) 1757 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C); 1758 // canonicalize constant to RHS 1759 if (N0C && !N1C) 1760 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0); 1761 // fold (mul x, 0) -> 0 1762 if (N1C && N1C->isNullValue()) 1763 return N1; 1764 // fold (mul x, -1) -> 0-x 1765 if (N1C && N1C->isAllOnesValue()) 1766 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1767 DAG.getConstant(0, VT), N0); 1768 // fold (mul x, (1 << c)) -> x << c 1769 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1770 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1771 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1772 getShiftAmountTy(N0.getValueType()))); 1773 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1774 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) { 1775 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2(); 1776 // FIXME: If the input is something that is easily negated (e.g. a 1777 // single-use add), we should put the negate there. 1778 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1779 DAG.getConstant(0, VT), 1780 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1781 DAG.getConstant(Log2Val, 1782 getShiftAmountTy(N0.getValueType())))); 1783 } 1784 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1785 if (N1C && N0.getOpcode() == ISD::SHL && 1786 isa<ConstantSDNode>(N0.getOperand(1))) { 1787 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1788 N1, N0.getOperand(1)); 1789 AddToWorkList(C3.getNode()); 1790 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1791 N0.getOperand(0), C3); 1792 } 1793 1794 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1795 // use. 1796 { 1797 SDValue Sh(0,0), Y(0,0); 1798 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1799 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) && 1800 N0.getNode()->hasOneUse()) { 1801 Sh = N0; Y = N1; 1802 } else if (N1.getOpcode() == ISD::SHL && 1803 isa<ConstantSDNode>(N1.getOperand(1)) && 1804 N1.getNode()->hasOneUse()) { 1805 Sh = N1; Y = N0; 1806 } 1807 1808 if (Sh.getNode()) { 1809 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1810 Sh.getOperand(0), Y); 1811 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1812 Mul, Sh.getOperand(1)); 1813 } 1814 } 1815 1816 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1817 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1818 isa<ConstantSDNode>(N0.getOperand(1))) 1819 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1820 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT, 1821 N0.getOperand(0), N1), 1822 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT, 1823 N0.getOperand(1), N1)); 1824 1825 // reassociate mul 1826 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1); 1827 if (RMUL.getNode() != 0) 1828 return RMUL; 1829 1830 return SDValue(); 1831 } 1832 1833 SDValue DAGCombiner::visitSDIV(SDNode *N) { 1834 SDValue N0 = N->getOperand(0); 1835 SDValue N1 = N->getOperand(1); 1836 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1837 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1838 EVT VT = N->getValueType(0); 1839 1840 // fold vector ops 1841 if (VT.isVector()) { 1842 SDValue FoldedVOp = SimplifyVBinOp(N); 1843 if (FoldedVOp.getNode()) return FoldedVOp; 1844 } 1845 1846 // fold (sdiv c1, c2) -> c1/c2 1847 if (N0C && N1C && !N1C->isNullValue()) 1848 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1849 // fold (sdiv X, 1) -> X 1850 if (N1C && N1C->getAPIntValue() == 1LL) 1851 return N0; 1852 // fold (sdiv X, -1) -> 0-X 1853 if (N1C && N1C->isAllOnesValue()) 1854 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1855 DAG.getConstant(0, VT), N0); 1856 // If we know the sign bits of both operands are zero, strength reduce to a 1857 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1858 if (!VT.isVector()) { 1859 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1860 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(), 1861 N0, N1); 1862 } 1863 // fold (sdiv X, pow2) -> simple ops after legalize 1864 if (N1C && !N1C->isNullValue() && 1865 (N1C->getAPIntValue().isPowerOf2() || 1866 (-N1C->getAPIntValue()).isPowerOf2())) { 1867 // If dividing by powers of two is cheap, then don't perform the following 1868 // fold. 1869 if (TLI.isPow2DivCheap()) 1870 return SDValue(); 1871 1872 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1873 1874 // Splat the sign bit into the register 1875 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 1876 DAG.getConstant(VT.getSizeInBits()-1, 1877 getShiftAmountTy(N0.getValueType()))); 1878 AddToWorkList(SGN.getNode()); 1879 1880 // Add (N0 < 0) ? abs2 - 1 : 0; 1881 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN, 1882 DAG.getConstant(VT.getSizeInBits() - lg2, 1883 getShiftAmountTy(SGN.getValueType()))); 1884 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL); 1885 AddToWorkList(SRL.getNode()); 1886 AddToWorkList(ADD.getNode()); // Divide by pow2 1887 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD, 1888 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 1889 1890 // If we're dividing by a positive value, we're done. Otherwise, we must 1891 // negate the result. 1892 if (N1C->getAPIntValue().isNonNegative()) 1893 return SRA; 1894 1895 AddToWorkList(SRA.getNode()); 1896 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1897 DAG.getConstant(0, VT), SRA); 1898 } 1899 1900 // if integer divide is expensive and we satisfy the requirements, emit an 1901 // alternate sequence. 1902 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1903 SDValue Op = BuildSDIV(N); 1904 if (Op.getNode()) return Op; 1905 } 1906 1907 // undef / X -> 0 1908 if (N0.getOpcode() == ISD::UNDEF) 1909 return DAG.getConstant(0, VT); 1910 // X / undef -> undef 1911 if (N1.getOpcode() == ISD::UNDEF) 1912 return N1; 1913 1914 return SDValue(); 1915 } 1916 1917 SDValue DAGCombiner::visitUDIV(SDNode *N) { 1918 SDValue N0 = N->getOperand(0); 1919 SDValue N1 = N->getOperand(1); 1920 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1921 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1922 EVT VT = N->getValueType(0); 1923 1924 // fold vector ops 1925 if (VT.isVector()) { 1926 SDValue FoldedVOp = SimplifyVBinOp(N); 1927 if (FoldedVOp.getNode()) return FoldedVOp; 1928 } 1929 1930 // fold (udiv c1, c2) -> c1/c2 1931 if (N0C && N1C && !N1C->isNullValue()) 1932 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 1933 // fold (udiv x, (1 << c)) -> x >>u c 1934 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1935 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 1936 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1937 getShiftAmountTy(N0.getValueType()))); 1938 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 1939 if (N1.getOpcode() == ISD::SHL) { 1940 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 1941 if (SHC->getAPIntValue().isPowerOf2()) { 1942 EVT ADDVT = N1.getOperand(1).getValueType(); 1943 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT, 1944 N1.getOperand(1), 1945 DAG.getConstant(SHC->getAPIntValue() 1946 .logBase2(), 1947 ADDVT)); 1948 AddToWorkList(Add.getNode()); 1949 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add); 1950 } 1951 } 1952 } 1953 // fold (udiv x, c) -> alternate 1954 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1955 SDValue Op = BuildUDIV(N); 1956 if (Op.getNode()) return Op; 1957 } 1958 1959 // undef / X -> 0 1960 if (N0.getOpcode() == ISD::UNDEF) 1961 return DAG.getConstant(0, VT); 1962 // X / undef -> undef 1963 if (N1.getOpcode() == ISD::UNDEF) 1964 return N1; 1965 1966 return SDValue(); 1967 } 1968 1969 SDValue DAGCombiner::visitSREM(SDNode *N) { 1970 SDValue N0 = N->getOperand(0); 1971 SDValue N1 = N->getOperand(1); 1972 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1974 EVT VT = N->getValueType(0); 1975 1976 // fold (srem c1, c2) -> c1%c2 1977 if (N0C && N1C && !N1C->isNullValue()) 1978 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 1979 // If we know the sign bits of both operands are zero, strength reduce to a 1980 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 1981 if (!VT.isVector()) { 1982 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1983 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1); 1984 } 1985 1986 // If X/C can be simplified by the division-by-constant logic, lower 1987 // X%C to the equivalent of X-X/C*C. 1988 if (N1C && !N1C->isNullValue()) { 1989 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1); 1990 AddToWorkList(Div.getNode()); 1991 SDValue OptimizedDiv = combine(Div.getNode()); 1992 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 1993 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1994 OptimizedDiv, N1); 1995 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 1996 AddToWorkList(Mul.getNode()); 1997 return Sub; 1998 } 1999 } 2000 2001 // undef % X -> 0 2002 if (N0.getOpcode() == ISD::UNDEF) 2003 return DAG.getConstant(0, VT); 2004 // X % undef -> undef 2005 if (N1.getOpcode() == ISD::UNDEF) 2006 return N1; 2007 2008 return SDValue(); 2009 } 2010 2011 SDValue DAGCombiner::visitUREM(SDNode *N) { 2012 SDValue N0 = N->getOperand(0); 2013 SDValue N1 = N->getOperand(1); 2014 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2015 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2016 EVT VT = N->getValueType(0); 2017 2018 // fold (urem c1, c2) -> c1%c2 2019 if (N0C && N1C && !N1C->isNullValue()) 2020 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2021 // fold (urem x, pow2) -> (and x, pow2-1) 2022 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2023 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, 2024 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2025 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2026 if (N1.getOpcode() == ISD::SHL) { 2027 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2028 if (SHC->getAPIntValue().isPowerOf2()) { 2029 SDValue Add = 2030 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, 2031 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2032 VT)); 2033 AddToWorkList(Add.getNode()); 2034 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add); 2035 } 2036 } 2037 } 2038 2039 // If X/C can be simplified by the division-by-constant logic, lower 2040 // X%C to the equivalent of X-X/C*C. 2041 if (N1C && !N1C->isNullValue()) { 2042 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1); 2043 AddToWorkList(Div.getNode()); 2044 SDValue OptimizedDiv = combine(Div.getNode()); 2045 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2046 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 2047 OptimizedDiv, N1); 2048 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 2049 AddToWorkList(Mul.getNode()); 2050 return Sub; 2051 } 2052 } 2053 2054 // undef % X -> 0 2055 if (N0.getOpcode() == ISD::UNDEF) 2056 return DAG.getConstant(0, VT); 2057 // X % undef -> undef 2058 if (N1.getOpcode() == ISD::UNDEF) 2059 return N1; 2060 2061 return SDValue(); 2062 } 2063 2064 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2065 SDValue N0 = N->getOperand(0); 2066 SDValue N1 = N->getOperand(1); 2067 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2068 EVT VT = N->getValueType(0); 2069 DebugLoc DL = N->getDebugLoc(); 2070 2071 // fold (mulhs x, 0) -> 0 2072 if (N1C && N1C->isNullValue()) 2073 return N1; 2074 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2075 if (N1C && N1C->getAPIntValue() == 1) 2076 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0, 2077 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2078 getShiftAmountTy(N0.getValueType()))); 2079 // fold (mulhs x, undef) -> 0 2080 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2081 return DAG.getConstant(0, VT); 2082 2083 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2084 // plus a shift. 2085 if (VT.isSimple() && !VT.isVector()) { 2086 MVT Simple = VT.getSimpleVT(); 2087 unsigned SimpleSize = Simple.getSizeInBits(); 2088 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2089 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2090 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2091 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2092 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2093 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2094 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2095 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2096 } 2097 } 2098 2099 return SDValue(); 2100 } 2101 2102 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2103 SDValue N0 = N->getOperand(0); 2104 SDValue N1 = N->getOperand(1); 2105 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2106 EVT VT = N->getValueType(0); 2107 DebugLoc DL = N->getDebugLoc(); 2108 2109 // fold (mulhu x, 0) -> 0 2110 if (N1C && N1C->isNullValue()) 2111 return N1; 2112 // fold (mulhu x, 1) -> 0 2113 if (N1C && N1C->getAPIntValue() == 1) 2114 return DAG.getConstant(0, N0.getValueType()); 2115 // fold (mulhu x, undef) -> 0 2116 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2117 return DAG.getConstant(0, VT); 2118 2119 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2120 // plus a shift. 2121 if (VT.isSimple() && !VT.isVector()) { 2122 MVT Simple = VT.getSimpleVT(); 2123 unsigned SimpleSize = Simple.getSizeInBits(); 2124 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2125 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2126 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2127 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2128 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2129 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2130 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2131 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2132 } 2133 } 2134 2135 return SDValue(); 2136 } 2137 2138 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2139 /// compute two values. LoOp and HiOp give the opcodes for the two computations 2140 /// that are being performed. Return true if a simplification was made. 2141 /// 2142 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2143 unsigned HiOp) { 2144 // If the high half is not needed, just compute the low half. 2145 bool HiExists = N->hasAnyUseOfValue(1); 2146 if (!HiExists && 2147 (!LegalOperations || 2148 TLI.isOperationLegal(LoOp, N->getValueType(0)))) { 2149 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 2150 N->op_begin(), N->getNumOperands()); 2151 return CombineTo(N, Res, Res); 2152 } 2153 2154 // If the low half is not needed, just compute the high half. 2155 bool LoExists = N->hasAnyUseOfValue(0); 2156 if (!LoExists && 2157 (!LegalOperations || 2158 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2159 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 2160 N->op_begin(), N->getNumOperands()); 2161 return CombineTo(N, Res, Res); 2162 } 2163 2164 // If both halves are used, return as it is. 2165 if (LoExists && HiExists) 2166 return SDValue(); 2167 2168 // If the two computed results can be simplified separately, separate them. 2169 if (LoExists) { 2170 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 2171 N->op_begin(), N->getNumOperands()); 2172 AddToWorkList(Lo.getNode()); 2173 SDValue LoOpt = combine(Lo.getNode()); 2174 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2175 (!LegalOperations || 2176 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2177 return CombineTo(N, LoOpt, LoOpt); 2178 } 2179 2180 if (HiExists) { 2181 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 2182 N->op_begin(), N->getNumOperands()); 2183 AddToWorkList(Hi.getNode()); 2184 SDValue HiOpt = combine(Hi.getNode()); 2185 if (HiOpt.getNode() && HiOpt != Hi && 2186 (!LegalOperations || 2187 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2188 return CombineTo(N, HiOpt, HiOpt); 2189 } 2190 2191 return SDValue(); 2192 } 2193 2194 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2195 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2196 if (Res.getNode()) return Res; 2197 2198 EVT VT = N->getValueType(0); 2199 DebugLoc DL = N->getDebugLoc(); 2200 2201 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2202 // plus a shift. 2203 if (VT.isSimple() && !VT.isVector()) { 2204 MVT Simple = VT.getSimpleVT(); 2205 unsigned SimpleSize = Simple.getSizeInBits(); 2206 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2207 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2208 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2209 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2210 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2211 // Compute the high part as N1. 2212 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2213 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2214 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2215 // Compute the low part as N0. 2216 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2217 return CombineTo(N, Lo, Hi); 2218 } 2219 } 2220 2221 return SDValue(); 2222 } 2223 2224 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2225 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2226 if (Res.getNode()) return Res; 2227 2228 EVT VT = N->getValueType(0); 2229 DebugLoc DL = N->getDebugLoc(); 2230 2231 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2232 // plus a shift. 2233 if (VT.isSimple() && !VT.isVector()) { 2234 MVT Simple = VT.getSimpleVT(); 2235 unsigned SimpleSize = Simple.getSizeInBits(); 2236 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2237 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2238 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2239 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2240 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2241 // Compute the high part as N1. 2242 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2243 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2244 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2245 // Compute the low part as N0. 2246 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2247 return CombineTo(N, Lo, Hi); 2248 } 2249 } 2250 2251 return SDValue(); 2252 } 2253 2254 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2255 // (smulo x, 2) -> (saddo x, x) 2256 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2257 if (C2->getAPIntValue() == 2) 2258 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(), 2259 N->getOperand(0), N->getOperand(0)); 2260 2261 return SDValue(); 2262 } 2263 2264 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2265 // (umulo x, 2) -> (uaddo x, x) 2266 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2267 if (C2->getAPIntValue() == 2) 2268 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(), 2269 N->getOperand(0), N->getOperand(0)); 2270 2271 return SDValue(); 2272 } 2273 2274 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2275 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2276 if (Res.getNode()) return Res; 2277 2278 return SDValue(); 2279 } 2280 2281 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2282 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2283 if (Res.getNode()) return Res; 2284 2285 return SDValue(); 2286 } 2287 2288 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2289 /// two operands of the same opcode, try to simplify it. 2290 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2291 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2292 EVT VT = N0.getValueType(); 2293 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2294 2295 // Bail early if none of these transforms apply. 2296 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2297 2298 // For each of OP in AND/OR/XOR: 2299 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2300 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2301 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2302 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2303 // 2304 // do not sink logical op inside of a vector extend, since it may combine 2305 // into a vsetcc. 2306 EVT Op0VT = N0.getOperand(0).getValueType(); 2307 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2308 N0.getOpcode() == ISD::SIGN_EXTEND || 2309 // Avoid infinite looping with PromoteIntBinOp. 2310 (N0.getOpcode() == ISD::ANY_EXTEND && 2311 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2312 (N0.getOpcode() == ISD::TRUNCATE && 2313 (!TLI.isZExtFree(VT, Op0VT) || 2314 !TLI.isTruncateFree(Op0VT, VT)) && 2315 TLI.isTypeLegal(Op0VT))) && 2316 !VT.isVector() && 2317 Op0VT == N1.getOperand(0).getValueType() && 2318 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2319 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2320 N0.getOperand(0).getValueType(), 2321 N0.getOperand(0), N1.getOperand(0)); 2322 AddToWorkList(ORNode.getNode()); 2323 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode); 2324 } 2325 2326 // For each of OP in SHL/SRL/SRA/AND... 2327 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2328 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2329 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2330 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2331 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2332 N0.getOperand(1) == N1.getOperand(1)) { 2333 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2334 N0.getOperand(0).getValueType(), 2335 N0.getOperand(0), N1.getOperand(0)); 2336 AddToWorkList(ORNode.getNode()); 2337 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 2338 ORNode, N0.getOperand(1)); 2339 } 2340 2341 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2342 // Only perform this optimization after type legalization and before 2343 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2344 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2345 // we don't want to undo this promotion. 2346 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2347 // on scalars. 2348 if ((N0.getOpcode() == ISD::BITCAST || N0.getOpcode() == ISD::SCALAR_TO_VECTOR) 2349 && Level == AfterLegalizeTypes) { 2350 SDValue In0 = N0.getOperand(0); 2351 SDValue In1 = N1.getOperand(0); 2352 EVT In0Ty = In0.getValueType(); 2353 EVT In1Ty = In1.getValueType(); 2354 // If both incoming values are integers, and the original types are the same. 2355 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2356 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), In0Ty, In0, In1); 2357 SDValue BC = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, Op); 2358 AddToWorkList(Op.getNode()); 2359 return BC; 2360 } 2361 } 2362 2363 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2364 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2365 // If both shuffles use the same mask, and both shuffle within a single 2366 // vector, then it is worthwhile to move the swizzle after the operation. 2367 // The type-legalizer generates this pattern when loading illegal 2368 // vector types from memory. In many cases this allows additional shuffle 2369 // optimizations. 2370 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 2371 N0.getOperand(1).getOpcode() == ISD::UNDEF && 2372 N1.getOperand(1).getOpcode() == ISD::UNDEF) { 2373 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2374 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2375 2376 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() && 2377 "Inputs to shuffles are not the same type"); 2378 2379 unsigned NumElts = VT.getVectorNumElements(); 2380 2381 // Check that both shuffles use the same mask. The masks are known to be of 2382 // the same length because the result vector type is the same. 2383 bool SameMask = true; 2384 for (unsigned i = 0; i != NumElts; ++i) { 2385 int Idx0 = SVN0->getMaskElt(i); 2386 int Idx1 = SVN1->getMaskElt(i); 2387 if (Idx0 != Idx1) { 2388 SameMask = false; 2389 break; 2390 } 2391 } 2392 2393 if (SameMask) { 2394 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT, 2395 N0.getOperand(0), N1.getOperand(0)); 2396 AddToWorkList(Op.getNode()); 2397 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op, 2398 DAG.getUNDEF(VT), &SVN0->getMask()[0]); 2399 } 2400 } 2401 2402 return SDValue(); 2403 } 2404 2405 SDValue DAGCombiner::visitAND(SDNode *N) { 2406 SDValue N0 = N->getOperand(0); 2407 SDValue N1 = N->getOperand(1); 2408 SDValue LL, LR, RL, RR, CC0, CC1; 2409 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2410 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2411 EVT VT = N1.getValueType(); 2412 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2413 2414 // fold vector ops 2415 if (VT.isVector()) { 2416 SDValue FoldedVOp = SimplifyVBinOp(N); 2417 if (FoldedVOp.getNode()) return FoldedVOp; 2418 } 2419 2420 // fold (and x, undef) -> 0 2421 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2422 return DAG.getConstant(0, VT); 2423 // fold (and c1, c2) -> c1&c2 2424 if (N0C && N1C) 2425 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2426 // canonicalize constant to RHS 2427 if (N0C && !N1C) 2428 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0); 2429 // fold (and x, -1) -> x 2430 if (N1C && N1C->isAllOnesValue()) 2431 return N0; 2432 // if (and x, c) is known to be zero, return 0 2433 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2434 APInt::getAllOnesValue(BitWidth))) 2435 return DAG.getConstant(0, VT); 2436 // reassociate and 2437 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1); 2438 if (RAND.getNode() != 0) 2439 return RAND; 2440 // fold (and (or x, C), D) -> D if (C & D) == D 2441 if (N1C && N0.getOpcode() == ISD::OR) 2442 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2443 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2444 return N1; 2445 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2446 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2447 SDValue N0Op0 = N0.getOperand(0); 2448 APInt Mask = ~N1C->getAPIntValue(); 2449 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2450 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2451 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), 2452 N0.getValueType(), N0Op0); 2453 2454 // Replace uses of the AND with uses of the Zero extend node. 2455 CombineTo(N, Zext); 2456 2457 // We actually want to replace all uses of the any_extend with the 2458 // zero_extend, to avoid duplicating things. This will later cause this 2459 // AND to be folded. 2460 CombineTo(N0.getNode(), Zext); 2461 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2462 } 2463 } 2464 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2465 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2466 // already be zero by virtue of the width of the base type of the load. 2467 // 2468 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2469 // more cases. 2470 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2471 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2472 N0.getOpcode() == ISD::LOAD) { 2473 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2474 N0 : N0.getOperand(0) ); 2475 2476 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2477 // This can be a pure constant or a vector splat, in which case we treat the 2478 // vector as a scalar and use the splat value. 2479 APInt Constant = APInt::getNullValue(1); 2480 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2481 Constant = C->getAPIntValue(); 2482 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2483 APInt SplatValue, SplatUndef; 2484 unsigned SplatBitSize; 2485 bool HasAnyUndefs; 2486 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2487 SplatBitSize, HasAnyUndefs); 2488 if (IsSplat) { 2489 // Undef bits can contribute to a possible optimisation if set, so 2490 // set them. 2491 SplatValue |= SplatUndef; 2492 2493 // The splat value may be something like "0x00FFFFFF", which means 0 for 2494 // the first vector value and FF for the rest, repeating. We need a mask 2495 // that will apply equally to all members of the vector, so AND all the 2496 // lanes of the constant together. 2497 EVT VT = Vector->getValueType(0); 2498 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2499 Constant = APInt::getAllOnesValue(BitWidth); 2500 for (unsigned i = 0, n = VT.getVectorNumElements(); i < n; ++i) 2501 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2502 } 2503 } 2504 2505 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2506 // actually legal and isn't going to get expanded, else this is a false 2507 // optimisation. 2508 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2509 Load->getMemoryVT()); 2510 2511 // Resize the constant to the same size as the original memory access before 2512 // extension. If it is still the AllOnesValue then this AND is completely 2513 // unneeded. 2514 Constant = 2515 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2516 2517 bool B; 2518 switch (Load->getExtensionType()) { 2519 default: B = false; break; 2520 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2521 case ISD::ZEXTLOAD: 2522 case ISD::NON_EXTLOAD: B = true; break; 2523 } 2524 2525 if (B && Constant.isAllOnesValue()) { 2526 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2527 // preserve semantics once we get rid of the AND. 2528 SDValue NewLoad(Load, 0); 2529 if (Load->getExtensionType() == ISD::EXTLOAD) { 2530 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2531 Load->getValueType(0), Load->getDebugLoc(), 2532 Load->getChain(), Load->getBasePtr(), 2533 Load->getOffset(), Load->getMemoryVT(), 2534 Load->getMemOperand()); 2535 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2536 if (Load->getNumValues() == 3) { 2537 // PRE/POST_INC loads have 3 values. 2538 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2539 NewLoad.getValue(2) }; 2540 CombineTo(Load, To, 3, true); 2541 } else { 2542 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2543 } 2544 } 2545 2546 // Fold the AND away, taking care not to fold to the old load node if we 2547 // replaced it. 2548 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2549 2550 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2551 } 2552 } 2553 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2554 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2555 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2556 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2557 2558 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2559 LL.getValueType().isInteger()) { 2560 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2561 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2562 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2563 LR.getValueType(), LL, RL); 2564 AddToWorkList(ORNode.getNode()); 2565 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2566 } 2567 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2568 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2569 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(), 2570 LR.getValueType(), LL, RL); 2571 AddToWorkList(ANDNode.getNode()); 2572 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 2573 } 2574 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2575 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2576 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2577 LR.getValueType(), LL, RL); 2578 AddToWorkList(ORNode.getNode()); 2579 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2580 } 2581 } 2582 // canonicalize equivalent to ll == rl 2583 if (LL == RR && LR == RL) { 2584 Op1 = ISD::getSetCCSwappedOperands(Op1); 2585 std::swap(RL, RR); 2586 } 2587 if (LL == RL && LR == RR) { 2588 bool isInteger = LL.getValueType().isInteger(); 2589 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2590 if (Result != ISD::SETCC_INVALID && 2591 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 2592 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 2593 LL, LR, Result); 2594 } 2595 } 2596 2597 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2598 if (N0.getOpcode() == N1.getOpcode()) { 2599 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2600 if (Tmp.getNode()) return Tmp; 2601 } 2602 2603 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2604 // fold (and (sra)) -> (and (srl)) when possible. 2605 if (!VT.isVector() && 2606 SimplifyDemandedBits(SDValue(N, 0))) 2607 return SDValue(N, 0); 2608 2609 // fold (zext_inreg (extload x)) -> (zextload x) 2610 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2611 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2612 EVT MemVT = LN0->getMemoryVT(); 2613 // If we zero all the possible extended bits, then we can turn this into 2614 // a zextload if we are running before legalize or the operation is legal. 2615 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2616 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2617 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2618 ((!LegalOperations && !LN0->isVolatile()) || 2619 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2620 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2621 LN0->getChain(), LN0->getBasePtr(), 2622 LN0->getPointerInfo(), MemVT, 2623 LN0->isVolatile(), LN0->isNonTemporal(), 2624 LN0->getAlignment()); 2625 AddToWorkList(N); 2626 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2627 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2628 } 2629 } 2630 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2631 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2632 N0.hasOneUse()) { 2633 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2634 EVT MemVT = LN0->getMemoryVT(); 2635 // If we zero all the possible extended bits, then we can turn this into 2636 // a zextload if we are running before legalize or the operation is legal. 2637 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2638 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2639 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2640 ((!LegalOperations && !LN0->isVolatile()) || 2641 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2642 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2643 LN0->getChain(), 2644 LN0->getBasePtr(), LN0->getPointerInfo(), 2645 MemVT, 2646 LN0->isVolatile(), LN0->isNonTemporal(), 2647 LN0->getAlignment()); 2648 AddToWorkList(N); 2649 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2650 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2651 } 2652 } 2653 2654 // fold (and (load x), 255) -> (zextload x, i8) 2655 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2656 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2657 if (N1C && (N0.getOpcode() == ISD::LOAD || 2658 (N0.getOpcode() == ISD::ANY_EXTEND && 2659 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2660 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2661 LoadSDNode *LN0 = HasAnyExt 2662 ? cast<LoadSDNode>(N0.getOperand(0)) 2663 : cast<LoadSDNode>(N0); 2664 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2665 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) { 2666 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2667 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2668 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2669 EVT LoadedVT = LN0->getMemoryVT(); 2670 2671 if (ExtVT == LoadedVT && 2672 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2673 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2674 2675 SDValue NewLoad = 2676 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2677 LN0->getChain(), LN0->getBasePtr(), 2678 LN0->getPointerInfo(), 2679 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2680 LN0->getAlignment()); 2681 AddToWorkList(N); 2682 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2683 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2684 } 2685 2686 // Do not change the width of a volatile load. 2687 // Do not generate loads of non-round integer types since these can 2688 // be expensive (and would be wrong if the type is not byte sized). 2689 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2690 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2691 EVT PtrType = LN0->getOperand(1).getValueType(); 2692 2693 unsigned Alignment = LN0->getAlignment(); 2694 SDValue NewPtr = LN0->getBasePtr(); 2695 2696 // For big endian targets, we need to add an offset to the pointer 2697 // to load the correct bytes. For little endian systems, we merely 2698 // need to read fewer bytes from the same pointer. 2699 if (TLI.isBigEndian()) { 2700 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2701 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2702 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2703 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType, 2704 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2705 Alignment = MinAlign(Alignment, PtrOff); 2706 } 2707 2708 AddToWorkList(NewPtr.getNode()); 2709 2710 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2711 SDValue Load = 2712 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2713 LN0->getChain(), NewPtr, 2714 LN0->getPointerInfo(), 2715 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2716 Alignment); 2717 AddToWorkList(N); 2718 CombineTo(LN0, Load, Load.getValue(1)); 2719 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2720 } 2721 } 2722 } 2723 } 2724 2725 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2726 VT.getSizeInBits() <= 64) { 2727 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2728 APInt ADDC = ADDI->getAPIntValue(); 2729 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2730 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2731 // immediate for an add, but it is legal if its top c2 bits are set, 2732 // transform the ADD so the immediate doesn't need to be materialized 2733 // in a register. 2734 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2735 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2736 SRLI->getZExtValue()); 2737 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2738 ADDC |= Mask; 2739 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2740 SDValue NewAdd = 2741 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, 2742 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2743 CombineTo(N0.getNode(), NewAdd); 2744 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2745 } 2746 } 2747 } 2748 } 2749 } 2750 } 2751 2752 2753 return SDValue(); 2754 } 2755 2756 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2757 /// 2758 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2759 bool DemandHighBits) { 2760 if (!LegalOperations) 2761 return SDValue(); 2762 2763 EVT VT = N->getValueType(0); 2764 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2765 return SDValue(); 2766 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2767 return SDValue(); 2768 2769 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2770 bool LookPassAnd0 = false; 2771 bool LookPassAnd1 = false; 2772 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2773 std::swap(N0, N1); 2774 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2775 std::swap(N0, N1); 2776 if (N0.getOpcode() == ISD::AND) { 2777 if (!N0.getNode()->hasOneUse()) 2778 return SDValue(); 2779 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2780 if (!N01C || N01C->getZExtValue() != 0xFF00) 2781 return SDValue(); 2782 N0 = N0.getOperand(0); 2783 LookPassAnd0 = true; 2784 } 2785 2786 if (N1.getOpcode() == ISD::AND) { 2787 if (!N1.getNode()->hasOneUse()) 2788 return SDValue(); 2789 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2790 if (!N11C || N11C->getZExtValue() != 0xFF) 2791 return SDValue(); 2792 N1 = N1.getOperand(0); 2793 LookPassAnd1 = true; 2794 } 2795 2796 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2797 std::swap(N0, N1); 2798 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2799 return SDValue(); 2800 if (!N0.getNode()->hasOneUse() || 2801 !N1.getNode()->hasOneUse()) 2802 return SDValue(); 2803 2804 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2805 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2806 if (!N01C || !N11C) 2807 return SDValue(); 2808 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 2809 return SDValue(); 2810 2811 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 2812 SDValue N00 = N0->getOperand(0); 2813 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 2814 if (!N00.getNode()->hasOneUse()) 2815 return SDValue(); 2816 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 2817 if (!N001C || N001C->getZExtValue() != 0xFF) 2818 return SDValue(); 2819 N00 = N00.getOperand(0); 2820 LookPassAnd0 = true; 2821 } 2822 2823 SDValue N10 = N1->getOperand(0); 2824 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 2825 if (!N10.getNode()->hasOneUse()) 2826 return SDValue(); 2827 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 2828 if (!N101C || N101C->getZExtValue() != 0xFF00) 2829 return SDValue(); 2830 N10 = N10.getOperand(0); 2831 LookPassAnd1 = true; 2832 } 2833 2834 if (N00 != N10) 2835 return SDValue(); 2836 2837 // Make sure everything beyond the low halfword is zero since the SRL 16 2838 // will clear the top bits. 2839 unsigned OpSizeInBits = VT.getSizeInBits(); 2840 if (DemandHighBits && OpSizeInBits > 16 && 2841 (!LookPassAnd0 || !LookPassAnd1) && 2842 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16))) 2843 return SDValue(); 2844 2845 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00); 2846 if (OpSizeInBits > 16) 2847 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res, 2848 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 2849 return Res; 2850 } 2851 2852 /// isBSwapHWordElement - Return true if the specified node is an element 2853 /// that makes up a 32-bit packed halfword byteswap. i.e. 2854 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 2855 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) { 2856 if (!N.getNode()->hasOneUse()) 2857 return false; 2858 2859 unsigned Opc = N.getOpcode(); 2860 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 2861 return false; 2862 2863 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2864 if (!N1C) 2865 return false; 2866 2867 unsigned Num; 2868 switch (N1C->getZExtValue()) { 2869 default: 2870 return false; 2871 case 0xFF: Num = 0; break; 2872 case 0xFF00: Num = 1; break; 2873 case 0xFF0000: Num = 2; break; 2874 case 0xFF000000: Num = 3; break; 2875 } 2876 2877 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 2878 SDValue N0 = N.getOperand(0); 2879 if (Opc == ISD::AND) { 2880 if (Num == 0 || Num == 2) { 2881 // (x >> 8) & 0xff 2882 // (x >> 8) & 0xff0000 2883 if (N0.getOpcode() != ISD::SRL) 2884 return false; 2885 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2886 if (!C || C->getZExtValue() != 8) 2887 return false; 2888 } else { 2889 // (x << 8) & 0xff00 2890 // (x << 8) & 0xff000000 2891 if (N0.getOpcode() != ISD::SHL) 2892 return false; 2893 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2894 if (!C || C->getZExtValue() != 8) 2895 return false; 2896 } 2897 } else if (Opc == ISD::SHL) { 2898 // (x & 0xff) << 8 2899 // (x & 0xff0000) << 8 2900 if (Num != 0 && Num != 2) 2901 return false; 2902 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2903 if (!C || C->getZExtValue() != 8) 2904 return false; 2905 } else { // Opc == ISD::SRL 2906 // (x & 0xff00) >> 8 2907 // (x & 0xff000000) >> 8 2908 if (Num != 1 && Num != 3) 2909 return false; 2910 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2911 if (!C || C->getZExtValue() != 8) 2912 return false; 2913 } 2914 2915 if (Parts[Num]) 2916 return false; 2917 2918 Parts[Num] = N0.getOperand(0).getNode(); 2919 return true; 2920 } 2921 2922 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 2923 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 2924 /// => (rotl (bswap x), 16) 2925 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 2926 if (!LegalOperations) 2927 return SDValue(); 2928 2929 EVT VT = N->getValueType(0); 2930 if (VT != MVT::i32) 2931 return SDValue(); 2932 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2933 return SDValue(); 2934 2935 SmallVector<SDNode*,4> Parts(4, (SDNode*)0); 2936 // Look for either 2937 // (or (or (and), (and)), (or (and), (and))) 2938 // (or (or (or (and), (and)), (and)), (and)) 2939 if (N0.getOpcode() != ISD::OR) 2940 return SDValue(); 2941 SDValue N00 = N0.getOperand(0); 2942 SDValue N01 = N0.getOperand(1); 2943 2944 if (N1.getOpcode() == ISD::OR) { 2945 // (or (or (and), (and)), (or (and), (and))) 2946 SDValue N000 = N00.getOperand(0); 2947 if (!isBSwapHWordElement(N000, Parts)) 2948 return SDValue(); 2949 2950 SDValue N001 = N00.getOperand(1); 2951 if (!isBSwapHWordElement(N001, Parts)) 2952 return SDValue(); 2953 SDValue N010 = N01.getOperand(0); 2954 if (!isBSwapHWordElement(N010, Parts)) 2955 return SDValue(); 2956 SDValue N011 = N01.getOperand(1); 2957 if (!isBSwapHWordElement(N011, Parts)) 2958 return SDValue(); 2959 } else { 2960 // (or (or (or (and), (and)), (and)), (and)) 2961 if (!isBSwapHWordElement(N1, Parts)) 2962 return SDValue(); 2963 if (!isBSwapHWordElement(N01, Parts)) 2964 return SDValue(); 2965 if (N00.getOpcode() != ISD::OR) 2966 return SDValue(); 2967 SDValue N000 = N00.getOperand(0); 2968 if (!isBSwapHWordElement(N000, Parts)) 2969 return SDValue(); 2970 SDValue N001 = N00.getOperand(1); 2971 if (!isBSwapHWordElement(N001, Parts)) 2972 return SDValue(); 2973 } 2974 2975 // Make sure the parts are all coming from the same node. 2976 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 2977 return SDValue(); 2978 2979 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, 2980 SDValue(Parts[0],0)); 2981 2982 // Result of the bswap should be rotated by 16. If it's not legal, than 2983 // do (x << 16) | (x >> 16). 2984 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 2985 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 2986 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt); 2987 else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 2988 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt); 2989 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, 2990 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt), 2991 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt)); 2992 } 2993 2994 SDValue DAGCombiner::visitOR(SDNode *N) { 2995 SDValue N0 = N->getOperand(0); 2996 SDValue N1 = N->getOperand(1); 2997 SDValue LL, LR, RL, RR, CC0, CC1; 2998 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2999 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3000 EVT VT = N1.getValueType(); 3001 3002 // fold vector ops 3003 if (VT.isVector()) { 3004 SDValue FoldedVOp = SimplifyVBinOp(N); 3005 if (FoldedVOp.getNode()) return FoldedVOp; 3006 } 3007 3008 // fold (or x, undef) -> -1 3009 if (!LegalOperations && 3010 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3011 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3012 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3013 } 3014 // fold (or c1, c2) -> c1|c2 3015 if (N0C && N1C) 3016 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3017 // canonicalize constant to RHS 3018 if (N0C && !N1C) 3019 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0); 3020 // fold (or x, 0) -> x 3021 if (N1C && N1C->isNullValue()) 3022 return N0; 3023 // fold (or x, -1) -> -1 3024 if (N1C && N1C->isAllOnesValue()) 3025 return N1; 3026 // fold (or x, c) -> c iff (x & ~c) == 0 3027 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3028 return N1; 3029 3030 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3031 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3032 if (BSwap.getNode() != 0) 3033 return BSwap; 3034 BSwap = MatchBSwapHWordLow(N, N0, N1); 3035 if (BSwap.getNode() != 0) 3036 return BSwap; 3037 3038 // reassociate or 3039 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1); 3040 if (ROR.getNode() != 0) 3041 return ROR; 3042 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3043 // iff (c1 & c2) == 0. 3044 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3045 isa<ConstantSDNode>(N0.getOperand(1))) { 3046 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3047 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) 3048 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 3049 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 3050 N0.getOperand(0), N1), 3051 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)); 3052 } 3053 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3054 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3055 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3056 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3057 3058 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3059 LL.getValueType().isInteger()) { 3060 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3061 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3062 if (cast<ConstantSDNode>(LR)->isNullValue() && 3063 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3064 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(), 3065 LR.getValueType(), LL, RL); 3066 AddToWorkList(ORNode.getNode()); 3067 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 3068 } 3069 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3070 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3071 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3072 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3073 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(), 3074 LR.getValueType(), LL, RL); 3075 AddToWorkList(ANDNode.getNode()); 3076 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 3077 } 3078 } 3079 // canonicalize equivalent to ll == rl 3080 if (LL == RR && LR == RL) { 3081 Op1 = ISD::getSetCCSwappedOperands(Op1); 3082 std::swap(RL, RR); 3083 } 3084 if (LL == RL && LR == RR) { 3085 bool isInteger = LL.getValueType().isInteger(); 3086 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3087 if (Result != ISD::SETCC_INVALID && 3088 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 3089 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 3090 LL, LR, Result); 3091 } 3092 } 3093 3094 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3095 if (N0.getOpcode() == N1.getOpcode()) { 3096 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3097 if (Tmp.getNode()) return Tmp; 3098 } 3099 3100 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3101 if (N0.getOpcode() == ISD::AND && 3102 N1.getOpcode() == ISD::AND && 3103 N0.getOperand(1).getOpcode() == ISD::Constant && 3104 N1.getOperand(1).getOpcode() == ISD::Constant && 3105 // Don't increase # computations. 3106 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3107 // We can only do this xform if we know that bits from X that are set in C2 3108 // but not in C1 are already zero. Likewise for Y. 3109 const APInt &LHSMask = 3110 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3111 const APInt &RHSMask = 3112 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3113 3114 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3115 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3116 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 3117 N0.getOperand(0), N1.getOperand(0)); 3118 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X, 3119 DAG.getConstant(LHSMask | RHSMask, VT)); 3120 } 3121 } 3122 3123 // See if this is some rotate idiom. 3124 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc())) 3125 return SDValue(Rot, 0); 3126 3127 // Simplify the operands using demanded-bits information. 3128 if (!VT.isVector() && 3129 SimplifyDemandedBits(SDValue(N, 0))) 3130 return SDValue(N, 0); 3131 3132 return SDValue(); 3133 } 3134 3135 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3136 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3137 if (Op.getOpcode() == ISD::AND) { 3138 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3139 Mask = Op.getOperand(1); 3140 Op = Op.getOperand(0); 3141 } else { 3142 return false; 3143 } 3144 } 3145 3146 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3147 Shift = Op; 3148 return true; 3149 } 3150 3151 return false; 3152 } 3153 3154 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3155 // idioms for rotate, and if the target supports rotation instructions, generate 3156 // a rot[lr]. 3157 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) { 3158 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3159 EVT VT = LHS.getValueType(); 3160 if (!TLI.isTypeLegal(VT)) return 0; 3161 3162 // The target must have at least one rotate flavor. 3163 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3164 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3165 if (!HasROTL && !HasROTR) return 0; 3166 3167 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3168 SDValue LHSShift; // The shift. 3169 SDValue LHSMask; // AND value if any. 3170 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3171 return 0; // Not part of a rotate. 3172 3173 SDValue RHSShift; // The shift. 3174 SDValue RHSMask; // AND value if any. 3175 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3176 return 0; // Not part of a rotate. 3177 3178 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3179 return 0; // Not shifting the same value. 3180 3181 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3182 return 0; // Shifts must disagree. 3183 3184 // Canonicalize shl to left side in a shl/srl pair. 3185 if (RHSShift.getOpcode() == ISD::SHL) { 3186 std::swap(LHS, RHS); 3187 std::swap(LHSShift, RHSShift); 3188 std::swap(LHSMask , RHSMask ); 3189 } 3190 3191 unsigned OpSizeInBits = VT.getSizeInBits(); 3192 SDValue LHSShiftArg = LHSShift.getOperand(0); 3193 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3194 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3195 3196 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3197 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3198 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3199 RHSShiftAmt.getOpcode() == ISD::Constant) { 3200 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3201 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3202 if ((LShVal + RShVal) != OpSizeInBits) 3203 return 0; 3204 3205 SDValue Rot; 3206 if (HasROTL) 3207 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt); 3208 else 3209 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt); 3210 3211 // If there is an AND of either shifted operand, apply it to the result. 3212 if (LHSMask.getNode() || RHSMask.getNode()) { 3213 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3214 3215 if (LHSMask.getNode()) { 3216 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3217 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3218 } 3219 if (RHSMask.getNode()) { 3220 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3221 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3222 } 3223 3224 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3225 } 3226 3227 return Rot.getNode(); 3228 } 3229 3230 // If there is a mask here, and we have a variable shift, we can't be sure 3231 // that we're masking out the right stuff. 3232 if (LHSMask.getNode() || RHSMask.getNode()) 3233 return 0; 3234 3235 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y) 3236 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y)) 3237 if (RHSShiftAmt.getOpcode() == ISD::SUB && 3238 LHSShiftAmt == RHSShiftAmt.getOperand(1)) { 3239 if (ConstantSDNode *SUBC = 3240 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) { 3241 if (SUBC->getAPIntValue() == OpSizeInBits) { 3242 if (HasROTL) 3243 return DAG.getNode(ISD::ROTL, DL, VT, 3244 LHSShiftArg, LHSShiftAmt).getNode(); 3245 else 3246 return DAG.getNode(ISD::ROTR, DL, VT, 3247 LHSShiftArg, RHSShiftAmt).getNode(); 3248 } 3249 } 3250 } 3251 3252 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y) 3253 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y)) 3254 if (LHSShiftAmt.getOpcode() == ISD::SUB && 3255 RHSShiftAmt == LHSShiftAmt.getOperand(1)) { 3256 if (ConstantSDNode *SUBC = 3257 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) { 3258 if (SUBC->getAPIntValue() == OpSizeInBits) { 3259 if (HasROTR) 3260 return DAG.getNode(ISD::ROTR, DL, VT, 3261 LHSShiftArg, RHSShiftAmt).getNode(); 3262 else 3263 return DAG.getNode(ISD::ROTL, DL, VT, 3264 LHSShiftArg, LHSShiftAmt).getNode(); 3265 } 3266 } 3267 } 3268 3269 // Look for sign/zext/any-extended or truncate cases: 3270 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 3271 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 3272 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND 3273 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3274 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 3275 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 3276 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND 3277 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3278 SDValue LExtOp0 = LHSShiftAmt.getOperand(0); 3279 SDValue RExtOp0 = RHSShiftAmt.getOperand(0); 3280 if (RExtOp0.getOpcode() == ISD::SUB && 3281 RExtOp0.getOperand(1) == LExtOp0) { 3282 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3283 // (rotl x, y) 3284 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3285 // (rotr x, (sub 32, y)) 3286 if (ConstantSDNode *SUBC = 3287 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) { 3288 if (SUBC->getAPIntValue() == OpSizeInBits) { 3289 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3290 LHSShiftArg, 3291 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 3292 } 3293 } 3294 } else if (LExtOp0.getOpcode() == ISD::SUB && 3295 RExtOp0 == LExtOp0.getOperand(1)) { 3296 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3297 // (rotr x, y) 3298 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3299 // (rotl x, (sub 32, y)) 3300 if (ConstantSDNode *SUBC = 3301 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) { 3302 if (SUBC->getAPIntValue() == OpSizeInBits) { 3303 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, 3304 LHSShiftArg, 3305 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 3306 } 3307 } 3308 } 3309 } 3310 3311 return 0; 3312 } 3313 3314 SDValue DAGCombiner::visitXOR(SDNode *N) { 3315 SDValue N0 = N->getOperand(0); 3316 SDValue N1 = N->getOperand(1); 3317 SDValue LHS, RHS, CC; 3318 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3320 EVT VT = N0.getValueType(); 3321 3322 // fold vector ops 3323 if (VT.isVector()) { 3324 SDValue FoldedVOp = SimplifyVBinOp(N); 3325 if (FoldedVOp.getNode()) return FoldedVOp; 3326 } 3327 3328 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3329 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3330 return DAG.getConstant(0, VT); 3331 // fold (xor x, undef) -> undef 3332 if (N0.getOpcode() == ISD::UNDEF) 3333 return N0; 3334 if (N1.getOpcode() == ISD::UNDEF) 3335 return N1; 3336 // fold (xor c1, c2) -> c1^c2 3337 if (N0C && N1C) 3338 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3339 // canonicalize constant to RHS 3340 if (N0C && !N1C) 3341 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 3342 // fold (xor x, 0) -> x 3343 if (N1C && N1C->isNullValue()) 3344 return N0; 3345 // reassociate xor 3346 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1); 3347 if (RXOR.getNode() != 0) 3348 return RXOR; 3349 3350 // fold !(x cc y) -> (x !cc y) 3351 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3352 bool isInt = LHS.getValueType().isInteger(); 3353 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3354 isInt); 3355 3356 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) { 3357 switch (N0.getOpcode()) { 3358 default: 3359 llvm_unreachable("Unhandled SetCC Equivalent!"); 3360 case ISD::SETCC: 3361 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC); 3362 case ISD::SELECT_CC: 3363 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2), 3364 N0.getOperand(3), NotCC); 3365 } 3366 } 3367 } 3368 3369 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3370 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3371 N0.getNode()->hasOneUse() && 3372 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3373 SDValue V = N0.getOperand(0); 3374 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V, 3375 DAG.getConstant(1, V.getValueType())); 3376 AddToWorkList(V.getNode()); 3377 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V); 3378 } 3379 3380 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3381 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3382 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3383 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3384 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3385 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3386 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 3387 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 3388 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3389 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 3390 } 3391 } 3392 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3393 if (N1C && N1C->isAllOnesValue() && 3394 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3395 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3396 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3397 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3398 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 3399 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 3400 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3401 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 3402 } 3403 } 3404 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3405 if (N1C && N0.getOpcode() == ISD::XOR) { 3406 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3407 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3408 if (N00C) 3409 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1), 3410 DAG.getConstant(N1C->getAPIntValue() ^ 3411 N00C->getAPIntValue(), VT)); 3412 if (N01C) 3413 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0), 3414 DAG.getConstant(N1C->getAPIntValue() ^ 3415 N01C->getAPIntValue(), VT)); 3416 } 3417 // fold (xor x, x) -> 0 3418 if (N0 == N1) 3419 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations); 3420 3421 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3422 if (N0.getOpcode() == N1.getOpcode()) { 3423 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3424 if (Tmp.getNode()) return Tmp; 3425 } 3426 3427 // Simplify the expression using non-local knowledge. 3428 if (!VT.isVector() && 3429 SimplifyDemandedBits(SDValue(N, 0))) 3430 return SDValue(N, 0); 3431 3432 return SDValue(); 3433 } 3434 3435 /// visitShiftByConstant - Handle transforms common to the three shifts, when 3436 /// the shift amount is a constant. 3437 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 3438 SDNode *LHS = N->getOperand(0).getNode(); 3439 if (!LHS->hasOneUse()) return SDValue(); 3440 3441 // We want to pull some binops through shifts, so that we have (and (shift)) 3442 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3443 // thing happens with address calculations, so it's important to canonicalize 3444 // it. 3445 bool HighBitSet = false; // Can we transform this if the high bit is set? 3446 3447 switch (LHS->getOpcode()) { 3448 default: return SDValue(); 3449 case ISD::OR: 3450 case ISD::XOR: 3451 HighBitSet = false; // We can only transform sra if the high bit is clear. 3452 break; 3453 case ISD::AND: 3454 HighBitSet = true; // We can only transform sra if the high bit is set. 3455 break; 3456 case ISD::ADD: 3457 if (N->getOpcode() != ISD::SHL) 3458 return SDValue(); // only shl(add) not sr[al](add). 3459 HighBitSet = false; // We can only transform sra if the high bit is clear. 3460 break; 3461 } 3462 3463 // We require the RHS of the binop to be a constant as well. 3464 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3465 if (!BinOpCst) return SDValue(); 3466 3467 // FIXME: disable this unless the input to the binop is a shift by a constant. 3468 // If it is not a shift, it pessimizes some common cases like: 3469 // 3470 // void foo(int *X, int i) { X[i & 1235] = 1; } 3471 // int bar(int *X, int i) { return X[i & 255]; } 3472 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3473 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3474 BinOpLHSVal->getOpcode() != ISD::SRA && 3475 BinOpLHSVal->getOpcode() != ISD::SRL) || 3476 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3477 return SDValue(); 3478 3479 EVT VT = N->getValueType(0); 3480 3481 // If this is a signed shift right, and the high bit is modified by the 3482 // logical operation, do not perform the transformation. The highBitSet 3483 // boolean indicates the value of the high bit of the constant which would 3484 // cause it to be modified for this operation. 3485 if (N->getOpcode() == ISD::SRA) { 3486 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3487 if (BinOpRHSSignSet != HighBitSet) 3488 return SDValue(); 3489 } 3490 3491 // Fold the constants, shifting the binop RHS by the shift amount. 3492 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(), 3493 N->getValueType(0), 3494 LHS->getOperand(1), N->getOperand(1)); 3495 3496 // Create the new shift. 3497 SDValue NewShift = DAG.getNode(N->getOpcode(), 3498 LHS->getOperand(0).getDebugLoc(), 3499 VT, LHS->getOperand(0), N->getOperand(1)); 3500 3501 // Create the new binop. 3502 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS); 3503 } 3504 3505 SDValue DAGCombiner::visitSHL(SDNode *N) { 3506 SDValue N0 = N->getOperand(0); 3507 SDValue N1 = N->getOperand(1); 3508 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3509 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3510 EVT VT = N0.getValueType(); 3511 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3512 3513 // fold (shl c1, c2) -> c1<<c2 3514 if (N0C && N1C) 3515 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3516 // fold (shl 0, x) -> 0 3517 if (N0C && N0C->isNullValue()) 3518 return N0; 3519 // fold (shl x, c >= size(x)) -> undef 3520 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3521 return DAG.getUNDEF(VT); 3522 // fold (shl x, 0) -> x 3523 if (N1C && N1C->isNullValue()) 3524 return N0; 3525 // fold (shl undef, x) -> 0 3526 if (N0.getOpcode() == ISD::UNDEF) 3527 return DAG.getConstant(0, VT); 3528 // if (shl x, c) is known to be zero, return 0 3529 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3530 APInt::getAllOnesValue(OpSizeInBits))) 3531 return DAG.getConstant(0, VT); 3532 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3533 if (N1.getOpcode() == ISD::TRUNCATE && 3534 N1.getOperand(0).getOpcode() == ISD::AND && 3535 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3536 SDValue N101 = N1.getOperand(0).getOperand(1); 3537 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3538 EVT TruncVT = N1.getValueType(); 3539 SDValue N100 = N1.getOperand(0).getOperand(0); 3540 APInt TruncC = N101C->getAPIntValue(); 3541 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3542 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 3543 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT, 3544 DAG.getNode(ISD::TRUNCATE, 3545 N->getDebugLoc(), 3546 TruncVT, N100), 3547 DAG.getConstant(TruncC, TruncVT))); 3548 } 3549 } 3550 3551 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3552 return SDValue(N, 0); 3553 3554 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3555 if (N1C && N0.getOpcode() == ISD::SHL && 3556 N0.getOperand(1).getOpcode() == ISD::Constant) { 3557 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3558 uint64_t c2 = N1C->getZExtValue(); 3559 if (c1 + c2 >= OpSizeInBits) 3560 return DAG.getConstant(0, VT); 3561 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0), 3562 DAG.getConstant(c1 + c2, N1.getValueType())); 3563 } 3564 3565 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3566 // For this to be valid, the second form must not preserve any of the bits 3567 // that are shifted out by the inner shift in the first form. This means 3568 // the outer shift size must be >= the number of bits added by the ext. 3569 // As a corollary, we don't care what kind of ext it is. 3570 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3571 N0.getOpcode() == ISD::ANY_EXTEND || 3572 N0.getOpcode() == ISD::SIGN_EXTEND) && 3573 N0.getOperand(0).getOpcode() == ISD::SHL && 3574 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3575 uint64_t c1 = 3576 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3577 uint64_t c2 = N1C->getZExtValue(); 3578 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3579 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3580 if (c2 >= OpSizeInBits - InnerShiftSize) { 3581 if (c1 + c2 >= OpSizeInBits) 3582 return DAG.getConstant(0, VT); 3583 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT, 3584 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT, 3585 N0.getOperand(0)->getOperand(0)), 3586 DAG.getConstant(c1 + c2, N1.getValueType())); 3587 } 3588 } 3589 3590 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 3591 // (and (srl x, (sub c1, c2), MASK) 3592 // Only fold this if the inner shift has no other uses -- if it does, folding 3593 // this will increase the total number of instructions. 3594 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 3595 N0.getOperand(1).getOpcode() == ISD::Constant) { 3596 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3597 if (c1 < VT.getSizeInBits()) { 3598 uint64_t c2 = N1C->getZExtValue(); 3599 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3600 VT.getSizeInBits() - c1); 3601 SDValue Shift; 3602 if (c2 > c1) { 3603 Mask = Mask.shl(c2-c1); 3604 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0), 3605 DAG.getConstant(c2-c1, N1.getValueType())); 3606 } else { 3607 Mask = Mask.lshr(c1-c2); 3608 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), 3609 DAG.getConstant(c1-c2, N1.getValueType())); 3610 } 3611 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift, 3612 DAG.getConstant(Mask, VT)); 3613 } 3614 } 3615 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 3616 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 3617 SDValue HiBitsMask = 3618 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 3619 VT.getSizeInBits() - 3620 N1C->getZExtValue()), 3621 VT); 3622 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 3623 HiBitsMask); 3624 } 3625 3626 if (N1C) { 3627 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 3628 if (NewSHL.getNode()) 3629 return NewSHL; 3630 } 3631 3632 return SDValue(); 3633 } 3634 3635 SDValue DAGCombiner::visitSRA(SDNode *N) { 3636 SDValue N0 = N->getOperand(0); 3637 SDValue N1 = N->getOperand(1); 3638 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3639 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3640 EVT VT = N0.getValueType(); 3641 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3642 3643 // fold (sra c1, c2) -> (sra c1, c2) 3644 if (N0C && N1C) 3645 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 3646 // fold (sra 0, x) -> 0 3647 if (N0C && N0C->isNullValue()) 3648 return N0; 3649 // fold (sra -1, x) -> -1 3650 if (N0C && N0C->isAllOnesValue()) 3651 return N0; 3652 // fold (sra x, (setge c, size(x))) -> undef 3653 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3654 return DAG.getUNDEF(VT); 3655 // fold (sra x, 0) -> x 3656 if (N1C && N1C->isNullValue()) 3657 return N0; 3658 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 3659 // sext_inreg. 3660 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 3661 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 3662 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 3663 if (VT.isVector()) 3664 ExtVT = EVT::getVectorVT(*DAG.getContext(), 3665 ExtVT, VT.getVectorNumElements()); 3666 if ((!LegalOperations || 3667 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 3668 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 3669 N0.getOperand(0), DAG.getValueType(ExtVT)); 3670 } 3671 3672 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 3673 if (N1C && N0.getOpcode() == ISD::SRA) { 3674 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3675 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 3676 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 3677 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0), 3678 DAG.getConstant(Sum, N1C->getValueType(0))); 3679 } 3680 } 3681 3682 // fold (sra (shl X, m), (sub result_size, n)) 3683 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 3684 // result_size - n != m. 3685 // If truncate is free for the target sext(shl) is likely to result in better 3686 // code. 3687 if (N0.getOpcode() == ISD::SHL) { 3688 // Get the two constanst of the shifts, CN0 = m, CN = n. 3689 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3690 if (N01C && N1C) { 3691 // Determine what the truncate's result bitsize and type would be. 3692 EVT TruncVT = 3693 EVT::getIntegerVT(*DAG.getContext(), 3694 OpSizeInBits - N1C->getZExtValue()); 3695 // Determine the residual right-shift amount. 3696 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 3697 3698 // If the shift is not a no-op (in which case this should be just a sign 3699 // extend already), the truncated to type is legal, sign_extend is legal 3700 // on that type, and the truncate to that type is both legal and free, 3701 // perform the transform. 3702 if ((ShiftAmt > 0) && 3703 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 3704 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 3705 TLI.isTruncateFree(VT, TruncVT)) { 3706 3707 SDValue Amt = DAG.getConstant(ShiftAmt, 3708 getShiftAmountTy(N0.getOperand(0).getValueType())); 3709 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, 3710 N0.getOperand(0), Amt); 3711 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT, 3712 Shift); 3713 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), 3714 N->getValueType(0), Trunc); 3715 } 3716 } 3717 } 3718 3719 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 3720 if (N1.getOpcode() == ISD::TRUNCATE && 3721 N1.getOperand(0).getOpcode() == ISD::AND && 3722 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3723 SDValue N101 = N1.getOperand(0).getOperand(1); 3724 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3725 EVT TruncVT = N1.getValueType(); 3726 SDValue N100 = N1.getOperand(0).getOperand(0); 3727 APInt TruncC = N101C->getAPIntValue(); 3728 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 3729 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 3730 DAG.getNode(ISD::AND, N->getDebugLoc(), 3731 TruncVT, 3732 DAG.getNode(ISD::TRUNCATE, 3733 N->getDebugLoc(), 3734 TruncVT, N100), 3735 DAG.getConstant(TruncC, TruncVT))); 3736 } 3737 } 3738 3739 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2)) 3740 // if c1 is equal to the number of bits the trunc removes 3741 if (N0.getOpcode() == ISD::TRUNCATE && 3742 (N0.getOperand(0).getOpcode() == ISD::SRL || 3743 N0.getOperand(0).getOpcode() == ISD::SRA) && 3744 N0.getOperand(0).hasOneUse() && 3745 N0.getOperand(0).getOperand(1).hasOneUse() && 3746 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 3747 EVT LargeVT = N0.getOperand(0).getValueType(); 3748 ConstantSDNode *LargeShiftAmt = 3749 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1)); 3750 3751 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits == 3752 LargeShiftAmt->getZExtValue()) { 3753 SDValue Amt = 3754 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(), 3755 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType())); 3756 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT, 3757 N0.getOperand(0).getOperand(0), Amt); 3758 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA); 3759 } 3760 } 3761 3762 // Simplify, based on bits shifted out of the LHS. 3763 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3764 return SDValue(N, 0); 3765 3766 3767 // If the sign bit is known to be zero, switch this to a SRL. 3768 if (DAG.SignBitIsZero(N0)) 3769 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1); 3770 3771 if (N1C) { 3772 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 3773 if (NewSRA.getNode()) 3774 return NewSRA; 3775 } 3776 3777 return SDValue(); 3778 } 3779 3780 SDValue DAGCombiner::visitSRL(SDNode *N) { 3781 SDValue N0 = N->getOperand(0); 3782 SDValue N1 = N->getOperand(1); 3783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3785 EVT VT = N0.getValueType(); 3786 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3787 3788 // fold (srl c1, c2) -> c1 >>u c2 3789 if (N0C && N1C) 3790 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 3791 // fold (srl 0, x) -> 0 3792 if (N0C && N0C->isNullValue()) 3793 return N0; 3794 // fold (srl x, c >= size(x)) -> undef 3795 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3796 return DAG.getUNDEF(VT); 3797 // fold (srl x, 0) -> x 3798 if (N1C && N1C->isNullValue()) 3799 return N0; 3800 // if (srl x, c) is known to be zero, return 0 3801 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3802 APInt::getAllOnesValue(OpSizeInBits))) 3803 return DAG.getConstant(0, VT); 3804 3805 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 3806 if (N1C && N0.getOpcode() == ISD::SRL && 3807 N0.getOperand(1).getOpcode() == ISD::Constant) { 3808 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3809 uint64_t c2 = N1C->getZExtValue(); 3810 if (c1 + c2 >= OpSizeInBits) 3811 return DAG.getConstant(0, VT); 3812 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), 3813 DAG.getConstant(c1 + c2, N1.getValueType())); 3814 } 3815 3816 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 3817 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 3818 N0.getOperand(0).getOpcode() == ISD::SRL && 3819 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3820 uint64_t c1 = 3821 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3822 uint64_t c2 = N1C->getZExtValue(); 3823 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3824 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 3825 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3826 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 3827 if (c1 + OpSizeInBits == InnerShiftSize) { 3828 if (c1 + c2 >= InnerShiftSize) 3829 return DAG.getConstant(0, VT); 3830 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT, 3831 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT, 3832 N0.getOperand(0)->getOperand(0), 3833 DAG.getConstant(c1 + c2, ShiftCountVT))); 3834 } 3835 } 3836 3837 // fold (srl (shl x, c), c) -> (and x, cst2) 3838 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 3839 N0.getValueSizeInBits() <= 64) { 3840 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 3841 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 3842 DAG.getConstant(~0ULL >> ShAmt, VT)); 3843 } 3844 3845 3846 // fold (srl (anyextend x), c) -> (anyextend (srl x, c)) 3847 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3848 // Shifting in all undef bits? 3849 EVT SmallVT = N0.getOperand(0).getValueType(); 3850 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 3851 return DAG.getUNDEF(VT); 3852 3853 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 3854 uint64_t ShiftAmt = N1C->getZExtValue(); 3855 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT, 3856 N0.getOperand(0), 3857 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 3858 AddToWorkList(SmallShift.getNode()); 3859 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift); 3860 } 3861 } 3862 3863 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 3864 // bit, which is unmodified by sra. 3865 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 3866 if (N0.getOpcode() == ISD::SRA) 3867 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1); 3868 } 3869 3870 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 3871 if (N1C && N0.getOpcode() == ISD::CTLZ && 3872 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 3873 APInt KnownZero, KnownOne; 3874 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 3875 3876 // If any of the input bits are KnownOne, then the input couldn't be all 3877 // zeros, thus the result of the srl will always be zero. 3878 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 3879 3880 // If all of the bits input the to ctlz node are known to be zero, then 3881 // the result of the ctlz is "32" and the result of the shift is one. 3882 APInt UnknownBits = ~KnownZero; 3883 if (UnknownBits == 0) return DAG.getConstant(1, VT); 3884 3885 // Otherwise, check to see if there is exactly one bit input to the ctlz. 3886 if ((UnknownBits & (UnknownBits - 1)) == 0) { 3887 // Okay, we know that only that the single bit specified by UnknownBits 3888 // could be set on input to the CTLZ node. If this bit is set, the SRL 3889 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 3890 // to an SRL/XOR pair, which is likely to simplify more. 3891 unsigned ShAmt = UnknownBits.countTrailingZeros(); 3892 SDValue Op = N0.getOperand(0); 3893 3894 if (ShAmt) { 3895 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op, 3896 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 3897 AddToWorkList(Op.getNode()); 3898 } 3899 3900 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 3901 Op, DAG.getConstant(1, VT)); 3902 } 3903 } 3904 3905 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 3906 if (N1.getOpcode() == ISD::TRUNCATE && 3907 N1.getOperand(0).getOpcode() == ISD::AND && 3908 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3909 SDValue N101 = N1.getOperand(0).getOperand(1); 3910 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3911 EVT TruncVT = N1.getValueType(); 3912 SDValue N100 = N1.getOperand(0).getOperand(0); 3913 APInt TruncC = N101C->getAPIntValue(); 3914 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3915 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 3916 DAG.getNode(ISD::AND, N->getDebugLoc(), 3917 TruncVT, 3918 DAG.getNode(ISD::TRUNCATE, 3919 N->getDebugLoc(), 3920 TruncVT, N100), 3921 DAG.getConstant(TruncC, TruncVT))); 3922 } 3923 } 3924 3925 // fold operands of srl based on knowledge that the low bits are not 3926 // demanded. 3927 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3928 return SDValue(N, 0); 3929 3930 if (N1C) { 3931 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 3932 if (NewSRL.getNode()) 3933 return NewSRL; 3934 } 3935 3936 // Attempt to convert a srl of a load into a narrower zero-extending load. 3937 SDValue NarrowLoad = ReduceLoadWidth(N); 3938 if (NarrowLoad.getNode()) 3939 return NarrowLoad; 3940 3941 // Here is a common situation. We want to optimize: 3942 // 3943 // %a = ... 3944 // %b = and i32 %a, 2 3945 // %c = srl i32 %b, 1 3946 // brcond i32 %c ... 3947 // 3948 // into 3949 // 3950 // %a = ... 3951 // %b = and %a, 2 3952 // %c = setcc eq %b, 0 3953 // brcond %c ... 3954 // 3955 // However when after the source operand of SRL is optimized into AND, the SRL 3956 // itself may not be optimized further. Look for it and add the BRCOND into 3957 // the worklist. 3958 if (N->hasOneUse()) { 3959 SDNode *Use = *N->use_begin(); 3960 if (Use->getOpcode() == ISD::BRCOND) 3961 AddToWorkList(Use); 3962 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 3963 // Also look pass the truncate. 3964 Use = *Use->use_begin(); 3965 if (Use->getOpcode() == ISD::BRCOND) 3966 AddToWorkList(Use); 3967 } 3968 } 3969 3970 return SDValue(); 3971 } 3972 3973 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 3974 SDValue N0 = N->getOperand(0); 3975 EVT VT = N->getValueType(0); 3976 3977 // fold (ctlz c1) -> c2 3978 if (isa<ConstantSDNode>(N0)) 3979 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0); 3980 return SDValue(); 3981 } 3982 3983 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 3984 SDValue N0 = N->getOperand(0); 3985 EVT VT = N->getValueType(0); 3986 3987 // fold (ctlz_zero_undef c1) -> c2 3988 if (isa<ConstantSDNode>(N0)) 3989 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0); 3990 return SDValue(); 3991 } 3992 3993 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 3994 SDValue N0 = N->getOperand(0); 3995 EVT VT = N->getValueType(0); 3996 3997 // fold (cttz c1) -> c2 3998 if (isa<ConstantSDNode>(N0)) 3999 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0); 4000 return SDValue(); 4001 } 4002 4003 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4004 SDValue N0 = N->getOperand(0); 4005 EVT VT = N->getValueType(0); 4006 4007 // fold (cttz_zero_undef c1) -> c2 4008 if (isa<ConstantSDNode>(N0)) 4009 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0); 4010 return SDValue(); 4011 } 4012 4013 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4014 SDValue N0 = N->getOperand(0); 4015 EVT VT = N->getValueType(0); 4016 4017 // fold (ctpop c1) -> c2 4018 if (isa<ConstantSDNode>(N0)) 4019 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0); 4020 return SDValue(); 4021 } 4022 4023 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4024 SDValue N0 = N->getOperand(0); 4025 SDValue N1 = N->getOperand(1); 4026 SDValue N2 = N->getOperand(2); 4027 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4028 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4029 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4030 EVT VT = N->getValueType(0); 4031 EVT VT0 = N0.getValueType(); 4032 4033 // fold (select C, X, X) -> X 4034 if (N1 == N2) 4035 return N1; 4036 // fold (select true, X, Y) -> X 4037 if (N0C && !N0C->isNullValue()) 4038 return N1; 4039 // fold (select false, X, Y) -> Y 4040 if (N0C && N0C->isNullValue()) 4041 return N2; 4042 // fold (select C, 1, X) -> (or C, X) 4043 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4044 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 4045 // fold (select C, 0, 1) -> (xor C, 1) 4046 if (VT.isInteger() && 4047 (VT0 == MVT::i1 || 4048 (VT0.isInteger() && 4049 TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) && 4050 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4051 SDValue XORNode; 4052 if (VT == VT0) 4053 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0, 4054 N0, DAG.getConstant(1, VT0)); 4055 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0, 4056 N0, DAG.getConstant(1, VT0)); 4057 AddToWorkList(XORNode.getNode()); 4058 if (VT.bitsGT(VT0)) 4059 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode); 4060 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode); 4061 } 4062 // fold (select C, 0, X) -> (and (not C), X) 4063 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4064 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 4065 AddToWorkList(NOTNode.getNode()); 4066 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2); 4067 } 4068 // fold (select C, X, 1) -> (or (not C), X) 4069 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4070 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 4071 AddToWorkList(NOTNode.getNode()); 4072 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1); 4073 } 4074 // fold (select C, X, 0) -> (and C, X) 4075 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4076 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 4077 // fold (select X, X, Y) -> (or X, Y) 4078 // fold (select X, 1, Y) -> (or X, Y) 4079 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4080 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 4081 // fold (select X, Y, X) -> (and X, Y) 4082 // fold (select X, Y, 0) -> (and X, Y) 4083 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4084 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 4085 4086 // If we can fold this based on the true/false value, do so. 4087 if (SimplifySelectOps(N, N1, N2)) 4088 return SDValue(N, 0); // Don't revisit N. 4089 4090 // fold selects based on a setcc into other things, such as min/max/abs 4091 if (N0.getOpcode() == ISD::SETCC) { 4092 // FIXME: 4093 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4094 // having to say they don't support SELECT_CC on every type the DAG knows 4095 // about, since there is no way to mark an opcode illegal at all value types 4096 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4097 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4098 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, 4099 N0.getOperand(0), N0.getOperand(1), 4100 N1, N2, N0.getOperand(2)); 4101 return SimplifySelect(N->getDebugLoc(), N0, N1, N2); 4102 } 4103 4104 return SDValue(); 4105 } 4106 4107 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4108 SDValue N0 = N->getOperand(0); 4109 SDValue N1 = N->getOperand(1); 4110 SDValue N2 = N->getOperand(2); 4111 SDValue N3 = N->getOperand(3); 4112 SDValue N4 = N->getOperand(4); 4113 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4114 4115 // fold select_cc lhs, rhs, x, x, cc -> x 4116 if (N2 == N3) 4117 return N2; 4118 4119 // Determine if the condition we're dealing with is constant 4120 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 4121 N0, N1, CC, N->getDebugLoc(), false); 4122 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 4123 4124 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 4125 if (!SCCC->isNullValue()) 4126 return N2; // cond always true -> true val 4127 else 4128 return N3; // cond always false -> false val 4129 } 4130 4131 // Fold to a simpler select_cc 4132 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC) 4133 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(), 4134 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4135 SCC.getOperand(2)); 4136 4137 // If we can fold this based on the true/false value, do so. 4138 if (SimplifySelectOps(N, N2, N3)) 4139 return SDValue(N, 0); // Don't revisit N. 4140 4141 // fold select_cc into other things, such as min/max/abs 4142 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC); 4143 } 4144 4145 SDValue DAGCombiner::visitSETCC(SDNode *N) { 4146 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4147 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4148 N->getDebugLoc()); 4149 } 4150 4151 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4152 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4153 // transformation. Returns true if extension are possible and the above 4154 // mentioned transformation is profitable. 4155 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4156 unsigned ExtOpc, 4157 SmallVector<SDNode*, 4> &ExtendNodes, 4158 const TargetLowering &TLI) { 4159 bool HasCopyToRegUses = false; 4160 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4161 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4162 UE = N0.getNode()->use_end(); 4163 UI != UE; ++UI) { 4164 SDNode *User = *UI; 4165 if (User == N) 4166 continue; 4167 if (UI.getUse().getResNo() != N0.getResNo()) 4168 continue; 4169 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4170 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4171 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4172 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4173 // Sign bits will be lost after a zext. 4174 return false; 4175 bool Add = false; 4176 for (unsigned i = 0; i != 2; ++i) { 4177 SDValue UseOp = User->getOperand(i); 4178 if (UseOp == N0) 4179 continue; 4180 if (!isa<ConstantSDNode>(UseOp)) 4181 return false; 4182 Add = true; 4183 } 4184 if (Add) 4185 ExtendNodes.push_back(User); 4186 continue; 4187 } 4188 // If truncates aren't free and there are users we can't 4189 // extend, it isn't worthwhile. 4190 if (!isTruncFree) 4191 return false; 4192 // Remember if this value is live-out. 4193 if (User->getOpcode() == ISD::CopyToReg) 4194 HasCopyToRegUses = true; 4195 } 4196 4197 if (HasCopyToRegUses) { 4198 bool BothLiveOut = false; 4199 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4200 UI != UE; ++UI) { 4201 SDUse &Use = UI.getUse(); 4202 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4203 BothLiveOut = true; 4204 break; 4205 } 4206 } 4207 if (BothLiveOut) 4208 // Both unextended and extended values are live out. There had better be 4209 // a good reason for the transformation. 4210 return ExtendNodes.size(); 4211 } 4212 return true; 4213 } 4214 4215 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs, 4216 SDValue Trunc, SDValue ExtLoad, DebugLoc DL, 4217 ISD::NodeType ExtType) { 4218 // Extend SetCC uses if necessary. 4219 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4220 SDNode *SetCC = SetCCs[i]; 4221 SmallVector<SDValue, 4> Ops; 4222 4223 for (unsigned j = 0; j != 2; ++j) { 4224 SDValue SOp = SetCC->getOperand(j); 4225 if (SOp == Trunc) 4226 Ops.push_back(ExtLoad); 4227 else 4228 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4229 } 4230 4231 Ops.push_back(SetCC->getOperand(2)); 4232 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4233 &Ops[0], Ops.size())); 4234 } 4235 } 4236 4237 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4238 SDValue N0 = N->getOperand(0); 4239 EVT VT = N->getValueType(0); 4240 4241 // fold (sext c1) -> c1 4242 if (isa<ConstantSDNode>(N0)) 4243 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0); 4244 4245 // fold (sext (sext x)) -> (sext x) 4246 // fold (sext (aext x)) -> (sext x) 4247 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4248 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, 4249 N0.getOperand(0)); 4250 4251 if (N0.getOpcode() == ISD::TRUNCATE) { 4252 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4253 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4254 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4255 if (NarrowLoad.getNode()) { 4256 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4257 if (NarrowLoad.getNode() != N0.getNode()) { 4258 CombineTo(N0.getNode(), NarrowLoad); 4259 // CombineTo deleted the truncate, if needed, but not what's under it. 4260 AddToWorkList(oye); 4261 } 4262 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4263 } 4264 4265 // See if the value being truncated is already sign extended. If so, just 4266 // eliminate the trunc/sext pair. 4267 SDValue Op = N0.getOperand(0); 4268 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4269 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4270 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4271 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4272 4273 if (OpBits == DestBits) { 4274 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4275 // bits, it is already ready. 4276 if (NumSignBits > DestBits-MidBits) 4277 return Op; 4278 } else if (OpBits < DestBits) { 4279 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4280 // bits, just sext from i32. 4281 if (NumSignBits > OpBits-MidBits) 4282 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op); 4283 } else { 4284 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4285 // bits, just truncate to i32. 4286 if (NumSignBits > OpBits-MidBits) 4287 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4288 } 4289 4290 // fold (sext (truncate x)) -> (sextinreg x). 4291 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4292 N0.getValueType())) { 4293 if (OpBits < DestBits) 4294 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op); 4295 else if (OpBits > DestBits) 4296 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op); 4297 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op, 4298 DAG.getValueType(N0.getValueType())); 4299 } 4300 } 4301 4302 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4303 // None of the supported targets knows how to perform load and sign extend 4304 // on vectors in one instruction. We only perform this transformation on 4305 // scalars. 4306 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4307 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4308 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4309 bool DoXform = true; 4310 SmallVector<SDNode*, 4> SetCCs; 4311 if (!N0.hasOneUse()) 4312 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4313 if (DoXform) { 4314 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4315 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4316 LN0->getChain(), 4317 LN0->getBasePtr(), LN0->getPointerInfo(), 4318 N0.getValueType(), 4319 LN0->isVolatile(), LN0->isNonTemporal(), 4320 LN0->getAlignment()); 4321 CombineTo(N, ExtLoad); 4322 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4323 N0.getValueType(), ExtLoad); 4324 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4325 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4326 ISD::SIGN_EXTEND); 4327 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4328 } 4329 } 4330 4331 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4332 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4333 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4334 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4335 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4336 EVT MemVT = LN0->getMemoryVT(); 4337 if ((!LegalOperations && !LN0->isVolatile()) || 4338 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4339 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4340 LN0->getChain(), 4341 LN0->getBasePtr(), LN0->getPointerInfo(), 4342 MemVT, 4343 LN0->isVolatile(), LN0->isNonTemporal(), 4344 LN0->getAlignment()); 4345 CombineTo(N, ExtLoad); 4346 CombineTo(N0.getNode(), 4347 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4348 N0.getValueType(), ExtLoad), 4349 ExtLoad.getValue(1)); 4350 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4351 } 4352 } 4353 4354 // fold (sext (and/or/xor (load x), cst)) -> 4355 // (and/or/xor (sextload x), (sext cst)) 4356 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4357 N0.getOpcode() == ISD::XOR) && 4358 isa<LoadSDNode>(N0.getOperand(0)) && 4359 N0.getOperand(1).getOpcode() == ISD::Constant && 4360 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4361 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4362 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4363 if (LN0->getExtensionType() != ISD::ZEXTLOAD) { 4364 bool DoXform = true; 4365 SmallVector<SDNode*, 4> SetCCs; 4366 if (!N0.hasOneUse()) 4367 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4368 SetCCs, TLI); 4369 if (DoXform) { 4370 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT, 4371 LN0->getChain(), LN0->getBasePtr(), 4372 LN0->getPointerInfo(), 4373 LN0->getMemoryVT(), 4374 LN0->isVolatile(), 4375 LN0->isNonTemporal(), 4376 LN0->getAlignment()); 4377 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4378 Mask = Mask.sext(VT.getSizeInBits()); 4379 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 4380 ExtLoad, DAG.getConstant(Mask, VT)); 4381 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4382 N0.getOperand(0).getDebugLoc(), 4383 N0.getOperand(0).getValueType(), ExtLoad); 4384 CombineTo(N, And); 4385 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4386 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4387 ISD::SIGN_EXTEND); 4388 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4389 } 4390 } 4391 } 4392 4393 if (N0.getOpcode() == ISD::SETCC) { 4394 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4395 // Only do this before legalize for now. 4396 if (VT.isVector() && !LegalOperations) { 4397 EVT N0VT = N0.getOperand(0).getValueType(); 4398 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 4399 // of the same size as the compared operands. Only optimize sext(setcc()) 4400 // if this is the case. 4401 EVT SVT = TLI.getSetCCResultType(N0VT); 4402 4403 // We know that the # elements of the results is the same as the 4404 // # elements of the compare (and the # elements of the compare result 4405 // for that matter). Check to see that they are the same size. If so, 4406 // we know that the element size of the sext'd result matches the 4407 // element size of the compare operands. 4408 if (VT.getSizeInBits() == SVT.getSizeInBits()) 4409 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4410 N0.getOperand(1), 4411 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4412 // If the desired elements are smaller or larger than the source 4413 // elements we can use a matching integer vector type and then 4414 // truncate/sign extend 4415 else { 4416 EVT MatchingElementType = 4417 EVT::getIntegerVT(*DAG.getContext(), 4418 N0VT.getScalarType().getSizeInBits()); 4419 EVT MatchingVectorType = 4420 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4421 N0VT.getVectorNumElements()); 4422 4423 if (SVT == MatchingVectorType) { 4424 SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, 4425 N0.getOperand(0), N0.getOperand(1), 4426 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4427 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT); 4428 } 4429 } 4430 } 4431 4432 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc) 4433 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 4434 SDValue NegOne = 4435 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 4436 SDValue SCC = 4437 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4438 NegOne, DAG.getConstant(0, VT), 4439 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4440 if (SCC.getNode()) return SCC; 4441 if (!LegalOperations || 4442 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT))) 4443 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT, 4444 DAG.getSetCC(N->getDebugLoc(), 4445 TLI.getSetCCResultType(VT), 4446 N0.getOperand(0), N0.getOperand(1), 4447 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4448 NegOne, DAG.getConstant(0, VT)); 4449 } 4450 4451 // fold (sext x) -> (zext x) if the sign bit is known zero. 4452 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 4453 DAG.SignBitIsZero(N0)) 4454 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 4455 4456 return SDValue(); 4457 } 4458 4459 // isTruncateOf - If N is a truncate of some other value, return true, record 4460 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 4461 // This function computes KnownZero to avoid a duplicated call to 4462 // ComputeMaskedBits in the caller. 4463 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 4464 APInt &KnownZero) { 4465 APInt KnownOne; 4466 if (N->getOpcode() == ISD::TRUNCATE) { 4467 Op = N->getOperand(0); 4468 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4469 return true; 4470 } 4471 4472 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 4473 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 4474 return false; 4475 4476 SDValue Op0 = N->getOperand(0); 4477 SDValue Op1 = N->getOperand(1); 4478 assert(Op0.getValueType() == Op1.getValueType()); 4479 4480 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 4481 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 4482 if (COp0 && COp0->isNullValue()) 4483 Op = Op1; 4484 else if (COp1 && COp1->isNullValue()) 4485 Op = Op0; 4486 else 4487 return false; 4488 4489 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4490 4491 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 4492 return false; 4493 4494 return true; 4495 } 4496 4497 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 4498 SDValue N0 = N->getOperand(0); 4499 EVT VT = N->getValueType(0); 4500 4501 // fold (zext c1) -> c1 4502 if (isa<ConstantSDNode>(N0)) 4503 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 4504 // fold (zext (zext x)) -> (zext x) 4505 // fold (zext (aext x)) -> (zext x) 4506 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4507 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, 4508 N0.getOperand(0)); 4509 4510 // fold (zext (truncate x)) -> (zext x) or 4511 // (zext (truncate x)) -> (truncate x) 4512 // This is valid when the truncated bits of x are already zero. 4513 // FIXME: We should extend this to work for vectors too. 4514 SDValue Op; 4515 APInt KnownZero; 4516 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 4517 APInt TruncatedBits = 4518 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 4519 APInt(Op.getValueSizeInBits(), 0) : 4520 APInt::getBitsSet(Op.getValueSizeInBits(), 4521 N0.getValueSizeInBits(), 4522 std::min(Op.getValueSizeInBits(), 4523 VT.getSizeInBits())); 4524 if (TruncatedBits == (KnownZero & TruncatedBits)) { 4525 if (VT.bitsGT(Op.getValueType())) 4526 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op); 4527 if (VT.bitsLT(Op.getValueType())) 4528 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4529 4530 return Op; 4531 } 4532 } 4533 4534 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4535 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 4536 if (N0.getOpcode() == ISD::TRUNCATE) { 4537 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4538 if (NarrowLoad.getNode()) { 4539 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4540 if (NarrowLoad.getNode() != N0.getNode()) { 4541 CombineTo(N0.getNode(), NarrowLoad); 4542 // CombineTo deleted the truncate, if needed, but not what's under it. 4543 AddToWorkList(oye); 4544 } 4545 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4546 } 4547 } 4548 4549 // fold (zext (truncate x)) -> (and x, mask) 4550 if (N0.getOpcode() == ISD::TRUNCATE && 4551 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 4552 4553 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4554 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 4555 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4556 if (NarrowLoad.getNode()) { 4557 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4558 if (NarrowLoad.getNode() != N0.getNode()) { 4559 CombineTo(N0.getNode(), NarrowLoad); 4560 // CombineTo deleted the truncate, if needed, but not what's under it. 4561 AddToWorkList(oye); 4562 } 4563 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4564 } 4565 4566 SDValue Op = N0.getOperand(0); 4567 if (Op.getValueType().bitsLT(VT)) { 4568 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op); 4569 AddToWorkList(Op.getNode()); 4570 } else if (Op.getValueType().bitsGT(VT)) { 4571 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4572 AddToWorkList(Op.getNode()); 4573 } 4574 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), 4575 N0.getValueType().getScalarType()); 4576 } 4577 4578 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 4579 // if either of the casts is not free. 4580 if (N0.getOpcode() == ISD::AND && 4581 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4582 N0.getOperand(1).getOpcode() == ISD::Constant && 4583 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4584 N0.getValueType()) || 4585 !TLI.isZExtFree(N0.getValueType(), VT))) { 4586 SDValue X = N0.getOperand(0).getOperand(0); 4587 if (X.getValueType().bitsLT(VT)) { 4588 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X); 4589 } else if (X.getValueType().bitsGT(VT)) { 4590 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 4591 } 4592 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4593 Mask = Mask.zext(VT.getSizeInBits()); 4594 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4595 X, DAG.getConstant(Mask, VT)); 4596 } 4597 4598 // fold (zext (load x)) -> (zext (truncate (zextload x))) 4599 // None of the supported targets knows how to perform load and vector_zext 4600 // on vectors in one instruction. We only perform this transformation on 4601 // scalars. 4602 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4603 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4604 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 4605 bool DoXform = true; 4606 SmallVector<SDNode*, 4> SetCCs; 4607 if (!N0.hasOneUse()) 4608 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 4609 if (DoXform) { 4610 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4611 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 4612 LN0->getChain(), 4613 LN0->getBasePtr(), LN0->getPointerInfo(), 4614 N0.getValueType(), 4615 LN0->isVolatile(), LN0->isNonTemporal(), 4616 LN0->getAlignment()); 4617 CombineTo(N, ExtLoad); 4618 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4619 N0.getValueType(), ExtLoad); 4620 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4621 4622 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4623 ISD::ZERO_EXTEND); 4624 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4625 } 4626 } 4627 4628 // fold (zext (and/or/xor (load x), cst)) -> 4629 // (and/or/xor (zextload x), (zext cst)) 4630 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4631 N0.getOpcode() == ISD::XOR) && 4632 isa<LoadSDNode>(N0.getOperand(0)) && 4633 N0.getOperand(1).getOpcode() == ISD::Constant && 4634 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 4635 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4636 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4637 if (LN0->getExtensionType() != ISD::SEXTLOAD) { 4638 bool DoXform = true; 4639 SmallVector<SDNode*, 4> SetCCs; 4640 if (!N0.hasOneUse()) 4641 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 4642 SetCCs, TLI); 4643 if (DoXform) { 4644 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, 4645 LN0->getChain(), LN0->getBasePtr(), 4646 LN0->getPointerInfo(), 4647 LN0->getMemoryVT(), 4648 LN0->isVolatile(), 4649 LN0->isNonTemporal(), 4650 LN0->getAlignment()); 4651 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4652 Mask = Mask.zext(VT.getSizeInBits()); 4653 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 4654 ExtLoad, DAG.getConstant(Mask, VT)); 4655 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4656 N0.getOperand(0).getDebugLoc(), 4657 N0.getOperand(0).getValueType(), ExtLoad); 4658 CombineTo(N, And); 4659 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4660 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4661 ISD::ZERO_EXTEND); 4662 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4663 } 4664 } 4665 } 4666 4667 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 4668 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 4669 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4670 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4671 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4672 EVT MemVT = LN0->getMemoryVT(); 4673 if ((!LegalOperations && !LN0->isVolatile()) || 4674 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 4675 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 4676 LN0->getChain(), 4677 LN0->getBasePtr(), LN0->getPointerInfo(), 4678 MemVT, 4679 LN0->isVolatile(), LN0->isNonTemporal(), 4680 LN0->getAlignment()); 4681 CombineTo(N, ExtLoad); 4682 CombineTo(N0.getNode(), 4683 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(), 4684 ExtLoad), 4685 ExtLoad.getValue(1)); 4686 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4687 } 4688 } 4689 4690 if (N0.getOpcode() == ISD::SETCC) { 4691 if (!LegalOperations && VT.isVector()) { 4692 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 4693 // Only do this before legalize for now. 4694 EVT N0VT = N0.getOperand(0).getValueType(); 4695 EVT EltVT = VT.getVectorElementType(); 4696 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 4697 DAG.getConstant(1, EltVT)); 4698 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4699 // We know that the # elements of the results is the same as the 4700 // # elements of the compare (and the # elements of the compare result 4701 // for that matter). Check to see that they are the same size. If so, 4702 // we know that the element size of the sext'd result matches the 4703 // element size of the compare operands. 4704 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4705 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4706 N0.getOperand(1), 4707 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4708 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 4709 &OneOps[0], OneOps.size())); 4710 4711 // If the desired elements are smaller or larger than the source 4712 // elements we can use a matching integer vector type and then 4713 // truncate/sign extend 4714 EVT MatchingElementType = 4715 EVT::getIntegerVT(*DAG.getContext(), 4716 N0VT.getScalarType().getSizeInBits()); 4717 EVT MatchingVectorType = 4718 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4719 N0VT.getVectorNumElements()); 4720 SDValue VsetCC = 4721 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0), 4722 N0.getOperand(1), 4723 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4724 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4725 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT), 4726 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 4727 &OneOps[0], OneOps.size())); 4728 } 4729 4730 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 4731 SDValue SCC = 4732 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4733 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 4734 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4735 if (SCC.getNode()) return SCC; 4736 } 4737 4738 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 4739 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 4740 isa<ConstantSDNode>(N0.getOperand(1)) && 4741 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 4742 N0.hasOneUse()) { 4743 SDValue ShAmt = N0.getOperand(1); 4744 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 4745 if (N0.getOpcode() == ISD::SHL) { 4746 SDValue InnerZExt = N0.getOperand(0); 4747 // If the original shl may be shifting out bits, do not perform this 4748 // transformation. 4749 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 4750 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 4751 if (ShAmtVal > KnownZeroBits) 4752 return SDValue(); 4753 } 4754 4755 DebugLoc DL = N->getDebugLoc(); 4756 4757 // Ensure that the shift amount is wide enough for the shifted value. 4758 if (VT.getSizeInBits() >= 256) 4759 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 4760 4761 return DAG.getNode(N0.getOpcode(), DL, VT, 4762 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 4763 ShAmt); 4764 } 4765 4766 return SDValue(); 4767 } 4768 4769 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 4770 SDValue N0 = N->getOperand(0); 4771 EVT VT = N->getValueType(0); 4772 4773 // fold (aext c1) -> c1 4774 if (isa<ConstantSDNode>(N0)) 4775 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0); 4776 // fold (aext (aext x)) -> (aext x) 4777 // fold (aext (zext x)) -> (zext x) 4778 // fold (aext (sext x)) -> (sext x) 4779 if (N0.getOpcode() == ISD::ANY_EXTEND || 4780 N0.getOpcode() == ISD::ZERO_EXTEND || 4781 N0.getOpcode() == ISD::SIGN_EXTEND) 4782 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0)); 4783 4784 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 4785 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 4786 if (N0.getOpcode() == ISD::TRUNCATE) { 4787 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4788 if (NarrowLoad.getNode()) { 4789 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4790 if (NarrowLoad.getNode() != N0.getNode()) { 4791 CombineTo(N0.getNode(), NarrowLoad); 4792 // CombineTo deleted the truncate, if needed, but not what's under it. 4793 AddToWorkList(oye); 4794 } 4795 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4796 } 4797 } 4798 4799 // fold (aext (truncate x)) 4800 if (N0.getOpcode() == ISD::TRUNCATE) { 4801 SDValue TruncOp = N0.getOperand(0); 4802 if (TruncOp.getValueType() == VT) 4803 return TruncOp; // x iff x size == zext size. 4804 if (TruncOp.getValueType().bitsGT(VT)) 4805 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp); 4806 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp); 4807 } 4808 4809 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 4810 // if the trunc is not free. 4811 if (N0.getOpcode() == ISD::AND && 4812 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4813 N0.getOperand(1).getOpcode() == ISD::Constant && 4814 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4815 N0.getValueType())) { 4816 SDValue X = N0.getOperand(0).getOperand(0); 4817 if (X.getValueType().bitsLT(VT)) { 4818 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X); 4819 } else if (X.getValueType().bitsGT(VT)) { 4820 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X); 4821 } 4822 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4823 Mask = Mask.zext(VT.getSizeInBits()); 4824 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4825 X, DAG.getConstant(Mask, VT)); 4826 } 4827 4828 // fold (aext (load x)) -> (aext (truncate (extload x))) 4829 // None of the supported targets knows how to perform load and any_ext 4830 // on vectors in one instruction. We only perform this transformation on 4831 // scalars. 4832 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4833 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4834 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 4835 bool DoXform = true; 4836 SmallVector<SDNode*, 4> SetCCs; 4837 if (!N0.hasOneUse()) 4838 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 4839 if (DoXform) { 4840 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4841 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 4842 LN0->getChain(), 4843 LN0->getBasePtr(), LN0->getPointerInfo(), 4844 N0.getValueType(), 4845 LN0->isVolatile(), LN0->isNonTemporal(), 4846 LN0->getAlignment()); 4847 CombineTo(N, ExtLoad); 4848 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4849 N0.getValueType(), ExtLoad); 4850 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4851 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4852 ISD::ANY_EXTEND); 4853 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4854 } 4855 } 4856 4857 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 4858 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 4859 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 4860 if (N0.getOpcode() == ISD::LOAD && 4861 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4862 N0.hasOneUse()) { 4863 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4864 EVT MemVT = LN0->getMemoryVT(); 4865 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(), 4866 VT, LN0->getChain(), LN0->getBasePtr(), 4867 LN0->getPointerInfo(), MemVT, 4868 LN0->isVolatile(), LN0->isNonTemporal(), 4869 LN0->getAlignment()); 4870 CombineTo(N, ExtLoad); 4871 CombineTo(N0.getNode(), 4872 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4873 N0.getValueType(), ExtLoad), 4874 ExtLoad.getValue(1)); 4875 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4876 } 4877 4878 if (N0.getOpcode() == ISD::SETCC) { 4879 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 4880 // Only do this before legalize for now. 4881 if (VT.isVector() && !LegalOperations) { 4882 EVT N0VT = N0.getOperand(0).getValueType(); 4883 // We know that the # elements of the results is the same as the 4884 // # elements of the compare (and the # elements of the compare result 4885 // for that matter). Check to see that they are the same size. If so, 4886 // we know that the element size of the sext'd result matches the 4887 // element size of the compare operands. 4888 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4889 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4890 N0.getOperand(1), 4891 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4892 // If the desired elements are smaller or larger than the source 4893 // elements we can use a matching integer vector type and then 4894 // truncate/sign extend 4895 else { 4896 EVT MatchingElementType = 4897 EVT::getIntegerVT(*DAG.getContext(), 4898 N0VT.getScalarType().getSizeInBits()); 4899 EVT MatchingVectorType = 4900 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4901 N0VT.getVectorNumElements()); 4902 SDValue VsetCC = 4903 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0), 4904 N0.getOperand(1), 4905 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4906 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT); 4907 } 4908 } 4909 4910 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 4911 SDValue SCC = 4912 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4913 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 4914 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4915 if (SCC.getNode()) 4916 return SCC; 4917 } 4918 4919 return SDValue(); 4920 } 4921 4922 /// GetDemandedBits - See if the specified operand can be simplified with the 4923 /// knowledge that only the bits specified by Mask are used. If so, return the 4924 /// simpler operand, otherwise return a null SDValue. 4925 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 4926 switch (V.getOpcode()) { 4927 default: break; 4928 case ISD::Constant: { 4929 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 4930 assert(CV != 0 && "Const value should be ConstSDNode."); 4931 const APInt &CVal = CV->getAPIntValue(); 4932 APInt NewVal = CVal & Mask; 4933 if (NewVal != CVal) { 4934 return DAG.getConstant(NewVal, V.getValueType()); 4935 } 4936 break; 4937 } 4938 case ISD::OR: 4939 case ISD::XOR: 4940 // If the LHS or RHS don't contribute bits to the or, drop them. 4941 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 4942 return V.getOperand(1); 4943 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 4944 return V.getOperand(0); 4945 break; 4946 case ISD::SRL: 4947 // Only look at single-use SRLs. 4948 if (!V.getNode()->hasOneUse()) 4949 break; 4950 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 4951 // See if we can recursively simplify the LHS. 4952 unsigned Amt = RHSC->getZExtValue(); 4953 4954 // Watch out for shift count overflow though. 4955 if (Amt >= Mask.getBitWidth()) break; 4956 APInt NewMask = Mask << Amt; 4957 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 4958 if (SimplifyLHS.getNode()) 4959 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(), 4960 SimplifyLHS, V.getOperand(1)); 4961 } 4962 } 4963 return SDValue(); 4964 } 4965 4966 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N 4967 /// bits and then truncated to a narrower type and where N is a multiple 4968 /// of number of bits of the narrower type, transform it to a narrower load 4969 /// from address + N / num of bits of new type. If the result is to be 4970 /// extended, also fold the extension to form a extending load. 4971 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 4972 unsigned Opc = N->getOpcode(); 4973 4974 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 4975 SDValue N0 = N->getOperand(0); 4976 EVT VT = N->getValueType(0); 4977 EVT ExtVT = VT; 4978 4979 // This transformation isn't valid for vector loads. 4980 if (VT.isVector()) 4981 return SDValue(); 4982 4983 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 4984 // extended to VT. 4985 if (Opc == ISD::SIGN_EXTEND_INREG) { 4986 ExtType = ISD::SEXTLOAD; 4987 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 4988 } else if (Opc == ISD::SRL) { 4989 // Another special-case: SRL is basically zero-extending a narrower value. 4990 ExtType = ISD::ZEXTLOAD; 4991 N0 = SDValue(N, 0); 4992 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4993 if (!N01) return SDValue(); 4994 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 4995 VT.getSizeInBits() - N01->getZExtValue()); 4996 } 4997 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 4998 return SDValue(); 4999 5000 unsigned EVTBits = ExtVT.getSizeInBits(); 5001 5002 // Do not generate loads of non-round integer types since these can 5003 // be expensive (and would be wrong if the type is not byte sized). 5004 if (!ExtVT.isRound()) 5005 return SDValue(); 5006 5007 unsigned ShAmt = 0; 5008 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5009 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5010 ShAmt = N01->getZExtValue(); 5011 // Is the shift amount a multiple of size of VT? 5012 if ((ShAmt & (EVTBits-1)) == 0) { 5013 N0 = N0.getOperand(0); 5014 // Is the load width a multiple of size of VT? 5015 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5016 return SDValue(); 5017 } 5018 5019 // At this point, we must have a load or else we can't do the transform. 5020 if (!isa<LoadSDNode>(N0)) return SDValue(); 5021 5022 // If the shift amount is larger than the input type then we're not 5023 // accessing any of the loaded bytes. If the load was a zextload/extload 5024 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5025 // If the load was a sextload then the result is a splat of the sign bit 5026 // of the extended byte. This is not worth optimizing for. 5027 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5028 return SDValue(); 5029 } 5030 } 5031 5032 // If the load is shifted left (and the result isn't shifted back right), 5033 // we can fold the truncate through the shift. 5034 unsigned ShLeftAmt = 0; 5035 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5036 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5037 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5038 ShLeftAmt = N01->getZExtValue(); 5039 N0 = N0.getOperand(0); 5040 } 5041 } 5042 5043 // If we haven't found a load, we can't narrow it. Don't transform one with 5044 // multiple uses, this would require adding a new load. 5045 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() || 5046 // Don't change the width of a volatile load. 5047 cast<LoadSDNode>(N0)->isVolatile()) 5048 return SDValue(); 5049 5050 // Verify that we are actually reducing a load width here. 5051 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits) 5052 return SDValue(); 5053 5054 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5055 EVT PtrType = N0.getOperand(1).getValueType(); 5056 5057 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5058 // It's not possible to generate a constant of extended or untyped type. 5059 return SDValue(); 5060 5061 // For big endian targets, we need to adjust the offset to the pointer to 5062 // load the correct bytes. 5063 if (TLI.isBigEndian()) { 5064 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5065 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5066 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5067 } 5068 5069 uint64_t PtrOff = ShAmt / 8; 5070 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5071 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), 5072 PtrType, LN0->getBasePtr(), 5073 DAG.getConstant(PtrOff, PtrType)); 5074 AddToWorkList(NewPtr.getNode()); 5075 5076 SDValue Load; 5077 if (ExtType == ISD::NON_EXTLOAD) 5078 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr, 5079 LN0->getPointerInfo().getWithOffset(PtrOff), 5080 LN0->isVolatile(), LN0->isNonTemporal(), 5081 LN0->isInvariant(), NewAlign); 5082 else 5083 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr, 5084 LN0->getPointerInfo().getWithOffset(PtrOff), 5085 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5086 NewAlign); 5087 5088 // Replace the old load's chain with the new load's chain. 5089 WorkListRemover DeadNodes(*this); 5090 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5091 5092 // Shift the result left, if we've swallowed a left shift. 5093 SDValue Result = Load; 5094 if (ShLeftAmt != 0) { 5095 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5096 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5097 ShImmTy = VT; 5098 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, 5099 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5100 } 5101 5102 // Return the new loaded value. 5103 return Result; 5104 } 5105 5106 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5107 SDValue N0 = N->getOperand(0); 5108 SDValue N1 = N->getOperand(1); 5109 EVT VT = N->getValueType(0); 5110 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5111 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5112 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5113 5114 // fold (sext_in_reg c1) -> c1 5115 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5116 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1); 5117 5118 // If the input is already sign extended, just drop the extension. 5119 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5120 return N0; 5121 5122 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5123 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5124 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) { 5125 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 5126 N0.getOperand(0), N1); 5127 } 5128 5129 // fold (sext_in_reg (sext x)) -> (sext x) 5130 // fold (sext_in_reg (aext x)) -> (sext x) 5131 // if x is small enough. 5132 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5133 SDValue N00 = N0.getOperand(0); 5134 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5135 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5136 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1); 5137 } 5138 5139 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5140 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5141 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT); 5142 5143 // fold operands of sext_in_reg based on knowledge that the top bits are not 5144 // demanded. 5145 if (SimplifyDemandedBits(SDValue(N, 0))) 5146 return SDValue(N, 0); 5147 5148 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5149 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5150 SDValue NarrowLoad = ReduceLoadWidth(N); 5151 if (NarrowLoad.getNode()) 5152 return NarrowLoad; 5153 5154 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5155 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5156 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5157 if (N0.getOpcode() == ISD::SRL) { 5158 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5159 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5160 // We can turn this into an SRA iff the input to the SRL is already sign 5161 // extended enough. 5162 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5163 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5164 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, 5165 N0.getOperand(0), N0.getOperand(1)); 5166 } 5167 } 5168 5169 // fold (sext_inreg (extload x)) -> (sextload x) 5170 if (ISD::isEXTLoad(N0.getNode()) && 5171 ISD::isUNINDEXEDLoad(N0.getNode()) && 5172 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5173 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5174 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5175 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5176 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 5177 LN0->getChain(), 5178 LN0->getBasePtr(), LN0->getPointerInfo(), 5179 EVT, 5180 LN0->isVolatile(), LN0->isNonTemporal(), 5181 LN0->getAlignment()); 5182 CombineTo(N, ExtLoad); 5183 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5184 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5185 } 5186 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5187 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5188 N0.hasOneUse() && 5189 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5190 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5191 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5192 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5193 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 5194 LN0->getChain(), 5195 LN0->getBasePtr(), LN0->getPointerInfo(), 5196 EVT, 5197 LN0->isVolatile(), LN0->isNonTemporal(), 5198 LN0->getAlignment()); 5199 CombineTo(N, ExtLoad); 5200 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5201 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5202 } 5203 5204 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5205 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5206 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5207 N0.getOperand(1), false); 5208 if (BSwap.getNode() != 0) 5209 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 5210 BSwap, N1); 5211 } 5212 5213 return SDValue(); 5214 } 5215 5216 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5217 SDValue N0 = N->getOperand(0); 5218 EVT VT = N->getValueType(0); 5219 bool isLE = TLI.isLittleEndian(); 5220 5221 // noop truncate 5222 if (N0.getValueType() == N->getValueType(0)) 5223 return N0; 5224 // fold (truncate c1) -> c1 5225 if (isa<ConstantSDNode>(N0)) 5226 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0); 5227 // fold (truncate (truncate x)) -> (truncate x) 5228 if (N0.getOpcode() == ISD::TRUNCATE) 5229 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 5230 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5231 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5232 N0.getOpcode() == ISD::SIGN_EXTEND || 5233 N0.getOpcode() == ISD::ANY_EXTEND) { 5234 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5235 // if the source is smaller than the dest, we still need an extend 5236 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 5237 N0.getOperand(0)); 5238 else if (N0.getOperand(0).getValueType().bitsGT(VT)) 5239 // if the source is larger than the dest, than we just need the truncate 5240 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 5241 else 5242 // if the source and dest are the same type, we can drop both the extend 5243 // and the truncate. 5244 return N0.getOperand(0); 5245 } 5246 5247 // Fold extract-and-trunc into a narrow extract. For example: 5248 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5249 // i32 y = TRUNCATE(i64 x) 5250 // -- becomes -- 5251 // v16i8 b = BITCAST (v2i64 val) 5252 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5253 // 5254 // Note: We only run this optimization after type legalization (which often 5255 // creates this pattern) and before operation legalization after which 5256 // we need to be more careful about the vector instructions that we generate. 5257 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5258 LegalTypes && !LegalOperations && N0->hasOneUse()) { 5259 5260 EVT VecTy = N0.getOperand(0).getValueType(); 5261 EVT ExTy = N0.getValueType(); 5262 EVT TrTy = N->getValueType(0); 5263 5264 unsigned NumElem = VecTy.getVectorNumElements(); 5265 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5266 5267 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5268 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5269 5270 SDValue EltNo = N0->getOperand(1); 5271 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5272 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5273 EVT IndexTy = N0->getOperand(1).getValueType(); 5274 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5275 5276 SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 5277 NVT, N0.getOperand(0)); 5278 5279 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5280 N->getDebugLoc(), TrTy, V, 5281 DAG.getConstant(Index, IndexTy)); 5282 } 5283 } 5284 5285 // See if we can simplify the input to this truncate through knowledge that 5286 // only the low bits are being used. 5287 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5288 // Currently we only perform this optimization on scalars because vectors 5289 // may have different active low bits. 5290 if (!VT.isVector()) { 5291 SDValue Shorter = 5292 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5293 VT.getSizeInBits())); 5294 if (Shorter.getNode()) 5295 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter); 5296 } 5297 // fold (truncate (load x)) -> (smaller load x) 5298 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5299 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5300 SDValue Reduced = ReduceLoadWidth(N); 5301 if (Reduced.getNode()) 5302 return Reduced; 5303 } 5304 5305 // Simplify the operands using demanded-bits information. 5306 if (!VT.isVector() && 5307 SimplifyDemandedBits(SDValue(N, 0))) 5308 return SDValue(N, 0); 5309 5310 return SDValue(); 5311 } 5312 5313 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 5314 SDValue Elt = N->getOperand(i); 5315 if (Elt.getOpcode() != ISD::MERGE_VALUES) 5316 return Elt.getNode(); 5317 return Elt.getOperand(Elt.getResNo()).getNode(); 5318 } 5319 5320 /// CombineConsecutiveLoads - build_pair (load, load) -> load 5321 /// if load locations are consecutive. 5322 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 5323 assert(N->getOpcode() == ISD::BUILD_PAIR); 5324 5325 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 5326 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 5327 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 5328 LD1->getPointerInfo().getAddrSpace() != 5329 LD2->getPointerInfo().getAddrSpace()) 5330 return SDValue(); 5331 EVT LD1VT = LD1->getValueType(0); 5332 5333 if (ISD::isNON_EXTLoad(LD2) && 5334 LD2->hasOneUse() && 5335 // If both are volatile this would reduce the number of volatile loads. 5336 // If one is volatile it might be ok, but play conservative and bail out. 5337 !LD1->isVolatile() && 5338 !LD2->isVolatile() && 5339 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 5340 unsigned Align = LD1->getAlignment(); 5341 unsigned NewAlign = TLI.getTargetData()-> 5342 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5343 5344 if (NewAlign <= Align && 5345 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 5346 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(), 5347 LD1->getBasePtr(), LD1->getPointerInfo(), 5348 false, false, false, Align); 5349 } 5350 5351 return SDValue(); 5352 } 5353 5354 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 5355 SDValue N0 = N->getOperand(0); 5356 EVT VT = N->getValueType(0); 5357 5358 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 5359 // Only do this before legalize, since afterward the target may be depending 5360 // on the bitconvert. 5361 // First check to see if this is all constant. 5362 if (!LegalTypes && 5363 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 5364 VT.isVector()) { 5365 bool isSimple = true; 5366 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) 5367 if (N0.getOperand(i).getOpcode() != ISD::UNDEF && 5368 N0.getOperand(i).getOpcode() != ISD::Constant && 5369 N0.getOperand(i).getOpcode() != ISD::ConstantFP) { 5370 isSimple = false; 5371 break; 5372 } 5373 5374 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 5375 assert(!DestEltVT.isVector() && 5376 "Element type of vector ValueType must not be vector!"); 5377 if (isSimple) 5378 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 5379 } 5380 5381 // If the input is a constant, let getNode fold it. 5382 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 5383 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0); 5384 if (Res.getNode() != N) { 5385 if (!LegalOperations || 5386 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 5387 return Res; 5388 5389 // Folding it resulted in an illegal node, and it's too late to 5390 // do that. Clean up the old node and forego the transformation. 5391 // Ideally this won't happen very often, because instcombine 5392 // and the earlier dagcombine runs (where illegal nodes are 5393 // permitted) should have folded most of them already. 5394 DAG.DeleteNode(Res.getNode()); 5395 } 5396 } 5397 5398 // (conv (conv x, t1), t2) -> (conv x, t2) 5399 if (N0.getOpcode() == ISD::BITCAST) 5400 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, 5401 N0.getOperand(0)); 5402 5403 // fold (conv (load x)) -> (load (conv*)x) 5404 // If the resultant load doesn't need a higher alignment than the original! 5405 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 5406 // Do not change the width of a volatile load. 5407 !cast<LoadSDNode>(N0)->isVolatile() && 5408 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) { 5409 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5410 unsigned Align = TLI.getTargetData()-> 5411 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5412 unsigned OrigAlign = LN0->getAlignment(); 5413 5414 if (Align <= OrigAlign) { 5415 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(), 5416 LN0->getBasePtr(), LN0->getPointerInfo(), 5417 LN0->isVolatile(), LN0->isNonTemporal(), 5418 LN0->isInvariant(), OrigAlign); 5419 AddToWorkList(N); 5420 CombineTo(N0.getNode(), 5421 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5422 N0.getValueType(), Load), 5423 Load.getValue(1)); 5424 return Load; 5425 } 5426 } 5427 5428 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 5429 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 5430 // This often reduces constant pool loads. 5431 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) || 5432 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) && 5433 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) { 5434 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT, 5435 N0.getOperand(0)); 5436 AddToWorkList(NewConv.getNode()); 5437 5438 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5439 if (N0.getOpcode() == ISD::FNEG) 5440 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 5441 NewConv, DAG.getConstant(SignBit, VT)); 5442 assert(N0.getOpcode() == ISD::FABS); 5443 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 5444 NewConv, DAG.getConstant(~SignBit, VT)); 5445 } 5446 5447 // fold (bitconvert (fcopysign cst, x)) -> 5448 // (or (and (bitconvert x), sign), (and cst, (not sign))) 5449 // Note that we don't handle (copysign x, cst) because this can always be 5450 // folded to an fneg or fabs. 5451 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 5452 isa<ConstantFPSDNode>(N0.getOperand(0)) && 5453 VT.isInteger() && !VT.isVector()) { 5454 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 5455 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 5456 if (isTypeLegal(IntXVT)) { 5457 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5458 IntXVT, N0.getOperand(1)); 5459 AddToWorkList(X.getNode()); 5460 5461 // If X has a different width than the result/lhs, sext it or truncate it. 5462 unsigned VTWidth = VT.getSizeInBits(); 5463 if (OrigXWidth < VTWidth) { 5464 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X); 5465 AddToWorkList(X.getNode()); 5466 } else if (OrigXWidth > VTWidth) { 5467 // To get the sign bit in the right place, we have to shift it right 5468 // before truncating. 5469 X = DAG.getNode(ISD::SRL, X.getDebugLoc(), 5470 X.getValueType(), X, 5471 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 5472 AddToWorkList(X.getNode()); 5473 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 5474 AddToWorkList(X.getNode()); 5475 } 5476 5477 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5478 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT, 5479 X, DAG.getConstant(SignBit, VT)); 5480 AddToWorkList(X.getNode()); 5481 5482 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5483 VT, N0.getOperand(0)); 5484 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT, 5485 Cst, DAG.getConstant(~SignBit, VT)); 5486 AddToWorkList(Cst.getNode()); 5487 5488 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst); 5489 } 5490 } 5491 5492 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 5493 if (N0.getOpcode() == ISD::BUILD_PAIR) { 5494 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 5495 if (CombineLD.getNode()) 5496 return CombineLD; 5497 } 5498 5499 return SDValue(); 5500 } 5501 5502 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 5503 EVT VT = N->getValueType(0); 5504 return CombineConsecutiveLoads(N, VT); 5505 } 5506 5507 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 5508 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 5509 /// destination element value type. 5510 SDValue DAGCombiner:: 5511 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 5512 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 5513 5514 // If this is already the right type, we're done. 5515 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 5516 5517 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 5518 unsigned DstBitSize = DstEltVT.getSizeInBits(); 5519 5520 // If this is a conversion of N elements of one type to N elements of another 5521 // type, convert each element. This handles FP<->INT cases. 5522 if (SrcBitSize == DstBitSize) { 5523 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5524 BV->getValueType(0).getVectorNumElements()); 5525 5526 // Due to the FP element handling below calling this routine recursively, 5527 // we can end up with a scalar-to-vector node here. 5528 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 5529 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT, 5530 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(), 5531 DstEltVT, BV->getOperand(0))); 5532 5533 SmallVector<SDValue, 8> Ops; 5534 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5535 SDValue Op = BV->getOperand(i); 5536 // If the vector element type is not legal, the BUILD_VECTOR operands 5537 // are promoted and implicitly truncated. Make that explicit here. 5538 if (Op.getValueType() != SrcEltVT) 5539 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op); 5540 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(), 5541 DstEltVT, Op)); 5542 AddToWorkList(Ops.back().getNode()); 5543 } 5544 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5545 &Ops[0], Ops.size()); 5546 } 5547 5548 // Otherwise, we're growing or shrinking the elements. To avoid having to 5549 // handle annoying details of growing/shrinking FP values, we convert them to 5550 // int first. 5551 if (SrcEltVT.isFloatingPoint()) { 5552 // Convert the input float vector to a int vector where the elements are the 5553 // same sizes. 5554 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 5555 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 5556 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 5557 SrcEltVT = IntVT; 5558 } 5559 5560 // Now we know the input is an integer vector. If the output is a FP type, 5561 // convert to integer first, then to FP of the right size. 5562 if (DstEltVT.isFloatingPoint()) { 5563 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 5564 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 5565 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 5566 5567 // Next, convert to FP elements of the same size. 5568 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 5569 } 5570 5571 // Okay, we know the src/dst types are both integers of differing types. 5572 // Handling growing first. 5573 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 5574 if (SrcBitSize < DstBitSize) { 5575 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 5576 5577 SmallVector<SDValue, 8> Ops; 5578 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 5579 i += NumInputsPerOutput) { 5580 bool isLE = TLI.isLittleEndian(); 5581 APInt NewBits = APInt(DstBitSize, 0); 5582 bool EltIsUndef = true; 5583 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 5584 // Shift the previously computed bits over. 5585 NewBits <<= SrcBitSize; 5586 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 5587 if (Op.getOpcode() == ISD::UNDEF) continue; 5588 EltIsUndef = false; 5589 5590 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 5591 zextOrTrunc(SrcBitSize).zext(DstBitSize); 5592 } 5593 5594 if (EltIsUndef) 5595 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5596 else 5597 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 5598 } 5599 5600 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 5601 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5602 &Ops[0], Ops.size()); 5603 } 5604 5605 // Finally, this must be the case where we are shrinking elements: each input 5606 // turns into multiple outputs. 5607 bool isS2V = ISD::isScalarToVector(BV); 5608 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 5609 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5610 NumOutputsPerInput*BV->getNumOperands()); 5611 SmallVector<SDValue, 8> Ops; 5612 5613 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5614 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 5615 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 5616 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5617 continue; 5618 } 5619 5620 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 5621 getAPIntValue().zextOrTrunc(SrcBitSize); 5622 5623 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 5624 APInt ThisVal = OpVal.trunc(DstBitSize); 5625 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 5626 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 5627 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 5628 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT, 5629 Ops[0]); 5630 OpVal = OpVal.lshr(DstBitSize); 5631 } 5632 5633 // For big endian targets, swap the order of the pieces of each element. 5634 if (TLI.isBigEndian()) 5635 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 5636 } 5637 5638 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5639 &Ops[0], Ops.size()); 5640 } 5641 5642 SDValue DAGCombiner::visitFADD(SDNode *N) { 5643 SDValue N0 = N->getOperand(0); 5644 SDValue N1 = N->getOperand(1); 5645 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5646 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5647 EVT VT = N->getValueType(0); 5648 5649 // fold vector ops 5650 if (VT.isVector()) { 5651 SDValue FoldedVOp = SimplifyVBinOp(N); 5652 if (FoldedVOp.getNode()) return FoldedVOp; 5653 } 5654 5655 // fold (fadd c1, c2) -> c1 + c2 5656 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5657 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1); 5658 // canonicalize constant to RHS 5659 if (N0CFP && !N1CFP) 5660 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0); 5661 // fold (fadd A, 0) -> A 5662 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5663 N1CFP->getValueAPF().isZero()) 5664 return N0; 5665 // fold (fadd A, (fneg B)) -> (fsub A, B) 5666 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5667 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5668 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, 5669 GetNegatedExpression(N1, DAG, LegalOperations)); 5670 // fold (fadd (fneg A), B) -> (fsub B, A) 5671 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5672 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5673 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1, 5674 GetNegatedExpression(N0, DAG, LegalOperations)); 5675 5676 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 5677 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5678 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 5679 isa<ConstantFPSDNode>(N0.getOperand(1))) 5680 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0), 5681 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5682 N0.getOperand(1), N1)); 5683 5684 // FADD -> FMA combines: 5685 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 5686 DAG.getTarget().Options.UnsafeFPMath) && 5687 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) && 5688 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) { 5689 5690 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 5691 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) { 5692 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, 5693 N0.getOperand(0), N0.getOperand(1), N1); 5694 } 5695 5696 // fold (fadd x, (fmul y, z)) -> (fma x, y, z) 5697 // Note: Commutes FADD operands. 5698 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) { 5699 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, 5700 N1.getOperand(0), N1.getOperand(1), N0); 5701 } 5702 } 5703 5704 return SDValue(); 5705 } 5706 5707 SDValue DAGCombiner::visitFSUB(SDNode *N) { 5708 SDValue N0 = N->getOperand(0); 5709 SDValue N1 = N->getOperand(1); 5710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5711 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5712 EVT VT = N->getValueType(0); 5713 DebugLoc dl = N->getDebugLoc(); 5714 5715 // fold vector ops 5716 if (VT.isVector()) { 5717 SDValue FoldedVOp = SimplifyVBinOp(N); 5718 if (FoldedVOp.getNode()) return FoldedVOp; 5719 } 5720 5721 // fold (fsub c1, c2) -> c1-c2 5722 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5723 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1); 5724 // fold (fsub A, 0) -> A 5725 if (DAG.getTarget().Options.UnsafeFPMath && 5726 N1CFP && N1CFP->getValueAPF().isZero()) 5727 return N0; 5728 // fold (fsub 0, B) -> -B 5729 if (DAG.getTarget().Options.UnsafeFPMath && 5730 N0CFP && N0CFP->getValueAPF().isZero()) { 5731 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 5732 return GetNegatedExpression(N1, DAG, LegalOperations); 5733 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 5734 return DAG.getNode(ISD::FNEG, dl, VT, N1); 5735 } 5736 // fold (fsub A, (fneg B)) -> (fadd A, B) 5737 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 5738 return DAG.getNode(ISD::FADD, dl, VT, N0, 5739 GetNegatedExpression(N1, DAG, LegalOperations)); 5740 5741 // If 'unsafe math' is enabled, fold 5742 // (fsub x, x) -> 0.0 & 5743 // (fsub x, (fadd x, y)) -> (fneg y) & 5744 // (fsub x, (fadd y, x)) -> (fneg y) 5745 if (DAG.getTarget().Options.UnsafeFPMath) { 5746 if (N0 == N1) 5747 return DAG.getConstantFP(0.0f, VT); 5748 5749 if (N1.getOpcode() == ISD::FADD) { 5750 SDValue N10 = N1->getOperand(0); 5751 SDValue N11 = N1->getOperand(1); 5752 5753 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 5754 &DAG.getTarget().Options)) 5755 return GetNegatedExpression(N11, DAG, LegalOperations); 5756 else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 5757 &DAG.getTarget().Options)) 5758 return GetNegatedExpression(N10, DAG, LegalOperations); 5759 } 5760 } 5761 5762 // FSUB -> FMA combines: 5763 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 5764 DAG.getTarget().Options.UnsafeFPMath) && 5765 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) && 5766 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) { 5767 5768 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 5769 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) { 5770 return DAG.getNode(ISD::FMA, dl, VT, 5771 N0.getOperand(0), N0.getOperand(1), 5772 DAG.getNode(ISD::FNEG, dl, VT, N1)); 5773 } 5774 5775 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 5776 // Note: Commutes FSUB operands. 5777 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) { 5778 return DAG.getNode(ISD::FMA, dl, VT, 5779 DAG.getNode(ISD::FNEG, dl, VT, 5780 N1.getOperand(0)), 5781 N1.getOperand(1), N0); 5782 } 5783 5784 // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 5785 if (N0.getOpcode() == ISD::FNEG && 5786 N0.getOperand(0).getOpcode() == ISD::FMUL && 5787 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 5788 SDValue N00 = N0.getOperand(0).getOperand(0); 5789 SDValue N01 = N0.getOperand(0).getOperand(1); 5790 return DAG.getNode(ISD::FMA, dl, VT, 5791 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 5792 DAG.getNode(ISD::FNEG, dl, VT, N1)); 5793 } 5794 } 5795 5796 return SDValue(); 5797 } 5798 5799 SDValue DAGCombiner::visitFMUL(SDNode *N) { 5800 SDValue N0 = N->getOperand(0); 5801 SDValue N1 = N->getOperand(1); 5802 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5803 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5804 EVT VT = N->getValueType(0); 5805 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5806 5807 // fold vector ops 5808 if (VT.isVector()) { 5809 SDValue FoldedVOp = SimplifyVBinOp(N); 5810 if (FoldedVOp.getNode()) return FoldedVOp; 5811 } 5812 5813 // fold (fmul c1, c2) -> c1*c2 5814 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5815 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1); 5816 // canonicalize constant to RHS 5817 if (N0CFP && !N1CFP) 5818 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0); 5819 // fold (fmul A, 0) -> 0 5820 if (DAG.getTarget().Options.UnsafeFPMath && 5821 N1CFP && N1CFP->getValueAPF().isZero()) 5822 return N1; 5823 // fold (fmul A, 0) -> 0, vector edition. 5824 if (DAG.getTarget().Options.UnsafeFPMath && 5825 ISD::isBuildVectorAllZeros(N1.getNode())) 5826 return N1; 5827 // fold (fmul A, 1.0) -> A 5828 if (N1CFP && N1CFP->isExactlyValue(1.0)) 5829 return N0; 5830 // fold (fmul X, 2.0) -> (fadd X, X) 5831 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 5832 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0); 5833 // fold (fmul X, -1.0) -> (fneg X) 5834 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 5835 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 5836 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0); 5837 5838 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 5839 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 5840 &DAG.getTarget().Options)) { 5841 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 5842 &DAG.getTarget().Options)) { 5843 // Both can be negated for free, check to see if at least one is cheaper 5844 // negated. 5845 if (LHSNeg == 2 || RHSNeg == 2) 5846 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5847 GetNegatedExpression(N0, DAG, LegalOperations), 5848 GetNegatedExpression(N1, DAG, LegalOperations)); 5849 } 5850 } 5851 5852 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 5853 if (DAG.getTarget().Options.UnsafeFPMath && 5854 N1CFP && N0.getOpcode() == ISD::FMUL && 5855 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 5856 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0), 5857 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5858 N0.getOperand(1), N1)); 5859 5860 return SDValue(); 5861 } 5862 5863 SDValue DAGCombiner::visitFMA(SDNode *N) { 5864 SDValue N0 = N->getOperand(0); 5865 SDValue N1 = N->getOperand(1); 5866 SDValue N2 = N->getOperand(2); 5867 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5868 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5869 EVT VT = N->getValueType(0); 5870 5871 if (N0CFP && N0CFP->isExactlyValue(1.0)) 5872 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2); 5873 if (N1CFP && N1CFP->isExactlyValue(1.0)) 5874 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2); 5875 5876 // Canonicalize (fma c, x, y) -> (fma x, c, y) 5877 if (N0CFP && !N1CFP) 5878 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2); 5879 5880 return SDValue(); 5881 } 5882 5883 SDValue DAGCombiner::visitFDIV(SDNode *N) { 5884 SDValue N0 = N->getOperand(0); 5885 SDValue N1 = N->getOperand(1); 5886 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5887 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5888 EVT VT = N->getValueType(0); 5889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5890 5891 // fold vector ops 5892 if (VT.isVector()) { 5893 SDValue FoldedVOp = SimplifyVBinOp(N); 5894 if (FoldedVOp.getNode()) return FoldedVOp; 5895 } 5896 5897 // fold (fdiv c1, c2) -> c1/c2 5898 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5899 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1); 5900 5901 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 5902 if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) { 5903 // Compute the reciprocal 1.0 / c2. 5904 APFloat N1APF = N1CFP->getValueAPF(); 5905 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 5906 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 5907 // Only do the transform if the reciprocal is a legal fp immediate that 5908 // isn't too nasty (eg NaN, denormal, ...). 5909 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 5910 (!LegalOperations || 5911 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 5912 // backend)... we should handle this gracefully after Legalize. 5913 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 5914 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 5915 TLI.isFPImmLegal(Recip, VT))) 5916 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, 5917 DAG.getConstantFP(Recip, VT)); 5918 } 5919 5920 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 5921 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 5922 &DAG.getTarget().Options)) { 5923 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 5924 &DAG.getTarget().Options)) { 5925 // Both can be negated for free, check to see if at least one is cheaper 5926 // negated. 5927 if (LHSNeg == 2 || RHSNeg == 2) 5928 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, 5929 GetNegatedExpression(N0, DAG, LegalOperations), 5930 GetNegatedExpression(N1, DAG, LegalOperations)); 5931 } 5932 } 5933 5934 return SDValue(); 5935 } 5936 5937 SDValue DAGCombiner::visitFREM(SDNode *N) { 5938 SDValue N0 = N->getOperand(0); 5939 SDValue N1 = N->getOperand(1); 5940 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5941 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5942 EVT VT = N->getValueType(0); 5943 5944 // fold (frem c1, c2) -> fmod(c1,c2) 5945 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5946 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1); 5947 5948 return SDValue(); 5949 } 5950 5951 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 5952 SDValue N0 = N->getOperand(0); 5953 SDValue N1 = N->getOperand(1); 5954 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5955 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5956 EVT VT = N->getValueType(0); 5957 5958 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold 5959 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1); 5960 5961 if (N1CFP) { 5962 const APFloat& V = N1CFP->getValueAPF(); 5963 // copysign(x, c1) -> fabs(x) iff ispos(c1) 5964 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 5965 if (!V.isNegative()) { 5966 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 5967 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 5968 } else { 5969 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 5970 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, 5971 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0)); 5972 } 5973 } 5974 5975 // copysign(fabs(x), y) -> copysign(x, y) 5976 // copysign(fneg(x), y) -> copysign(x, y) 5977 // copysign(copysign(x,z), y) -> copysign(x, y) 5978 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 5979 N0.getOpcode() == ISD::FCOPYSIGN) 5980 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 5981 N0.getOperand(0), N1); 5982 5983 // copysign(x, abs(y)) -> abs(x) 5984 if (N1.getOpcode() == ISD::FABS) 5985 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 5986 5987 // copysign(x, copysign(y,z)) -> copysign(x, z) 5988 if (N1.getOpcode() == ISD::FCOPYSIGN) 5989 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 5990 N0, N1.getOperand(1)); 5991 5992 // copysign(x, fp_extend(y)) -> copysign(x, y) 5993 // copysign(x, fp_round(y)) -> copysign(x, y) 5994 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 5995 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 5996 N0, N1.getOperand(0)); 5997 5998 return SDValue(); 5999 } 6000 6001 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6002 SDValue N0 = N->getOperand(0); 6003 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6004 EVT VT = N->getValueType(0); 6005 EVT OpVT = N0.getValueType(); 6006 6007 // fold (sint_to_fp c1) -> c1fp 6008 if (N0C && OpVT != MVT::ppcf128 && 6009 // ...but only if the target supports immediate floating-point values 6010 (!LegalOperations || 6011 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6012 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 6013 6014 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6015 // but UINT_TO_FP is legal on this target, try to convert. 6016 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6017 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6018 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6019 if (DAG.SignBitIsZero(N0)) 6020 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 6021 } 6022 6023 // The next optimizations are desireable only if SELECT_CC can be lowered. 6024 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6025 // having to say they don't support SELECT_CC on every type the DAG knows 6026 // about, since there is no way to mark an opcode illegal at all value types 6027 // (See also visitSELECT) 6028 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6029 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6030 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6031 !VT.isVector() && 6032 (!LegalOperations || 6033 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6034 SDValue Ops[] = 6035 { N0.getOperand(0), N0.getOperand(1), 6036 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6037 N0.getOperand(2) }; 6038 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6039 } 6040 6041 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6042 // (select_cc x, y, 1.0, 0.0,, cc) 6043 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6044 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6045 (!LegalOperations || 6046 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6047 SDValue Ops[] = 6048 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6049 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6050 N0.getOperand(0).getOperand(2) }; 6051 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6052 } 6053 } 6054 6055 return SDValue(); 6056 } 6057 6058 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6059 SDValue N0 = N->getOperand(0); 6060 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6061 EVT VT = N->getValueType(0); 6062 EVT OpVT = N0.getValueType(); 6063 6064 // fold (uint_to_fp c1) -> c1fp 6065 if (N0C && OpVT != MVT::ppcf128 && 6066 // ...but only if the target supports immediate floating-point values 6067 (!LegalOperations || 6068 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6069 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 6070 6071 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 6072 // but SINT_TO_FP is legal on this target, try to convert. 6073 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 6074 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 6075 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 6076 if (DAG.SignBitIsZero(N0)) 6077 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 6078 } 6079 6080 // The next optimizations are desireable only if SELECT_CC can be lowered. 6081 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6082 // having to say they don't support SELECT_CC on every type the DAG knows 6083 // about, since there is no way to mark an opcode illegal at all value types 6084 // (See also visitSELECT) 6085 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6086 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6087 6088 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 6089 (!LegalOperations || 6090 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6091 SDValue Ops[] = 6092 { N0.getOperand(0), N0.getOperand(1), 6093 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 6094 N0.getOperand(2) }; 6095 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6096 } 6097 } 6098 6099 return SDValue(); 6100 } 6101 6102 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 6103 SDValue N0 = N->getOperand(0); 6104 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6105 EVT VT = N->getValueType(0); 6106 6107 // fold (fp_to_sint c1fp) -> c1 6108 if (N0CFP) 6109 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0); 6110 6111 return SDValue(); 6112 } 6113 6114 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 6115 SDValue N0 = N->getOperand(0); 6116 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6117 EVT VT = N->getValueType(0); 6118 6119 // fold (fp_to_uint c1fp) -> c1 6120 if (N0CFP && VT != MVT::ppcf128) 6121 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0); 6122 6123 return SDValue(); 6124 } 6125 6126 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 6127 SDValue N0 = N->getOperand(0); 6128 SDValue N1 = N->getOperand(1); 6129 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6130 EVT VT = N->getValueType(0); 6131 6132 // fold (fp_round c1fp) -> c1fp 6133 if (N0CFP && N0.getValueType() != MVT::ppcf128) 6134 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1); 6135 6136 // fold (fp_round (fp_extend x)) -> x 6137 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 6138 return N0.getOperand(0); 6139 6140 // fold (fp_round (fp_round x)) -> (fp_round x) 6141 if (N0.getOpcode() == ISD::FP_ROUND) { 6142 // This is a value preserving truncation if both round's are. 6143 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 6144 N0.getNode()->getConstantOperandVal(1) == 1; 6145 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0), 6146 DAG.getIntPtrConstant(IsTrunc)); 6147 } 6148 6149 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 6150 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 6151 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT, 6152 N0.getOperand(0), N1); 6153 AddToWorkList(Tmp.getNode()); 6154 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6155 Tmp, N0.getOperand(1)); 6156 } 6157 6158 return SDValue(); 6159 } 6160 6161 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 6162 SDValue N0 = N->getOperand(0); 6163 EVT VT = N->getValueType(0); 6164 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6165 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6166 6167 // fold (fp_round_inreg c1fp) -> c1fp 6168 if (N0CFP && isTypeLegal(EVT)) { 6169 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 6170 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round); 6171 } 6172 6173 return SDValue(); 6174 } 6175 6176 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 6177 SDValue N0 = N->getOperand(0); 6178 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6179 EVT VT = N->getValueType(0); 6180 6181 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 6182 if (N->hasOneUse() && 6183 N->use_begin()->getOpcode() == ISD::FP_ROUND) 6184 return SDValue(); 6185 6186 // fold (fp_extend c1fp) -> c1fp 6187 if (N0CFP && VT != MVT::ppcf128) 6188 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0); 6189 6190 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 6191 // value of X. 6192 if (N0.getOpcode() == ISD::FP_ROUND 6193 && N0.getNode()->getConstantOperandVal(1) == 1) { 6194 SDValue In = N0.getOperand(0); 6195 if (In.getValueType() == VT) return In; 6196 if (VT.bitsLT(In.getValueType())) 6197 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, 6198 In, N0.getOperand(1)); 6199 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In); 6200 } 6201 6202 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 6203 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() && 6204 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6205 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 6206 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6207 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 6208 LN0->getChain(), 6209 LN0->getBasePtr(), LN0->getPointerInfo(), 6210 N0.getValueType(), 6211 LN0->isVolatile(), LN0->isNonTemporal(), 6212 LN0->getAlignment()); 6213 CombineTo(N, ExtLoad); 6214 CombineTo(N0.getNode(), 6215 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), 6216 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 6217 ExtLoad.getValue(1)); 6218 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6219 } 6220 6221 return SDValue(); 6222 } 6223 6224 SDValue DAGCombiner::visitFNEG(SDNode *N) { 6225 SDValue N0 = N->getOperand(0); 6226 EVT VT = N->getValueType(0); 6227 6228 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 6229 &DAG.getTarget().Options)) 6230 return GetNegatedExpression(N0, DAG, LegalOperations); 6231 6232 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 6233 // constant pool values. 6234 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 6235 !VT.isVector() && 6236 N0.getNode()->hasOneUse() && 6237 N0.getOperand(0).getValueType().isInteger()) { 6238 SDValue Int = N0.getOperand(0); 6239 EVT IntVT = Int.getValueType(); 6240 if (IntVT.isInteger() && !IntVT.isVector()) { 6241 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int, 6242 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6243 AddToWorkList(Int.getNode()); 6244 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 6245 VT, Int); 6246 } 6247 } 6248 6249 return SDValue(); 6250 } 6251 6252 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 6253 SDValue N0 = N->getOperand(0); 6254 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6255 EVT VT = N->getValueType(0); 6256 6257 // fold (fceil c1) -> fceil(c1) 6258 if (N0CFP && VT != MVT::ppcf128) 6259 return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0); 6260 6261 return SDValue(); 6262 } 6263 6264 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 6265 SDValue N0 = N->getOperand(0); 6266 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6267 EVT VT = N->getValueType(0); 6268 6269 // fold (ftrunc c1) -> ftrunc(c1) 6270 if (N0CFP && VT != MVT::ppcf128) 6271 return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0); 6272 6273 return SDValue(); 6274 } 6275 6276 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 6277 SDValue N0 = N->getOperand(0); 6278 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6279 EVT VT = N->getValueType(0); 6280 6281 // fold (ffloor c1) -> ffloor(c1) 6282 if (N0CFP && VT != MVT::ppcf128) 6283 return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0); 6284 6285 return SDValue(); 6286 } 6287 6288 SDValue DAGCombiner::visitFABS(SDNode *N) { 6289 SDValue N0 = N->getOperand(0); 6290 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6291 EVT VT = N->getValueType(0); 6292 6293 // fold (fabs c1) -> fabs(c1) 6294 if (N0CFP && VT != MVT::ppcf128) 6295 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 6296 // fold (fabs (fabs x)) -> (fabs x) 6297 if (N0.getOpcode() == ISD::FABS) 6298 return N->getOperand(0); 6299 // fold (fabs (fneg x)) -> (fabs x) 6300 // fold (fabs (fcopysign x, y)) -> (fabs x) 6301 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 6302 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0)); 6303 6304 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 6305 // constant pool values. 6306 if (!TLI.isFAbsFree(VT) && 6307 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 6308 N0.getOperand(0).getValueType().isInteger() && 6309 !N0.getOperand(0).getValueType().isVector()) { 6310 SDValue Int = N0.getOperand(0); 6311 EVT IntVT = Int.getValueType(); 6312 if (IntVT.isInteger() && !IntVT.isVector()) { 6313 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int, 6314 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6315 AddToWorkList(Int.getNode()); 6316 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 6317 N->getValueType(0), Int); 6318 } 6319 } 6320 6321 return SDValue(); 6322 } 6323 6324 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 6325 SDValue Chain = N->getOperand(0); 6326 SDValue N1 = N->getOperand(1); 6327 SDValue N2 = N->getOperand(2); 6328 6329 // If N is a constant we could fold this into a fallthrough or unconditional 6330 // branch. However that doesn't happen very often in normal code, because 6331 // Instcombine/SimplifyCFG should have handled the available opportunities. 6332 // If we did this folding here, it would be necessary to update the 6333 // MachineBasicBlock CFG, which is awkward. 6334 6335 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 6336 // on the target. 6337 if (N1.getOpcode() == ISD::SETCC && 6338 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) { 6339 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 6340 Chain, N1.getOperand(2), 6341 N1.getOperand(0), N1.getOperand(1), N2); 6342 } 6343 6344 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 6345 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 6346 (N1.getOperand(0).hasOneUse() && 6347 N1.getOperand(0).getOpcode() == ISD::SRL))) { 6348 SDNode *Trunc = 0; 6349 if (N1.getOpcode() == ISD::TRUNCATE) { 6350 // Look pass the truncate. 6351 Trunc = N1.getNode(); 6352 N1 = N1.getOperand(0); 6353 } 6354 6355 // Match this pattern so that we can generate simpler code: 6356 // 6357 // %a = ... 6358 // %b = and i32 %a, 2 6359 // %c = srl i32 %b, 1 6360 // brcond i32 %c ... 6361 // 6362 // into 6363 // 6364 // %a = ... 6365 // %b = and i32 %a, 2 6366 // %c = setcc eq %b, 0 6367 // brcond %c ... 6368 // 6369 // This applies only when the AND constant value has one bit set and the 6370 // SRL constant is equal to the log2 of the AND constant. The back-end is 6371 // smart enough to convert the result into a TEST/JMP sequence. 6372 SDValue Op0 = N1.getOperand(0); 6373 SDValue Op1 = N1.getOperand(1); 6374 6375 if (Op0.getOpcode() == ISD::AND && 6376 Op1.getOpcode() == ISD::Constant) { 6377 SDValue AndOp1 = Op0.getOperand(1); 6378 6379 if (AndOp1.getOpcode() == ISD::Constant) { 6380 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 6381 6382 if (AndConst.isPowerOf2() && 6383 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 6384 SDValue SetCC = 6385 DAG.getSetCC(N->getDebugLoc(), 6386 TLI.getSetCCResultType(Op0.getValueType()), 6387 Op0, DAG.getConstant(0, Op0.getValueType()), 6388 ISD::SETNE); 6389 6390 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6391 MVT::Other, Chain, SetCC, N2); 6392 // Don't add the new BRCond into the worklist or else SimplifySelectCC 6393 // will convert it back to (X & C1) >> C2. 6394 CombineTo(N, NewBRCond, false); 6395 // Truncate is dead. 6396 if (Trunc) { 6397 removeFromWorkList(Trunc); 6398 DAG.DeleteNode(Trunc); 6399 } 6400 // Replace the uses of SRL with SETCC 6401 WorkListRemover DeadNodes(*this); 6402 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6403 removeFromWorkList(N1.getNode()); 6404 DAG.DeleteNode(N1.getNode()); 6405 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6406 } 6407 } 6408 } 6409 6410 if (Trunc) 6411 // Restore N1 if the above transformation doesn't match. 6412 N1 = N->getOperand(1); 6413 } 6414 6415 // Transform br(xor(x, y)) -> br(x != y) 6416 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 6417 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 6418 SDNode *TheXor = N1.getNode(); 6419 SDValue Op0 = TheXor->getOperand(0); 6420 SDValue Op1 = TheXor->getOperand(1); 6421 if (Op0.getOpcode() == Op1.getOpcode()) { 6422 // Avoid missing important xor optimizations. 6423 SDValue Tmp = visitXOR(TheXor); 6424 if (Tmp.getNode() && Tmp.getNode() != TheXor) { 6425 DEBUG(dbgs() << "\nReplacing.8 "; 6426 TheXor->dump(&DAG); 6427 dbgs() << "\nWith: "; 6428 Tmp.getNode()->dump(&DAG); 6429 dbgs() << '\n'); 6430 WorkListRemover DeadNodes(*this); 6431 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 6432 removeFromWorkList(TheXor); 6433 DAG.DeleteNode(TheXor); 6434 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6435 MVT::Other, Chain, Tmp, N2); 6436 } 6437 } 6438 6439 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 6440 bool Equal = false; 6441 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 6442 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 6443 Op0.getOpcode() == ISD::XOR) { 6444 TheXor = Op0.getNode(); 6445 Equal = true; 6446 } 6447 6448 EVT SetCCVT = N1.getValueType(); 6449 if (LegalTypes) 6450 SetCCVT = TLI.getSetCCResultType(SetCCVT); 6451 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(), 6452 SetCCVT, 6453 Op0, Op1, 6454 Equal ? ISD::SETEQ : ISD::SETNE); 6455 // Replace the uses of XOR with SETCC 6456 WorkListRemover DeadNodes(*this); 6457 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6458 removeFromWorkList(N1.getNode()); 6459 DAG.DeleteNode(N1.getNode()); 6460 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6461 MVT::Other, Chain, SetCC, N2); 6462 } 6463 } 6464 6465 return SDValue(); 6466 } 6467 6468 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 6469 // 6470 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 6471 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 6472 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 6473 6474 // If N is a constant we could fold this into a fallthrough or unconditional 6475 // branch. However that doesn't happen very often in normal code, because 6476 // Instcombine/SimplifyCFG should have handled the available opportunities. 6477 // If we did this folding here, it would be necessary to update the 6478 // MachineBasicBlock CFG, which is awkward. 6479 6480 // Use SimplifySetCC to simplify SETCC's. 6481 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()), 6482 CondLHS, CondRHS, CC->get(), N->getDebugLoc(), 6483 false); 6484 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 6485 6486 // fold to a simpler setcc 6487 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 6488 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 6489 N->getOperand(0), Simp.getOperand(2), 6490 Simp.getOperand(0), Simp.getOperand(1), 6491 N->getOperand(4)); 6492 6493 return SDValue(); 6494 } 6495 6496 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 6497 /// uses N as its base pointer and that N may be folded in the load / store 6498 /// addressing mode. 6499 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 6500 SelectionDAG &DAG, 6501 const TargetLowering &TLI) { 6502 EVT VT; 6503 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 6504 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 6505 return false; 6506 VT = Use->getValueType(0); 6507 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 6508 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 6509 return false; 6510 VT = ST->getValue().getValueType(); 6511 } else 6512 return false; 6513 6514 TargetLowering::AddrMode AM; 6515 if (N->getOpcode() == ISD::ADD) { 6516 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6517 if (Offset) 6518 // [reg +/- imm] 6519 AM.BaseOffs = Offset->getSExtValue(); 6520 else 6521 // [reg +/- reg] 6522 AM.Scale = 1; 6523 } else if (N->getOpcode() == ISD::SUB) { 6524 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6525 if (Offset) 6526 // [reg +/- imm] 6527 AM.BaseOffs = -Offset->getSExtValue(); 6528 else 6529 // [reg +/- reg] 6530 AM.Scale = 1; 6531 } else 6532 return false; 6533 6534 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 6535 } 6536 6537 /// CombineToPreIndexedLoadStore - Try turning a load / store into a 6538 /// pre-indexed load / store when the base pointer is an add or subtract 6539 /// and it has other uses besides the load / store. After the 6540 /// transformation, the new indexed load / store has effectively folded 6541 /// the add / subtract in and all of its other uses are redirected to the 6542 /// new load / store. 6543 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 6544 if (Level < AfterLegalizeDAG) 6545 return false; 6546 6547 bool isLoad = true; 6548 SDValue Ptr; 6549 EVT VT; 6550 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 6551 if (LD->isIndexed()) 6552 return false; 6553 VT = LD->getMemoryVT(); 6554 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 6555 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 6556 return false; 6557 Ptr = LD->getBasePtr(); 6558 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 6559 if (ST->isIndexed()) 6560 return false; 6561 VT = ST->getMemoryVT(); 6562 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 6563 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 6564 return false; 6565 Ptr = ST->getBasePtr(); 6566 isLoad = false; 6567 } else { 6568 return false; 6569 } 6570 6571 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 6572 // out. There is no reason to make this a preinc/predec. 6573 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 6574 Ptr.getNode()->hasOneUse()) 6575 return false; 6576 6577 // Ask the target to do addressing mode selection. 6578 SDValue BasePtr; 6579 SDValue Offset; 6580 ISD::MemIndexedMode AM = ISD::UNINDEXED; 6581 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 6582 return false; 6583 // Don't create a indexed load / store with zero offset. 6584 if (isa<ConstantSDNode>(Offset) && 6585 cast<ConstantSDNode>(Offset)->isNullValue()) 6586 return false; 6587 6588 // Try turning it into a pre-indexed load / store except when: 6589 // 1) The new base ptr is a frame index. 6590 // 2) If N is a store and the new base ptr is either the same as or is a 6591 // predecessor of the value being stored. 6592 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 6593 // that would create a cycle. 6594 // 4) All uses are load / store ops that use it as old base ptr. 6595 6596 // Check #1. Preinc'ing a frame index would require copying the stack pointer 6597 // (plus the implicit offset) to a register to preinc anyway. 6598 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 6599 return false; 6600 6601 // Check #2. 6602 if (!isLoad) { 6603 SDValue Val = cast<StoreSDNode>(N)->getValue(); 6604 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 6605 return false; 6606 } 6607 6608 // Now check for #3 and #4. 6609 bool RealUse = false; 6610 6611 // Caches for hasPredecessorHelper 6612 SmallPtrSet<const SDNode *, 32> Visited; 6613 SmallVector<const SDNode *, 16> Worklist; 6614 6615 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 6616 E = Ptr.getNode()->use_end(); I != E; ++I) { 6617 SDNode *Use = *I; 6618 if (Use == N) 6619 continue; 6620 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 6621 return false; 6622 6623 // If Ptr may be folded in addressing mode of other use, then it's 6624 // not profitable to do this transformation. 6625 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 6626 RealUse = true; 6627 } 6628 6629 if (!RealUse) 6630 return false; 6631 6632 SDValue Result; 6633 if (isLoad) 6634 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 6635 BasePtr, Offset, AM); 6636 else 6637 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 6638 BasePtr, Offset, AM); 6639 ++PreIndexedNodes; 6640 ++NodesCombined; 6641 DEBUG(dbgs() << "\nReplacing.4 "; 6642 N->dump(&DAG); 6643 dbgs() << "\nWith: "; 6644 Result.getNode()->dump(&DAG); 6645 dbgs() << '\n'); 6646 WorkListRemover DeadNodes(*this); 6647 if (isLoad) { 6648 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 6649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 6650 } else { 6651 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 6652 } 6653 6654 // Finally, since the node is now dead, remove it from the graph. 6655 DAG.DeleteNode(N); 6656 6657 // Replace the uses of Ptr with uses of the updated base value. 6658 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 6659 removeFromWorkList(Ptr.getNode()); 6660 DAG.DeleteNode(Ptr.getNode()); 6661 6662 return true; 6663 } 6664 6665 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a 6666 /// add / sub of the base pointer node into a post-indexed load / store. 6667 /// The transformation folded the add / subtract into the new indexed 6668 /// load / store effectively and all of its uses are redirected to the 6669 /// new load / store. 6670 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 6671 if (Level < AfterLegalizeDAG) 6672 return false; 6673 6674 bool isLoad = true; 6675 SDValue Ptr; 6676 EVT VT; 6677 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 6678 if (LD->isIndexed()) 6679 return false; 6680 VT = LD->getMemoryVT(); 6681 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 6682 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 6683 return false; 6684 Ptr = LD->getBasePtr(); 6685 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 6686 if (ST->isIndexed()) 6687 return false; 6688 VT = ST->getMemoryVT(); 6689 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 6690 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 6691 return false; 6692 Ptr = ST->getBasePtr(); 6693 isLoad = false; 6694 } else { 6695 return false; 6696 } 6697 6698 if (Ptr.getNode()->hasOneUse()) 6699 return false; 6700 6701 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 6702 E = Ptr.getNode()->use_end(); I != E; ++I) { 6703 SDNode *Op = *I; 6704 if (Op == N || 6705 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 6706 continue; 6707 6708 SDValue BasePtr; 6709 SDValue Offset; 6710 ISD::MemIndexedMode AM = ISD::UNINDEXED; 6711 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 6712 // Don't create a indexed load / store with zero offset. 6713 if (isa<ConstantSDNode>(Offset) && 6714 cast<ConstantSDNode>(Offset)->isNullValue()) 6715 continue; 6716 6717 // Try turning it into a post-indexed load / store except when 6718 // 1) All uses are load / store ops that use it as base ptr (and 6719 // it may be folded as addressing mmode). 6720 // 2) Op must be independent of N, i.e. Op is neither a predecessor 6721 // nor a successor of N. Otherwise, if Op is folded that would 6722 // create a cycle. 6723 6724 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 6725 continue; 6726 6727 // Check for #1. 6728 bool TryNext = false; 6729 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 6730 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 6731 SDNode *Use = *II; 6732 if (Use == Ptr.getNode()) 6733 continue; 6734 6735 // If all the uses are load / store addresses, then don't do the 6736 // transformation. 6737 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 6738 bool RealUse = false; 6739 for (SDNode::use_iterator III = Use->use_begin(), 6740 EEE = Use->use_end(); III != EEE; ++III) { 6741 SDNode *UseUse = *III; 6742 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 6743 RealUse = true; 6744 } 6745 6746 if (!RealUse) { 6747 TryNext = true; 6748 break; 6749 } 6750 } 6751 } 6752 6753 if (TryNext) 6754 continue; 6755 6756 // Check for #2 6757 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 6758 SDValue Result = isLoad 6759 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 6760 BasePtr, Offset, AM) 6761 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 6762 BasePtr, Offset, AM); 6763 ++PostIndexedNodes; 6764 ++NodesCombined; 6765 DEBUG(dbgs() << "\nReplacing.5 "; 6766 N->dump(&DAG); 6767 dbgs() << "\nWith: "; 6768 Result.getNode()->dump(&DAG); 6769 dbgs() << '\n'); 6770 WorkListRemover DeadNodes(*this); 6771 if (isLoad) { 6772 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 6773 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 6774 } else { 6775 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 6776 } 6777 6778 // Finally, since the node is now dead, remove it from the graph. 6779 DAG.DeleteNode(N); 6780 6781 // Replace the uses of Use with uses of the updated base value. 6782 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 6783 Result.getValue(isLoad ? 1 : 0)); 6784 removeFromWorkList(Op); 6785 DAG.DeleteNode(Op); 6786 return true; 6787 } 6788 } 6789 } 6790 6791 return false; 6792 } 6793 6794 SDValue DAGCombiner::visitLOAD(SDNode *N) { 6795 LoadSDNode *LD = cast<LoadSDNode>(N); 6796 SDValue Chain = LD->getChain(); 6797 SDValue Ptr = LD->getBasePtr(); 6798 6799 // If load is not volatile and there are no uses of the loaded value (and 6800 // the updated indexed value in case of indexed loads), change uses of the 6801 // chain value into uses of the chain input (i.e. delete the dead load). 6802 if (!LD->isVolatile()) { 6803 if (N->getValueType(1) == MVT::Other) { 6804 // Unindexed loads. 6805 if (!N->hasAnyUseOfValue(0)) { 6806 // It's not safe to use the two value CombineTo variant here. e.g. 6807 // v1, chain2 = load chain1, loc 6808 // v2, chain3 = load chain2, loc 6809 // v3 = add v2, c 6810 // Now we replace use of chain2 with chain1. This makes the second load 6811 // isomorphic to the one we are deleting, and thus makes this load live. 6812 DEBUG(dbgs() << "\nReplacing.6 "; 6813 N->dump(&DAG); 6814 dbgs() << "\nWith chain: "; 6815 Chain.getNode()->dump(&DAG); 6816 dbgs() << "\n"); 6817 WorkListRemover DeadNodes(*this); 6818 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 6819 6820 if (N->use_empty()) { 6821 removeFromWorkList(N); 6822 DAG.DeleteNode(N); 6823 } 6824 6825 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6826 } 6827 } else { 6828 // Indexed loads. 6829 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 6830 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 6831 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 6832 DEBUG(dbgs() << "\nReplacing.7 "; 6833 N->dump(&DAG); 6834 dbgs() << "\nWith: "; 6835 Undef.getNode()->dump(&DAG); 6836 dbgs() << " and 2 other values\n"); 6837 WorkListRemover DeadNodes(*this); 6838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 6839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 6840 DAG.getUNDEF(N->getValueType(1))); 6841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 6842 removeFromWorkList(N); 6843 DAG.DeleteNode(N); 6844 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6845 } 6846 } 6847 } 6848 6849 // If this load is directly stored, replace the load value with the stored 6850 // value. 6851 // TODO: Handle store large -> read small portion. 6852 // TODO: Handle TRUNCSTORE/LOADEXT 6853 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 6854 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 6855 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 6856 if (PrevST->getBasePtr() == Ptr && 6857 PrevST->getValue().getValueType() == N->getValueType(0)) 6858 return CombineTo(N, Chain.getOperand(1), Chain); 6859 } 6860 } 6861 6862 // Try to infer better alignment information than the load already has. 6863 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 6864 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 6865 if (Align > LD->getAlignment()) 6866 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(), 6867 LD->getValueType(0), 6868 Chain, Ptr, LD->getPointerInfo(), 6869 LD->getMemoryVT(), 6870 LD->isVolatile(), LD->isNonTemporal(), Align); 6871 } 6872 } 6873 6874 if (CombinerAA) { 6875 // Walk up chain skipping non-aliasing memory nodes. 6876 SDValue BetterChain = FindBetterChain(N, Chain); 6877 6878 // If there is a better chain. 6879 if (Chain != BetterChain) { 6880 SDValue ReplLoad; 6881 6882 // Replace the chain to void dependency. 6883 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 6884 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(), 6885 BetterChain, Ptr, LD->getPointerInfo(), 6886 LD->isVolatile(), LD->isNonTemporal(), 6887 LD->isInvariant(), LD->getAlignment()); 6888 } else { 6889 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(), 6890 LD->getValueType(0), 6891 BetterChain, Ptr, LD->getPointerInfo(), 6892 LD->getMemoryVT(), 6893 LD->isVolatile(), 6894 LD->isNonTemporal(), 6895 LD->getAlignment()); 6896 } 6897 6898 // Create token factor to keep old chain connected. 6899 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 6900 MVT::Other, Chain, ReplLoad.getValue(1)); 6901 6902 // Make sure the new and old chains are cleaned up. 6903 AddToWorkList(Token.getNode()); 6904 6905 // Replace uses with load result and token factor. Don't add users 6906 // to work list. 6907 return CombineTo(N, ReplLoad.getValue(0), Token, false); 6908 } 6909 } 6910 6911 // Try transforming N to an indexed load. 6912 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 6913 return SDValue(N, 0); 6914 6915 return SDValue(); 6916 } 6917 6918 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 6919 /// load is having specific bytes cleared out. If so, return the byte size 6920 /// being masked out and the shift amount. 6921 static std::pair<unsigned, unsigned> 6922 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 6923 std::pair<unsigned, unsigned> Result(0, 0); 6924 6925 // Check for the structure we're looking for. 6926 if (V->getOpcode() != ISD::AND || 6927 !isa<ConstantSDNode>(V->getOperand(1)) || 6928 !ISD::isNormalLoad(V->getOperand(0).getNode())) 6929 return Result; 6930 6931 // Check the chain and pointer. 6932 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 6933 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 6934 6935 // The store should be chained directly to the load or be an operand of a 6936 // tokenfactor. 6937 if (LD == Chain.getNode()) 6938 ; // ok. 6939 else if (Chain->getOpcode() != ISD::TokenFactor) 6940 return Result; // Fail. 6941 else { 6942 bool isOk = false; 6943 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 6944 if (Chain->getOperand(i).getNode() == LD) { 6945 isOk = true; 6946 break; 6947 } 6948 if (!isOk) return Result; 6949 } 6950 6951 // This only handles simple types. 6952 if (V.getValueType() != MVT::i16 && 6953 V.getValueType() != MVT::i32 && 6954 V.getValueType() != MVT::i64) 6955 return Result; 6956 6957 // Check the constant mask. Invert it so that the bits being masked out are 6958 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 6959 // follow the sign bit for uniformity. 6960 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 6961 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask); 6962 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 6963 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask); 6964 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 6965 if (NotMaskLZ == 64) return Result; // All zero mask. 6966 6967 // See if we have a continuous run of bits. If so, we have 0*1+0* 6968 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 6969 return Result; 6970 6971 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 6972 if (V.getValueType() != MVT::i64 && NotMaskLZ) 6973 NotMaskLZ -= 64-V.getValueSizeInBits(); 6974 6975 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 6976 switch (MaskedBytes) { 6977 case 1: 6978 case 2: 6979 case 4: break; 6980 default: return Result; // All one mask, or 5-byte mask. 6981 } 6982 6983 // Verify that the first bit starts at a multiple of mask so that the access 6984 // is aligned the same as the access width. 6985 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 6986 6987 Result.first = MaskedBytes; 6988 Result.second = NotMaskTZ/8; 6989 return Result; 6990 } 6991 6992 6993 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 6994 /// provides a value as specified by MaskInfo. If so, replace the specified 6995 /// store with a narrower store of truncated IVal. 6996 static SDNode * 6997 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 6998 SDValue IVal, StoreSDNode *St, 6999 DAGCombiner *DC) { 7000 unsigned NumBytes = MaskInfo.first; 7001 unsigned ByteShift = MaskInfo.second; 7002 SelectionDAG &DAG = DC->getDAG(); 7003 7004 // Check to see if IVal is all zeros in the part being masked in by the 'or' 7005 // that uses this. If not, this is not a replacement. 7006 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 7007 ByteShift*8, (ByteShift+NumBytes)*8); 7008 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 7009 7010 // Check that it is legal on the target to do this. It is legal if the new 7011 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 7012 // legalization. 7013 MVT VT = MVT::getIntegerVT(NumBytes*8); 7014 if (!DC->isTypeLegal(VT)) 7015 return 0; 7016 7017 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 7018 // shifted by ByteShift and truncated down to NumBytes. 7019 if (ByteShift) 7020 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal, 7021 DAG.getConstant(ByteShift*8, 7022 DC->getShiftAmountTy(IVal.getValueType()))); 7023 7024 // Figure out the offset for the store and the alignment of the access. 7025 unsigned StOffset; 7026 unsigned NewAlign = St->getAlignment(); 7027 7028 if (DAG.getTargetLoweringInfo().isLittleEndian()) 7029 StOffset = ByteShift; 7030 else 7031 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 7032 7033 SDValue Ptr = St->getBasePtr(); 7034 if (StOffset) { 7035 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(), 7036 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 7037 NewAlign = MinAlign(NewAlign, StOffset); 7038 } 7039 7040 // Truncate down to the new size. 7041 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal); 7042 7043 ++OpsNarrowed; 7044 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr, 7045 St->getPointerInfo().getWithOffset(StOffset), 7046 false, false, NewAlign).getNode(); 7047 } 7048 7049 7050 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 7051 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 7052 /// of the loaded bits, try narrowing the load and store if it would end up 7053 /// being a win for performance or code size. 7054 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 7055 StoreSDNode *ST = cast<StoreSDNode>(N); 7056 if (ST->isVolatile()) 7057 return SDValue(); 7058 7059 SDValue Chain = ST->getChain(); 7060 SDValue Value = ST->getValue(); 7061 SDValue Ptr = ST->getBasePtr(); 7062 EVT VT = Value.getValueType(); 7063 7064 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 7065 return SDValue(); 7066 7067 unsigned Opc = Value.getOpcode(); 7068 7069 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 7070 // is a byte mask indicating a consecutive number of bytes, check to see if 7071 // Y is known to provide just those bytes. If so, we try to replace the 7072 // load + replace + store sequence with a single (narrower) store, which makes 7073 // the load dead. 7074 if (Opc == ISD::OR) { 7075 std::pair<unsigned, unsigned> MaskedLoad; 7076 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 7077 if (MaskedLoad.first) 7078 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7079 Value.getOperand(1), ST,this)) 7080 return SDValue(NewST, 0); 7081 7082 // Or is commutative, so try swapping X and Y. 7083 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 7084 if (MaskedLoad.first) 7085 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7086 Value.getOperand(0), ST,this)) 7087 return SDValue(NewST, 0); 7088 } 7089 7090 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 7091 Value.getOperand(1).getOpcode() != ISD::Constant) 7092 return SDValue(); 7093 7094 SDValue N0 = Value.getOperand(0); 7095 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7096 Chain == SDValue(N0.getNode(), 1)) { 7097 LoadSDNode *LD = cast<LoadSDNode>(N0); 7098 if (LD->getBasePtr() != Ptr || 7099 LD->getPointerInfo().getAddrSpace() != 7100 ST->getPointerInfo().getAddrSpace()) 7101 return SDValue(); 7102 7103 // Find the type to narrow it the load / op / store to. 7104 SDValue N1 = Value.getOperand(1); 7105 unsigned BitWidth = N1.getValueSizeInBits(); 7106 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 7107 if (Opc == ISD::AND) 7108 Imm ^= APInt::getAllOnesValue(BitWidth); 7109 if (Imm == 0 || Imm.isAllOnesValue()) 7110 return SDValue(); 7111 unsigned ShAmt = Imm.countTrailingZeros(); 7112 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 7113 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 7114 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7115 while (NewBW < BitWidth && 7116 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 7117 TLI.isNarrowingProfitable(VT, NewVT))) { 7118 NewBW = NextPowerOf2(NewBW); 7119 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7120 } 7121 if (NewBW >= BitWidth) 7122 return SDValue(); 7123 7124 // If the lsb changed does not start at the type bitwidth boundary, 7125 // start at the previous one. 7126 if (ShAmt % NewBW) 7127 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 7128 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW); 7129 if ((Imm & Mask) == Imm) { 7130 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 7131 if (Opc == ISD::AND) 7132 NewImm ^= APInt::getAllOnesValue(NewBW); 7133 uint64_t PtrOff = ShAmt / 8; 7134 // For big endian targets, we need to adjust the offset to the pointer to 7135 // load the correct bytes. 7136 if (TLI.isBigEndian()) 7137 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 7138 7139 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 7140 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 7141 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy)) 7142 return SDValue(); 7143 7144 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(), 7145 Ptr.getValueType(), Ptr, 7146 DAG.getConstant(PtrOff, Ptr.getValueType())); 7147 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(), 7148 LD->getChain(), NewPtr, 7149 LD->getPointerInfo().getWithOffset(PtrOff), 7150 LD->isVolatile(), LD->isNonTemporal(), 7151 LD->isInvariant(), NewAlign); 7152 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD, 7153 DAG.getConstant(NewImm, NewVT)); 7154 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(), 7155 NewVal, NewPtr, 7156 ST->getPointerInfo().getWithOffset(PtrOff), 7157 false, false, NewAlign); 7158 7159 AddToWorkList(NewPtr.getNode()); 7160 AddToWorkList(NewLD.getNode()); 7161 AddToWorkList(NewVal.getNode()); 7162 WorkListRemover DeadNodes(*this); 7163 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 7164 ++OpsNarrowed; 7165 return NewST; 7166 } 7167 } 7168 7169 return SDValue(); 7170 } 7171 7172 /// TransformFPLoadStorePair - For a given floating point load / store pair, 7173 /// if the load value isn't used by any other operations, then consider 7174 /// transforming the pair to integer load / store operations if the target 7175 /// deems the transformation profitable. 7176 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 7177 StoreSDNode *ST = cast<StoreSDNode>(N); 7178 SDValue Chain = ST->getChain(); 7179 SDValue Value = ST->getValue(); 7180 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 7181 Value.hasOneUse() && 7182 Chain == SDValue(Value.getNode(), 1)) { 7183 LoadSDNode *LD = cast<LoadSDNode>(Value); 7184 EVT VT = LD->getMemoryVT(); 7185 if (!VT.isFloatingPoint() || 7186 VT != ST->getMemoryVT() || 7187 LD->isNonTemporal() || 7188 ST->isNonTemporal() || 7189 LD->getPointerInfo().getAddrSpace() != 0 || 7190 ST->getPointerInfo().getAddrSpace() != 0) 7191 return SDValue(); 7192 7193 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7194 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 7195 !TLI.isOperationLegal(ISD::STORE, IntVT) || 7196 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 7197 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 7198 return SDValue(); 7199 7200 unsigned LDAlign = LD->getAlignment(); 7201 unsigned STAlign = ST->getAlignment(); 7202 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 7203 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy); 7204 if (LDAlign < ABIAlign || STAlign < ABIAlign) 7205 return SDValue(); 7206 7207 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(), 7208 LD->getChain(), LD->getBasePtr(), 7209 LD->getPointerInfo(), 7210 false, false, false, LDAlign); 7211 7212 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(), 7213 NewLD, ST->getBasePtr(), 7214 ST->getPointerInfo(), 7215 false, false, STAlign); 7216 7217 AddToWorkList(NewLD.getNode()); 7218 AddToWorkList(NewST.getNode()); 7219 WorkListRemover DeadNodes(*this); 7220 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 7221 ++LdStFP2Int; 7222 return NewST; 7223 } 7224 7225 return SDValue(); 7226 } 7227 7228 SDValue DAGCombiner::visitSTORE(SDNode *N) { 7229 StoreSDNode *ST = cast<StoreSDNode>(N); 7230 SDValue Chain = ST->getChain(); 7231 SDValue Value = ST->getValue(); 7232 SDValue Ptr = ST->getBasePtr(); 7233 7234 // If this is a store of a bit convert, store the input value if the 7235 // resultant store does not need a higher alignment than the original. 7236 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 7237 ST->isUnindexed()) { 7238 unsigned OrigAlign = ST->getAlignment(); 7239 EVT SVT = Value.getOperand(0).getValueType(); 7240 unsigned Align = TLI.getTargetData()-> 7241 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 7242 if (Align <= OrigAlign && 7243 ((!LegalOperations && !ST->isVolatile()) || 7244 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 7245 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0), 7246 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7247 ST->isNonTemporal(), OrigAlign); 7248 } 7249 7250 // Turn 'store undef, Ptr' -> nothing. 7251 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 7252 return Chain; 7253 7254 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 7255 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 7256 // NOTE: If the original store is volatile, this transform must not increase 7257 // the number of stores. For example, on x86-32 an f64 can be stored in one 7258 // processor operation but an i64 (which is not legal) requires two. So the 7259 // transform should not be done in this case. 7260 if (Value.getOpcode() != ISD::TargetConstantFP) { 7261 SDValue Tmp; 7262 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) { 7263 default: llvm_unreachable("Unknown FP type"); 7264 case MVT::f16: // We don't do this for these yet. 7265 case MVT::f80: 7266 case MVT::f128: 7267 case MVT::ppcf128: 7268 break; 7269 case MVT::f32: 7270 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 7271 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 7272 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 7273 bitcastToAPInt().getZExtValue(), MVT::i32); 7274 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 7275 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7276 ST->isNonTemporal(), ST->getAlignment()); 7277 } 7278 break; 7279 case MVT::f64: 7280 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 7281 !ST->isVolatile()) || 7282 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 7283 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 7284 getZExtValue(), MVT::i64); 7285 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 7286 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7287 ST->isNonTemporal(), ST->getAlignment()); 7288 } 7289 7290 if (!ST->isVolatile() && 7291 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 7292 // Many FP stores are not made apparent until after legalize, e.g. for 7293 // argument passing. Since this is so common, custom legalize the 7294 // 64-bit integer store into two 32-bit stores. 7295 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 7296 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 7297 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 7298 if (TLI.isBigEndian()) std::swap(Lo, Hi); 7299 7300 unsigned Alignment = ST->getAlignment(); 7301 bool isVolatile = ST->isVolatile(); 7302 bool isNonTemporal = ST->isNonTemporal(); 7303 7304 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo, 7305 Ptr, ST->getPointerInfo(), 7306 isVolatile, isNonTemporal, 7307 ST->getAlignment()); 7308 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr, 7309 DAG.getConstant(4, Ptr.getValueType())); 7310 Alignment = MinAlign(Alignment, 4U); 7311 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi, 7312 Ptr, ST->getPointerInfo().getWithOffset(4), 7313 isVolatile, isNonTemporal, 7314 Alignment); 7315 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 7316 St0, St1); 7317 } 7318 7319 break; 7320 } 7321 } 7322 } 7323 7324 // Try to infer better alignment information than the store already has. 7325 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 7326 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7327 if (Align > ST->getAlignment()) 7328 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value, 7329 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7330 ST->isVolatile(), ST->isNonTemporal(), Align); 7331 } 7332 } 7333 7334 // Try transforming a pair floating point load / store ops to integer 7335 // load / store ops. 7336 SDValue NewST = TransformFPLoadStorePair(N); 7337 if (NewST.getNode()) 7338 return NewST; 7339 7340 if (CombinerAA) { 7341 // Walk up chain skipping non-aliasing memory nodes. 7342 SDValue BetterChain = FindBetterChain(N, Chain); 7343 7344 // If there is a better chain. 7345 if (Chain != BetterChain) { 7346 SDValue ReplStore; 7347 7348 // Replace the chain to avoid dependency. 7349 if (ST->isTruncatingStore()) { 7350 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr, 7351 ST->getPointerInfo(), 7352 ST->getMemoryVT(), ST->isVolatile(), 7353 ST->isNonTemporal(), ST->getAlignment()); 7354 } else { 7355 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr, 7356 ST->getPointerInfo(), 7357 ST->isVolatile(), ST->isNonTemporal(), 7358 ST->getAlignment()); 7359 } 7360 7361 // Create token to keep both nodes around. 7362 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 7363 MVT::Other, Chain, ReplStore); 7364 7365 // Make sure the new and old chains are cleaned up. 7366 AddToWorkList(Token.getNode()); 7367 7368 // Don't add users to work list. 7369 return CombineTo(N, Token, false); 7370 } 7371 } 7372 7373 // Try transforming N to an indexed store. 7374 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7375 return SDValue(N, 0); 7376 7377 // FIXME: is there such a thing as a truncating indexed store? 7378 if (ST->isTruncatingStore() && ST->isUnindexed() && 7379 Value.getValueType().isInteger()) { 7380 // See if we can simplify the input to this truncstore with knowledge that 7381 // only the low bits are being used. For example: 7382 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 7383 SDValue Shorter = 7384 GetDemandedBits(Value, 7385 APInt::getLowBitsSet( 7386 Value.getValueType().getScalarType().getSizeInBits(), 7387 ST->getMemoryVT().getScalarType().getSizeInBits())); 7388 AddToWorkList(Value.getNode()); 7389 if (Shorter.getNode()) 7390 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter, 7391 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7392 ST->isVolatile(), ST->isNonTemporal(), 7393 ST->getAlignment()); 7394 7395 // Otherwise, see if we can simplify the operation with 7396 // SimplifyDemandedBits, which only works if the value has a single use. 7397 if (SimplifyDemandedBits(Value, 7398 APInt::getLowBitsSet( 7399 Value.getValueType().getScalarType().getSizeInBits(), 7400 ST->getMemoryVT().getScalarType().getSizeInBits()))) 7401 return SDValue(N, 0); 7402 } 7403 7404 // If this is a load followed by a store to the same location, then the store 7405 // is dead/noop. 7406 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 7407 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 7408 ST->isUnindexed() && !ST->isVolatile() && 7409 // There can't be any side effects between the load and store, such as 7410 // a call or store. 7411 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 7412 // The store is dead, remove it. 7413 return Chain; 7414 } 7415 } 7416 7417 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 7418 // truncating store. We can do this even if this is already a truncstore. 7419 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 7420 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 7421 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 7422 ST->getMemoryVT())) { 7423 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0), 7424 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7425 ST->isVolatile(), ST->isNonTemporal(), 7426 ST->getAlignment()); 7427 } 7428 7429 return ReduceLoadOpStoreWidth(N); 7430 } 7431 7432 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 7433 SDValue InVec = N->getOperand(0); 7434 SDValue InVal = N->getOperand(1); 7435 SDValue EltNo = N->getOperand(2); 7436 DebugLoc dl = N->getDebugLoc(); 7437 7438 // If the inserted element is an UNDEF, just use the input vector. 7439 if (InVal.getOpcode() == ISD::UNDEF) 7440 return InVec; 7441 7442 EVT VT = InVec.getValueType(); 7443 7444 // If we can't generate a legal BUILD_VECTOR, exit 7445 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 7446 return SDValue(); 7447 7448 // Check that we know which element is being inserted 7449 if (!isa<ConstantSDNode>(EltNo)) 7450 return SDValue(); 7451 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7452 7453 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 7454 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 7455 // vector elements. 7456 SmallVector<SDValue, 8> Ops; 7457 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 7458 Ops.append(InVec.getNode()->op_begin(), 7459 InVec.getNode()->op_end()); 7460 } else if (InVec.getOpcode() == ISD::UNDEF) { 7461 unsigned NElts = VT.getVectorNumElements(); 7462 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 7463 } else { 7464 return SDValue(); 7465 } 7466 7467 // Insert the element 7468 if (Elt < Ops.size()) { 7469 // All the operands of BUILD_VECTOR must have the same type; 7470 // we enforce that here. 7471 EVT OpVT = Ops[0].getValueType(); 7472 if (InVal.getValueType() != OpVT) 7473 InVal = OpVT.bitsGT(InVal.getValueType()) ? 7474 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 7475 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 7476 Ops[Elt] = InVal; 7477 } 7478 7479 // Return the new vector 7480 return DAG.getNode(ISD::BUILD_VECTOR, dl, 7481 VT, &Ops[0], Ops.size()); 7482 } 7483 7484 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 7485 // (vextract (scalar_to_vector val, 0) -> val 7486 SDValue InVec = N->getOperand(0); 7487 EVT VT = InVec.getValueType(); 7488 EVT NVT = N->getValueType(0); 7489 7490 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7491 // Check if the result type doesn't match the inserted element type. A 7492 // SCALAR_TO_VECTOR may truncate the inserted element and the 7493 // EXTRACT_VECTOR_ELT may widen the extracted vector. 7494 SDValue InOp = InVec.getOperand(0); 7495 if (InOp.getValueType() != NVT) { 7496 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 7497 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT); 7498 } 7499 return InOp; 7500 } 7501 7502 SDValue EltNo = N->getOperand(1); 7503 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 7504 7505 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 7506 // We only perform this optimization before the op legalization phase because 7507 // we may introduce new vector instructions which are not backed by TD patterns. 7508 // For example on AVX, extracting elements from a wide vector without using 7509 // extract_subvector. 7510 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 7511 && ConstEltNo && !LegalOperations) { 7512 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7513 int NumElem = VT.getVectorNumElements(); 7514 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 7515 // Find the new index to extract from. 7516 int OrigElt = SVOp->getMaskElt(Elt); 7517 7518 // Extracting an undef index is undef. 7519 if (OrigElt == -1) 7520 return DAG.getUNDEF(NVT); 7521 7522 // Select the right vector half to extract from. 7523 if (OrigElt < NumElem) { 7524 InVec = InVec->getOperand(0); 7525 } else { 7526 InVec = InVec->getOperand(1); 7527 OrigElt -= NumElem; 7528 } 7529 7530 EVT IndexTy = N->getOperand(1).getValueType(); 7531 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT, 7532 InVec, DAG.getConstant(OrigElt, IndexTy)); 7533 } 7534 7535 // Perform only after legalization to ensure build_vector / vector_shuffle 7536 // optimizations have already been done. 7537 if (!LegalOperations) return SDValue(); 7538 7539 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 7540 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 7541 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 7542 7543 if (ConstEltNo) { 7544 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7545 bool NewLoad = false; 7546 bool BCNumEltsChanged = false; 7547 EVT ExtVT = VT.getVectorElementType(); 7548 EVT LVT = ExtVT; 7549 7550 // If the result of load has to be truncated, then it's not necessarily 7551 // profitable. 7552 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 7553 return SDValue(); 7554 7555 if (InVec.getOpcode() == ISD::BITCAST) { 7556 // Don't duplicate a load with other uses. 7557 if (!InVec.hasOneUse()) 7558 return SDValue(); 7559 7560 EVT BCVT = InVec.getOperand(0).getValueType(); 7561 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 7562 return SDValue(); 7563 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 7564 BCNumEltsChanged = true; 7565 InVec = InVec.getOperand(0); 7566 ExtVT = BCVT.getVectorElementType(); 7567 NewLoad = true; 7568 } 7569 7570 LoadSDNode *LN0 = NULL; 7571 const ShuffleVectorSDNode *SVN = NULL; 7572 if (ISD::isNormalLoad(InVec.getNode())) { 7573 LN0 = cast<LoadSDNode>(InVec); 7574 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 7575 InVec.getOperand(0).getValueType() == ExtVT && 7576 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 7577 // Don't duplicate a load with other uses. 7578 if (!InVec.hasOneUse()) 7579 return SDValue(); 7580 7581 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 7582 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 7583 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 7584 // => 7585 // (load $addr+1*size) 7586 7587 // Don't duplicate a load with other uses. 7588 if (!InVec.hasOneUse()) 7589 return SDValue(); 7590 7591 // If the bit convert changed the number of elements, it is unsafe 7592 // to examine the mask. 7593 if (BCNumEltsChanged) 7594 return SDValue(); 7595 7596 // Select the input vector, guarding against out of range extract vector. 7597 unsigned NumElems = VT.getVectorNumElements(); 7598 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 7599 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 7600 7601 if (InVec.getOpcode() == ISD::BITCAST) { 7602 // Don't duplicate a load with other uses. 7603 if (!InVec.hasOneUse()) 7604 return SDValue(); 7605 7606 InVec = InVec.getOperand(0); 7607 } 7608 if (ISD::isNormalLoad(InVec.getNode())) { 7609 LN0 = cast<LoadSDNode>(InVec); 7610 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 7611 } 7612 } 7613 7614 // Make sure we found a non-volatile load and the extractelement is 7615 // the only use. 7616 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 7617 return SDValue(); 7618 7619 // If Idx was -1 above, Elt is going to be -1, so just return undef. 7620 if (Elt == -1) 7621 return DAG.getUNDEF(LVT); 7622 7623 unsigned Align = LN0->getAlignment(); 7624 if (NewLoad) { 7625 // Check the resultant load doesn't need a higher alignment than the 7626 // original load. 7627 unsigned NewAlign = 7628 TLI.getTargetData() 7629 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 7630 7631 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 7632 return SDValue(); 7633 7634 Align = NewAlign; 7635 } 7636 7637 SDValue NewPtr = LN0->getBasePtr(); 7638 unsigned PtrOff = 0; 7639 7640 if (Elt) { 7641 PtrOff = LVT.getSizeInBits() * Elt / 8; 7642 EVT PtrType = NewPtr.getValueType(); 7643 if (TLI.isBigEndian()) 7644 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 7645 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr, 7646 DAG.getConstant(PtrOff, PtrType)); 7647 } 7648 7649 // The replacement we need to do here is a little tricky: we need to 7650 // replace an extractelement of a load with a load. 7651 // Use ReplaceAllUsesOfValuesWith to do the replacement. 7652 // Note that this replacement assumes that the extractvalue is the only 7653 // use of the load; that's okay because we don't want to perform this 7654 // transformation in other cases anyway. 7655 SDValue Load; 7656 SDValue Chain; 7657 if (NVT.bitsGT(LVT)) { 7658 // If the result type of vextract is wider than the load, then issue an 7659 // extending load instead. 7660 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 7661 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 7662 Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(), 7663 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 7664 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align); 7665 Chain = Load.getValue(1); 7666 } else { 7667 Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr, 7668 LN0->getPointerInfo().getWithOffset(PtrOff), 7669 LN0->isVolatile(), LN0->isNonTemporal(), 7670 LN0->isInvariant(), Align); 7671 Chain = Load.getValue(1); 7672 if (NVT.bitsLT(LVT)) 7673 Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load); 7674 else 7675 Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load); 7676 } 7677 WorkListRemover DeadNodes(*this); 7678 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 7679 SDValue To[] = { Load, Chain }; 7680 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 7681 // Since we're explcitly calling ReplaceAllUses, add the new node to the 7682 // worklist explicitly as well. 7683 AddToWorkList(Load.getNode()); 7684 AddUsersToWorkList(Load.getNode()); // Add users too 7685 // Make sure to revisit this node to clean it up; it will usually be dead. 7686 AddToWorkList(N); 7687 return SDValue(N, 0); 7688 } 7689 7690 return SDValue(); 7691 } 7692 7693 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 7694 unsigned NumInScalars = N->getNumOperands(); 7695 DebugLoc dl = N->getDebugLoc(); 7696 EVT VT = N->getValueType(0); 7697 7698 // A vector built entirely of undefs is undef. 7699 if (ISD::allOperandsUndef(N)) 7700 return DAG.getUNDEF(VT); 7701 7702 // Check to see if this is a BUILD_VECTOR of a bunch of values 7703 // which come from any_extend or zero_extend nodes. If so, we can create 7704 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 7705 // optimizations. We do not handle sign-extend because we can't fill the sign 7706 // using shuffles. 7707 EVT SourceType = MVT::Other; 7708 bool AllAnyExt = true; 7709 7710 for (unsigned i = 0; i != NumInScalars; ++i) { 7711 SDValue In = N->getOperand(i); 7712 // Ignore undef inputs. 7713 if (In.getOpcode() == ISD::UNDEF) continue; 7714 7715 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 7716 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 7717 7718 // Abort if the element is not an extension. 7719 if (!ZeroExt && !AnyExt) { 7720 SourceType = MVT::Other; 7721 break; 7722 } 7723 7724 // The input is a ZeroExt or AnyExt. Check the original type. 7725 EVT InTy = In.getOperand(0).getValueType(); 7726 7727 // Check that all of the widened source types are the same. 7728 if (SourceType == MVT::Other) 7729 // First time. 7730 SourceType = InTy; 7731 else if (InTy != SourceType) { 7732 // Multiple income types. Abort. 7733 SourceType = MVT::Other; 7734 break; 7735 } 7736 7737 // Check if all of the extends are ANY_EXTENDs. 7738 AllAnyExt &= AnyExt; 7739 } 7740 7741 // In order to have valid types, all of the inputs must be extended from the 7742 // same source type and all of the inputs must be any or zero extend. 7743 // Scalar sizes must be a power of two. 7744 EVT OutScalarTy = N->getValueType(0).getScalarType(); 7745 bool ValidTypes = SourceType != MVT::Other && 7746 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 7747 isPowerOf2_32(SourceType.getSizeInBits()); 7748 7749 // We perform this optimization post type-legalization because 7750 // the type-legalizer often scalarizes integer-promoted vectors. 7751 // Performing this optimization before may create bit-casts which 7752 // will be type-legalized to complex code sequences. 7753 // We perform this optimization only before the operation legalizer because we 7754 // may introduce illegal operations. 7755 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 7756 // turn into a single shuffle instruction. 7757 if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) && 7758 ValidTypes) { 7759 bool isLE = TLI.isLittleEndian(); 7760 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 7761 assert(ElemRatio > 1 && "Invalid element size ratio"); 7762 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 7763 DAG.getConstant(0, SourceType); 7764 7765 unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements(); 7766 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 7767 7768 // Populate the new build_vector 7769 for (unsigned i=0; i < N->getNumOperands(); ++i) { 7770 SDValue Cast = N->getOperand(i); 7771 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 7772 Cast.getOpcode() == ISD::ZERO_EXTEND || 7773 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 7774 SDValue In; 7775 if (Cast.getOpcode() == ISD::UNDEF) 7776 In = DAG.getUNDEF(SourceType); 7777 else 7778 In = Cast->getOperand(0); 7779 unsigned Index = isLE ? (i * ElemRatio) : 7780 (i * ElemRatio + (ElemRatio - 1)); 7781 7782 assert(Index < Ops.size() && "Invalid index"); 7783 Ops[Index] = In; 7784 } 7785 7786 // The type of the new BUILD_VECTOR node. 7787 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 7788 assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() && 7789 "Invalid vector size"); 7790 // Check if the new vector type is legal. 7791 if (!isTypeLegal(VecVT)) return SDValue(); 7792 7793 // Make the new BUILD_VECTOR. 7794 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 7795 VecVT, &Ops[0], Ops.size()); 7796 7797 // The new BUILD_VECTOR node has the potential to be further optimized. 7798 AddToWorkList(BV.getNode()); 7799 // Bitcast to the desired type. 7800 return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV); 7801 } 7802 7803 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 7804 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 7805 // at most two distinct vectors, turn this into a shuffle node. 7806 7807 // May only combine to shuffle after legalize if shuffle is legal. 7808 if (LegalOperations && 7809 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 7810 return SDValue(); 7811 7812 SDValue VecIn1, VecIn2; 7813 for (unsigned i = 0; i != NumInScalars; ++i) { 7814 // Ignore undef inputs. 7815 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 7816 7817 // If this input is something other than a EXTRACT_VECTOR_ELT with a 7818 // constant index, bail out. 7819 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7820 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 7821 VecIn1 = VecIn2 = SDValue(0, 0); 7822 break; 7823 } 7824 7825 // We allow up to two distinct input vectors. 7826 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 7827 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 7828 continue; 7829 7830 if (VecIn1.getNode() == 0) { 7831 VecIn1 = ExtractedFromVec; 7832 } else if (VecIn2.getNode() == 0) { 7833 VecIn2 = ExtractedFromVec; 7834 } else { 7835 // Too many inputs. 7836 VecIn1 = VecIn2 = SDValue(0, 0); 7837 break; 7838 } 7839 } 7840 7841 // If everything is good, we can make a shuffle operation. 7842 if (VecIn1.getNode()) { 7843 SmallVector<int, 8> Mask; 7844 for (unsigned i = 0; i != NumInScalars; ++i) { 7845 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 7846 Mask.push_back(-1); 7847 continue; 7848 } 7849 7850 // If extracting from the first vector, just use the index directly. 7851 SDValue Extract = N->getOperand(i); 7852 SDValue ExtVal = Extract.getOperand(1); 7853 if (Extract.getOperand(0) == VecIn1) { 7854 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 7855 if (ExtIndex > VT.getVectorNumElements()) 7856 return SDValue(); 7857 7858 Mask.push_back(ExtIndex); 7859 continue; 7860 } 7861 7862 // Otherwise, use InIdx + VecSize 7863 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 7864 Mask.push_back(Idx+NumInScalars); 7865 } 7866 7867 // We can't generate a shuffle node with mismatched input and output types. 7868 // Attempt to transform a single input vector to the correct type. 7869 if ((VT != VecIn1.getValueType())) { 7870 // We don't support shuffeling between TWO values of different types. 7871 if (VecIn2.getNode() != 0) 7872 return SDValue(); 7873 7874 // We only support widening of vectors which are half the size of the 7875 // output registers. For example XMM->YMM widening on X86 with AVX. 7876 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 7877 return SDValue(); 7878 7879 // If the element type of the input vector is not the same as 7880 // the output element type, make concat_vectors based on input element 7881 // type and then bitcast it to the output vector type. 7882 // 7883 // In another words avoid nodes like this: 7884 // <NODE> v16i8 = concat_vectors v4i16 v4i16 7885 // Replace it with this one: 7886 // <NODE0> v8i16 = concat_vectors v4i16 v4i16 7887 // <NODE1> v16i8 = bitcast NODE0 7888 EVT ItemType = VecIn1.getValueType().getVectorElementType(); 7889 if (ItemType != VT.getVectorElementType()) { 7890 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), 7891 ItemType, 7892 VecIn1.getValueType().getVectorNumElements()*2); 7893 // Widen the input vector by adding undef values. 7894 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, 7895 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 7896 VecIn1 = DAG.getNode(ISD::BITCAST, dl, VT, VecIn1); 7897 } else 7898 // Widen the input vector by adding undef values. 7899 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 7900 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 7901 7902 } 7903 7904 // If VecIn2 is unused then change it to undef. 7905 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 7906 7907 // Check that we were able to transform all incoming values to the same type. 7908 if (VecIn2.getValueType() != VecIn1.getValueType() || 7909 VecIn1.getValueType() != VT) 7910 return SDValue(); 7911 7912 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 7913 if (!isTypeLegal(VT)) 7914 return SDValue(); 7915 7916 // Return the new VECTOR_SHUFFLE node. 7917 SDValue Ops[2]; 7918 Ops[0] = VecIn1; 7919 Ops[1] = VecIn2; 7920 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]); 7921 } 7922 7923 return SDValue(); 7924 } 7925 7926 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 7927 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 7928 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 7929 // inputs come from at most two distinct vectors, turn this into a shuffle 7930 // node. 7931 7932 // If we only have one input vector, we don't need to do any concatenation. 7933 if (N->getNumOperands() == 1) 7934 return N->getOperand(0); 7935 7936 // Check if all of the operands are undefs. 7937 if (ISD::allOperandsUndef(N)) 7938 return DAG.getUNDEF(N->getValueType(0)); 7939 7940 return SDValue(); 7941 } 7942 7943 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 7944 EVT NVT = N->getValueType(0); 7945 SDValue V = N->getOperand(0); 7946 7947 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 7948 // Handle only simple case where vector being inserted and vector 7949 // being extracted are of same type, and are half size of larger vectors. 7950 EVT BigVT = V->getOperand(0).getValueType(); 7951 EVT SmallVT = V->getOperand(1).getValueType(); 7952 if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 7953 return SDValue(); 7954 7955 // Only handle cases where both indexes are constants with the same type. 7956 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7957 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 7958 7959 if (InsIdx && ExtIdx && 7960 InsIdx->getValueType(0).getSizeInBits() <= 64 && 7961 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 7962 // Combine: 7963 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 7964 // Into: 7965 // indices are equal => V1 7966 // otherwise => (extract_subvec V1, ExtIdx) 7967 if (InsIdx->getZExtValue() == ExtIdx->getZExtValue()) 7968 return V->getOperand(1); 7969 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT, 7970 V->getOperand(0), N->getOperand(1)); 7971 } 7972 } 7973 7974 return SDValue(); 7975 } 7976 7977 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 7978 EVT VT = N->getValueType(0); 7979 unsigned NumElts = VT.getVectorNumElements(); 7980 7981 SDValue N0 = N->getOperand(0); 7982 SDValue N1 = N->getOperand(1); 7983 7984 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 7985 7986 // Canonicalize shuffle undef, undef -> undef 7987 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 7988 return DAG.getUNDEF(VT); 7989 7990 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 7991 7992 // Canonicalize shuffle v, v -> v, undef 7993 if (N0 == N1) { 7994 SmallVector<int, 8> NewMask; 7995 for (unsigned i = 0; i != NumElts; ++i) { 7996 int Idx = SVN->getMaskElt(i); 7997 if (Idx >= (int)NumElts) Idx -= NumElts; 7998 NewMask.push_back(Idx); 7999 } 8000 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT), 8001 &NewMask[0]); 8002 } 8003 8004 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 8005 if (N0.getOpcode() == ISD::UNDEF) { 8006 SmallVector<int, 8> NewMask; 8007 for (unsigned i = 0; i != NumElts; ++i) { 8008 int Idx = SVN->getMaskElt(i); 8009 if (Idx >= 0) { 8010 if (Idx < (int)NumElts) 8011 Idx += NumElts; 8012 else 8013 Idx -= NumElts; 8014 } 8015 NewMask.push_back(Idx); 8016 } 8017 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT), 8018 &NewMask[0]); 8019 } 8020 8021 // Remove references to rhs if it is undef 8022 if (N1.getOpcode() == ISD::UNDEF) { 8023 bool Changed = false; 8024 SmallVector<int, 8> NewMask; 8025 for (unsigned i = 0; i != NumElts; ++i) { 8026 int Idx = SVN->getMaskElt(i); 8027 if (Idx >= (int)NumElts) { 8028 Idx = -1; 8029 Changed = true; 8030 } 8031 NewMask.push_back(Idx); 8032 } 8033 if (Changed) 8034 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]); 8035 } 8036 8037 // If it is a splat, check if the argument vector is another splat or a 8038 // build_vector with all scalar elements the same. 8039 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 8040 SDNode *V = N0.getNode(); 8041 8042 // If this is a bit convert that changes the element type of the vector but 8043 // not the number of vector elements, look through it. Be careful not to 8044 // look though conversions that change things like v4f32 to v2f64. 8045 if (V->getOpcode() == ISD::BITCAST) { 8046 SDValue ConvInput = V->getOperand(0); 8047 if (ConvInput.getValueType().isVector() && 8048 ConvInput.getValueType().getVectorNumElements() == NumElts) 8049 V = ConvInput.getNode(); 8050 } 8051 8052 if (V->getOpcode() == ISD::BUILD_VECTOR) { 8053 assert(V->getNumOperands() == NumElts && 8054 "BUILD_VECTOR has wrong number of operands"); 8055 SDValue Base; 8056 bool AllSame = true; 8057 for (unsigned i = 0; i != NumElts; ++i) { 8058 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 8059 Base = V->getOperand(i); 8060 break; 8061 } 8062 } 8063 // Splat of <u, u, u, u>, return <u, u, u, u> 8064 if (!Base.getNode()) 8065 return N0; 8066 for (unsigned i = 0; i != NumElts; ++i) { 8067 if (V->getOperand(i) != Base) { 8068 AllSame = false; 8069 break; 8070 } 8071 } 8072 // Splat of <x, x, x, x>, return <x, x, x, x> 8073 if (AllSame) 8074 return N0; 8075 } 8076 } 8077 8078 // If this shuffle node is simply a swizzle of another shuffle node, 8079 // and it reverses the swizzle of the previous shuffle then we can 8080 // optimize shuffle(shuffle(x, undef), undef) -> x. 8081 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 8082 N1.getOpcode() == ISD::UNDEF) { 8083 8084 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 8085 8086 // Shuffle nodes can only reverse shuffles with a single non-undef value. 8087 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 8088 return SDValue(); 8089 8090 // The incoming shuffle must be of the same type as the result of the 8091 // current shuffle. 8092 assert(OtherSV->getOperand(0).getValueType() == VT && 8093 "Shuffle types don't match"); 8094 8095 for (unsigned i = 0; i != NumElts; ++i) { 8096 int Idx = SVN->getMaskElt(i); 8097 assert(Idx < (int)NumElts && "Index references undef operand"); 8098 // Next, this index comes from the first value, which is the incoming 8099 // shuffle. Adopt the incoming index. 8100 if (Idx >= 0) 8101 Idx = OtherSV->getMaskElt(Idx); 8102 8103 // The combined shuffle must map each index to itself. 8104 if (Idx >= 0 && (unsigned)Idx != i) 8105 return SDValue(); 8106 } 8107 8108 return OtherSV->getOperand(0); 8109 } 8110 8111 return SDValue(); 8112 } 8113 8114 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) { 8115 if (!TLI.getShouldFoldAtomicFences()) 8116 return SDValue(); 8117 8118 SDValue atomic = N->getOperand(0); 8119 switch (atomic.getOpcode()) { 8120 case ISD::ATOMIC_CMP_SWAP: 8121 case ISD::ATOMIC_SWAP: 8122 case ISD::ATOMIC_LOAD_ADD: 8123 case ISD::ATOMIC_LOAD_SUB: 8124 case ISD::ATOMIC_LOAD_AND: 8125 case ISD::ATOMIC_LOAD_OR: 8126 case ISD::ATOMIC_LOAD_XOR: 8127 case ISD::ATOMIC_LOAD_NAND: 8128 case ISD::ATOMIC_LOAD_MIN: 8129 case ISD::ATOMIC_LOAD_MAX: 8130 case ISD::ATOMIC_LOAD_UMIN: 8131 case ISD::ATOMIC_LOAD_UMAX: 8132 break; 8133 default: 8134 return SDValue(); 8135 } 8136 8137 SDValue fence = atomic.getOperand(0); 8138 if (fence.getOpcode() != ISD::MEMBARRIER) 8139 return SDValue(); 8140 8141 switch (atomic.getOpcode()) { 8142 case ISD::ATOMIC_CMP_SWAP: 8143 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(), 8144 fence.getOperand(0), 8145 atomic.getOperand(1), atomic.getOperand(2), 8146 atomic.getOperand(3)), atomic.getResNo()); 8147 case ISD::ATOMIC_SWAP: 8148 case ISD::ATOMIC_LOAD_ADD: 8149 case ISD::ATOMIC_LOAD_SUB: 8150 case ISD::ATOMIC_LOAD_AND: 8151 case ISD::ATOMIC_LOAD_OR: 8152 case ISD::ATOMIC_LOAD_XOR: 8153 case ISD::ATOMIC_LOAD_NAND: 8154 case ISD::ATOMIC_LOAD_MIN: 8155 case ISD::ATOMIC_LOAD_MAX: 8156 case ISD::ATOMIC_LOAD_UMIN: 8157 case ISD::ATOMIC_LOAD_UMAX: 8158 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(), 8159 fence.getOperand(0), 8160 atomic.getOperand(1), atomic.getOperand(2)), 8161 atomic.getResNo()); 8162 default: 8163 return SDValue(); 8164 } 8165 } 8166 8167 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 8168 /// an AND to a vector_shuffle with the destination vector and a zero vector. 8169 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 8170 /// vector_shuffle V, Zero, <0, 4, 2, 4> 8171 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 8172 EVT VT = N->getValueType(0); 8173 DebugLoc dl = N->getDebugLoc(); 8174 SDValue LHS = N->getOperand(0); 8175 SDValue RHS = N->getOperand(1); 8176 if (N->getOpcode() == ISD::AND) { 8177 if (RHS.getOpcode() == ISD::BITCAST) 8178 RHS = RHS.getOperand(0); 8179 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 8180 SmallVector<int, 8> Indices; 8181 unsigned NumElts = RHS.getNumOperands(); 8182 for (unsigned i = 0; i != NumElts; ++i) { 8183 SDValue Elt = RHS.getOperand(i); 8184 if (!isa<ConstantSDNode>(Elt)) 8185 return SDValue(); 8186 8187 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 8188 Indices.push_back(i); 8189 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 8190 Indices.push_back(NumElts); 8191 else 8192 return SDValue(); 8193 } 8194 8195 // Let's see if the target supports this vector_shuffle. 8196 EVT RVT = RHS.getValueType(); 8197 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 8198 return SDValue(); 8199 8200 // Return the new VECTOR_SHUFFLE node. 8201 EVT EltVT = RVT.getVectorElementType(); 8202 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 8203 DAG.getConstant(0, EltVT)); 8204 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8205 RVT, &ZeroOps[0], ZeroOps.size()); 8206 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 8207 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 8208 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 8209 } 8210 } 8211 8212 return SDValue(); 8213 } 8214 8215 /// SimplifyVBinOp - Visit a binary vector operation, like ADD. 8216 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 8217 // After legalize, the target may be depending on adds and other 8218 // binary ops to provide legal ways to construct constants or other 8219 // things. Simplifying them may result in a loss of legality. 8220 if (LegalOperations) return SDValue(); 8221 8222 assert(N->getValueType(0).isVector() && 8223 "SimplifyVBinOp only works on vectors!"); 8224 8225 SDValue LHS = N->getOperand(0); 8226 SDValue RHS = N->getOperand(1); 8227 SDValue Shuffle = XformToShuffleWithZero(N); 8228 if (Shuffle.getNode()) return Shuffle; 8229 8230 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 8231 // this operation. 8232 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 8233 RHS.getOpcode() == ISD::BUILD_VECTOR) { 8234 SmallVector<SDValue, 8> Ops; 8235 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 8236 SDValue LHSOp = LHS.getOperand(i); 8237 SDValue RHSOp = RHS.getOperand(i); 8238 // If these two elements can't be folded, bail out. 8239 if ((LHSOp.getOpcode() != ISD::UNDEF && 8240 LHSOp.getOpcode() != ISD::Constant && 8241 LHSOp.getOpcode() != ISD::ConstantFP) || 8242 (RHSOp.getOpcode() != ISD::UNDEF && 8243 RHSOp.getOpcode() != ISD::Constant && 8244 RHSOp.getOpcode() != ISD::ConstantFP)) 8245 break; 8246 8247 // Can't fold divide by zero. 8248 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 8249 N->getOpcode() == ISD::FDIV) { 8250 if ((RHSOp.getOpcode() == ISD::Constant && 8251 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 8252 (RHSOp.getOpcode() == ISD::ConstantFP && 8253 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 8254 break; 8255 } 8256 8257 EVT VT = LHSOp.getValueType(); 8258 EVT RVT = RHSOp.getValueType(); 8259 if (RVT != VT) { 8260 // Integer BUILD_VECTOR operands may have types larger than the element 8261 // size (e.g., when the element type is not legal). Prior to type 8262 // legalization, the types may not match between the two BUILD_VECTORS. 8263 // Truncate one of the operands to make them match. 8264 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 8265 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp); 8266 } else { 8267 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp); 8268 VT = RVT; 8269 } 8270 } 8271 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT, 8272 LHSOp, RHSOp); 8273 if (FoldOp.getOpcode() != ISD::UNDEF && 8274 FoldOp.getOpcode() != ISD::Constant && 8275 FoldOp.getOpcode() != ISD::ConstantFP) 8276 break; 8277 Ops.push_back(FoldOp); 8278 AddToWorkList(FoldOp.getNode()); 8279 } 8280 8281 if (Ops.size() == LHS.getNumOperands()) 8282 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8283 LHS.getValueType(), &Ops[0], Ops.size()); 8284 } 8285 8286 return SDValue(); 8287 } 8288 8289 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0, 8290 SDValue N1, SDValue N2){ 8291 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 8292 8293 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 8294 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8295 8296 // If we got a simplified select_cc node back from SimplifySelectCC, then 8297 // break it down into a new SETCC node, and a new SELECT node, and then return 8298 // the SELECT node, since we were called with a SELECT node. 8299 if (SCC.getNode()) { 8300 // Check to see if we got a select_cc back (to turn into setcc/select). 8301 // Otherwise, just return whatever node we got back, like fabs. 8302 if (SCC.getOpcode() == ISD::SELECT_CC) { 8303 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(), 8304 N0.getValueType(), 8305 SCC.getOperand(0), SCC.getOperand(1), 8306 SCC.getOperand(4)); 8307 AddToWorkList(SETCC.getNode()); 8308 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(), 8309 SCC.getOperand(2), SCC.getOperand(3), SETCC); 8310 } 8311 8312 return SCC; 8313 } 8314 return SDValue(); 8315 } 8316 8317 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 8318 /// are the two values being selected between, see if we can simplify the 8319 /// select. Callers of this should assume that TheSelect is deleted if this 8320 /// returns true. As such, they should return the appropriate thing (e.g. the 8321 /// node) back to the top-level of the DAG combiner loop to avoid it being 8322 /// looked at. 8323 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 8324 SDValue RHS) { 8325 8326 // Cannot simplify select with vector condition 8327 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 8328 8329 // If this is a select from two identical things, try to pull the operation 8330 // through the select. 8331 if (LHS.getOpcode() != RHS.getOpcode() || 8332 !LHS.hasOneUse() || !RHS.hasOneUse()) 8333 return false; 8334 8335 // If this is a load and the token chain is identical, replace the select 8336 // of two loads with a load through a select of the address to load from. 8337 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 8338 // constants have been dropped into the constant pool. 8339 if (LHS.getOpcode() == ISD::LOAD) { 8340 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 8341 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 8342 8343 // Token chains must be identical. 8344 if (LHS.getOperand(0) != RHS.getOperand(0) || 8345 // Do not let this transformation reduce the number of volatile loads. 8346 LLD->isVolatile() || RLD->isVolatile() || 8347 // If this is an EXTLOAD, the VT's must match. 8348 LLD->getMemoryVT() != RLD->getMemoryVT() || 8349 // If this is an EXTLOAD, the kind of extension must match. 8350 (LLD->getExtensionType() != RLD->getExtensionType() && 8351 // The only exception is if one of the extensions is anyext. 8352 LLD->getExtensionType() != ISD::EXTLOAD && 8353 RLD->getExtensionType() != ISD::EXTLOAD) || 8354 // FIXME: this discards src value information. This is 8355 // over-conservative. It would be beneficial to be able to remember 8356 // both potential memory locations. Since we are discarding 8357 // src value info, don't do the transformation if the memory 8358 // locations are not in the default address space. 8359 LLD->getPointerInfo().getAddrSpace() != 0 || 8360 RLD->getPointerInfo().getAddrSpace() != 0) 8361 return false; 8362 8363 // Check that the select condition doesn't reach either load. If so, 8364 // folding this will induce a cycle into the DAG. If not, this is safe to 8365 // xform, so create a select of the addresses. 8366 SDValue Addr; 8367 if (TheSelect->getOpcode() == ISD::SELECT) { 8368 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 8369 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 8370 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 8371 return false; 8372 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(), 8373 LLD->getBasePtr().getValueType(), 8374 TheSelect->getOperand(0), LLD->getBasePtr(), 8375 RLD->getBasePtr()); 8376 } else { // Otherwise SELECT_CC 8377 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 8378 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 8379 8380 if ((LLD->hasAnyUseOfValue(1) && 8381 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 8382 (RLD->hasAnyUseOfValue(1) && 8383 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 8384 return false; 8385 8386 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(), 8387 LLD->getBasePtr().getValueType(), 8388 TheSelect->getOperand(0), 8389 TheSelect->getOperand(1), 8390 LLD->getBasePtr(), RLD->getBasePtr(), 8391 TheSelect->getOperand(4)); 8392 } 8393 8394 SDValue Load; 8395 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 8396 Load = DAG.getLoad(TheSelect->getValueType(0), 8397 TheSelect->getDebugLoc(), 8398 // FIXME: Discards pointer info. 8399 LLD->getChain(), Addr, MachinePointerInfo(), 8400 LLD->isVolatile(), LLD->isNonTemporal(), 8401 LLD->isInvariant(), LLD->getAlignment()); 8402 } else { 8403 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 8404 RLD->getExtensionType() : LLD->getExtensionType(), 8405 TheSelect->getDebugLoc(), 8406 TheSelect->getValueType(0), 8407 // FIXME: Discards pointer info. 8408 LLD->getChain(), Addr, MachinePointerInfo(), 8409 LLD->getMemoryVT(), LLD->isVolatile(), 8410 LLD->isNonTemporal(), LLD->getAlignment()); 8411 } 8412 8413 // Users of the select now use the result of the load. 8414 CombineTo(TheSelect, Load); 8415 8416 // Users of the old loads now use the new load's chain. We know the 8417 // old-load value is dead now. 8418 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 8419 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 8420 return true; 8421 } 8422 8423 return false; 8424 } 8425 8426 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 8427 /// where 'cond' is the comparison specified by CC. 8428 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, 8429 SDValue N2, SDValue N3, 8430 ISD::CondCode CC, bool NotExtCompare) { 8431 // (x ? y : y) -> y. 8432 if (N2 == N3) return N2; 8433 8434 EVT VT = N2.getValueType(); 8435 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 8436 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 8437 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 8438 8439 // Determine if the condition we're dealing with is constant 8440 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 8441 N0, N1, CC, DL, false); 8442 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 8443 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 8444 8445 // fold select_cc true, x, y -> x 8446 if (SCCC && !SCCC->isNullValue()) 8447 return N2; 8448 // fold select_cc false, x, y -> y 8449 if (SCCC && SCCC->isNullValue()) 8450 return N3; 8451 8452 // Check to see if we can simplify the select into an fabs node 8453 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 8454 // Allow either -0.0 or 0.0 8455 if (CFP->getValueAPF().isZero()) { 8456 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 8457 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 8458 N0 == N2 && N3.getOpcode() == ISD::FNEG && 8459 N2 == N3.getOperand(0)) 8460 return DAG.getNode(ISD::FABS, DL, VT, N0); 8461 8462 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 8463 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 8464 N0 == N3 && N2.getOpcode() == ISD::FNEG && 8465 N2.getOperand(0) == N3) 8466 return DAG.getNode(ISD::FABS, DL, VT, N3); 8467 } 8468 } 8469 8470 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 8471 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 8472 // in it. This is a win when the constant is not otherwise available because 8473 // it replaces two constant pool loads with one. We only do this if the FP 8474 // type is known to be legal, because if it isn't, then we are before legalize 8475 // types an we want the other legalization to happen first (e.g. to avoid 8476 // messing with soft float) and if the ConstantFP is not legal, because if 8477 // it is legal, we may not need to store the FP constant in a constant pool. 8478 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 8479 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 8480 if (TLI.isTypeLegal(N2.getValueType()) && 8481 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 8482 TargetLowering::Legal) && 8483 // If both constants have multiple uses, then we won't need to do an 8484 // extra load, they are likely around in registers for other users. 8485 (TV->hasOneUse() || FV->hasOneUse())) { 8486 Constant *Elts[] = { 8487 const_cast<ConstantFP*>(FV->getConstantFPValue()), 8488 const_cast<ConstantFP*>(TV->getConstantFPValue()) 8489 }; 8490 Type *FPTy = Elts[0]->getType(); 8491 const TargetData &TD = *TLI.getTargetData(); 8492 8493 // Create a ConstantArray of the two constants. 8494 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 8495 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 8496 TD.getPrefTypeAlignment(FPTy)); 8497 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 8498 8499 // Get the offsets to the 0 and 1 element of the array so that we can 8500 // select between them. 8501 SDValue Zero = DAG.getIntPtrConstant(0); 8502 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 8503 SDValue One = DAG.getIntPtrConstant(EltSize); 8504 8505 SDValue Cond = DAG.getSetCC(DL, 8506 TLI.getSetCCResultType(N0.getValueType()), 8507 N0, N1, CC); 8508 AddToWorkList(Cond.getNode()); 8509 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(), 8510 Cond, One, Zero); 8511 AddToWorkList(CstOffset.getNode()); 8512 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx, 8513 CstOffset); 8514 AddToWorkList(CPIdx.getNode()); 8515 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 8516 MachinePointerInfo::getConstantPool(), false, 8517 false, false, Alignment); 8518 8519 } 8520 } 8521 8522 // Check to see if we can perform the "gzip trick", transforming 8523 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 8524 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 8525 (N1C->isNullValue() || // (a < 0) ? b : 0 8526 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 8527 EVT XType = N0.getValueType(); 8528 EVT AType = N2.getValueType(); 8529 if (XType.bitsGE(AType)) { 8530 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 8531 // single-bit constant. 8532 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 8533 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 8534 ShCtV = XType.getSizeInBits()-ShCtV-1; 8535 SDValue ShCt = DAG.getConstant(ShCtV, 8536 getShiftAmountTy(N0.getValueType())); 8537 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), 8538 XType, N0, ShCt); 8539 AddToWorkList(Shift.getNode()); 8540 8541 if (XType.bitsGT(AType)) { 8542 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 8543 AddToWorkList(Shift.getNode()); 8544 } 8545 8546 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 8547 } 8548 8549 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), 8550 XType, N0, 8551 DAG.getConstant(XType.getSizeInBits()-1, 8552 getShiftAmountTy(N0.getValueType()))); 8553 AddToWorkList(Shift.getNode()); 8554 8555 if (XType.bitsGT(AType)) { 8556 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 8557 AddToWorkList(Shift.getNode()); 8558 } 8559 8560 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 8561 } 8562 } 8563 8564 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 8565 // where y is has a single bit set. 8566 // A plaintext description would be, we can turn the SELECT_CC into an AND 8567 // when the condition can be materialized as an all-ones register. Any 8568 // single bit-test can be materialized as an all-ones register with 8569 // shift-left and shift-right-arith. 8570 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 8571 N0->getValueType(0) == VT && 8572 N1C && N1C->isNullValue() && 8573 N2C && N2C->isNullValue()) { 8574 SDValue AndLHS = N0->getOperand(0); 8575 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8576 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 8577 // Shift the tested bit over the sign bit. 8578 APInt AndMask = ConstAndRHS->getAPIntValue(); 8579 SDValue ShlAmt = 8580 DAG.getConstant(AndMask.countLeadingZeros(), 8581 getShiftAmountTy(AndLHS.getValueType())); 8582 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt); 8583 8584 // Now arithmetic right shift it all the way over, so the result is either 8585 // all-ones, or zero. 8586 SDValue ShrAmt = 8587 DAG.getConstant(AndMask.getBitWidth()-1, 8588 getShiftAmountTy(Shl.getValueType())); 8589 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt); 8590 8591 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 8592 } 8593 } 8594 8595 // fold select C, 16, 0 -> shl C, 4 8596 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 8597 TLI.getBooleanContents(N0.getValueType().isVector()) == 8598 TargetLowering::ZeroOrOneBooleanContent) { 8599 8600 // If the caller doesn't want us to simplify this into a zext of a compare, 8601 // don't do it. 8602 if (NotExtCompare && N2C->getAPIntValue() == 1) 8603 return SDValue(); 8604 8605 // Get a SetCC of the condition 8606 // FIXME: Should probably make sure that setcc is legal if we ever have a 8607 // target where it isn't. 8608 SDValue Temp, SCC; 8609 // cast from setcc result type to select result type 8610 if (LegalTypes) { 8611 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()), 8612 N0, N1, CC); 8613 if (N2.getValueType().bitsLT(SCC.getValueType())) 8614 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType()); 8615 else 8616 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 8617 N2.getValueType(), SCC); 8618 } else { 8619 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC); 8620 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 8621 N2.getValueType(), SCC); 8622 } 8623 8624 AddToWorkList(SCC.getNode()); 8625 AddToWorkList(Temp.getNode()); 8626 8627 if (N2C->getAPIntValue() == 1) 8628 return Temp; 8629 8630 // shl setcc result by log2 n2c 8631 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 8632 DAG.getConstant(N2C->getAPIntValue().logBase2(), 8633 getShiftAmountTy(Temp.getValueType()))); 8634 } 8635 8636 // Check to see if this is the equivalent of setcc 8637 // FIXME: Turn all of these into setcc if setcc if setcc is legal 8638 // otherwise, go ahead with the folds. 8639 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 8640 EVT XType = N0.getValueType(); 8641 if (!LegalOperations || 8642 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) { 8643 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC); 8644 if (Res.getValueType() != VT) 8645 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 8646 return Res; 8647 } 8648 8649 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 8650 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 8651 (!LegalOperations || 8652 TLI.isOperationLegal(ISD::CTLZ, XType))) { 8653 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0); 8654 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 8655 DAG.getConstant(Log2_32(XType.getSizeInBits()), 8656 getShiftAmountTy(Ctlz.getValueType()))); 8657 } 8658 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 8659 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 8660 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(), 8661 XType, DAG.getConstant(0, XType), N0); 8662 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType); 8663 return DAG.getNode(ISD::SRL, DL, XType, 8664 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 8665 DAG.getConstant(XType.getSizeInBits()-1, 8666 getShiftAmountTy(XType))); 8667 } 8668 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 8669 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 8670 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0, 8671 DAG.getConstant(XType.getSizeInBits()-1, 8672 getShiftAmountTy(N0.getValueType()))); 8673 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 8674 } 8675 } 8676 8677 // Check to see if this is an integer abs. 8678 // select_cc setg[te] X, 0, X, -X -> 8679 // select_cc setgt X, -1, X, -X -> 8680 // select_cc setl[te] X, 0, -X, X -> 8681 // select_cc setlt X, 1, -X, X -> 8682 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 8683 if (N1C) { 8684 ConstantSDNode *SubC = NULL; 8685 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 8686 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 8687 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 8688 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 8689 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 8690 (N1C->isOne() && CC == ISD::SETLT)) && 8691 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 8692 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 8693 8694 EVT XType = N0.getValueType(); 8695 if (SubC && SubC->isNullValue() && XType.isInteger()) { 8696 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, 8697 N0, 8698 DAG.getConstant(XType.getSizeInBits()-1, 8699 getShiftAmountTy(N0.getValueType()))); 8700 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), 8701 XType, N0, Shift); 8702 AddToWorkList(Shift.getNode()); 8703 AddToWorkList(Add.getNode()); 8704 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 8705 } 8706 } 8707 8708 return SDValue(); 8709 } 8710 8711 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 8712 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 8713 SDValue N1, ISD::CondCode Cond, 8714 DebugLoc DL, bool foldBooleans) { 8715 TargetLowering::DAGCombinerInfo 8716 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 8717 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 8718 } 8719 8720 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 8721 /// return a DAG expression to select that will generate the same value by 8722 /// multiplying by a magic number. See: 8723 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 8724 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 8725 std::vector<SDNode*> Built; 8726 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 8727 8728 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 8729 ii != ee; ++ii) 8730 AddToWorkList(*ii); 8731 return S; 8732 } 8733 8734 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 8735 /// return a DAG expression to select that will generate the same value by 8736 /// multiplying by a magic number. See: 8737 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 8738 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 8739 std::vector<SDNode*> Built; 8740 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 8741 8742 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 8743 ii != ee; ++ii) 8744 AddToWorkList(*ii); 8745 return S; 8746 } 8747 8748 /// FindBaseOffset - Return true if base is a frame index, which is known not 8749 // to alias with anything but itself. Provides base object and offset as 8750 // results. 8751 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 8752 const GlobalValue *&GV, void *&CV) { 8753 // Assume it is a primitive operation. 8754 Base = Ptr; Offset = 0; GV = 0; CV = 0; 8755 8756 // If it's an adding a simple constant then integrate the offset. 8757 if (Base.getOpcode() == ISD::ADD) { 8758 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 8759 Base = Base.getOperand(0); 8760 Offset += C->getZExtValue(); 8761 } 8762 } 8763 8764 // Return the underlying GlobalValue, and update the Offset. Return false 8765 // for GlobalAddressSDNode since the same GlobalAddress may be represented 8766 // by multiple nodes with different offsets. 8767 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 8768 GV = G->getGlobal(); 8769 Offset += G->getOffset(); 8770 return false; 8771 } 8772 8773 // Return the underlying Constant value, and update the Offset. Return false 8774 // for ConstantSDNodes since the same constant pool entry may be represented 8775 // by multiple nodes with different offsets. 8776 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 8777 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal() 8778 : (void *)C->getConstVal(); 8779 Offset += C->getOffset(); 8780 return false; 8781 } 8782 // If it's any of the following then it can't alias with anything but itself. 8783 return isa<FrameIndexSDNode>(Base); 8784 } 8785 8786 /// isAlias - Return true if there is any possibility that the two addresses 8787 /// overlap. 8788 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, 8789 const Value *SrcValue1, int SrcValueOffset1, 8790 unsigned SrcValueAlign1, 8791 const MDNode *TBAAInfo1, 8792 SDValue Ptr2, int64_t Size2, 8793 const Value *SrcValue2, int SrcValueOffset2, 8794 unsigned SrcValueAlign2, 8795 const MDNode *TBAAInfo2) const { 8796 // If they are the same then they must be aliases. 8797 if (Ptr1 == Ptr2) return true; 8798 8799 // Gather base node and offset information. 8800 SDValue Base1, Base2; 8801 int64_t Offset1, Offset2; 8802 const GlobalValue *GV1, *GV2; 8803 void *CV1, *CV2; 8804 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 8805 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 8806 8807 // If they have a same base address then check to see if they overlap. 8808 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 8809 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 8810 8811 // It is possible for different frame indices to alias each other, mostly 8812 // when tail call optimization reuses return address slots for arguments. 8813 // To catch this case, look up the actual index of frame indices to compute 8814 // the real alias relationship. 8815 if (isFrameIndex1 && isFrameIndex2) { 8816 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8817 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 8818 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 8819 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 8820 } 8821 8822 // Otherwise, if we know what the bases are, and they aren't identical, then 8823 // we know they cannot alias. 8824 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 8825 return false; 8826 8827 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 8828 // compared to the size and offset of the access, we may be able to prove they 8829 // do not alias. This check is conservative for now to catch cases created by 8830 // splitting vector types. 8831 if ((SrcValueAlign1 == SrcValueAlign2) && 8832 (SrcValueOffset1 != SrcValueOffset2) && 8833 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 8834 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 8835 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 8836 8837 // There is no overlap between these relatively aligned accesses of similar 8838 // size, return no alias. 8839 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 8840 return false; 8841 } 8842 8843 if (CombinerGlobalAA) { 8844 // Use alias analysis information. 8845 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 8846 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 8847 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 8848 AliasAnalysis::AliasResult AAResult = 8849 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1), 8850 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2)); 8851 if (AAResult == AliasAnalysis::NoAlias) 8852 return false; 8853 } 8854 8855 // Otherwise we have to assume they alias. 8856 return true; 8857 } 8858 8859 /// FindAliasInfo - Extracts the relevant alias information from the memory 8860 /// node. Returns true if the operand was a load. 8861 bool DAGCombiner::FindAliasInfo(SDNode *N, 8862 SDValue &Ptr, int64_t &Size, 8863 const Value *&SrcValue, 8864 int &SrcValueOffset, 8865 unsigned &SrcValueAlign, 8866 const MDNode *&TBAAInfo) const { 8867 LSBaseSDNode *LS = cast<LSBaseSDNode>(N); 8868 8869 Ptr = LS->getBasePtr(); 8870 Size = LS->getMemoryVT().getSizeInBits() >> 3; 8871 SrcValue = LS->getSrcValue(); 8872 SrcValueOffset = LS->getSrcValueOffset(); 8873 SrcValueAlign = LS->getOriginalAlignment(); 8874 TBAAInfo = LS->getTBAAInfo(); 8875 return isa<LoadSDNode>(LS); 8876 } 8877 8878 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 8879 /// looking for aliasing nodes and adding them to the Aliases vector. 8880 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 8881 SmallVector<SDValue, 8> &Aliases) { 8882 SmallVector<SDValue, 8> Chains; // List of chains to visit. 8883 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 8884 8885 // Get alias information for node. 8886 SDValue Ptr; 8887 int64_t Size; 8888 const Value *SrcValue; 8889 int SrcValueOffset; 8890 unsigned SrcValueAlign; 8891 const MDNode *SrcTBAAInfo; 8892 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset, 8893 SrcValueAlign, SrcTBAAInfo); 8894 8895 // Starting off. 8896 Chains.push_back(OriginalChain); 8897 unsigned Depth = 0; 8898 8899 // Look at each chain and determine if it is an alias. If so, add it to the 8900 // aliases list. If not, then continue up the chain looking for the next 8901 // candidate. 8902 while (!Chains.empty()) { 8903 SDValue Chain = Chains.back(); 8904 Chains.pop_back(); 8905 8906 // For TokenFactor nodes, look at each operand and only continue up the 8907 // chain until we find two aliases. If we've seen two aliases, assume we'll 8908 // find more and revert to original chain since the xform is unlikely to be 8909 // profitable. 8910 // 8911 // FIXME: The depth check could be made to return the last non-aliasing 8912 // chain we found before we hit a tokenfactor rather than the original 8913 // chain. 8914 if (Depth > 6 || Aliases.size() == 2) { 8915 Aliases.clear(); 8916 Aliases.push_back(OriginalChain); 8917 break; 8918 } 8919 8920 // Don't bother if we've been before. 8921 if (!Visited.insert(Chain.getNode())) 8922 continue; 8923 8924 switch (Chain.getOpcode()) { 8925 case ISD::EntryToken: 8926 // Entry token is ideal chain operand, but handled in FindBetterChain. 8927 break; 8928 8929 case ISD::LOAD: 8930 case ISD::STORE: { 8931 // Get alias information for Chain. 8932 SDValue OpPtr; 8933 int64_t OpSize; 8934 const Value *OpSrcValue; 8935 int OpSrcValueOffset; 8936 unsigned OpSrcValueAlign; 8937 const MDNode *OpSrcTBAAInfo; 8938 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 8939 OpSrcValue, OpSrcValueOffset, 8940 OpSrcValueAlign, 8941 OpSrcTBAAInfo); 8942 8943 // If chain is alias then stop here. 8944 if (!(IsLoad && IsOpLoad) && 8945 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign, 8946 SrcTBAAInfo, 8947 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset, 8948 OpSrcValueAlign, OpSrcTBAAInfo)) { 8949 Aliases.push_back(Chain); 8950 } else { 8951 // Look further up the chain. 8952 Chains.push_back(Chain.getOperand(0)); 8953 ++Depth; 8954 } 8955 break; 8956 } 8957 8958 case ISD::TokenFactor: 8959 // We have to check each of the operands of the token factor for "small" 8960 // token factors, so we queue them up. Adding the operands to the queue 8961 // (stack) in reverse order maintains the original order and increases the 8962 // likelihood that getNode will find a matching token factor (CSE.) 8963 if (Chain.getNumOperands() > 16) { 8964 Aliases.push_back(Chain); 8965 break; 8966 } 8967 for (unsigned n = Chain.getNumOperands(); n;) 8968 Chains.push_back(Chain.getOperand(--n)); 8969 ++Depth; 8970 break; 8971 8972 default: 8973 // For all other instructions we will just have to take what we can get. 8974 Aliases.push_back(Chain); 8975 break; 8976 } 8977 } 8978 } 8979 8980 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 8981 /// for a better chain (aliasing node.) 8982 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 8983 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 8984 8985 // Accumulate all the aliases to this node. 8986 GatherAllAliases(N, OldChain, Aliases); 8987 8988 // If no operands then chain to entry token. 8989 if (Aliases.size() == 0) 8990 return DAG.getEntryNode(); 8991 8992 // If a single operand then chain to it. We don't need to revisit it. 8993 if (Aliases.size() == 1) 8994 return Aliases[0]; 8995 8996 // Construct a custom tailored token factor. 8997 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 8998 &Aliases[0], Aliases.size()); 8999 } 9000 9001 // SelectionDAG::Combine - This is the entry point for the file. 9002 // 9003 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 9004 CodeGenOpt::Level OptLevel) { 9005 /// run - This is the main entry point to this class. 9006 /// 9007 DAGCombiner(*this, AA, OptLevel).Run(Level); 9008 } 9009