1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Turn on alias analysis during testing"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Include global information in alias analysis"));
59 /// Hidden option to stress test load slicing, i.e., when this option
60 /// is enabled, load slicing bypasses most of its profitability guards.
62 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63 cl::desc("Bypass the profitability model of load "
67 //------------------------------ DAGCombiner ---------------------------------//
71 const TargetLowering &TLI;
73 CodeGenOpt::Level OptLevel;
78 // Worklist of all of the nodes that need to be simplified.
80 // This has the semantics that when adding to the worklist,
81 // the item added must be next to be processed. It should
82 // also only appear once. The naive approach to this takes
85 // To reduce the insert/remove time to logarithmic, we use
86 // a set and a vector to maintain our worklist.
88 // The set contains the items on the worklist, but does not
89 // maintain the order they should be visited.
91 // The vector maintains the order nodes should be visited, but may
92 // contain duplicate or removed nodes. When choosing a node to
93 // visit, we pop off the order stack until we find an item that is
94 // also in the contents set. All operations are O(log N).
95 SmallPtrSet<SDNode*, 64> WorkListContents;
96 SmallVector<SDNode*, 64> WorkListOrder;
98 // AA - Used for DAG load/store alias analysis.
101 /// AddUsersToWorkList - When an instruction is simplified, add all users of
102 /// the instruction to the work lists because they might get more simplified
105 void AddUsersToWorkList(SDNode *N) {
106 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
111 /// visit - call the node-specific routine that knows how to fold each
112 /// particular type of node.
113 SDValue visit(SDNode *N);
116 /// AddToWorkList - Add to the work list making sure its instance is at the
117 /// back (next to be processed.)
118 void AddToWorkList(SDNode *N) {
119 WorkListContents.insert(N);
120 WorkListOrder.push_back(N);
123 /// removeFromWorkList - remove all instances of N from the worklist.
125 void removeFromWorkList(SDNode *N) {
126 WorkListContents.erase(N);
129 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
132 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133 return CombineTo(N, &Res, 1, AddTo);
136 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
138 SDValue To[] = { Res0, Res1 };
139 return CombineTo(N, To, 2, AddTo);
142 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
146 /// SimplifyDemandedBits - Check the specified integer node value to see if
147 /// it can be simplified or if things it uses can be simplified by bit
148 /// propagation. If so, return true.
149 bool SimplifyDemandedBits(SDValue Op) {
150 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151 APInt Demanded = APInt::getAllOnesValue(BitWidth);
152 return SimplifyDemandedBits(Op, Demanded);
155 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
157 bool CombineToPreIndexedLoadStore(SDNode *N);
158 bool CombineToPostIndexedLoadStore(SDNode *N);
159 bool SliceUpLoad(SDNode *N);
161 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165 SDValue PromoteIntBinOp(SDValue Op);
166 SDValue PromoteIntShiftOp(SDValue Op);
167 SDValue PromoteExtend(SDValue Op);
168 bool PromoteLoad(SDValue Op);
170 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172 ISD::NodeType ExtType);
174 /// combine - call the node-specific routine that knows how to fold each
175 /// particular type of node. If that doesn't do anything, try the
176 /// target-specific DAG combines.
177 SDValue combine(SDNode *N);
179 // Visitation implementation - Implement dag node combining for different
180 // node types. The semantics are as follows:
182 // SDValue.getNode() == 0 - No change was made
183 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
184 // otherwise - N should be replaced by the returned Operand.
186 SDValue visitTokenFactor(SDNode *N);
187 SDValue visitMERGE_VALUES(SDNode *N);
188 SDValue visitADD(SDNode *N);
189 SDValue visitSUB(SDNode *N);
190 SDValue visitADDC(SDNode *N);
191 SDValue visitSUBC(SDNode *N);
192 SDValue visitADDE(SDNode *N);
193 SDValue visitSUBE(SDNode *N);
194 SDValue visitMUL(SDNode *N);
195 SDValue visitSDIV(SDNode *N);
196 SDValue visitUDIV(SDNode *N);
197 SDValue visitSREM(SDNode *N);
198 SDValue visitUREM(SDNode *N);
199 SDValue visitMULHU(SDNode *N);
200 SDValue visitMULHS(SDNode *N);
201 SDValue visitSMUL_LOHI(SDNode *N);
202 SDValue visitUMUL_LOHI(SDNode *N);
203 SDValue visitSMULO(SDNode *N);
204 SDValue visitUMULO(SDNode *N);
205 SDValue visitSDIVREM(SDNode *N);
206 SDValue visitUDIVREM(SDNode *N);
207 SDValue visitAND(SDNode *N);
208 SDValue visitOR(SDNode *N);
209 SDValue visitXOR(SDNode *N);
210 SDValue SimplifyVBinOp(SDNode *N);
211 SDValue SimplifyVUnaryOp(SDNode *N);
212 SDValue visitSHL(SDNode *N);
213 SDValue visitSRA(SDNode *N);
214 SDValue visitSRL(SDNode *N);
215 SDValue visitCTLZ(SDNode *N);
216 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217 SDValue visitCTTZ(SDNode *N);
218 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219 SDValue visitCTPOP(SDNode *N);
220 SDValue visitSELECT(SDNode *N);
221 SDValue visitVSELECT(SDNode *N);
222 SDValue visitSELECT_CC(SDNode *N);
223 SDValue visitSETCC(SDNode *N);
224 SDValue visitSIGN_EXTEND(SDNode *N);
225 SDValue visitZERO_EXTEND(SDNode *N);
226 SDValue visitANY_EXTEND(SDNode *N);
227 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228 SDValue visitTRUNCATE(SDNode *N);
229 SDValue visitBITCAST(SDNode *N);
230 SDValue visitBUILD_PAIR(SDNode *N);
231 SDValue visitFADD(SDNode *N);
232 SDValue visitFSUB(SDNode *N);
233 SDValue visitFMUL(SDNode *N);
234 SDValue visitFMA(SDNode *N);
235 SDValue visitFDIV(SDNode *N);
236 SDValue visitFREM(SDNode *N);
237 SDValue visitFCOPYSIGN(SDNode *N);
238 SDValue visitSINT_TO_FP(SDNode *N);
239 SDValue visitUINT_TO_FP(SDNode *N);
240 SDValue visitFP_TO_SINT(SDNode *N);
241 SDValue visitFP_TO_UINT(SDNode *N);
242 SDValue visitFP_ROUND(SDNode *N);
243 SDValue visitFP_ROUND_INREG(SDNode *N);
244 SDValue visitFP_EXTEND(SDNode *N);
245 SDValue visitFNEG(SDNode *N);
246 SDValue visitFABS(SDNode *N);
247 SDValue visitFCEIL(SDNode *N);
248 SDValue visitFTRUNC(SDNode *N);
249 SDValue visitFFLOOR(SDNode *N);
250 SDValue visitBRCOND(SDNode *N);
251 SDValue visitBR_CC(SDNode *N);
252 SDValue visitLOAD(SDNode *N);
253 SDValue visitSTORE(SDNode *N);
254 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256 SDValue visitBUILD_VECTOR(SDNode *N);
257 SDValue visitCONCAT_VECTORS(SDNode *N);
258 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259 SDValue visitVECTOR_SHUFFLE(SDNode *N);
261 SDValue XformToShuffleWithZero(SDNode *N);
262 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
264 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
266 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270 SDValue N3, ISD::CondCode CC,
271 bool NotExtCompare = false);
272 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273 SDLoc DL, bool foldBooleans = true);
274 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
276 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278 SDValue BuildSDIV(SDNode *N);
279 SDValue BuildUDIV(SDNode *N);
280 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281 bool DemandHighBits = true);
282 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
284 SDValue InnerPos, SDValue InnerNeg,
285 unsigned PosOpcode, unsigned NegOpcode,
287 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
288 SDValue ReduceLoadWidth(SDNode *N);
289 SDValue ReduceLoadOpStoreWidth(SDNode *N);
290 SDValue TransformFPLoadStorePair(SDNode *N);
291 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
292 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
294 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
296 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
297 /// looking for aliasing nodes and adding them to the Aliases vector.
298 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
299 SmallVectorImpl<SDValue> &Aliases);
301 /// isAlias - Return true if there is any possibility that the two addresses
303 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
304 const Value *SrcValue1, int SrcValueOffset1,
305 unsigned SrcValueAlign1,
306 const MDNode *TBAAInfo1,
307 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
308 const Value *SrcValue2, int SrcValueOffset2,
309 unsigned SrcValueAlign2,
310 const MDNode *TBAAInfo2) const;
312 /// isAlias - Return true if there is any possibility that the two addresses
314 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
316 /// FindAliasInfo - Extracts the relevant alias information from the memory
317 /// node. Returns true if the operand was a load.
318 bool FindAliasInfo(SDNode *N,
319 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
320 const Value *&SrcValue, int &SrcValueOffset,
321 unsigned &SrcValueAlignment,
322 const MDNode *&TBAAInfo) const;
324 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for a better chain (aliasing node.)
326 SDValue FindBetterChain(SDNode *N, SDValue Chain);
328 /// Merge consecutive store operations into a wide store.
329 /// This optimization uses wide integers or vectors when possible.
330 /// \return True if some memory operations were changed.
331 bool MergeConsecutiveStores(StoreSDNode *N);
334 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
335 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
336 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
337 AttributeSet FnAttrs =
338 DAG.getMachineFunction().getFunction()->getAttributes();
340 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
341 Attribute::OptimizeForSize) ||
342 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
345 /// Run - runs the dag combiner on all nodes in the work list
346 void Run(CombineLevel AtLevel);
348 SelectionDAG &getDAG() const { return DAG; }
350 /// getShiftAmountTy - Returns a type large enough to hold any valid
351 /// shift amount - before type legalization these can be huge.
352 EVT getShiftAmountTy(EVT LHSTy) {
353 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
354 if (LHSTy.isVector())
356 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
357 : TLI.getPointerTy();
360 /// isTypeLegal - This method returns true if we are running before type
361 /// legalization or if the specified VT is legal.
362 bool isTypeLegal(const EVT &VT) {
363 if (!LegalTypes) return true;
364 return TLI.isTypeLegal(VT);
367 /// getSetCCResultType - Convenience wrapper around
368 /// TargetLowering::getSetCCResultType
369 EVT getSetCCResultType(EVT VT) const {
370 return TLI.getSetCCResultType(*DAG.getContext(), VT);
377 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
378 /// nodes from the worklist.
379 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
382 explicit WorkListRemover(DAGCombiner &dc)
383 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
385 virtual void NodeDeleted(SDNode *N, SDNode *E) {
386 DC.removeFromWorkList(N);
391 //===----------------------------------------------------------------------===//
392 // TargetLowering::DAGCombinerInfo implementation
393 //===----------------------------------------------------------------------===//
395 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
396 ((DAGCombiner*)DC)->AddToWorkList(N);
399 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
400 ((DAGCombiner*)DC)->removeFromWorkList(N);
403 SDValue TargetLowering::DAGCombinerInfo::
404 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
405 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
408 SDValue TargetLowering::DAGCombinerInfo::
409 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
410 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
414 SDValue TargetLowering::DAGCombinerInfo::
415 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
416 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
419 void TargetLowering::DAGCombinerInfo::
420 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
421 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
424 //===----------------------------------------------------------------------===//
426 //===----------------------------------------------------------------------===//
428 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
429 /// specified expression for the same cost as the expression itself, or 2 if we
430 /// can compute the negated form more cheaply than the expression itself.
431 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
432 const TargetLowering &TLI,
433 const TargetOptions *Options,
434 unsigned Depth = 0) {
435 // fneg is removable even if it has multiple uses.
436 if (Op.getOpcode() == ISD::FNEG) return 2;
438 // Don't allow anything with multiple uses.
439 if (!Op.hasOneUse()) return 0;
441 // Don't recurse exponentially.
442 if (Depth > 6) return 0;
444 switch (Op.getOpcode()) {
445 default: return false;
446 case ISD::ConstantFP:
447 // Don't invert constant FP values after legalize. The negated constant
448 // isn't necessarily legal.
449 return LegalOperations ? 0 : 1;
451 // FIXME: determine better conditions for this xform.
452 if (!Options->UnsafeFPMath) return 0;
454 // After operation legalization, it might not be legal to create new FSUBs.
455 if (LegalOperations &&
456 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
459 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
460 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
463 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
464 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
467 // We can't turn -(A-B) into B-A when we honor signed zeros.
468 if (!Options->UnsafeFPMath) return 0;
470 // fold (fneg (fsub A, B)) -> (fsub B, A)
475 if (Options->HonorSignDependentRoundingFPMath()) return 0;
477 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
478 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
482 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
488 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
493 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
494 /// returns the newly negated expression.
495 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
496 bool LegalOperations, unsigned Depth = 0) {
497 // fneg is removable even if it has multiple uses.
498 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
500 // Don't allow anything with multiple uses.
501 assert(Op.hasOneUse() && "Unknown reuse!");
503 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
504 switch (Op.getOpcode()) {
505 default: llvm_unreachable("Unknown code");
506 case ISD::ConstantFP: {
507 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
509 return DAG.getConstantFP(V, Op.getValueType());
512 // FIXME: determine better conditions for this xform.
513 assert(DAG.getTarget().Options.UnsafeFPMath);
515 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
516 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
517 DAG.getTargetLoweringInfo(),
518 &DAG.getTarget().Options, Depth+1))
519 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
520 GetNegatedExpression(Op.getOperand(0), DAG,
521 LegalOperations, Depth+1),
523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
525 GetNegatedExpression(Op.getOperand(1), DAG,
526 LegalOperations, Depth+1),
529 // We can't turn -(A-B) into B-A when we honor signed zeros.
530 assert(DAG.getTarget().Options.UnsafeFPMath);
532 // fold (fneg (fsub 0, B)) -> B
533 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
534 if (N0CFP->getValueAPF().isZero())
535 return Op.getOperand(1);
537 // fold (fneg (fsub A, B)) -> (fsub B, A)
538 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
539 Op.getOperand(1), Op.getOperand(0));
543 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
545 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
546 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
547 DAG.getTargetLoweringInfo(),
548 &DAG.getTarget().Options, Depth+1))
549 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
550 GetNegatedExpression(Op.getOperand(0), DAG,
551 LegalOperations, Depth+1),
554 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
555 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
557 GetNegatedExpression(Op.getOperand(1), DAG,
558 LegalOperations, Depth+1));
562 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563 GetNegatedExpression(Op.getOperand(0), DAG,
564 LegalOperations, Depth+1));
566 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
567 GetNegatedExpression(Op.getOperand(0), DAG,
568 LegalOperations, Depth+1),
574 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
575 // that selects between the values 1 and 0, making it equivalent to a setcc.
576 // Also, set the incoming LHS, RHS, and CC references to the appropriate
577 // nodes based on the type of node we are checking. This simplifies life a
578 // bit for the callers.
579 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
581 if (N.getOpcode() == ISD::SETCC) {
582 LHS = N.getOperand(0);
583 RHS = N.getOperand(1);
584 CC = N.getOperand(2);
587 if (N.getOpcode() == ISD::SELECT_CC &&
588 N.getOperand(2).getOpcode() == ISD::Constant &&
589 N.getOperand(3).getOpcode() == ISD::Constant &&
590 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
591 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
592 LHS = N.getOperand(0);
593 RHS = N.getOperand(1);
594 CC = N.getOperand(4);
600 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
601 // one use. If this is true, it allows the users to invert the operation for
602 // free when it is profitable to do so.
603 static bool isOneUseSetCC(SDValue N) {
605 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
610 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
611 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
612 if (isa<ConstantSDNode>(N))
614 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
615 if(BV && BV->isConstant())
620 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
621 SDValue N0, SDValue N1) {
622 EVT VT = N0.getValueType();
623 if (N0.getOpcode() == Opc) {
624 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
625 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
626 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
627 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
628 if (!OpNode.getNode())
630 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
632 if (N0.hasOneUse()) {
633 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
635 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
636 if (!OpNode.getNode())
638 AddToWorkList(OpNode.getNode());
639 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
644 if (N1.getOpcode() == Opc) {
645 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
646 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
647 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
648 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
649 if (!OpNode.getNode())
651 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
653 if (N1.hasOneUse()) {
654 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
656 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
657 if (!OpNode.getNode())
659 AddToWorkList(OpNode.getNode());
660 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
668 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
670 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
672 DEBUG(dbgs() << "\nReplacing.1 ";
674 dbgs() << "\nWith: ";
675 To[0].getNode()->dump(&DAG);
676 dbgs() << " and " << NumTo-1 << " other values\n";
677 for (unsigned i = 0, e = NumTo; i != e; ++i)
678 assert((!To[i].getNode() ||
679 N->getValueType(i) == To[i].getValueType()) &&
680 "Cannot combine value to value of different type!"));
681 WorkListRemover DeadNodes(*this);
682 DAG.ReplaceAllUsesWith(N, To);
684 // Push the new nodes and any users onto the worklist
685 for (unsigned i = 0, e = NumTo; i != e; ++i) {
686 if (To[i].getNode()) {
687 AddToWorkList(To[i].getNode());
688 AddUsersToWorkList(To[i].getNode());
693 // Finally, if the node is now dead, remove it from the graph. The node
694 // may not be dead if the replacement process recursively simplified to
695 // something else needing this node.
696 if (N->use_empty()) {
697 // Nodes can be reintroduced into the worklist. Make sure we do not
698 // process a node that has been replaced.
699 removeFromWorkList(N);
701 // Finally, since the node is now dead, remove it from the graph.
704 return SDValue(N, 0);
708 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
709 // Replace all uses. If any nodes become isomorphic to other nodes and
710 // are deleted, make sure to remove them from our worklist.
711 WorkListRemover DeadNodes(*this);
712 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
714 // Push the new node and any (possibly new) users onto the worklist.
715 AddToWorkList(TLO.New.getNode());
716 AddUsersToWorkList(TLO.New.getNode());
718 // Finally, if the node is now dead, remove it from the graph. The node
719 // may not be dead if the replacement process recursively simplified to
720 // something else needing this node.
721 if (TLO.Old.getNode()->use_empty()) {
722 removeFromWorkList(TLO.Old.getNode());
724 // If the operands of this node are only used by the node, they will now
725 // be dead. Make sure to visit them first to delete dead nodes early.
726 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
727 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
728 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
730 DAG.DeleteNode(TLO.Old.getNode());
734 /// SimplifyDemandedBits - Check the specified integer node value to see if
735 /// it can be simplified or if things it uses can be simplified by bit
736 /// propagation. If so, return true.
737 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
738 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
739 APInt KnownZero, KnownOne;
740 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
744 AddToWorkList(Op.getNode());
746 // Replace the old value with the new one.
748 DEBUG(dbgs() << "\nReplacing.2 ";
749 TLO.Old.getNode()->dump(&DAG);
750 dbgs() << "\nWith: ";
751 TLO.New.getNode()->dump(&DAG);
754 CommitTargetLoweringOpt(TLO);
758 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
760 EVT VT = Load->getValueType(0);
761 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
763 DEBUG(dbgs() << "\nReplacing.9 ";
765 dbgs() << "\nWith: ";
766 Trunc.getNode()->dump(&DAG);
768 WorkListRemover DeadNodes(*this);
769 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
770 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
771 removeFromWorkList(Load);
772 DAG.DeleteNode(Load);
773 AddToWorkList(Trunc.getNode());
776 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
779 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
780 EVT MemVT = LD->getMemoryVT();
781 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
782 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
784 : LD->getExtensionType();
786 return DAG.getExtLoad(ExtType, dl, PVT,
787 LD->getChain(), LD->getBasePtr(),
788 MemVT, LD->getMemOperand());
791 unsigned Opc = Op.getOpcode();
794 case ISD::AssertSext:
795 return DAG.getNode(ISD::AssertSext, dl, PVT,
796 SExtPromoteOperand(Op.getOperand(0), PVT),
798 case ISD::AssertZext:
799 return DAG.getNode(ISD::AssertZext, dl, PVT,
800 ZExtPromoteOperand(Op.getOperand(0), PVT),
802 case ISD::Constant: {
804 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
805 return DAG.getNode(ExtOpc, dl, PVT, Op);
809 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
811 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
814 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
815 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
817 EVT OldVT = Op.getValueType();
819 bool Replace = false;
820 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
821 if (NewOp.getNode() == 0)
823 AddToWorkList(NewOp.getNode());
826 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
827 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
828 DAG.getValueType(OldVT));
831 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
832 EVT OldVT = Op.getValueType();
834 bool Replace = false;
835 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
836 if (NewOp.getNode() == 0)
838 AddToWorkList(NewOp.getNode());
841 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
842 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
845 /// PromoteIntBinOp - Promote the specified integer binary operation if the
846 /// target indicates it is beneficial. e.g. On x86, it's usually better to
847 /// promote i16 operations to i32 since i16 instructions are longer.
848 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
849 if (!LegalOperations)
852 EVT VT = Op.getValueType();
853 if (VT.isVector() || !VT.isInteger())
856 // If operation type is 'undesirable', e.g. i16 on x86, consider
858 unsigned Opc = Op.getOpcode();
859 if (TLI.isTypeDesirableForOp(Opc, VT))
863 // Consult target whether it is a good idea to promote this operation and
864 // what's the right type to promote it to.
865 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
866 assert(PVT != VT && "Don't know what type to promote to!");
868 bool Replace0 = false;
869 SDValue N0 = Op.getOperand(0);
870 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
871 if (NN0.getNode() == 0)
874 bool Replace1 = false;
875 SDValue N1 = Op.getOperand(1);
880 NN1 = PromoteOperand(N1, PVT, Replace1);
881 if (NN1.getNode() == 0)
885 AddToWorkList(NN0.getNode());
887 AddToWorkList(NN1.getNode());
890 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
892 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
894 DEBUG(dbgs() << "\nPromoting ";
895 Op.getNode()->dump(&DAG));
897 return DAG.getNode(ISD::TRUNCATE, dl, VT,
898 DAG.getNode(Opc, dl, PVT, NN0, NN1));
903 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
904 /// target indicates it is beneficial. e.g. On x86, it's usually better to
905 /// promote i16 operations to i32 since i16 instructions are longer.
906 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
907 if (!LegalOperations)
910 EVT VT = Op.getValueType();
911 if (VT.isVector() || !VT.isInteger())
914 // If operation type is 'undesirable', e.g. i16 on x86, consider
916 unsigned Opc = Op.getOpcode();
917 if (TLI.isTypeDesirableForOp(Opc, VT))
921 // Consult target whether it is a good idea to promote this operation and
922 // what's the right type to promote it to.
923 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
924 assert(PVT != VT && "Don't know what type to promote to!");
926 bool Replace = false;
927 SDValue N0 = Op.getOperand(0);
929 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
930 else if (Opc == ISD::SRL)
931 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
933 N0 = PromoteOperand(N0, PVT, Replace);
934 if (N0.getNode() == 0)
937 AddToWorkList(N0.getNode());
939 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
941 DEBUG(dbgs() << "\nPromoting ";
942 Op.getNode()->dump(&DAG));
944 return DAG.getNode(ISD::TRUNCATE, dl, VT,
945 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
950 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
951 if (!LegalOperations)
954 EVT VT = Op.getValueType();
955 if (VT.isVector() || !VT.isInteger())
958 // If operation type is 'undesirable', e.g. i16 on x86, consider
960 unsigned Opc = Op.getOpcode();
961 if (TLI.isTypeDesirableForOp(Opc, VT))
965 // Consult target whether it is a good idea to promote this operation and
966 // what's the right type to promote it to.
967 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
968 assert(PVT != VT && "Don't know what type to promote to!");
969 // fold (aext (aext x)) -> (aext x)
970 // fold (aext (zext x)) -> (zext x)
971 // fold (aext (sext x)) -> (sext x)
972 DEBUG(dbgs() << "\nPromoting ";
973 Op.getNode()->dump(&DAG));
974 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
979 bool DAGCombiner::PromoteLoad(SDValue Op) {
980 if (!LegalOperations)
983 EVT VT = Op.getValueType();
984 if (VT.isVector() || !VT.isInteger())
987 // If operation type is 'undesirable', e.g. i16 on x86, consider
989 unsigned Opc = Op.getOpcode();
990 if (TLI.isTypeDesirableForOp(Opc, VT))
994 // Consult target whether it is a good idea to promote this operation and
995 // what's the right type to promote it to.
996 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
997 assert(PVT != VT && "Don't know what type to promote to!");
1000 SDNode *N = Op.getNode();
1001 LoadSDNode *LD = cast<LoadSDNode>(N);
1002 EVT MemVT = LD->getMemoryVT();
1003 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1004 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1006 : LD->getExtensionType();
1007 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1008 LD->getChain(), LD->getBasePtr(),
1009 MemVT, LD->getMemOperand());
1010 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1012 DEBUG(dbgs() << "\nPromoting ";
1015 Result.getNode()->dump(&DAG);
1017 WorkListRemover DeadNodes(*this);
1018 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1019 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1020 removeFromWorkList(N);
1022 AddToWorkList(Result.getNode());
1029 //===----------------------------------------------------------------------===//
1030 // Main DAG Combiner implementation
1031 //===----------------------------------------------------------------------===//
1033 void DAGCombiner::Run(CombineLevel AtLevel) {
1034 // set the instance variables, so that the various visit routines may use it.
1036 LegalOperations = Level >= AfterLegalizeVectorOps;
1037 LegalTypes = Level >= AfterLegalizeTypes;
1039 // Add all the dag nodes to the worklist.
1040 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1041 E = DAG.allnodes_end(); I != E; ++I)
1044 // Create a dummy node (which is not added to allnodes), that adds a reference
1045 // to the root node, preventing it from being deleted, and tracking any
1046 // changes of the root.
1047 HandleSDNode Dummy(DAG.getRoot());
1049 // The root of the dag may dangle to deleted nodes until the dag combiner is
1050 // done. Set it to null to avoid confusion.
1051 DAG.setRoot(SDValue());
1053 // while the worklist isn't empty, find a node and
1054 // try and combine it.
1055 while (!WorkListContents.empty()) {
1057 // The WorkListOrder holds the SDNodes in order, but it may contain
1059 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1060 // worklist *should* contain, and check the node we want to visit is should
1061 // actually be visited.
1063 N = WorkListOrder.pop_back_val();
1064 } while (!WorkListContents.erase(N));
1066 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1067 // N is deleted from the DAG, since they too may now be dead or may have a
1068 // reduced number of uses, allowing other xforms.
1069 if (N->use_empty() && N != &Dummy) {
1070 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1071 AddToWorkList(N->getOperand(i).getNode());
1077 SDValue RV = combine(N);
1079 if (RV.getNode() == 0)
1084 // If we get back the same node we passed in, rather than a new node or
1085 // zero, we know that the node must have defined multiple values and
1086 // CombineTo was used. Since CombineTo takes care of the worklist
1087 // mechanics for us, we have no work to do in this case.
1088 if (RV.getNode() == N)
1091 assert(N->getOpcode() != ISD::DELETED_NODE &&
1092 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1093 "Node was deleted but visit returned new node!");
1095 DEBUG(dbgs() << "\nReplacing.3 ";
1097 dbgs() << "\nWith: ";
1098 RV.getNode()->dump(&DAG);
1101 // Transfer debug value.
1102 DAG.TransferDbgValues(SDValue(N, 0), RV);
1103 WorkListRemover DeadNodes(*this);
1104 if (N->getNumValues() == RV.getNode()->getNumValues())
1105 DAG.ReplaceAllUsesWith(N, RV.getNode());
1107 assert(N->getValueType(0) == RV.getValueType() &&
1108 N->getNumValues() == 1 && "Type mismatch");
1110 DAG.ReplaceAllUsesWith(N, &OpV);
1113 // Push the new node and any users onto the worklist
1114 AddToWorkList(RV.getNode());
1115 AddUsersToWorkList(RV.getNode());
1117 // Add any uses of the old node to the worklist in case this node is the
1118 // last one that uses them. They may become dead after this node is
1120 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1121 AddToWorkList(N->getOperand(i).getNode());
1123 // Finally, if the node is now dead, remove it from the graph. The node
1124 // may not be dead if the replacement process recursively simplified to
1125 // something else needing this node.
1126 if (N->use_empty()) {
1127 // Nodes can be reintroduced into the worklist. Make sure we do not
1128 // process a node that has been replaced.
1129 removeFromWorkList(N);
1131 // Finally, since the node is now dead, remove it from the graph.
1136 // If the root changed (e.g. it was a dead load, update the root).
1137 DAG.setRoot(Dummy.getValue());
1138 DAG.RemoveDeadNodes();
1141 SDValue DAGCombiner::visit(SDNode *N) {
1142 switch (N->getOpcode()) {
1144 case ISD::TokenFactor: return visitTokenFactor(N);
1145 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1146 case ISD::ADD: return visitADD(N);
1147 case ISD::SUB: return visitSUB(N);
1148 case ISD::ADDC: return visitADDC(N);
1149 case ISD::SUBC: return visitSUBC(N);
1150 case ISD::ADDE: return visitADDE(N);
1151 case ISD::SUBE: return visitSUBE(N);
1152 case ISD::MUL: return visitMUL(N);
1153 case ISD::SDIV: return visitSDIV(N);
1154 case ISD::UDIV: return visitUDIV(N);
1155 case ISD::SREM: return visitSREM(N);
1156 case ISD::UREM: return visitUREM(N);
1157 case ISD::MULHU: return visitMULHU(N);
1158 case ISD::MULHS: return visitMULHS(N);
1159 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1160 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1161 case ISD::SMULO: return visitSMULO(N);
1162 case ISD::UMULO: return visitUMULO(N);
1163 case ISD::SDIVREM: return visitSDIVREM(N);
1164 case ISD::UDIVREM: return visitUDIVREM(N);
1165 case ISD::AND: return visitAND(N);
1166 case ISD::OR: return visitOR(N);
1167 case ISD::XOR: return visitXOR(N);
1168 case ISD::SHL: return visitSHL(N);
1169 case ISD::SRA: return visitSRA(N);
1170 case ISD::SRL: return visitSRL(N);
1171 case ISD::CTLZ: return visitCTLZ(N);
1172 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1173 case ISD::CTTZ: return visitCTTZ(N);
1174 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1175 case ISD::CTPOP: return visitCTPOP(N);
1176 case ISD::SELECT: return visitSELECT(N);
1177 case ISD::VSELECT: return visitVSELECT(N);
1178 case ISD::SELECT_CC: return visitSELECT_CC(N);
1179 case ISD::SETCC: return visitSETCC(N);
1180 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1181 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1182 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1183 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1184 case ISD::TRUNCATE: return visitTRUNCATE(N);
1185 case ISD::BITCAST: return visitBITCAST(N);
1186 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1187 case ISD::FADD: return visitFADD(N);
1188 case ISD::FSUB: return visitFSUB(N);
1189 case ISD::FMUL: return visitFMUL(N);
1190 case ISD::FMA: return visitFMA(N);
1191 case ISD::FDIV: return visitFDIV(N);
1192 case ISD::FREM: return visitFREM(N);
1193 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1194 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1195 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1196 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1197 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1198 case ISD::FP_ROUND: return visitFP_ROUND(N);
1199 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1200 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1201 case ISD::FNEG: return visitFNEG(N);
1202 case ISD::FABS: return visitFABS(N);
1203 case ISD::FFLOOR: return visitFFLOOR(N);
1204 case ISD::FCEIL: return visitFCEIL(N);
1205 case ISD::FTRUNC: return visitFTRUNC(N);
1206 case ISD::BRCOND: return visitBRCOND(N);
1207 case ISD::BR_CC: return visitBR_CC(N);
1208 case ISD::LOAD: return visitLOAD(N);
1209 case ISD::STORE: return visitSTORE(N);
1210 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1211 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1212 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1213 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1214 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1215 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1220 SDValue DAGCombiner::combine(SDNode *N) {
1221 SDValue RV = visit(N);
1223 // If nothing happened, try a target-specific DAG combine.
1224 if (RV.getNode() == 0) {
1225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 "Node was deleted but visit returned NULL!");
1228 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1229 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1231 // Expose the DAG combiner to the target combiner impls.
1232 TargetLowering::DAGCombinerInfo
1233 DagCombineInfo(DAG, Level, false, this);
1235 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1239 // If nothing happened still, try promoting the operation.
1240 if (RV.getNode() == 0) {
1241 switch (N->getOpcode()) {
1249 RV = PromoteIntBinOp(SDValue(N, 0));
1254 RV = PromoteIntShiftOp(SDValue(N, 0));
1256 case ISD::SIGN_EXTEND:
1257 case ISD::ZERO_EXTEND:
1258 case ISD::ANY_EXTEND:
1259 RV = PromoteExtend(SDValue(N, 0));
1262 if (PromoteLoad(SDValue(N, 0)))
1268 // If N is a commutative binary node, try commuting it to enable more
1270 if (RV.getNode() == 0 &&
1271 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1272 N->getNumValues() == 1) {
1273 SDValue N0 = N->getOperand(0);
1274 SDValue N1 = N->getOperand(1);
1276 // Constant operands are canonicalized to RHS.
1277 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1278 SDValue Ops[] = { N1, N0 };
1279 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1282 return SDValue(CSENode, 0);
1289 /// getInputChainForNode - Given a node, return its input chain if it has one,
1290 /// otherwise return a null sd operand.
1291 static SDValue getInputChainForNode(SDNode *N) {
1292 if (unsigned NumOps = N->getNumOperands()) {
1293 if (N->getOperand(0).getValueType() == MVT::Other)
1294 return N->getOperand(0);
1295 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1296 return N->getOperand(NumOps-1);
1297 for (unsigned i = 1; i < NumOps-1; ++i)
1298 if (N->getOperand(i).getValueType() == MVT::Other)
1299 return N->getOperand(i);
1304 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1305 // If N has two operands, where one has an input chain equal to the other,
1306 // the 'other' chain is redundant.
1307 if (N->getNumOperands() == 2) {
1308 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1309 return N->getOperand(0);
1310 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1311 return N->getOperand(1);
1314 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1315 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1316 SmallPtrSet<SDNode*, 16> SeenOps;
1317 bool Changed = false; // If we should replace this token factor.
1319 // Start out with this token factor.
1322 // Iterate through token factors. The TFs grows when new token factors are
1324 for (unsigned i = 0; i < TFs.size(); ++i) {
1325 SDNode *TF = TFs[i];
1327 // Check each of the operands.
1328 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1329 SDValue Op = TF->getOperand(i);
1331 switch (Op.getOpcode()) {
1332 case ISD::EntryToken:
1333 // Entry tokens don't need to be added to the list. They are
1338 case ISD::TokenFactor:
1339 if (Op.hasOneUse() &&
1340 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1341 // Queue up for processing.
1342 TFs.push_back(Op.getNode());
1343 // Clean up in case the token factor is removed.
1344 AddToWorkList(Op.getNode());
1351 // Only add if it isn't already in the list.
1352 if (SeenOps.insert(Op.getNode()))
1363 // If we've change things around then replace token factor.
1366 // The entry token is the only possible outcome.
1367 Result = DAG.getEntryNode();
1369 // New and improved token factor.
1370 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1371 MVT::Other, &Ops[0], Ops.size());
1374 // Don't add users to work list.
1375 return CombineTo(N, Result, false);
1381 /// MERGE_VALUES can always be eliminated.
1382 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1383 WorkListRemover DeadNodes(*this);
1384 // Replacing results may cause a different MERGE_VALUES to suddenly
1385 // be CSE'd with N, and carry its uses with it. Iterate until no
1386 // uses remain, to ensure that the node can be safely deleted.
1387 // First add the users of this node to the work list so that they
1388 // can be tried again once they have new operands.
1389 AddUsersToWorkList(N);
1391 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1392 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1393 } while (!N->use_empty());
1394 removeFromWorkList(N);
1396 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1400 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1401 SelectionDAG &DAG) {
1402 EVT VT = N0.getValueType();
1403 SDValue N00 = N0.getOperand(0);
1404 SDValue N01 = N0.getOperand(1);
1405 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1407 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1408 isa<ConstantSDNode>(N00.getOperand(1))) {
1409 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1410 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1411 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1412 N00.getOperand(0), N01),
1413 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1414 N00.getOperand(1), N01));
1415 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1421 SDValue DAGCombiner::visitADD(SDNode *N) {
1422 SDValue N0 = N->getOperand(0);
1423 SDValue N1 = N->getOperand(1);
1424 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1425 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1426 EVT VT = N0.getValueType();
1429 if (VT.isVector()) {
1430 SDValue FoldedVOp = SimplifyVBinOp(N);
1431 if (FoldedVOp.getNode()) return FoldedVOp;
1433 // fold (add x, 0) -> x, vector edition
1434 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1436 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1440 // fold (add x, undef) -> undef
1441 if (N0.getOpcode() == ISD::UNDEF)
1443 if (N1.getOpcode() == ISD::UNDEF)
1445 // fold (add c1, c2) -> c1+c2
1447 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1448 // canonicalize constant to RHS
1450 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1451 // fold (add x, 0) -> x
1452 if (N1C && N1C->isNullValue())
1454 // fold (add Sym, c) -> Sym+c
1455 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1456 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1457 GA->getOpcode() == ISD::GlobalAddress)
1458 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1460 (uint64_t)N1C->getSExtValue());
1461 // fold ((c1-A)+c2) -> (c1+c2)-A
1462 if (N1C && N0.getOpcode() == ISD::SUB)
1463 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1464 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1465 DAG.getConstant(N1C->getAPIntValue()+
1466 N0C->getAPIntValue(), VT),
1469 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1470 if (RADD.getNode() != 0)
1472 // fold ((0-A) + B) -> B-A
1473 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1474 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1475 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1476 // fold (A + (0-B)) -> A-B
1477 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1478 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1479 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1480 // fold (A+(B-A)) -> B
1481 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1482 return N1.getOperand(0);
1483 // fold ((B-A)+A) -> B
1484 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1485 return N0.getOperand(0);
1486 // fold (A+(B-(A+C))) to (B-C)
1487 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1488 N0 == N1.getOperand(1).getOperand(0))
1489 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1490 N1.getOperand(1).getOperand(1));
1491 // fold (A+(B-(C+A))) to (B-C)
1492 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1493 N0 == N1.getOperand(1).getOperand(1))
1494 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1495 N1.getOperand(1).getOperand(0));
1496 // fold (A+((B-A)+or-C)) to (B+or-C)
1497 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1498 N1.getOperand(0).getOpcode() == ISD::SUB &&
1499 N0 == N1.getOperand(0).getOperand(1))
1500 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1501 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1503 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1504 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1505 SDValue N00 = N0.getOperand(0);
1506 SDValue N01 = N0.getOperand(1);
1507 SDValue N10 = N1.getOperand(0);
1508 SDValue N11 = N1.getOperand(1);
1510 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1511 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1512 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1513 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1516 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1517 return SDValue(N, 0);
1519 // fold (a+b) -> (a|b) iff a and b share no bits.
1520 if (VT.isInteger() && !VT.isVector()) {
1521 APInt LHSZero, LHSOne;
1522 APInt RHSZero, RHSOne;
1523 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1525 if (LHSZero.getBoolValue()) {
1526 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1528 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1529 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1530 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1531 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1535 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1536 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1537 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1538 if (Result.getNode()) return Result;
1540 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1541 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1542 if (Result.getNode()) return Result;
1545 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1546 if (N1.getOpcode() == ISD::SHL &&
1547 N1.getOperand(0).getOpcode() == ISD::SUB)
1548 if (ConstantSDNode *C =
1549 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1550 if (C->getAPIntValue() == 0)
1551 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1552 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1553 N1.getOperand(0).getOperand(1),
1555 if (N0.getOpcode() == ISD::SHL &&
1556 N0.getOperand(0).getOpcode() == ISD::SUB)
1557 if (ConstantSDNode *C =
1558 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1559 if (C->getAPIntValue() == 0)
1560 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1561 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1562 N0.getOperand(0).getOperand(1),
1565 if (N1.getOpcode() == ISD::AND) {
1566 SDValue AndOp0 = N1.getOperand(0);
1567 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1568 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1569 unsigned DestBits = VT.getScalarType().getSizeInBits();
1571 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1572 // and similar xforms where the inner op is either ~0 or 0.
1573 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1575 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1579 // add (sext i1), X -> sub X, (zext i1)
1580 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1581 N0.getOperand(0).getValueType() == MVT::i1 &&
1582 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1584 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1585 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1591 SDValue DAGCombiner::visitADDC(SDNode *N) {
1592 SDValue N0 = N->getOperand(0);
1593 SDValue N1 = N->getOperand(1);
1594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1596 EVT VT = N0.getValueType();
1598 // If the flag result is dead, turn this into an ADD.
1599 if (!N->hasAnyUseOfValue(1))
1600 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1601 DAG.getNode(ISD::CARRY_FALSE,
1602 SDLoc(N), MVT::Glue));
1604 // canonicalize constant to RHS.
1606 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1608 // fold (addc x, 0) -> x + no carry out
1609 if (N1C && N1C->isNullValue())
1610 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1611 SDLoc(N), MVT::Glue));
1613 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1614 APInt LHSZero, LHSOne;
1615 APInt RHSZero, RHSOne;
1616 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1618 if (LHSZero.getBoolValue()) {
1619 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1621 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1622 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1623 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1624 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1625 DAG.getNode(ISD::CARRY_FALSE,
1626 SDLoc(N), MVT::Glue));
1632 SDValue DAGCombiner::visitADDE(SDNode *N) {
1633 SDValue N0 = N->getOperand(0);
1634 SDValue N1 = N->getOperand(1);
1635 SDValue CarryIn = N->getOperand(2);
1636 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1637 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1639 // canonicalize constant to RHS
1641 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1644 // fold (adde x, y, false) -> (addc x, y)
1645 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1646 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1651 // Since it may not be valid to emit a fold to zero for vector initializers
1652 // check if we can before folding.
1653 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1655 bool LegalOperations, bool LegalTypes) {
1657 return DAG.getConstant(0, VT);
1658 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1659 return DAG.getConstant(0, VT);
1663 SDValue DAGCombiner::visitSUB(SDNode *N) {
1664 SDValue N0 = N->getOperand(0);
1665 SDValue N1 = N->getOperand(1);
1666 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1667 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1668 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1669 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1670 EVT VT = N0.getValueType();
1673 if (VT.isVector()) {
1674 SDValue FoldedVOp = SimplifyVBinOp(N);
1675 if (FoldedVOp.getNode()) return FoldedVOp;
1677 // fold (sub x, 0) -> x, vector edition
1678 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1682 // fold (sub x, x) -> 0
1683 // FIXME: Refactor this and xor and other similar operations together.
1685 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1686 // fold (sub c1, c2) -> c1-c2
1688 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1689 // fold (sub x, c) -> (add x, -c)
1691 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1692 DAG.getConstant(-N1C->getAPIntValue(), VT));
1693 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1694 if (N0C && N0C->isAllOnesValue())
1695 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1696 // fold A-(A-B) -> B
1697 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1698 return N1.getOperand(1);
1699 // fold (A+B)-A -> B
1700 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1701 return N0.getOperand(1);
1702 // fold (A+B)-B -> A
1703 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1704 return N0.getOperand(0);
1705 // fold C2-(A+C1) -> (C2-C1)-A
1706 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1707 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1709 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1712 // fold ((A+(B+or-C))-B) -> A+or-C
1713 if (N0.getOpcode() == ISD::ADD &&
1714 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1715 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1716 N0.getOperand(1).getOperand(0) == N1)
1717 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1718 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1719 // fold ((A+(C+B))-B) -> A+C
1720 if (N0.getOpcode() == ISD::ADD &&
1721 N0.getOperand(1).getOpcode() == ISD::ADD &&
1722 N0.getOperand(1).getOperand(1) == N1)
1723 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1724 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1725 // fold ((A-(B-C))-C) -> A-B
1726 if (N0.getOpcode() == ISD::SUB &&
1727 N0.getOperand(1).getOpcode() == ISD::SUB &&
1728 N0.getOperand(1).getOperand(1) == N1)
1729 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1732 // If either operand of a sub is undef, the result is undef
1733 if (N0.getOpcode() == ISD::UNDEF)
1735 if (N1.getOpcode() == ISD::UNDEF)
1738 // If the relocation model supports it, consider symbol offsets.
1739 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1740 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1741 // fold (sub Sym, c) -> Sym-c
1742 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1743 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1745 (uint64_t)N1C->getSExtValue());
1746 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1747 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1748 if (GA->getGlobal() == GB->getGlobal())
1749 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1756 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1757 SDValue N0 = N->getOperand(0);
1758 SDValue N1 = N->getOperand(1);
1759 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761 EVT VT = N0.getValueType();
1763 // If the flag result is dead, turn this into an SUB.
1764 if (!N->hasAnyUseOfValue(1))
1765 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1766 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1769 // fold (subc x, x) -> 0 + no borrow
1771 return CombineTo(N, DAG.getConstant(0, VT),
1772 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1775 // fold (subc x, 0) -> x + no borrow
1776 if (N1C && N1C->isNullValue())
1777 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1780 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1781 if (N0C && N0C->isAllOnesValue())
1782 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1783 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1789 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1790 SDValue N0 = N->getOperand(0);
1791 SDValue N1 = N->getOperand(1);
1792 SDValue CarryIn = N->getOperand(2);
1794 // fold (sube x, y, false) -> (subc x, y)
1795 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1796 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1801 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1802 /// elements are all the same constant or undefined.
1803 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1804 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1809 unsigned SplatBitSize;
1811 EVT EltVT = N->getValueType(0).getVectorElementType();
1812 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1814 EltVT.getSizeInBits() >= SplatBitSize);
1817 SDValue DAGCombiner::visitMUL(SDNode *N) {
1818 SDValue N0 = N->getOperand(0);
1819 SDValue N1 = N->getOperand(1);
1820 EVT VT = N0.getValueType();
1822 // fold (mul x, undef) -> 0
1823 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1824 return DAG.getConstant(0, VT);
1826 bool N0IsConst = false;
1827 bool N1IsConst = false;
1828 APInt ConstValue0, ConstValue1;
1830 if (VT.isVector()) {
1831 SDValue FoldedVOp = SimplifyVBinOp(N);
1832 if (FoldedVOp.getNode()) return FoldedVOp;
1834 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1835 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1837 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1838 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1840 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1841 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1845 // fold (mul c1, c2) -> c1*c2
1846 if (N0IsConst && N1IsConst)
1847 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1849 // canonicalize constant to RHS
1850 if (N0IsConst && !N1IsConst)
1851 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1852 // fold (mul x, 0) -> 0
1853 if (N1IsConst && ConstValue1 == 0)
1855 // We require a splat of the entire scalar bit width for non-contiguous
1858 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1859 // fold (mul x, 1) -> x
1860 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1862 // fold (mul x, -1) -> 0-x
1863 if (N1IsConst && ConstValue1.isAllOnesValue())
1864 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1865 DAG.getConstant(0, VT), N0);
1866 // fold (mul x, (1 << c)) -> x << c
1867 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1868 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1869 DAG.getConstant(ConstValue1.logBase2(),
1870 getShiftAmountTy(N0.getValueType())));
1871 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1872 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1873 unsigned Log2Val = (-ConstValue1).logBase2();
1874 // FIXME: If the input is something that is easily negated (e.g. a
1875 // single-use add), we should put the negate there.
1876 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1877 DAG.getConstant(0, VT),
1878 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1879 DAG.getConstant(Log2Val,
1880 getShiftAmountTy(N0.getValueType()))));
1884 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1885 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1886 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1887 isa<ConstantSDNode>(N0.getOperand(1)))) {
1888 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1889 N1, N0.getOperand(1));
1890 AddToWorkList(C3.getNode());
1891 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1892 N0.getOperand(0), C3);
1895 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1898 SDValue Sh(0,0), Y(0,0);
1899 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1900 if (N0.getOpcode() == ISD::SHL &&
1901 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1902 isa<ConstantSDNode>(N0.getOperand(1))) &&
1903 N0.getNode()->hasOneUse()) {
1905 } else if (N1.getOpcode() == ISD::SHL &&
1906 isa<ConstantSDNode>(N1.getOperand(1)) &&
1907 N1.getNode()->hasOneUse()) {
1912 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1913 Sh.getOperand(0), Y);
1914 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1915 Mul, Sh.getOperand(1));
1919 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1920 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1921 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922 isa<ConstantSDNode>(N0.getOperand(1))))
1923 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1924 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1925 N0.getOperand(0), N1),
1926 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1927 N0.getOperand(1), N1));
1930 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1931 if (RMUL.getNode() != 0)
1937 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1938 SDValue N0 = N->getOperand(0);
1939 SDValue N1 = N->getOperand(1);
1940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1942 EVT VT = N->getValueType(0);
1945 if (VT.isVector()) {
1946 SDValue FoldedVOp = SimplifyVBinOp(N);
1947 if (FoldedVOp.getNode()) return FoldedVOp;
1950 // fold (sdiv c1, c2) -> c1/c2
1951 if (N0C && N1C && !N1C->isNullValue())
1952 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1953 // fold (sdiv X, 1) -> X
1954 if (N1C && N1C->getAPIntValue() == 1LL)
1956 // fold (sdiv X, -1) -> 0-X
1957 if (N1C && N1C->isAllOnesValue())
1958 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1959 DAG.getConstant(0, VT), N0);
1960 // If we know the sign bits of both operands are zero, strength reduce to a
1961 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1962 if (!VT.isVector()) {
1963 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1964 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1967 // fold (sdiv X, pow2) -> simple ops after legalize
1968 if (N1C && !N1C->isNullValue() &&
1969 (N1C->getAPIntValue().isPowerOf2() ||
1970 (-N1C->getAPIntValue()).isPowerOf2())) {
1971 // If dividing by powers of two is cheap, then don't perform the following
1973 if (TLI.isPow2DivCheap())
1976 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1978 // Splat the sign bit into the register
1979 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1980 DAG.getConstant(VT.getSizeInBits()-1,
1981 getShiftAmountTy(N0.getValueType())));
1982 AddToWorkList(SGN.getNode());
1984 // Add (N0 < 0) ? abs2 - 1 : 0;
1985 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1986 DAG.getConstant(VT.getSizeInBits() - lg2,
1987 getShiftAmountTy(SGN.getValueType())));
1988 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1989 AddToWorkList(SRL.getNode());
1990 AddToWorkList(ADD.getNode()); // Divide by pow2
1991 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1992 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1994 // If we're dividing by a positive value, we're done. Otherwise, we must
1995 // negate the result.
1996 if (N1C->getAPIntValue().isNonNegative())
1999 AddToWorkList(SRA.getNode());
2000 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2001 DAG.getConstant(0, VT), SRA);
2004 // if integer divide is expensive and we satisfy the requirements, emit an
2005 // alternate sequence.
2006 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2007 SDValue Op = BuildSDIV(N);
2008 if (Op.getNode()) return Op;
2012 if (N0.getOpcode() == ISD::UNDEF)
2013 return DAG.getConstant(0, VT);
2014 // X / undef -> undef
2015 if (N1.getOpcode() == ISD::UNDEF)
2021 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2022 SDValue N0 = N->getOperand(0);
2023 SDValue N1 = N->getOperand(1);
2024 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2026 EVT VT = N->getValueType(0);
2029 if (VT.isVector()) {
2030 SDValue FoldedVOp = SimplifyVBinOp(N);
2031 if (FoldedVOp.getNode()) return FoldedVOp;
2034 // fold (udiv c1, c2) -> c1/c2
2035 if (N0C && N1C && !N1C->isNullValue())
2036 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2037 // fold (udiv x, (1 << c)) -> x >>u c
2038 if (N1C && N1C->getAPIntValue().isPowerOf2())
2039 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2040 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2041 getShiftAmountTy(N0.getValueType())));
2042 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2043 if (N1.getOpcode() == ISD::SHL) {
2044 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2045 if (SHC->getAPIntValue().isPowerOf2()) {
2046 EVT ADDVT = N1.getOperand(1).getValueType();
2047 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2049 DAG.getConstant(SHC->getAPIntValue()
2052 AddToWorkList(Add.getNode());
2053 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2057 // fold (udiv x, c) -> alternate
2058 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2059 SDValue Op = BuildUDIV(N);
2060 if (Op.getNode()) return Op;
2064 if (N0.getOpcode() == ISD::UNDEF)
2065 return DAG.getConstant(0, VT);
2066 // X / undef -> undef
2067 if (N1.getOpcode() == ISD::UNDEF)
2073 SDValue DAGCombiner::visitSREM(SDNode *N) {
2074 SDValue N0 = N->getOperand(0);
2075 SDValue N1 = N->getOperand(1);
2076 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2077 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2078 EVT VT = N->getValueType(0);
2080 // fold (srem c1, c2) -> c1%c2
2081 if (N0C && N1C && !N1C->isNullValue())
2082 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2083 // If we know the sign bits of both operands are zero, strength reduce to a
2084 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2085 if (!VT.isVector()) {
2086 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2087 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2090 // If X/C can be simplified by the division-by-constant logic, lower
2091 // X%C to the equivalent of X-X/C*C.
2092 if (N1C && !N1C->isNullValue()) {
2093 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2094 AddToWorkList(Div.getNode());
2095 SDValue OptimizedDiv = combine(Div.getNode());
2096 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2097 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2099 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2100 AddToWorkList(Mul.getNode());
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return DAG.getConstant(0, VT);
2108 // X % undef -> undef
2109 if (N1.getOpcode() == ISD::UNDEF)
2115 SDValue DAGCombiner::visitUREM(SDNode *N) {
2116 SDValue N0 = N->getOperand(0);
2117 SDValue N1 = N->getOperand(1);
2118 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2119 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2120 EVT VT = N->getValueType(0);
2122 // fold (urem c1, c2) -> c1%c2
2123 if (N0C && N1C && !N1C->isNullValue())
2124 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2125 // fold (urem x, pow2) -> (and x, pow2-1)
2126 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2127 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2128 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2129 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2130 if (N1.getOpcode() == ISD::SHL) {
2131 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2132 if (SHC->getAPIntValue().isPowerOf2()) {
2134 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2135 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2137 AddToWorkList(Add.getNode());
2138 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2143 // If X/C can be simplified by the division-by-constant logic, lower
2144 // X%C to the equivalent of X-X/C*C.
2145 if (N1C && !N1C->isNullValue()) {
2146 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2147 AddToWorkList(Div.getNode());
2148 SDValue OptimizedDiv = combine(Div.getNode());
2149 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2150 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2152 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2153 AddToWorkList(Mul.getNode());
2159 if (N0.getOpcode() == ISD::UNDEF)
2160 return DAG.getConstant(0, VT);
2161 // X % undef -> undef
2162 if (N1.getOpcode() == ISD::UNDEF)
2168 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2169 SDValue N0 = N->getOperand(0);
2170 SDValue N1 = N->getOperand(1);
2171 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2172 EVT VT = N->getValueType(0);
2175 // fold (mulhs x, 0) -> 0
2176 if (N1C && N1C->isNullValue())
2178 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2179 if (N1C && N1C->getAPIntValue() == 1)
2180 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2181 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2182 getShiftAmountTy(N0.getValueType())));
2183 // fold (mulhs x, undef) -> 0
2184 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2185 return DAG.getConstant(0, VT);
2187 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2189 if (VT.isSimple() && !VT.isVector()) {
2190 MVT Simple = VT.getSimpleVT();
2191 unsigned SimpleSize = Simple.getSizeInBits();
2192 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2193 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2194 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2195 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2196 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2197 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2198 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2199 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2206 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2207 SDValue N0 = N->getOperand(0);
2208 SDValue N1 = N->getOperand(1);
2209 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2210 EVT VT = N->getValueType(0);
2213 // fold (mulhu x, 0) -> 0
2214 if (N1C && N1C->isNullValue())
2216 // fold (mulhu x, 1) -> 0
2217 if (N1C && N1C->getAPIntValue() == 1)
2218 return DAG.getConstant(0, N0.getValueType());
2219 // fold (mulhu x, undef) -> 0
2220 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2221 return DAG.getConstant(0, VT);
2223 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2225 if (VT.isSimple() && !VT.isVector()) {
2226 MVT Simple = VT.getSimpleVT();
2227 unsigned SimpleSize = Simple.getSizeInBits();
2228 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2229 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2230 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2231 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2232 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2233 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2234 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2235 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2242 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2243 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2244 /// that are being performed. Return true if a simplification was made.
2246 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2248 // If the high half is not needed, just compute the low half.
2249 bool HiExists = N->hasAnyUseOfValue(1);
2251 (!LegalOperations ||
2252 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2253 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2254 N->op_begin(), N->getNumOperands());
2255 return CombineTo(N, Res, Res);
2258 // If the low half is not needed, just compute the high half.
2259 bool LoExists = N->hasAnyUseOfValue(0);
2261 (!LegalOperations ||
2262 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2263 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2264 N->op_begin(), N->getNumOperands());
2265 return CombineTo(N, Res, Res);
2268 // If both halves are used, return as it is.
2269 if (LoExists && HiExists)
2272 // If the two computed results can be simplified separately, separate them.
2274 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2275 N->op_begin(), N->getNumOperands());
2276 AddToWorkList(Lo.getNode());
2277 SDValue LoOpt = combine(Lo.getNode());
2278 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2279 (!LegalOperations ||
2280 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2281 return CombineTo(N, LoOpt, LoOpt);
2285 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2286 N->op_begin(), N->getNumOperands());
2287 AddToWorkList(Hi.getNode());
2288 SDValue HiOpt = combine(Hi.getNode());
2289 if (HiOpt.getNode() && HiOpt != Hi &&
2290 (!LegalOperations ||
2291 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2292 return CombineTo(N, HiOpt, HiOpt);
2298 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2299 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2300 if (Res.getNode()) return Res;
2302 EVT VT = N->getValueType(0);
2305 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2307 if (VT.isSimple() && !VT.isVector()) {
2308 MVT Simple = VT.getSimpleVT();
2309 unsigned SimpleSize = Simple.getSizeInBits();
2310 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2313 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2314 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2315 // Compute the high part as N1.
2316 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2317 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2318 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2319 // Compute the low part as N0.
2320 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2321 return CombineTo(N, Lo, Hi);
2328 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2329 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2330 if (Res.getNode()) return Res;
2332 EVT VT = N->getValueType(0);
2335 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337 if (VT.isSimple() && !VT.isVector()) {
2338 MVT Simple = VT.getSimpleVT();
2339 unsigned SimpleSize = Simple.getSizeInBits();
2340 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2341 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2342 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2343 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2344 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2345 // Compute the high part as N1.
2346 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2347 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2348 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2349 // Compute the low part as N0.
2350 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2351 return CombineTo(N, Lo, Hi);
2358 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2359 // (smulo x, 2) -> (saddo x, x)
2360 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2361 if (C2->getAPIntValue() == 2)
2362 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2363 N->getOperand(0), N->getOperand(0));
2368 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2369 // (umulo x, 2) -> (uaddo x, x)
2370 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2371 if (C2->getAPIntValue() == 2)
2372 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2373 N->getOperand(0), N->getOperand(0));
2378 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2379 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2380 if (Res.getNode()) return Res;
2385 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2386 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2387 if (Res.getNode()) return Res;
2392 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2393 /// two operands of the same opcode, try to simplify it.
2394 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2395 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2396 EVT VT = N0.getValueType();
2397 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2399 // Bail early if none of these transforms apply.
2400 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2402 // For each of OP in AND/OR/XOR:
2403 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2404 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2405 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2406 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2408 // do not sink logical op inside of a vector extend, since it may combine
2410 EVT Op0VT = N0.getOperand(0).getValueType();
2411 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2412 N0.getOpcode() == ISD::SIGN_EXTEND ||
2413 // Avoid infinite looping with PromoteIntBinOp.
2414 (N0.getOpcode() == ISD::ANY_EXTEND &&
2415 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2416 (N0.getOpcode() == ISD::TRUNCATE &&
2417 (!TLI.isZExtFree(VT, Op0VT) ||
2418 !TLI.isTruncateFree(Op0VT, VT)) &&
2419 TLI.isTypeLegal(Op0VT))) &&
2421 Op0VT == N1.getOperand(0).getValueType() &&
2422 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2423 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2424 N0.getOperand(0).getValueType(),
2425 N0.getOperand(0), N1.getOperand(0));
2426 AddToWorkList(ORNode.getNode());
2427 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2430 // For each of OP in SHL/SRL/SRA/AND...
2431 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2432 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2433 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2434 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2435 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2436 N0.getOperand(1) == N1.getOperand(1)) {
2437 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2438 N0.getOperand(0).getValueType(),
2439 N0.getOperand(0), N1.getOperand(0));
2440 AddToWorkList(ORNode.getNode());
2441 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2442 ORNode, N0.getOperand(1));
2445 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2446 // Only perform this optimization after type legalization and before
2447 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2448 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2449 // we don't want to undo this promotion.
2450 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2452 if ((N0.getOpcode() == ISD::BITCAST ||
2453 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2454 Level == AfterLegalizeTypes) {
2455 SDValue In0 = N0.getOperand(0);
2456 SDValue In1 = N1.getOperand(0);
2457 EVT In0Ty = In0.getValueType();
2458 EVT In1Ty = In1.getValueType();
2460 // If both incoming values are integers, and the original types are the
2462 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2463 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2464 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2465 AddToWorkList(Op.getNode());
2470 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2471 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2472 // If both shuffles use the same mask, and both shuffle within a single
2473 // vector, then it is worthwhile to move the swizzle after the operation.
2474 // The type-legalizer generates this pattern when loading illegal
2475 // vector types from memory. In many cases this allows additional shuffle
2477 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2478 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2479 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2480 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2481 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2483 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2484 "Inputs to shuffles are not the same type");
2486 unsigned NumElts = VT.getVectorNumElements();
2488 // Check that both shuffles use the same mask. The masks are known to be of
2489 // the same length because the result vector type is the same.
2490 bool SameMask = true;
2491 for (unsigned i = 0; i != NumElts; ++i) {
2492 int Idx0 = SVN0->getMaskElt(i);
2493 int Idx1 = SVN1->getMaskElt(i);
2501 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2502 N0.getOperand(0), N1.getOperand(0));
2503 AddToWorkList(Op.getNode());
2504 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2505 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2512 SDValue DAGCombiner::visitAND(SDNode *N) {
2513 SDValue N0 = N->getOperand(0);
2514 SDValue N1 = N->getOperand(1);
2515 SDValue LL, LR, RL, RR, CC0, CC1;
2516 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2517 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2518 EVT VT = N1.getValueType();
2519 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2522 if (VT.isVector()) {
2523 SDValue FoldedVOp = SimplifyVBinOp(N);
2524 if (FoldedVOp.getNode()) return FoldedVOp;
2526 // fold (and x, 0) -> 0, vector edition
2527 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2529 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2532 // fold (and x, -1) -> x, vector edition
2533 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2535 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2539 // fold (and x, undef) -> 0
2540 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2541 return DAG.getConstant(0, VT);
2542 // fold (and c1, c2) -> c1&c2
2544 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2545 // canonicalize constant to RHS
2547 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2548 // fold (and x, -1) -> x
2549 if (N1C && N1C->isAllOnesValue())
2551 // if (and x, c) is known to be zero, return 0
2552 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2553 APInt::getAllOnesValue(BitWidth)))
2554 return DAG.getConstant(0, VT);
2556 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2557 if (RAND.getNode() != 0)
2559 // fold (and (or x, C), D) -> D if (C & D) == D
2560 if (N1C && N0.getOpcode() == ISD::OR)
2561 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2562 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2564 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2565 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2566 SDValue N0Op0 = N0.getOperand(0);
2567 APInt Mask = ~N1C->getAPIntValue();
2568 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2569 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2570 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2571 N0.getValueType(), N0Op0);
2573 // Replace uses of the AND with uses of the Zero extend node.
2576 // We actually want to replace all uses of the any_extend with the
2577 // zero_extend, to avoid duplicating things. This will later cause this
2578 // AND to be folded.
2579 CombineTo(N0.getNode(), Zext);
2580 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2583 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2584 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2585 // already be zero by virtue of the width of the base type of the load.
2587 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2589 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2590 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2591 N0.getOpcode() == ISD::LOAD) {
2592 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2593 N0 : N0.getOperand(0) );
2595 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2596 // This can be a pure constant or a vector splat, in which case we treat the
2597 // vector as a scalar and use the splat value.
2598 APInt Constant = APInt::getNullValue(1);
2599 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2600 Constant = C->getAPIntValue();
2601 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2602 APInt SplatValue, SplatUndef;
2603 unsigned SplatBitSize;
2605 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2606 SplatBitSize, HasAnyUndefs);
2608 // Undef bits can contribute to a possible optimisation if set, so
2610 SplatValue |= SplatUndef;
2612 // The splat value may be something like "0x00FFFFFF", which means 0 for
2613 // the first vector value and FF for the rest, repeating. We need a mask
2614 // that will apply equally to all members of the vector, so AND all the
2615 // lanes of the constant together.
2616 EVT VT = Vector->getValueType(0);
2617 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2619 // If the splat value has been compressed to a bitlength lower
2620 // than the size of the vector lane, we need to re-expand it to
2622 if (BitWidth > SplatBitSize)
2623 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2624 SplatBitSize < BitWidth;
2625 SplatBitSize = SplatBitSize * 2)
2626 SplatValue |= SplatValue.shl(SplatBitSize);
2628 Constant = APInt::getAllOnesValue(BitWidth);
2629 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2630 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2634 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2635 // actually legal and isn't going to get expanded, else this is a false
2637 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2638 Load->getMemoryVT());
2640 // Resize the constant to the same size as the original memory access before
2641 // extension. If it is still the AllOnesValue then this AND is completely
2644 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2647 switch (Load->getExtensionType()) {
2648 default: B = false; break;
2649 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2651 case ISD::NON_EXTLOAD: B = true; break;
2654 if (B && Constant.isAllOnesValue()) {
2655 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2656 // preserve semantics once we get rid of the AND.
2657 SDValue NewLoad(Load, 0);
2658 if (Load->getExtensionType() == ISD::EXTLOAD) {
2659 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2660 Load->getValueType(0), SDLoc(Load),
2661 Load->getChain(), Load->getBasePtr(),
2662 Load->getOffset(), Load->getMemoryVT(),
2663 Load->getMemOperand());
2664 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2665 if (Load->getNumValues() == 3) {
2666 // PRE/POST_INC loads have 3 values.
2667 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2668 NewLoad.getValue(2) };
2669 CombineTo(Load, To, 3, true);
2671 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2675 // Fold the AND away, taking care not to fold to the old load node if we
2677 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2679 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2682 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2683 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2684 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2685 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2687 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2688 LL.getValueType().isInteger()) {
2689 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2690 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2691 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2692 LR.getValueType(), LL, RL);
2693 AddToWorkList(ORNode.getNode());
2694 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2696 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2697 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2698 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2699 LR.getValueType(), LL, RL);
2700 AddToWorkList(ANDNode.getNode());
2701 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2703 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2704 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2705 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2706 LR.getValueType(), LL, RL);
2707 AddToWorkList(ORNode.getNode());
2708 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2711 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2712 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2713 Op0 == Op1 && LL.getValueType().isInteger() &&
2714 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2715 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2716 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2717 cast<ConstantSDNode>(RR)->isNullValue()))) {
2718 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2719 LL, DAG.getConstant(1, LL.getValueType()));
2720 AddToWorkList(ADDNode.getNode());
2721 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2722 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2724 // canonicalize equivalent to ll == rl
2725 if (LL == RR && LR == RL) {
2726 Op1 = ISD::getSetCCSwappedOperands(Op1);
2729 if (LL == RL && LR == RR) {
2730 bool isInteger = LL.getValueType().isInteger();
2731 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2732 if (Result != ISD::SETCC_INVALID &&
2733 (!LegalOperations ||
2734 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2735 TLI.isOperationLegal(ISD::SETCC,
2736 getSetCCResultType(N0.getSimpleValueType())))))
2737 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2742 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2743 if (N0.getOpcode() == N1.getOpcode()) {
2744 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2745 if (Tmp.getNode()) return Tmp;
2748 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2749 // fold (and (sra)) -> (and (srl)) when possible.
2750 if (!VT.isVector() &&
2751 SimplifyDemandedBits(SDValue(N, 0)))
2752 return SDValue(N, 0);
2754 // fold (zext_inreg (extload x)) -> (zextload x)
2755 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2756 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2757 EVT MemVT = LN0->getMemoryVT();
2758 // If we zero all the possible extended bits, then we can turn this into
2759 // a zextload if we are running before legalize or the operation is legal.
2760 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2761 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2762 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2763 ((!LegalOperations && !LN0->isVolatile()) ||
2764 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2765 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2766 LN0->getChain(), LN0->getBasePtr(),
2767 MemVT, LN0->getMemOperand());
2769 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2770 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2773 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2774 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2776 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2777 EVT MemVT = LN0->getMemoryVT();
2778 // If we zero all the possible extended bits, then we can turn this into
2779 // a zextload if we are running before legalize or the operation is legal.
2780 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2781 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2782 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2783 ((!LegalOperations && !LN0->isVolatile()) ||
2784 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2785 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2786 LN0->getChain(), LN0->getBasePtr(),
2787 MemVT, LN0->getMemOperand());
2789 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2794 // fold (and (load x), 255) -> (zextload x, i8)
2795 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2796 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2797 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2798 (N0.getOpcode() == ISD::ANY_EXTEND &&
2799 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2800 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2801 LoadSDNode *LN0 = HasAnyExt
2802 ? cast<LoadSDNode>(N0.getOperand(0))
2803 : cast<LoadSDNode>(N0);
2804 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2805 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2806 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2807 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2808 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2809 EVT LoadedVT = LN0->getMemoryVT();
2811 if (ExtVT == LoadedVT &&
2812 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2816 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2817 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2818 LN0->getMemOperand());
2820 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2824 // Do not change the width of a volatile load.
2825 // Do not generate loads of non-round integer types since these can
2826 // be expensive (and would be wrong if the type is not byte sized).
2827 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2828 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2829 EVT PtrType = LN0->getOperand(1).getValueType();
2831 unsigned Alignment = LN0->getAlignment();
2832 SDValue NewPtr = LN0->getBasePtr();
2834 // For big endian targets, we need to add an offset to the pointer
2835 // to load the correct bytes. For little endian systems, we merely
2836 // need to read fewer bytes from the same pointer.
2837 if (TLI.isBigEndian()) {
2838 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2839 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2840 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2841 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2842 NewPtr, DAG.getConstant(PtrOff, PtrType));
2843 Alignment = MinAlign(Alignment, PtrOff);
2846 AddToWorkList(NewPtr.getNode());
2848 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2850 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2851 LN0->getChain(), NewPtr,
2852 LN0->getPointerInfo(),
2853 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2854 Alignment, LN0->getTBAAInfo());
2856 CombineTo(LN0, Load, Load.getValue(1));
2857 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2863 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2864 VT.getSizeInBits() <= 64) {
2865 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2866 APInt ADDC = ADDI->getAPIntValue();
2867 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2868 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2869 // immediate for an add, but it is legal if its top c2 bits are set,
2870 // transform the ADD so the immediate doesn't need to be materialized
2872 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2873 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2874 SRLI->getZExtValue());
2875 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2877 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2879 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2880 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2881 CombineTo(N0.getNode(), NewAdd);
2882 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2890 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2891 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2892 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2893 N0.getOperand(1), false);
2894 if (BSwap.getNode())
2901 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2903 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2904 bool DemandHighBits) {
2905 if (!LegalOperations)
2908 EVT VT = N->getValueType(0);
2909 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2911 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2914 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2915 bool LookPassAnd0 = false;
2916 bool LookPassAnd1 = false;
2917 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2919 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2921 if (N0.getOpcode() == ISD::AND) {
2922 if (!N0.getNode()->hasOneUse())
2924 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2925 if (!N01C || N01C->getZExtValue() != 0xFF00)
2927 N0 = N0.getOperand(0);
2928 LookPassAnd0 = true;
2931 if (N1.getOpcode() == ISD::AND) {
2932 if (!N1.getNode()->hasOneUse())
2934 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2935 if (!N11C || N11C->getZExtValue() != 0xFF)
2937 N1 = N1.getOperand(0);
2938 LookPassAnd1 = true;
2941 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2943 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2945 if (!N0.getNode()->hasOneUse() ||
2946 !N1.getNode()->hasOneUse())
2949 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2950 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2953 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2956 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2957 SDValue N00 = N0->getOperand(0);
2958 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2959 if (!N00.getNode()->hasOneUse())
2961 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2962 if (!N001C || N001C->getZExtValue() != 0xFF)
2964 N00 = N00.getOperand(0);
2965 LookPassAnd0 = true;
2968 SDValue N10 = N1->getOperand(0);
2969 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2970 if (!N10.getNode()->hasOneUse())
2972 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2973 if (!N101C || N101C->getZExtValue() != 0xFF00)
2975 N10 = N10.getOperand(0);
2976 LookPassAnd1 = true;
2982 // Make sure everything beyond the low halfword gets set to zero since the SRL
2983 // 16 will clear the top bits.
2984 unsigned OpSizeInBits = VT.getSizeInBits();
2985 if (DemandHighBits && OpSizeInBits > 16) {
2986 // If the left-shift isn't masked out then the only way this is a bswap is
2987 // if all bits beyond the low 8 are 0. In that case the entire pattern
2988 // reduces to a left shift anyway: leave it for other parts of the combiner.
2992 // However, if the right shift isn't masked out then it might be because
2993 // it's not needed. See if we can spot that too.
2994 if (!LookPassAnd1 &&
2995 !DAG.MaskedValueIsZero(
2996 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3000 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3001 if (OpSizeInBits > 16)
3002 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3003 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3007 /// isBSwapHWordElement - Return true if the specified node is an element
3008 /// that makes up a 32-bit packed halfword byteswap. i.e.
3009 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3010 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3011 if (!N.getNode()->hasOneUse())
3014 unsigned Opc = N.getOpcode();
3015 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3018 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3023 switch (N1C->getZExtValue()) {
3026 case 0xFF: Num = 0; break;
3027 case 0xFF00: Num = 1; break;
3028 case 0xFF0000: Num = 2; break;
3029 case 0xFF000000: Num = 3; break;
3032 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3033 SDValue N0 = N.getOperand(0);
3034 if (Opc == ISD::AND) {
3035 if (Num == 0 || Num == 2) {
3037 // (x >> 8) & 0xff0000
3038 if (N0.getOpcode() != ISD::SRL)
3040 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3041 if (!C || C->getZExtValue() != 8)
3044 // (x << 8) & 0xff00
3045 // (x << 8) & 0xff000000
3046 if (N0.getOpcode() != ISD::SHL)
3048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3049 if (!C || C->getZExtValue() != 8)
3052 } else if (Opc == ISD::SHL) {
3054 // (x & 0xff0000) << 8
3055 if (Num != 0 && Num != 2)
3057 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3058 if (!C || C->getZExtValue() != 8)
3060 } else { // Opc == ISD::SRL
3061 // (x & 0xff00) >> 8
3062 // (x & 0xff000000) >> 8
3063 if (Num != 1 && Num != 3)
3065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3066 if (!C || C->getZExtValue() != 8)
3073 Parts[Num] = N0.getOperand(0).getNode();
3077 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3078 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3079 /// => (rotl (bswap x), 16)
3080 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3081 if (!LegalOperations)
3084 EVT VT = N->getValueType(0);
3087 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3090 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3092 // (or (or (and), (and)), (or (and), (and)))
3093 // (or (or (or (and), (and)), (and)), (and))
3094 if (N0.getOpcode() != ISD::OR)
3096 SDValue N00 = N0.getOperand(0);
3097 SDValue N01 = N0.getOperand(1);
3099 if (N1.getOpcode() == ISD::OR &&
3100 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3101 // (or (or (and), (and)), (or (and), (and)))
3102 SDValue N000 = N00.getOperand(0);
3103 if (!isBSwapHWordElement(N000, Parts))
3106 SDValue N001 = N00.getOperand(1);
3107 if (!isBSwapHWordElement(N001, Parts))
3109 SDValue N010 = N01.getOperand(0);
3110 if (!isBSwapHWordElement(N010, Parts))
3112 SDValue N011 = N01.getOperand(1);
3113 if (!isBSwapHWordElement(N011, Parts))
3116 // (or (or (or (and), (and)), (and)), (and))
3117 if (!isBSwapHWordElement(N1, Parts))
3119 if (!isBSwapHWordElement(N01, Parts))
3121 if (N00.getOpcode() != ISD::OR)
3123 SDValue N000 = N00.getOperand(0);
3124 if (!isBSwapHWordElement(N000, Parts))
3126 SDValue N001 = N00.getOperand(1);
3127 if (!isBSwapHWordElement(N001, Parts))
3131 // Make sure the parts are all coming from the same node.
3132 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3135 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3136 SDValue(Parts[0],0));
3138 // Result of the bswap should be rotated by 16. If it's not legal, then
3139 // do (x << 16) | (x >> 16).
3140 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3141 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3142 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3143 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3144 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3145 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3146 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3147 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3150 SDValue DAGCombiner::visitOR(SDNode *N) {
3151 SDValue N0 = N->getOperand(0);
3152 SDValue N1 = N->getOperand(1);
3153 SDValue LL, LR, RL, RR, CC0, CC1;
3154 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3155 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3156 EVT VT = N1.getValueType();
3159 if (VT.isVector()) {
3160 SDValue FoldedVOp = SimplifyVBinOp(N);
3161 if (FoldedVOp.getNode()) return FoldedVOp;
3163 // fold (or x, 0) -> x, vector edition
3164 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3166 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3169 // fold (or x, -1) -> -1, vector edition
3170 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3172 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3176 // fold (or x, undef) -> -1
3177 if (!LegalOperations &&
3178 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3179 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3180 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3182 // fold (or c1, c2) -> c1|c2
3184 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3185 // canonicalize constant to RHS
3187 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3188 // fold (or x, 0) -> x
3189 if (N1C && N1C->isNullValue())
3191 // fold (or x, -1) -> -1
3192 if (N1C && N1C->isAllOnesValue())
3194 // fold (or x, c) -> c iff (x & ~c) == 0
3195 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3198 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3199 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3200 if (BSwap.getNode() != 0)
3202 BSwap = MatchBSwapHWordLow(N, N0, N1);
3203 if (BSwap.getNode() != 0)
3207 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3208 if (ROR.getNode() != 0)
3210 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3211 // iff (c1 & c2) == 0.
3212 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3213 isa<ConstantSDNode>(N0.getOperand(1))) {
3214 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3215 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3216 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3219 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3220 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3221 N0.getOperand(0), N1), COR);
3224 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3225 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3226 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3227 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3229 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3230 LL.getValueType().isInteger()) {
3231 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3232 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3233 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3234 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3235 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3236 LR.getValueType(), LL, RL);
3237 AddToWorkList(ORNode.getNode());
3238 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3240 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3241 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3242 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3243 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3244 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3245 LR.getValueType(), LL, RL);
3246 AddToWorkList(ANDNode.getNode());
3247 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3250 // canonicalize equivalent to ll == rl
3251 if (LL == RR && LR == RL) {
3252 Op1 = ISD::getSetCCSwappedOperands(Op1);
3255 if (LL == RL && LR == RR) {
3256 bool isInteger = LL.getValueType().isInteger();
3257 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3258 if (Result != ISD::SETCC_INVALID &&
3259 (!LegalOperations ||
3260 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3261 TLI.isOperationLegal(ISD::SETCC,
3262 getSetCCResultType(N0.getValueType())))))
3263 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3268 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3269 if (N0.getOpcode() == N1.getOpcode()) {
3270 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3271 if (Tmp.getNode()) return Tmp;
3274 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3275 if (N0.getOpcode() == ISD::AND &&
3276 N1.getOpcode() == ISD::AND &&
3277 N0.getOperand(1).getOpcode() == ISD::Constant &&
3278 N1.getOperand(1).getOpcode() == ISD::Constant &&
3279 // Don't increase # computations.
3280 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3281 // We can only do this xform if we know that bits from X that are set in C2
3282 // but not in C1 are already zero. Likewise for Y.
3283 const APInt &LHSMask =
3284 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3285 const APInt &RHSMask =
3286 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3288 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3289 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3290 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3291 N0.getOperand(0), N1.getOperand(0));
3292 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3293 DAG.getConstant(LHSMask | RHSMask, VT));
3297 // See if this is some rotate idiom.
3298 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3299 return SDValue(Rot, 0);
3301 // Simplify the operands using demanded-bits information.
3302 if (!VT.isVector() &&
3303 SimplifyDemandedBits(SDValue(N, 0)))
3304 return SDValue(N, 0);
3309 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3310 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3311 if (Op.getOpcode() == ISD::AND) {
3312 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3313 Mask = Op.getOperand(1);
3314 Op = Op.getOperand(0);
3320 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3328 // Return true if we can prove that, whenever Neg and Pos are both in the
3329 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3330 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3332 // (or (shift1 X, Neg), (shift2 X, Pos))
3334 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3335 // shift1 by Neg. The range [0, OpSize) means that we only need to consider
3336 // shift amounts with defined behavior.
3337 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3338 // If OpSize is a power of 2 then:
3340 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3341 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3343 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3344 // for the stronger condition:
3346 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3348 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3349 // we can just replace Neg with Neg' for the rest of the function.
3351 // In other cases we check for the even stronger condition:
3353 // Neg == OpSize - Pos [B]
3355 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3356 // behavior if Pos == 0 (and consequently Neg == OpSize).
3358 // We could actually use [A] whenever OpSize is a power of 2, but the
3359 // only extra cases that it would match are those uninteresting ones
3360 // where Neg and Pos are never in range at the same time. E.g. for
3361 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3362 // as well as (sub 32, Pos), but:
3364 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3366 // always invokes undefined behavior for 32-bit X.
3368 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3369 unsigned LoBits = 0;
3370 if (Neg.getOpcode() == ISD::AND &&
3371 isPowerOf2_64(OpSize) &&
3372 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3373 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3374 Neg = Neg.getOperand(0);
3375 LoBits = Log2_64(OpSize);
3378 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3379 if (Neg.getOpcode() != ISD::SUB)
3381 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3384 SDValue NegOp1 = Neg.getOperand(1);
3386 // The condition we need is now:
3388 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3390 // If NegOp1 == Pos then we need:
3392 // OpSize & Mask == NegC & Mask
3394 // (because "x & Mask" is a truncation and distributes through subtraction).
3397 Width = NegC->getAPIntValue();
3398 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3399 // Then the condition we want to prove becomes:
3401 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3403 // which, again because "x & Mask" is a truncation, becomes:
3405 // NegC & Mask == (OpSize - PosC) & Mask
3406 // OpSize & Mask == (NegC + PosC) & Mask
3407 else if (Pos.getOpcode() == ISD::ADD &&
3408 Pos.getOperand(0) == NegOp1 &&
3409 Pos.getOperand(1).getOpcode() == ISD::Constant)
3410 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3411 NegC->getAPIntValue());
3415 // Now we just need to check that OpSize & Mask == Width & Mask.
3417 return Width.getLoBits(LoBits) == 0;
3418 return Width == OpSize;
3421 // A subroutine of MatchRotate used once we have found an OR of two opposite
3422 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3423 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3424 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3425 // Neg with outer conversions stripped away.
3426 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3427 SDValue Neg, SDValue InnerPos,
3428 SDValue InnerNeg, unsigned PosOpcode,
3429 unsigned NegOpcode, SDLoc DL) {
3430 // fold (or (shl x, (*ext y)),
3431 // (srl x, (*ext (sub 32, y)))) ->
3432 // (rotl x, y) or (rotr x, (sub 32, y))
3434 // fold (or (shl x, (*ext (sub 32, y))),
3435 // (srl x, (*ext y))) ->
3436 // (rotr x, y) or (rotl x, (sub 32, y))
3437 EVT VT = Shifted.getValueType();
3438 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3439 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3440 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3441 HasPos ? Pos : Neg).getNode();
3444 // fold (or (shl (*ext x), (*ext y)),
3445 // (srl (*ext x), (*ext (sub 32, y)))) ->
3446 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3448 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3449 // (srl (*ext x), (*ext y))) ->
3450 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3451 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3452 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3453 SDValue InnerShifted = Shifted.getOperand(0);
3454 EVT InnerVT = InnerShifted.getValueType();
3455 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3456 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3457 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3458 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3459 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3460 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3468 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3469 // idioms for rotate, and if the target supports rotation instructions, generate
3471 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3472 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3473 EVT VT = LHS.getValueType();
3474 if (!TLI.isTypeLegal(VT)) return 0;
3476 // The target must have at least one rotate flavor.
3477 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3478 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3479 if (!HasROTL && !HasROTR) return 0;
3481 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3482 SDValue LHSShift; // The shift.
3483 SDValue LHSMask; // AND value if any.
3484 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3485 return 0; // Not part of a rotate.
3487 SDValue RHSShift; // The shift.
3488 SDValue RHSMask; // AND value if any.
3489 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3490 return 0; // Not part of a rotate.
3492 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3493 return 0; // Not shifting the same value.
3495 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3496 return 0; // Shifts must disagree.
3498 // Canonicalize shl to left side in a shl/srl pair.
3499 if (RHSShift.getOpcode() == ISD::SHL) {
3500 std::swap(LHS, RHS);
3501 std::swap(LHSShift, RHSShift);
3502 std::swap(LHSMask , RHSMask );
3505 unsigned OpSizeInBits = VT.getSizeInBits();
3506 SDValue LHSShiftArg = LHSShift.getOperand(0);
3507 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3508 SDValue RHSShiftArg = RHSShift.getOperand(0);
3509 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3511 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3512 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3513 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3514 RHSShiftAmt.getOpcode() == ISD::Constant) {
3515 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3516 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3517 if ((LShVal + RShVal) != OpSizeInBits)
3520 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3521 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3523 // If there is an AND of either shifted operand, apply it to the result.
3524 if (LHSMask.getNode() || RHSMask.getNode()) {
3525 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3527 if (LHSMask.getNode()) {
3528 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3529 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3531 if (RHSMask.getNode()) {
3532 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3533 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3536 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3539 return Rot.getNode();
3542 // If there is a mask here, and we have a variable shift, we can't be sure
3543 // that we're masking out the right stuff.
3544 if (LHSMask.getNode() || RHSMask.getNode())
3547 // If the shift amount is sign/zext/any-extended just peel it off.
3548 SDValue LExtOp0 = LHSShiftAmt;
3549 SDValue RExtOp0 = RHSShiftAmt;
3550 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3551 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3552 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3553 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3554 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3555 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3556 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3557 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3558 LExtOp0 = LHSShiftAmt.getOperand(0);
3559 RExtOp0 = RHSShiftAmt.getOperand(0);
3562 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3563 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3567 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3568 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3575 SDValue DAGCombiner::visitXOR(SDNode *N) {
3576 SDValue N0 = N->getOperand(0);
3577 SDValue N1 = N->getOperand(1);
3578 SDValue LHS, RHS, CC;
3579 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3580 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3581 EVT VT = N0.getValueType();
3584 if (VT.isVector()) {
3585 SDValue FoldedVOp = SimplifyVBinOp(N);
3586 if (FoldedVOp.getNode()) return FoldedVOp;
3588 // fold (xor x, 0) -> x, vector edition
3589 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3591 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3595 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3596 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3597 return DAG.getConstant(0, VT);
3598 // fold (xor x, undef) -> undef
3599 if (N0.getOpcode() == ISD::UNDEF)
3601 if (N1.getOpcode() == ISD::UNDEF)
3603 // fold (xor c1, c2) -> c1^c2
3605 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3606 // canonicalize constant to RHS
3608 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3609 // fold (xor x, 0) -> x
3610 if (N1C && N1C->isNullValue())
3613 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3614 if (RXOR.getNode() != 0)
3617 // fold !(x cc y) -> (x !cc y)
3618 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3619 bool isInt = LHS.getValueType().isInteger();
3620 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3623 if (!LegalOperations ||
3624 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3625 switch (N0.getOpcode()) {
3627 llvm_unreachable("Unhandled SetCC Equivalent!");
3629 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3630 case ISD::SELECT_CC:
3631 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3632 N0.getOperand(3), NotCC);
3637 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3638 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3639 N0.getNode()->hasOneUse() &&
3640 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3641 SDValue V = N0.getOperand(0);
3642 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3643 DAG.getConstant(1, V.getValueType()));
3644 AddToWorkList(V.getNode());
3645 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3648 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3649 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3650 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3651 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3652 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3653 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3654 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3655 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3656 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3657 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3660 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3661 if (N1C && N1C->isAllOnesValue() &&
3662 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3663 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3664 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3665 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3666 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3667 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3668 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3669 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3672 // fold (xor (and x, y), y) -> (and (not x), y)
3673 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3674 N0->getOperand(1) == N1) {
3675 SDValue X = N0->getOperand(0);
3676 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3677 AddToWorkList(NotX.getNode());
3678 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3680 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3681 if (N1C && N0.getOpcode() == ISD::XOR) {
3682 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3683 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3685 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3686 DAG.getConstant(N1C->getAPIntValue() ^
3687 N00C->getAPIntValue(), VT));
3689 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3690 DAG.getConstant(N1C->getAPIntValue() ^
3691 N01C->getAPIntValue(), VT));
3693 // fold (xor x, x) -> 0
3695 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3697 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3698 if (N0.getOpcode() == N1.getOpcode()) {
3699 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3700 if (Tmp.getNode()) return Tmp;
3703 // Simplify the expression using non-local knowledge.
3704 if (!VT.isVector() &&
3705 SimplifyDemandedBits(SDValue(N, 0)))
3706 return SDValue(N, 0);
3711 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3712 /// the shift amount is a constant.
3713 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3714 SDNode *LHS = N->getOperand(0).getNode();
3715 if (!LHS->hasOneUse()) return SDValue();
3717 // We want to pull some binops through shifts, so that we have (and (shift))
3718 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3719 // thing happens with address calculations, so it's important to canonicalize
3721 bool HighBitSet = false; // Can we transform this if the high bit is set?
3723 switch (LHS->getOpcode()) {
3724 default: return SDValue();
3727 HighBitSet = false; // We can only transform sra if the high bit is clear.
3730 HighBitSet = true; // We can only transform sra if the high bit is set.
3733 if (N->getOpcode() != ISD::SHL)
3734 return SDValue(); // only shl(add) not sr[al](add).
3735 HighBitSet = false; // We can only transform sra if the high bit is clear.
3739 // We require the RHS of the binop to be a constant as well.
3740 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3741 if (!BinOpCst) return SDValue();
3743 // FIXME: disable this unless the input to the binop is a shift by a constant.
3744 // If it is not a shift, it pessimizes some common cases like:
3746 // void foo(int *X, int i) { X[i & 1235] = 1; }
3747 // int bar(int *X, int i) { return X[i & 255]; }
3748 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3749 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3750 BinOpLHSVal->getOpcode() != ISD::SRA &&
3751 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3752 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3755 EVT VT = N->getValueType(0);
3757 // If this is a signed shift right, and the high bit is modified by the
3758 // logical operation, do not perform the transformation. The highBitSet
3759 // boolean indicates the value of the high bit of the constant which would
3760 // cause it to be modified for this operation.
3761 if (N->getOpcode() == ISD::SRA) {
3762 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3763 if (BinOpRHSSignSet != HighBitSet)
3767 // Fold the constants, shifting the binop RHS by the shift amount.
3768 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3770 LHS->getOperand(1), N->getOperand(1));
3772 // Create the new shift.
3773 SDValue NewShift = DAG.getNode(N->getOpcode(),
3774 SDLoc(LHS->getOperand(0)),
3775 VT, LHS->getOperand(0), N->getOperand(1));
3777 // Create the new binop.
3778 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3781 SDValue DAGCombiner::visitSHL(SDNode *N) {
3782 SDValue N0 = N->getOperand(0);
3783 SDValue N1 = N->getOperand(1);
3784 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3785 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3786 EVT VT = N0.getValueType();
3787 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3790 if (VT.isVector()) {
3791 SDValue FoldedVOp = SimplifyVBinOp(N);
3792 if (FoldedVOp.getNode()) return FoldedVOp;
3795 // fold (shl c1, c2) -> c1<<c2
3797 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3798 // fold (shl 0, x) -> 0
3799 if (N0C && N0C->isNullValue())
3801 // fold (shl x, c >= size(x)) -> undef
3802 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3803 return DAG.getUNDEF(VT);
3804 // fold (shl x, 0) -> x
3805 if (N1C && N1C->isNullValue())
3807 // fold (shl undef, x) -> 0
3808 if (N0.getOpcode() == ISD::UNDEF)
3809 return DAG.getConstant(0, VT);
3810 // if (shl x, c) is known to be zero, return 0
3811 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3812 APInt::getAllOnesValue(OpSizeInBits)))
3813 return DAG.getConstant(0, VT);
3814 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3815 if (N1.getOpcode() == ISD::TRUNCATE &&
3816 N1.getOperand(0).getOpcode() == ISD::AND &&
3817 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3818 SDValue N101 = N1.getOperand(0).getOperand(1);
3819 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3820 EVT TruncVT = N1.getValueType();
3821 SDValue N100 = N1.getOperand(0).getOperand(0);
3822 APInt TruncC = N101C->getAPIntValue();
3823 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3824 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3825 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3826 DAG.getNode(ISD::TRUNCATE,
3829 DAG.getConstant(TruncC, TruncVT)));
3833 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3834 return SDValue(N, 0);
3836 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3837 if (N1C && N0.getOpcode() == ISD::SHL &&
3838 N0.getOperand(1).getOpcode() == ISD::Constant) {
3839 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3840 uint64_t c2 = N1C->getZExtValue();
3841 if (c1 + c2 >= OpSizeInBits)
3842 return DAG.getConstant(0, VT);
3843 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3844 DAG.getConstant(c1 + c2, N1.getValueType()));
3847 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3848 // For this to be valid, the second form must not preserve any of the bits
3849 // that are shifted out by the inner shift in the first form. This means
3850 // the outer shift size must be >= the number of bits added by the ext.
3851 // As a corollary, we don't care what kind of ext it is.
3852 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3853 N0.getOpcode() == ISD::ANY_EXTEND ||
3854 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3855 N0.getOperand(0).getOpcode() == ISD::SHL &&
3856 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3858 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3859 uint64_t c2 = N1C->getZExtValue();
3860 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3861 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3862 if (c2 >= OpSizeInBits - InnerShiftSize) {
3863 if (c1 + c2 >= OpSizeInBits)
3864 return DAG.getConstant(0, VT);
3865 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3866 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3867 N0.getOperand(0)->getOperand(0)),
3868 DAG.getConstant(c1 + c2, N1.getValueType()));
3872 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3873 // Only fold this if the inner zext has no other uses to avoid increasing
3874 // the total number of instructions.
3875 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3876 N0.getOperand(0).getOpcode() == ISD::SRL &&
3877 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3879 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3880 if (c1 < VT.getSizeInBits()) {
3881 uint64_t c2 = N1C->getZExtValue();
3883 SDValue NewOp0 = N0.getOperand(0);
3884 EVT CountVT = NewOp0.getOperand(1).getValueType();
3885 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3886 NewOp0, DAG.getConstant(c2, CountVT));
3887 AddToWorkList(NewSHL.getNode());
3888 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3893 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3894 // (and (srl x, (sub c1, c2), MASK)
3895 // Only fold this if the inner shift has no other uses -- if it does, folding
3896 // this will increase the total number of instructions.
3897 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3898 N0.getOperand(1).getOpcode() == ISD::Constant) {
3899 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3900 if (c1 < VT.getSizeInBits()) {
3901 uint64_t c2 = N1C->getZExtValue();
3902 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3903 VT.getSizeInBits() - c1);
3906 Mask = Mask.shl(c2-c1);
3907 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3908 DAG.getConstant(c2-c1, N1.getValueType()));
3910 Mask = Mask.lshr(c1-c2);
3911 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3912 DAG.getConstant(c1-c2, N1.getValueType()));
3914 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3915 DAG.getConstant(Mask, VT));
3918 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3919 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3920 SDValue HiBitsMask =
3921 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3922 VT.getSizeInBits() -
3923 N1C->getZExtValue()),
3925 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3930 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3931 if (NewSHL.getNode())
3938 SDValue DAGCombiner::visitSRA(SDNode *N) {
3939 SDValue N0 = N->getOperand(0);
3940 SDValue N1 = N->getOperand(1);
3941 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3942 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3943 EVT VT = N0.getValueType();
3944 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3947 if (VT.isVector()) {
3948 SDValue FoldedVOp = SimplifyVBinOp(N);
3949 if (FoldedVOp.getNode()) return FoldedVOp;
3952 // fold (sra c1, c2) -> (sra c1, c2)
3954 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3955 // fold (sra 0, x) -> 0
3956 if (N0C && N0C->isNullValue())
3958 // fold (sra -1, x) -> -1
3959 if (N0C && N0C->isAllOnesValue())
3961 // fold (sra x, (setge c, size(x))) -> undef
3962 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3963 return DAG.getUNDEF(VT);
3964 // fold (sra x, 0) -> x
3965 if (N1C && N1C->isNullValue())
3967 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3969 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3970 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3971 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3973 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3974 ExtVT, VT.getVectorNumElements());
3975 if ((!LegalOperations ||
3976 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3977 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3978 N0.getOperand(0), DAG.getValueType(ExtVT));
3981 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3982 if (N1C && N0.getOpcode() == ISD::SRA) {
3983 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3984 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3985 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3986 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3987 DAG.getConstant(Sum, N1C->getValueType(0)));
3991 // fold (sra (shl X, m), (sub result_size, n))
3992 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3993 // result_size - n != m.
3994 // If truncate is free for the target sext(shl) is likely to result in better
3996 if (N0.getOpcode() == ISD::SHL) {
3997 // Get the two constanst of the shifts, CN0 = m, CN = n.
3998 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4000 // Determine what the truncate's result bitsize and type would be.
4002 EVT::getIntegerVT(*DAG.getContext(),
4003 OpSizeInBits - N1C->getZExtValue());
4004 // Determine the residual right-shift amount.
4005 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4007 // If the shift is not a no-op (in which case this should be just a sign
4008 // extend already), the truncated to type is legal, sign_extend is legal
4009 // on that type, and the truncate to that type is both legal and free,
4010 // perform the transform.
4011 if ((ShiftAmt > 0) &&
4012 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4013 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4014 TLI.isTruncateFree(VT, TruncVT)) {
4016 SDValue Amt = DAG.getConstant(ShiftAmt,
4017 getShiftAmountTy(N0.getOperand(0).getValueType()));
4018 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4019 N0.getOperand(0), Amt);
4020 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4023 N->getValueType(0), Trunc);
4028 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4029 if (N1.getOpcode() == ISD::TRUNCATE &&
4030 N1.getOperand(0).getOpcode() == ISD::AND &&
4031 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4032 SDValue N101 = N1.getOperand(0).getOperand(1);
4033 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4034 EVT TruncVT = N1.getValueType();
4035 SDValue N100 = N1.getOperand(0).getOperand(0);
4036 APInt TruncC = N101C->getAPIntValue();
4037 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
4038 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4039 DAG.getNode(ISD::AND, SDLoc(N),
4041 DAG.getNode(ISD::TRUNCATE,
4044 DAG.getConstant(TruncC, TruncVT)));
4048 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4049 // if c1 is equal to the number of bits the trunc removes
4050 if (N0.getOpcode() == ISD::TRUNCATE &&
4051 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4052 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4053 N0.getOperand(0).hasOneUse() &&
4054 N0.getOperand(0).getOperand(1).hasOneUse() &&
4055 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4056 EVT LargeVT = N0.getOperand(0).getValueType();
4057 ConstantSDNode *LargeShiftAmt =
4058 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4060 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4061 LargeShiftAmt->getZExtValue()) {
4063 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4064 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4065 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4066 N0.getOperand(0).getOperand(0), Amt);
4067 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4071 // Simplify, based on bits shifted out of the LHS.
4072 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4073 return SDValue(N, 0);
4076 // If the sign bit is known to be zero, switch this to a SRL.
4077 if (DAG.SignBitIsZero(N0))
4078 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4081 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4082 if (NewSRA.getNode())
4089 SDValue DAGCombiner::visitSRL(SDNode *N) {
4090 SDValue N0 = N->getOperand(0);
4091 SDValue N1 = N->getOperand(1);
4092 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4093 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4094 EVT VT = N0.getValueType();
4095 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4098 if (VT.isVector()) {
4099 SDValue FoldedVOp = SimplifyVBinOp(N);
4100 if (FoldedVOp.getNode()) return FoldedVOp;
4103 // fold (srl c1, c2) -> c1 >>u c2
4105 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4106 // fold (srl 0, x) -> 0
4107 if (N0C && N0C->isNullValue())
4109 // fold (srl x, c >= size(x)) -> undef
4110 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4111 return DAG.getUNDEF(VT);
4112 // fold (srl x, 0) -> x
4113 if (N1C && N1C->isNullValue())
4115 // if (srl x, c) is known to be zero, return 0
4116 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4117 APInt::getAllOnesValue(OpSizeInBits)))
4118 return DAG.getConstant(0, VT);
4120 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4121 if (N1C && N0.getOpcode() == ISD::SRL &&
4122 N0.getOperand(1).getOpcode() == ISD::Constant) {
4123 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4124 uint64_t c2 = N1C->getZExtValue();
4125 if (c1 + c2 >= OpSizeInBits)
4126 return DAG.getConstant(0, VT);
4127 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4128 DAG.getConstant(c1 + c2, N1.getValueType()));
4131 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4132 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4133 N0.getOperand(0).getOpcode() == ISD::SRL &&
4134 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4136 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4137 uint64_t c2 = N1C->getZExtValue();
4138 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4139 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4140 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4141 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4142 if (c1 + OpSizeInBits == InnerShiftSize) {
4143 if (c1 + c2 >= InnerShiftSize)
4144 return DAG.getConstant(0, VT);
4145 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4146 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4147 N0.getOperand(0)->getOperand(0),
4148 DAG.getConstant(c1 + c2, ShiftCountVT)));
4152 // fold (srl (shl x, c), c) -> (and x, cst2)
4153 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4154 N0.getValueSizeInBits() <= 64) {
4155 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4156 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4157 DAG.getConstant(~0ULL >> ShAmt, VT));
4160 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4161 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4162 // Shifting in all undef bits?
4163 EVT SmallVT = N0.getOperand(0).getValueType();
4164 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4165 return DAG.getUNDEF(VT);
4167 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4168 uint64_t ShiftAmt = N1C->getZExtValue();
4169 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4171 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4172 AddToWorkList(SmallShift.getNode());
4173 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4174 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4175 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4176 DAG.getConstant(Mask, VT));
4180 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4181 // bit, which is unmodified by sra.
4182 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4183 if (N0.getOpcode() == ISD::SRA)
4184 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4187 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4188 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4189 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4190 APInt KnownZero, KnownOne;
4191 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4193 // If any of the input bits are KnownOne, then the input couldn't be all
4194 // zeros, thus the result of the srl will always be zero.
4195 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4197 // If all of the bits input the to ctlz node are known to be zero, then
4198 // the result of the ctlz is "32" and the result of the shift is one.
4199 APInt UnknownBits = ~KnownZero;
4200 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4202 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4203 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4204 // Okay, we know that only that the single bit specified by UnknownBits
4205 // could be set on input to the CTLZ node. If this bit is set, the SRL
4206 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4207 // to an SRL/XOR pair, which is likely to simplify more.
4208 unsigned ShAmt = UnknownBits.countTrailingZeros();
4209 SDValue Op = N0.getOperand(0);
4212 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4213 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4214 AddToWorkList(Op.getNode());
4217 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4218 Op, DAG.getConstant(1, VT));
4222 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4223 if (N1.getOpcode() == ISD::TRUNCATE &&
4224 N1.getOperand(0).getOpcode() == ISD::AND &&
4225 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4226 SDValue N101 = N1.getOperand(0).getOperand(1);
4227 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4228 EVT TruncVT = N1.getValueType();
4229 SDValue N100 = N1.getOperand(0).getOperand(0);
4230 APInt TruncC = N101C->getAPIntValue();
4231 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4232 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4233 DAG.getNode(ISD::AND, SDLoc(N),
4235 DAG.getNode(ISD::TRUNCATE,
4238 DAG.getConstant(TruncC, TruncVT)));
4242 // fold operands of srl based on knowledge that the low bits are not
4244 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4245 return SDValue(N, 0);
4248 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4249 if (NewSRL.getNode())
4253 // Attempt to convert a srl of a load into a narrower zero-extending load.
4254 SDValue NarrowLoad = ReduceLoadWidth(N);
4255 if (NarrowLoad.getNode())
4258 // Here is a common situation. We want to optimize:
4261 // %b = and i32 %a, 2
4262 // %c = srl i32 %b, 1
4263 // brcond i32 %c ...
4269 // %c = setcc eq %b, 0
4272 // However when after the source operand of SRL is optimized into AND, the SRL
4273 // itself may not be optimized further. Look for it and add the BRCOND into
4275 if (N->hasOneUse()) {
4276 SDNode *Use = *N->use_begin();
4277 if (Use->getOpcode() == ISD::BRCOND)
4279 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4280 // Also look pass the truncate.
4281 Use = *Use->use_begin();
4282 if (Use->getOpcode() == ISD::BRCOND)
4290 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4291 SDValue N0 = N->getOperand(0);
4292 EVT VT = N->getValueType(0);
4294 // fold (ctlz c1) -> c2
4295 if (isa<ConstantSDNode>(N0))
4296 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4300 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4301 SDValue N0 = N->getOperand(0);
4302 EVT VT = N->getValueType(0);
4304 // fold (ctlz_zero_undef c1) -> c2
4305 if (isa<ConstantSDNode>(N0))
4306 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4310 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4311 SDValue N0 = N->getOperand(0);
4312 EVT VT = N->getValueType(0);
4314 // fold (cttz c1) -> c2
4315 if (isa<ConstantSDNode>(N0))
4316 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4320 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4321 SDValue N0 = N->getOperand(0);
4322 EVT VT = N->getValueType(0);
4324 // fold (cttz_zero_undef c1) -> c2
4325 if (isa<ConstantSDNode>(N0))
4326 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4330 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4331 SDValue N0 = N->getOperand(0);
4332 EVT VT = N->getValueType(0);
4334 // fold (ctpop c1) -> c2
4335 if (isa<ConstantSDNode>(N0))
4336 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4340 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4341 SDValue N0 = N->getOperand(0);
4342 SDValue N1 = N->getOperand(1);
4343 SDValue N2 = N->getOperand(2);
4344 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4345 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4346 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4347 EVT VT = N->getValueType(0);
4348 EVT VT0 = N0.getValueType();
4350 // fold (select C, X, X) -> X
4353 // fold (select true, X, Y) -> X
4354 if (N0C && !N0C->isNullValue())
4356 // fold (select false, X, Y) -> Y
4357 if (N0C && N0C->isNullValue())
4359 // fold (select C, 1, X) -> (or C, X)
4360 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4361 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4362 // fold (select C, 0, 1) -> (xor C, 1)
4363 if (VT.isInteger() &&
4366 TLI.getBooleanContents(false) ==
4367 TargetLowering::ZeroOrOneBooleanContent)) &&
4368 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4371 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4372 N0, DAG.getConstant(1, VT0));
4373 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4374 N0, DAG.getConstant(1, VT0));
4375 AddToWorkList(XORNode.getNode());
4377 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4378 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4380 // fold (select C, 0, X) -> (and (not C), X)
4381 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4382 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4383 AddToWorkList(NOTNode.getNode());
4384 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4386 // fold (select C, X, 1) -> (or (not C), X)
4387 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4388 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4389 AddToWorkList(NOTNode.getNode());
4390 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4392 // fold (select C, X, 0) -> (and C, X)
4393 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4394 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4395 // fold (select X, X, Y) -> (or X, Y)
4396 // fold (select X, 1, Y) -> (or X, Y)
4397 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4398 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4399 // fold (select X, Y, X) -> (and X, Y)
4400 // fold (select X, Y, 0) -> (and X, Y)
4401 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4402 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4404 // If we can fold this based on the true/false value, do so.
4405 if (SimplifySelectOps(N, N1, N2))
4406 return SDValue(N, 0); // Don't revisit N.
4408 // fold selects based on a setcc into other things, such as min/max/abs
4409 if (N0.getOpcode() == ISD::SETCC) {
4411 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4412 // having to say they don't support SELECT_CC on every type the DAG knows
4413 // about, since there is no way to mark an opcode illegal at all value types
4414 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4415 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4416 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4417 N0.getOperand(0), N0.getOperand(1),
4418 N1, N2, N0.getOperand(2));
4419 return SimplifySelect(SDLoc(N), N0, N1, N2);
4426 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4429 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4431 // Split the inputs.
4432 SDValue Lo, Hi, LL, LH, RL, RH;
4433 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4434 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4436 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4437 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4439 return std::make_pair(Lo, Hi);
4442 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4443 SDValue N0 = N->getOperand(0);
4444 SDValue N1 = N->getOperand(1);
4445 SDValue N2 = N->getOperand(2);
4448 // Canonicalize integer abs.
4449 // vselect (setg[te] X, 0), X, -X ->
4450 // vselect (setgt X, -1), X, -X ->
4451 // vselect (setl[te] X, 0), -X, X ->
4452 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4453 if (N0.getOpcode() == ISD::SETCC) {
4454 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4455 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4457 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4459 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4460 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4461 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4462 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4463 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4464 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4465 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4468 EVT VT = LHS.getValueType();
4469 SDValue Shift = DAG.getNode(
4470 ISD::SRA, DL, VT, LHS,
4471 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4472 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4473 AddToWorkList(Shift.getNode());
4474 AddToWorkList(Add.getNode());
4475 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4479 // If the VSELECT result requires splitting and the mask is provided by a
4480 // SETCC, then split both nodes and its operands before legalization. This
4481 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4482 // and enables future optimizations (e.g. min/max pattern matching on X86).
4483 if (N0.getOpcode() == ISD::SETCC) {
4484 EVT VT = N->getValueType(0);
4486 // Check if any splitting is required.
4487 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4488 TargetLowering::TypeSplitVector)
4491 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4492 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4493 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4494 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4496 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4497 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4499 // Add the new VSELECT nodes to the work list in case they need to be split
4501 AddToWorkList(Lo.getNode());
4502 AddToWorkList(Hi.getNode());
4504 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4507 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4508 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4510 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4511 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4517 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4518 SDValue N0 = N->getOperand(0);
4519 SDValue N1 = N->getOperand(1);
4520 SDValue N2 = N->getOperand(2);
4521 SDValue N3 = N->getOperand(3);
4522 SDValue N4 = N->getOperand(4);
4523 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4525 // fold select_cc lhs, rhs, x, x, cc -> x
4529 // Determine if the condition we're dealing with is constant
4530 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4531 N0, N1, CC, SDLoc(N), false);
4532 if (SCC.getNode()) {
4533 AddToWorkList(SCC.getNode());
4535 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4536 if (!SCCC->isNullValue())
4537 return N2; // cond always true -> true val
4539 return N3; // cond always false -> false val
4542 // Fold to a simpler select_cc
4543 if (SCC.getOpcode() == ISD::SETCC)
4544 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4545 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4549 // If we can fold this based on the true/false value, do so.
4550 if (SimplifySelectOps(N, N2, N3))
4551 return SDValue(N, 0); // Don't revisit N.
4553 // fold select_cc into other things, such as min/max/abs
4554 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4557 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4558 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4559 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4563 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4564 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4565 // transformation. Returns true if extension are possible and the above
4566 // mentioned transformation is profitable.
4567 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4569 SmallVectorImpl<SDNode *> &ExtendNodes,
4570 const TargetLowering &TLI) {
4571 bool HasCopyToRegUses = false;
4572 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4573 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4574 UE = N0.getNode()->use_end();
4579 if (UI.getUse().getResNo() != N0.getResNo())
4581 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4582 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4583 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4584 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4585 // Sign bits will be lost after a zext.
4588 for (unsigned i = 0; i != 2; ++i) {
4589 SDValue UseOp = User->getOperand(i);
4592 if (!isa<ConstantSDNode>(UseOp))
4597 ExtendNodes.push_back(User);
4600 // If truncates aren't free and there are users we can't
4601 // extend, it isn't worthwhile.
4604 // Remember if this value is live-out.
4605 if (User->getOpcode() == ISD::CopyToReg)
4606 HasCopyToRegUses = true;
4609 if (HasCopyToRegUses) {
4610 bool BothLiveOut = false;
4611 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4613 SDUse &Use = UI.getUse();
4614 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4620 // Both unextended and extended values are live out. There had better be
4621 // a good reason for the transformation.
4622 return ExtendNodes.size();
4627 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4628 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4629 ISD::NodeType ExtType) {
4630 // Extend SetCC uses if necessary.
4631 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4632 SDNode *SetCC = SetCCs[i];
4633 SmallVector<SDValue, 4> Ops;
4635 for (unsigned j = 0; j != 2; ++j) {
4636 SDValue SOp = SetCC->getOperand(j);
4638 Ops.push_back(ExtLoad);
4640 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4643 Ops.push_back(SetCC->getOperand(2));
4644 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4645 &Ops[0], Ops.size()));
4649 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4650 SDValue N0 = N->getOperand(0);
4651 EVT VT = N->getValueType(0);
4653 // fold (sext c1) -> c1
4654 if (isa<ConstantSDNode>(N0))
4655 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4657 // fold (sext (sext x)) -> (sext x)
4658 // fold (sext (aext x)) -> (sext x)
4659 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4660 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4663 if (N0.getOpcode() == ISD::TRUNCATE) {
4664 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4665 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4666 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4667 if (NarrowLoad.getNode()) {
4668 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4669 if (NarrowLoad.getNode() != N0.getNode()) {
4670 CombineTo(N0.getNode(), NarrowLoad);
4671 // CombineTo deleted the truncate, if needed, but not what's under it.
4674 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4677 // See if the value being truncated is already sign extended. If so, just
4678 // eliminate the trunc/sext pair.
4679 SDValue Op = N0.getOperand(0);
4680 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4681 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4682 unsigned DestBits = VT.getScalarType().getSizeInBits();
4683 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4685 if (OpBits == DestBits) {
4686 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4687 // bits, it is already ready.
4688 if (NumSignBits > DestBits-MidBits)
4690 } else if (OpBits < DestBits) {
4691 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4692 // bits, just sext from i32.
4693 if (NumSignBits > OpBits-MidBits)
4694 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4696 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4697 // bits, just truncate to i32.
4698 if (NumSignBits > OpBits-MidBits)
4699 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4702 // fold (sext (truncate x)) -> (sextinreg x).
4703 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4704 N0.getValueType())) {
4705 if (OpBits < DestBits)
4706 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4707 else if (OpBits > DestBits)
4708 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4709 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4710 DAG.getValueType(N0.getValueType()));
4714 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4715 // None of the supported targets knows how to perform load and sign extend
4716 // on vectors in one instruction. We only perform this transformation on
4718 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4719 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4720 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4721 bool DoXform = true;
4722 SmallVector<SDNode*, 4> SetCCs;
4723 if (!N0.hasOneUse())
4724 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4726 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4727 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4729 LN0->getBasePtr(), N0.getValueType(),
4730 LN0->getMemOperand());
4731 CombineTo(N, ExtLoad);
4732 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4733 N0.getValueType(), ExtLoad);
4734 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4735 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4737 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4741 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4742 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4743 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4744 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4745 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4746 EVT MemVT = LN0->getMemoryVT();
4747 if ((!LegalOperations && !LN0->isVolatile()) ||
4748 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4749 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4751 LN0->getBasePtr(), MemVT,
4752 LN0->getMemOperand());
4753 CombineTo(N, ExtLoad);
4754 CombineTo(N0.getNode(),
4755 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4756 N0.getValueType(), ExtLoad),
4757 ExtLoad.getValue(1));
4758 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4762 // fold (sext (and/or/xor (load x), cst)) ->
4763 // (and/or/xor (sextload x), (sext cst))
4764 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4765 N0.getOpcode() == ISD::XOR) &&
4766 isa<LoadSDNode>(N0.getOperand(0)) &&
4767 N0.getOperand(1).getOpcode() == ISD::Constant &&
4768 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4769 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4770 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4771 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4772 bool DoXform = true;
4773 SmallVector<SDNode*, 4> SetCCs;
4774 if (!N0.hasOneUse())
4775 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4778 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4779 LN0->getChain(), LN0->getBasePtr(),
4781 LN0->getMemOperand());
4782 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4783 Mask = Mask.sext(VT.getSizeInBits());
4784 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4785 ExtLoad, DAG.getConstant(Mask, VT));
4786 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4787 SDLoc(N0.getOperand(0)),
4788 N0.getOperand(0).getValueType(), ExtLoad);
4790 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4791 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4793 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4798 if (N0.getOpcode() == ISD::SETCC) {
4799 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4800 // Only do this before legalize for now.
4801 if (VT.isVector() && !LegalOperations &&
4802 TLI.getBooleanContents(true) ==
4803 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4804 EVT N0VT = N0.getOperand(0).getValueType();
4805 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4806 // of the same size as the compared operands. Only optimize sext(setcc())
4807 // if this is the case.
4808 EVT SVT = getSetCCResultType(N0VT);
4810 // We know that the # elements of the results is the same as the
4811 // # elements of the compare (and the # elements of the compare result
4812 // for that matter). Check to see that they are the same size. If so,
4813 // we know that the element size of the sext'd result matches the
4814 // element size of the compare operands.
4815 if (VT.getSizeInBits() == SVT.getSizeInBits())
4816 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4818 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4820 // If the desired elements are smaller or larger than the source
4821 // elements we can use a matching integer vector type and then
4822 // truncate/sign extend
4823 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4824 if (SVT == MatchingVectorType) {
4825 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4826 N0.getOperand(0), N0.getOperand(1),
4827 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4828 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4832 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4833 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4835 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4837 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4838 NegOne, DAG.getConstant(0, VT),
4839 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4840 if (SCC.getNode()) return SCC;
4841 if (!VT.isVector() &&
4842 (!LegalOperations ||
4843 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4844 return DAG.getSelect(SDLoc(N), VT,
4845 DAG.getSetCC(SDLoc(N),
4846 getSetCCResultType(VT),
4847 N0.getOperand(0), N0.getOperand(1),
4848 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4849 NegOne, DAG.getConstant(0, VT));
4853 // fold (sext x) -> (zext x) if the sign bit is known zero.
4854 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4855 DAG.SignBitIsZero(N0))
4856 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4861 // isTruncateOf - If N is a truncate of some other value, return true, record
4862 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4863 // This function computes KnownZero to avoid a duplicated call to
4864 // ComputeMaskedBits in the caller.
4865 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4868 if (N->getOpcode() == ISD::TRUNCATE) {
4869 Op = N->getOperand(0);
4870 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4874 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4875 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4878 SDValue Op0 = N->getOperand(0);
4879 SDValue Op1 = N->getOperand(1);
4880 assert(Op0.getValueType() == Op1.getValueType());
4882 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4883 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4884 if (COp0 && COp0->isNullValue())
4886 else if (COp1 && COp1->isNullValue())
4891 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4893 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4899 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4900 SDValue N0 = N->getOperand(0);
4901 EVT VT = N->getValueType(0);
4903 // fold (zext c1) -> c1
4904 if (isa<ConstantSDNode>(N0))
4905 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4906 // fold (zext (zext x)) -> (zext x)
4907 // fold (zext (aext x)) -> (zext x)
4908 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4909 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4912 // fold (zext (truncate x)) -> (zext x) or
4913 // (zext (truncate x)) -> (truncate x)
4914 // This is valid when the truncated bits of x are already zero.
4915 // FIXME: We should extend this to work for vectors too.
4918 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4919 APInt TruncatedBits =
4920 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4921 APInt(Op.getValueSizeInBits(), 0) :
4922 APInt::getBitsSet(Op.getValueSizeInBits(),
4923 N0.getValueSizeInBits(),
4924 std::min(Op.getValueSizeInBits(),
4925 VT.getSizeInBits()));
4926 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4927 if (VT.bitsGT(Op.getValueType()))
4928 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4929 if (VT.bitsLT(Op.getValueType()))
4930 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4936 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4937 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4938 if (N0.getOpcode() == ISD::TRUNCATE) {
4939 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4940 if (NarrowLoad.getNode()) {
4941 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4942 if (NarrowLoad.getNode() != N0.getNode()) {
4943 CombineTo(N0.getNode(), NarrowLoad);
4944 // CombineTo deleted the truncate, if needed, but not what's under it.
4947 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4951 // fold (zext (truncate x)) -> (and x, mask)
4952 if (N0.getOpcode() == ISD::TRUNCATE &&
4953 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4955 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4956 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4957 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4958 if (NarrowLoad.getNode()) {
4959 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4960 if (NarrowLoad.getNode() != N0.getNode()) {
4961 CombineTo(N0.getNode(), NarrowLoad);
4962 // CombineTo deleted the truncate, if needed, but not what's under it.
4965 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4968 SDValue Op = N0.getOperand(0);
4969 if (Op.getValueType().bitsLT(VT)) {
4970 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4971 AddToWorkList(Op.getNode());
4972 } else if (Op.getValueType().bitsGT(VT)) {
4973 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4974 AddToWorkList(Op.getNode());
4976 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4977 N0.getValueType().getScalarType());
4980 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4981 // if either of the casts is not free.
4982 if (N0.getOpcode() == ISD::AND &&
4983 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4984 N0.getOperand(1).getOpcode() == ISD::Constant &&
4985 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4986 N0.getValueType()) ||
4987 !TLI.isZExtFree(N0.getValueType(), VT))) {
4988 SDValue X = N0.getOperand(0).getOperand(0);
4989 if (X.getValueType().bitsLT(VT)) {
4990 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4991 } else if (X.getValueType().bitsGT(VT)) {
4992 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4994 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4995 Mask = Mask.zext(VT.getSizeInBits());
4996 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4997 X, DAG.getConstant(Mask, VT));
5000 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5001 // None of the supported targets knows how to perform load and vector_zext
5002 // on vectors in one instruction. We only perform this transformation on
5004 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5005 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5006 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5007 bool DoXform = true;
5008 SmallVector<SDNode*, 4> SetCCs;
5009 if (!N0.hasOneUse())
5010 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5012 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5013 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5015 LN0->getBasePtr(), N0.getValueType(),
5016 LN0->getMemOperand());
5017 CombineTo(N, ExtLoad);
5018 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5019 N0.getValueType(), ExtLoad);
5020 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5022 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5024 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5028 // fold (zext (and/or/xor (load x), cst)) ->
5029 // (and/or/xor (zextload x), (zext cst))
5030 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5031 N0.getOpcode() == ISD::XOR) &&
5032 isa<LoadSDNode>(N0.getOperand(0)) &&
5033 N0.getOperand(1).getOpcode() == ISD::Constant &&
5034 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5035 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5036 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5037 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5038 bool DoXform = true;
5039 SmallVector<SDNode*, 4> SetCCs;
5040 if (!N0.hasOneUse())
5041 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5044 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5045 LN0->getChain(), LN0->getBasePtr(),
5047 LN0->getMemOperand());
5048 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5049 Mask = Mask.zext(VT.getSizeInBits());
5050 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5051 ExtLoad, DAG.getConstant(Mask, VT));
5052 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5053 SDLoc(N0.getOperand(0)),
5054 N0.getOperand(0).getValueType(), ExtLoad);
5056 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5057 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5059 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5064 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5065 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5066 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5067 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5068 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5069 EVT MemVT = LN0->getMemoryVT();
5070 if ((!LegalOperations && !LN0->isVolatile()) ||
5071 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5072 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5074 LN0->getBasePtr(), MemVT,
5075 LN0->getMemOperand());
5076 CombineTo(N, ExtLoad);
5077 CombineTo(N0.getNode(),
5078 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5080 ExtLoad.getValue(1));
5081 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5085 if (N0.getOpcode() == ISD::SETCC) {
5086 if (!LegalOperations && VT.isVector() &&
5087 N0.getValueType().getVectorElementType() == MVT::i1) {
5088 EVT N0VT = N0.getOperand(0).getValueType();
5089 if (getSetCCResultType(N0VT) == N0.getValueType())
5092 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5093 // Only do this before legalize for now.
5094 EVT EltVT = VT.getVectorElementType();
5095 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5096 DAG.getConstant(1, EltVT));
5097 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5098 // We know that the # elements of the results is the same as the
5099 // # elements of the compare (and the # elements of the compare result
5100 // for that matter). Check to see that they are the same size. If so,
5101 // we know that the element size of the sext'd result matches the
5102 // element size of the compare operands.
5103 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5104 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5106 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5107 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5108 &OneOps[0], OneOps.size()));
5110 // If the desired elements are smaller or larger than the source
5111 // elements we can use a matching integer vector type and then
5112 // truncate/sign extend
5113 EVT MatchingElementType =
5114 EVT::getIntegerVT(*DAG.getContext(),
5115 N0VT.getScalarType().getSizeInBits());
5116 EVT MatchingVectorType =
5117 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5118 N0VT.getVectorNumElements());
5120 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5122 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5123 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5124 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5125 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5126 &OneOps[0], OneOps.size()));
5129 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5131 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5132 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5133 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5134 if (SCC.getNode()) return SCC;
5137 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5138 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5139 isa<ConstantSDNode>(N0.getOperand(1)) &&
5140 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5142 SDValue ShAmt = N0.getOperand(1);
5143 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5144 if (N0.getOpcode() == ISD::SHL) {
5145 SDValue InnerZExt = N0.getOperand(0);
5146 // If the original shl may be shifting out bits, do not perform this
5148 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5149 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5150 if (ShAmtVal > KnownZeroBits)
5156 // Ensure that the shift amount is wide enough for the shifted value.
5157 if (VT.getSizeInBits() >= 256)
5158 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5160 return DAG.getNode(N0.getOpcode(), DL, VT,
5161 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5168 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5169 SDValue N0 = N->getOperand(0);
5170 EVT VT = N->getValueType(0);
5172 // fold (aext c1) -> c1
5173 if (isa<ConstantSDNode>(N0))
5174 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5175 // fold (aext (aext x)) -> (aext x)
5176 // fold (aext (zext x)) -> (zext x)
5177 // fold (aext (sext x)) -> (sext x)
5178 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5179 N0.getOpcode() == ISD::ZERO_EXTEND ||
5180 N0.getOpcode() == ISD::SIGN_EXTEND)
5181 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5183 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5184 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5185 if (N0.getOpcode() == ISD::TRUNCATE) {
5186 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5187 if (NarrowLoad.getNode()) {
5188 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5189 if (NarrowLoad.getNode() != N0.getNode()) {
5190 CombineTo(N0.getNode(), NarrowLoad);
5191 // CombineTo deleted the truncate, if needed, but not what's under it.
5194 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5198 // fold (aext (truncate x))
5199 if (N0.getOpcode() == ISD::TRUNCATE) {
5200 SDValue TruncOp = N0.getOperand(0);
5201 if (TruncOp.getValueType() == VT)
5202 return TruncOp; // x iff x size == zext size.
5203 if (TruncOp.getValueType().bitsGT(VT))
5204 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5205 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5208 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5209 // if the trunc is not free.
5210 if (N0.getOpcode() == ISD::AND &&
5211 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5212 N0.getOperand(1).getOpcode() == ISD::Constant &&
5213 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5214 N0.getValueType())) {
5215 SDValue X = N0.getOperand(0).getOperand(0);
5216 if (X.getValueType().bitsLT(VT)) {
5217 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5218 } else if (X.getValueType().bitsGT(VT)) {
5219 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5221 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5222 Mask = Mask.zext(VT.getSizeInBits());
5223 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5224 X, DAG.getConstant(Mask, VT));
5227 // fold (aext (load x)) -> (aext (truncate (extload x)))
5228 // None of the supported targets knows how to perform load and any_ext
5229 // on vectors in one instruction. We only perform this transformation on
5231 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5232 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5233 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5234 bool DoXform = true;
5235 SmallVector<SDNode*, 4> SetCCs;
5236 if (!N0.hasOneUse())
5237 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5239 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5240 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5242 LN0->getBasePtr(), N0.getValueType(),
5243 LN0->getMemOperand());
5244 CombineTo(N, ExtLoad);
5245 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5246 N0.getValueType(), ExtLoad);
5247 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5248 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5250 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5254 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5255 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5256 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5257 if (N0.getOpcode() == ISD::LOAD &&
5258 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5260 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5261 EVT MemVT = LN0->getMemoryVT();
5262 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5263 VT, LN0->getChain(), LN0->getBasePtr(),
5264 MemVT, LN0->getMemOperand());
5265 CombineTo(N, ExtLoad);
5266 CombineTo(N0.getNode(),
5267 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5268 N0.getValueType(), ExtLoad),
5269 ExtLoad.getValue(1));
5270 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5273 if (N0.getOpcode() == ISD::SETCC) {
5274 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5275 // Only do this before legalize for now.
5276 if (VT.isVector() && !LegalOperations) {
5277 EVT N0VT = N0.getOperand(0).getValueType();
5278 // We know that the # elements of the results is the same as the
5279 // # elements of the compare (and the # elements of the compare result
5280 // for that matter). Check to see that they are the same size. If so,
5281 // we know that the element size of the sext'd result matches the
5282 // element size of the compare operands.
5283 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5284 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5286 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5287 // If the desired elements are smaller or larger than the source
5288 // elements we can use a matching integer vector type and then
5289 // truncate/sign extend
5291 EVT MatchingElementType =
5292 EVT::getIntegerVT(*DAG.getContext(),
5293 N0VT.getScalarType().getSizeInBits());
5294 EVT MatchingVectorType =
5295 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5296 N0VT.getVectorNumElements());
5298 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5300 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5301 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5305 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5307 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5308 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5309 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5317 /// GetDemandedBits - See if the specified operand can be simplified with the
5318 /// knowledge that only the bits specified by Mask are used. If so, return the
5319 /// simpler operand, otherwise return a null SDValue.
5320 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5321 switch (V.getOpcode()) {
5323 case ISD::Constant: {
5324 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5325 assert(CV != 0 && "Const value should be ConstSDNode.");
5326 const APInt &CVal = CV->getAPIntValue();
5327 APInt NewVal = CVal & Mask;
5329 return DAG.getConstant(NewVal, V.getValueType());
5334 // If the LHS or RHS don't contribute bits to the or, drop them.
5335 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5336 return V.getOperand(1);
5337 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5338 return V.getOperand(0);
5341 // Only look at single-use SRLs.
5342 if (!V.getNode()->hasOneUse())
5344 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5345 // See if we can recursively simplify the LHS.
5346 unsigned Amt = RHSC->getZExtValue();
5348 // Watch out for shift count overflow though.
5349 if (Amt >= Mask.getBitWidth()) break;
5350 APInt NewMask = Mask << Amt;
5351 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5352 if (SimplifyLHS.getNode())
5353 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5354 SimplifyLHS, V.getOperand(1));
5360 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5361 /// bits and then truncated to a narrower type and where N is a multiple
5362 /// of number of bits of the narrower type, transform it to a narrower load
5363 /// from address + N / num of bits of new type. If the result is to be
5364 /// extended, also fold the extension to form a extending load.
5365 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5366 unsigned Opc = N->getOpcode();
5368 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5369 SDValue N0 = N->getOperand(0);
5370 EVT VT = N->getValueType(0);
5373 // This transformation isn't valid for vector loads.
5377 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5379 if (Opc == ISD::SIGN_EXTEND_INREG) {
5380 ExtType = ISD::SEXTLOAD;
5381 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5382 } else if (Opc == ISD::SRL) {
5383 // Another special-case: SRL is basically zero-extending a narrower value.
5384 ExtType = ISD::ZEXTLOAD;
5386 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5387 if (!N01) return SDValue();
5388 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5389 VT.getSizeInBits() - N01->getZExtValue());
5391 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5394 unsigned EVTBits = ExtVT.getSizeInBits();
5396 // Do not generate loads of non-round integer types since these can
5397 // be expensive (and would be wrong if the type is not byte sized).
5398 if (!ExtVT.isRound())
5402 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5403 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5404 ShAmt = N01->getZExtValue();
5405 // Is the shift amount a multiple of size of VT?
5406 if ((ShAmt & (EVTBits-1)) == 0) {
5407 N0 = N0.getOperand(0);
5408 // Is the load width a multiple of size of VT?
5409 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5413 // At this point, we must have a load or else we can't do the transform.
5414 if (!isa<LoadSDNode>(N0)) return SDValue();
5416 // Because a SRL must be assumed to *need* to zero-extend the high bits
5417 // (as opposed to anyext the high bits), we can't combine the zextload
5418 // lowering of SRL and an sextload.
5419 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5422 // If the shift amount is larger than the input type then we're not
5423 // accessing any of the loaded bytes. If the load was a zextload/extload
5424 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5425 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5430 // If the load is shifted left (and the result isn't shifted back right),
5431 // we can fold the truncate through the shift.
5432 unsigned ShLeftAmt = 0;
5433 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5434 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5435 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5436 ShLeftAmt = N01->getZExtValue();
5437 N0 = N0.getOperand(0);
5441 // If we haven't found a load, we can't narrow it. Don't transform one with
5442 // multiple uses, this would require adding a new load.
5443 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5446 // Don't change the width of a volatile load.
5447 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5448 if (LN0->isVolatile())
5451 // Verify that we are actually reducing a load width here.
5452 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5455 // For the transform to be legal, the load must produce only two values
5456 // (the value loaded and the chain). Don't transform a pre-increment
5457 // load, for example, which produces an extra value. Otherwise the
5458 // transformation is not equivalent, and the downstream logic to replace
5459 // uses gets things wrong.
5460 if (LN0->getNumValues() > 2)
5463 // If the load that we're shrinking is an extload and we're not just
5464 // discarding the extension we can't simply shrink the load. Bail.
5465 // TODO: It would be possible to merge the extensions in some cases.
5466 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5467 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5470 EVT PtrType = N0.getOperand(1).getValueType();
5472 if (PtrType == MVT::Untyped || PtrType.isExtended())
5473 // It's not possible to generate a constant of extended or untyped type.
5476 // For big endian targets, we need to adjust the offset to the pointer to
5477 // load the correct bytes.
5478 if (TLI.isBigEndian()) {
5479 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5480 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5481 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5484 uint64_t PtrOff = ShAmt / 8;
5485 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5486 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5487 PtrType, LN0->getBasePtr(),
5488 DAG.getConstant(PtrOff, PtrType));
5489 AddToWorkList(NewPtr.getNode());
5492 if (ExtType == ISD::NON_EXTLOAD)
5493 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5494 LN0->getPointerInfo().getWithOffset(PtrOff),
5495 LN0->isVolatile(), LN0->isNonTemporal(),
5496 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5498 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5499 LN0->getPointerInfo().getWithOffset(PtrOff),
5500 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5501 NewAlign, LN0->getTBAAInfo());
5503 // Replace the old load's chain with the new load's chain.
5504 WorkListRemover DeadNodes(*this);
5505 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5507 // Shift the result left, if we've swallowed a left shift.
5508 SDValue Result = Load;
5509 if (ShLeftAmt != 0) {
5510 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5511 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5513 // If the shift amount is as large as the result size (but, presumably,
5514 // no larger than the source) then the useful bits of the result are
5515 // zero; we can't simply return the shortened shift, because the result
5516 // of that operation is undefined.
5517 if (ShLeftAmt >= VT.getSizeInBits())
5518 Result = DAG.getConstant(0, VT);
5520 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5521 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5524 // Return the new loaded value.
5528 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5529 SDValue N0 = N->getOperand(0);
5530 SDValue N1 = N->getOperand(1);
5531 EVT VT = N->getValueType(0);
5532 EVT EVT = cast<VTSDNode>(N1)->getVT();
5533 unsigned VTBits = VT.getScalarType().getSizeInBits();
5534 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5536 // fold (sext_in_reg c1) -> c1
5537 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5538 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5540 // If the input is already sign extended, just drop the extension.
5541 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5544 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5545 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5546 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5547 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5548 N0.getOperand(0), N1);
5550 // fold (sext_in_reg (sext x)) -> (sext x)
5551 // fold (sext_in_reg (aext x)) -> (sext x)
5552 // if x is small enough.
5553 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5554 SDValue N00 = N0.getOperand(0);
5555 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5556 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5557 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5560 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5561 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5562 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5564 // fold operands of sext_in_reg based on knowledge that the top bits are not
5566 if (SimplifyDemandedBits(SDValue(N, 0)))
5567 return SDValue(N, 0);
5569 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5570 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5571 SDValue NarrowLoad = ReduceLoadWidth(N);
5572 if (NarrowLoad.getNode())
5575 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5576 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5577 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5578 if (N0.getOpcode() == ISD::SRL) {
5579 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5580 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5581 // We can turn this into an SRA iff the input to the SRL is already sign
5583 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5584 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5585 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5586 N0.getOperand(0), N0.getOperand(1));
5590 // fold (sext_inreg (extload x)) -> (sextload x)
5591 if (ISD::isEXTLoad(N0.getNode()) &&
5592 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5593 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5594 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5595 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5596 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5597 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5599 LN0->getBasePtr(), EVT,
5600 LN0->getMemOperand());
5601 CombineTo(N, ExtLoad);
5602 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5603 AddToWorkList(ExtLoad.getNode());
5604 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5606 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5607 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5609 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5610 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5611 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5612 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5613 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5615 LN0->getBasePtr(), EVT,
5616 LN0->getMemOperand());
5617 CombineTo(N, ExtLoad);
5618 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5619 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5622 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5623 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5624 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5625 N0.getOperand(1), false);
5626 if (BSwap.getNode() != 0)
5627 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5631 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5632 // into a build_vector.
5633 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5634 SmallVector<SDValue, 8> Elts;
5635 unsigned NumElts = N0->getNumOperands();
5636 unsigned ShAmt = VTBits - EVTBits;
5638 for (unsigned i = 0; i != NumElts; ++i) {
5639 SDValue Op = N0->getOperand(i);
5640 if (Op->getOpcode() == ISD::UNDEF) {
5645 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5646 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5647 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5648 Op.getValueType()));
5651 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5657 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5658 SDValue N0 = N->getOperand(0);
5659 EVT VT = N->getValueType(0);
5660 bool isLE = TLI.isLittleEndian();
5663 if (N0.getValueType() == N->getValueType(0))
5665 // fold (truncate c1) -> c1
5666 if (isa<ConstantSDNode>(N0))
5667 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5668 // fold (truncate (truncate x)) -> (truncate x)
5669 if (N0.getOpcode() == ISD::TRUNCATE)
5670 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5671 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5672 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5673 N0.getOpcode() == ISD::SIGN_EXTEND ||
5674 N0.getOpcode() == ISD::ANY_EXTEND) {
5675 if (N0.getOperand(0).getValueType().bitsLT(VT))
5676 // if the source is smaller than the dest, we still need an extend
5677 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5679 if (N0.getOperand(0).getValueType().bitsGT(VT))
5680 // if the source is larger than the dest, than we just need the truncate
5681 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5682 // if the source and dest are the same type, we can drop both the extend
5683 // and the truncate.
5684 return N0.getOperand(0);
5687 // Fold extract-and-trunc into a narrow extract. For example:
5688 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5689 // i32 y = TRUNCATE(i64 x)
5691 // v16i8 b = BITCAST (v2i64 val)
5692 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5694 // Note: We only run this optimization after type legalization (which often
5695 // creates this pattern) and before operation legalization after which
5696 // we need to be more careful about the vector instructions that we generate.
5697 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5698 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5700 EVT VecTy = N0.getOperand(0).getValueType();
5701 EVT ExTy = N0.getValueType();
5702 EVT TrTy = N->getValueType(0);
5704 unsigned NumElem = VecTy.getVectorNumElements();
5705 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5707 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5708 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5710 SDValue EltNo = N0->getOperand(1);
5711 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5712 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5713 EVT IndexTy = TLI.getVectorIdxTy();
5714 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5716 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5717 NVT, N0.getOperand(0));
5719 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5721 DAG.getConstant(Index, IndexTy));
5725 // Fold a series of buildvector, bitcast, and truncate if possible.
5727 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5728 // (2xi32 (buildvector x, y)).
5729 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5730 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5731 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5732 N0.getOperand(0).hasOneUse()) {
5734 SDValue BuildVect = N0.getOperand(0);
5735 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5736 EVT TruncVecEltTy = VT.getVectorElementType();
5738 // Check that the element types match.
5739 if (BuildVectEltTy == TruncVecEltTy) {
5740 // Now we only need to compute the offset of the truncated elements.
5741 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5742 unsigned TruncVecNumElts = VT.getVectorNumElements();
5743 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5745 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5746 "Invalid number of elements");
5748 SmallVector<SDValue, 8> Opnds;
5749 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5750 Opnds.push_back(BuildVect.getOperand(i));
5752 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5757 // See if we can simplify the input to this truncate through knowledge that
5758 // only the low bits are being used.
5759 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5760 // Currently we only perform this optimization on scalars because vectors
5761 // may have different active low bits.
5762 if (!VT.isVector()) {
5764 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5765 VT.getSizeInBits()));
5766 if (Shorter.getNode())
5767 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5769 // fold (truncate (load x)) -> (smaller load x)
5770 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5771 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5772 SDValue Reduced = ReduceLoadWidth(N);
5773 if (Reduced.getNode())
5775 // Handle the case where the load remains an extending load even
5776 // after truncation.
5777 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5778 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5779 if (!LN0->isVolatile() &&
5780 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5781 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5782 VT, LN0->getChain(), LN0->getBasePtr(),
5784 LN0->getMemOperand());
5785 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5790 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5791 // where ... are all 'undef'.
5792 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5793 SmallVector<EVT, 8> VTs;
5796 unsigned NumDefs = 0;
5798 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5799 SDValue X = N0.getOperand(i);
5800 if (X.getOpcode() != ISD::UNDEF) {
5805 // Stop if more than one members are non-undef.
5808 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5809 VT.getVectorElementType(),
5810 X.getValueType().getVectorNumElements()));
5814 return DAG.getUNDEF(VT);
5817 assert(V.getNode() && "The single defined operand is empty!");
5818 SmallVector<SDValue, 8> Opnds;
5819 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5821 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5824 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5825 AddToWorkList(NV.getNode());
5826 Opnds.push_back(NV);
5828 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5829 &Opnds[0], Opnds.size());
5833 // Simplify the operands using demanded-bits information.
5834 if (!VT.isVector() &&
5835 SimplifyDemandedBits(SDValue(N, 0)))
5836 return SDValue(N, 0);
5841 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5842 SDValue Elt = N->getOperand(i);
5843 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5844 return Elt.getNode();
5845 return Elt.getOperand(Elt.getResNo()).getNode();
5848 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5849 /// if load locations are consecutive.
5850 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5851 assert(N->getOpcode() == ISD::BUILD_PAIR);
5853 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5854 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5855 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5856 LD1->getPointerInfo().getAddrSpace() !=
5857 LD2->getPointerInfo().getAddrSpace())
5859 EVT LD1VT = LD1->getValueType(0);
5861 if (ISD::isNON_EXTLoad(LD2) &&
5863 // If both are volatile this would reduce the number of volatile loads.
5864 // If one is volatile it might be ok, but play conservative and bail out.
5865 !LD1->isVolatile() &&
5866 !LD2->isVolatile() &&
5867 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5868 unsigned Align = LD1->getAlignment();
5869 unsigned NewAlign = TLI.getDataLayout()->
5870 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5872 if (NewAlign <= Align &&
5873 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5874 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5875 LD1->getBasePtr(), LD1->getPointerInfo(),
5876 false, false, false, Align);
5882 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5883 SDValue N0 = N->getOperand(0);
5884 EVT VT = N->getValueType(0);
5886 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5887 // Only do this before legalize, since afterward the target may be depending
5888 // on the bitconvert.
5889 // First check to see if this is all constant.
5891 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5893 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
5895 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5896 assert(!DestEltVT.isVector() &&
5897 "Element type of vector ValueType must not be vector!");
5899 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5902 // If the input is a constant, let getNode fold it.
5903 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5904 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5905 if (Res.getNode() != N) {
5906 if (!LegalOperations ||
5907 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5910 // Folding it resulted in an illegal node, and it's too late to
5911 // do that. Clean up the old node and forego the transformation.
5912 // Ideally this won't happen very often, because instcombine
5913 // and the earlier dagcombine runs (where illegal nodes are
5914 // permitted) should have folded most of them already.
5915 DAG.DeleteNode(Res.getNode());
5919 // (conv (conv x, t1), t2) -> (conv x, t2)
5920 if (N0.getOpcode() == ISD::BITCAST)
5921 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5924 // fold (conv (load x)) -> (load (conv*)x)
5925 // If the resultant load doesn't need a higher alignment than the original!
5926 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5927 // Do not change the width of a volatile load.
5928 !cast<LoadSDNode>(N0)->isVolatile() &&
5929 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5930 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5931 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5932 unsigned Align = TLI.getDataLayout()->
5933 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5934 unsigned OrigAlign = LN0->getAlignment();
5936 if (Align <= OrigAlign) {
5937 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5938 LN0->getBasePtr(), LN0->getPointerInfo(),
5939 LN0->isVolatile(), LN0->isNonTemporal(),
5940 LN0->isInvariant(), OrigAlign,
5941 LN0->getTBAAInfo());
5943 CombineTo(N0.getNode(),
5944 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5945 N0.getValueType(), Load),
5951 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5952 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5953 // This often reduces constant pool loads.
5954 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5955 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5956 N0.getNode()->hasOneUse() && VT.isInteger() &&
5957 !VT.isVector() && !N0.getValueType().isVector()) {
5958 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5960 AddToWorkList(NewConv.getNode());
5962 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5963 if (N0.getOpcode() == ISD::FNEG)
5964 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5965 NewConv, DAG.getConstant(SignBit, VT));
5966 assert(N0.getOpcode() == ISD::FABS);
5967 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5968 NewConv, DAG.getConstant(~SignBit, VT));
5971 // fold (bitconvert (fcopysign cst, x)) ->
5972 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5973 // Note that we don't handle (copysign x, cst) because this can always be
5974 // folded to an fneg or fabs.
5975 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5976 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5977 VT.isInteger() && !VT.isVector()) {
5978 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5979 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5980 if (isTypeLegal(IntXVT)) {
5981 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5982 IntXVT, N0.getOperand(1));
5983 AddToWorkList(X.getNode());
5985 // If X has a different width than the result/lhs, sext it or truncate it.
5986 unsigned VTWidth = VT.getSizeInBits();
5987 if (OrigXWidth < VTWidth) {
5988 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5989 AddToWorkList(X.getNode());
5990 } else if (OrigXWidth > VTWidth) {
5991 // To get the sign bit in the right place, we have to shift it right
5992 // before truncating.
5993 X = DAG.getNode(ISD::SRL, SDLoc(X),
5994 X.getValueType(), X,
5995 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5996 AddToWorkList(X.getNode());
5997 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5998 AddToWorkList(X.getNode());
6001 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6002 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6003 X, DAG.getConstant(SignBit, VT));
6004 AddToWorkList(X.getNode());
6006 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6007 VT, N0.getOperand(0));
6008 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6009 Cst, DAG.getConstant(~SignBit, VT));
6010 AddToWorkList(Cst.getNode());
6012 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6016 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6017 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6018 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6019 if (CombineLD.getNode())
6026 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6027 EVT VT = N->getValueType(0);
6028 return CombineConsecutiveLoads(N, VT);
6031 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6032 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6033 /// destination element value type.
6034 SDValue DAGCombiner::
6035 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6036 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6038 // If this is already the right type, we're done.
6039 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6041 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6042 unsigned DstBitSize = DstEltVT.getSizeInBits();
6044 // If this is a conversion of N elements of one type to N elements of another
6045 // type, convert each element. This handles FP<->INT cases.
6046 if (SrcBitSize == DstBitSize) {
6047 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6048 BV->getValueType(0).getVectorNumElements());
6050 // Due to the FP element handling below calling this routine recursively,
6051 // we can end up with a scalar-to-vector node here.
6052 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6053 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6054 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6055 DstEltVT, BV->getOperand(0)));
6057 SmallVector<SDValue, 8> Ops;
6058 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6059 SDValue Op = BV->getOperand(i);
6060 // If the vector element type is not legal, the BUILD_VECTOR operands
6061 // are promoted and implicitly truncated. Make that explicit here.
6062 if (Op.getValueType() != SrcEltVT)
6063 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6064 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6066 AddToWorkList(Ops.back().getNode());
6068 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6069 &Ops[0], Ops.size());
6072 // Otherwise, we're growing or shrinking the elements. To avoid having to
6073 // handle annoying details of growing/shrinking FP values, we convert them to
6075 if (SrcEltVT.isFloatingPoint()) {
6076 // Convert the input float vector to a int vector where the elements are the
6078 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6079 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6080 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6084 // Now we know the input is an integer vector. If the output is a FP type,
6085 // convert to integer first, then to FP of the right size.
6086 if (DstEltVT.isFloatingPoint()) {
6087 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6088 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6089 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6091 // Next, convert to FP elements of the same size.
6092 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6095 // Okay, we know the src/dst types are both integers of differing types.
6096 // Handling growing first.
6097 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6098 if (SrcBitSize < DstBitSize) {
6099 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6101 SmallVector<SDValue, 8> Ops;
6102 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6103 i += NumInputsPerOutput) {
6104 bool isLE = TLI.isLittleEndian();
6105 APInt NewBits = APInt(DstBitSize, 0);
6106 bool EltIsUndef = true;
6107 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6108 // Shift the previously computed bits over.
6109 NewBits <<= SrcBitSize;
6110 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6111 if (Op.getOpcode() == ISD::UNDEF) continue;
6114 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6115 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6119 Ops.push_back(DAG.getUNDEF(DstEltVT));
6121 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6124 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6125 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6126 &Ops[0], Ops.size());
6129 // Finally, this must be the case where we are shrinking elements: each input
6130 // turns into multiple outputs.
6131 bool isS2V = ISD::isScalarToVector(BV);
6132 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6133 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6134 NumOutputsPerInput*BV->getNumOperands());
6135 SmallVector<SDValue, 8> Ops;
6137 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6138 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6139 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6140 Ops.push_back(DAG.getUNDEF(DstEltVT));
6144 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6145 getAPIntValue().zextOrTrunc(SrcBitSize);
6147 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6148 APInt ThisVal = OpVal.trunc(DstBitSize);
6149 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6150 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6151 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6152 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6154 OpVal = OpVal.lshr(DstBitSize);
6157 // For big endian targets, swap the order of the pieces of each element.
6158 if (TLI.isBigEndian())
6159 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6162 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6163 &Ops[0], Ops.size());
6166 SDValue DAGCombiner::visitFADD(SDNode *N) {
6167 SDValue N0 = N->getOperand(0);
6168 SDValue N1 = N->getOperand(1);
6169 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6170 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6171 EVT VT = N->getValueType(0);
6174 if (VT.isVector()) {
6175 SDValue FoldedVOp = SimplifyVBinOp(N);
6176 if (FoldedVOp.getNode()) return FoldedVOp;
6179 // fold (fadd c1, c2) -> c1 + c2
6181 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6182 // canonicalize constant to RHS
6183 if (N0CFP && !N1CFP)
6184 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6185 // fold (fadd A, 0) -> A
6186 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6187 N1CFP->getValueAPF().isZero())
6189 // fold (fadd A, (fneg B)) -> (fsub A, B)
6190 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6191 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6192 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6193 GetNegatedExpression(N1, DAG, LegalOperations));
6194 // fold (fadd (fneg A), B) -> (fsub B, A)
6195 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6196 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6197 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6198 GetNegatedExpression(N0, DAG, LegalOperations));
6200 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6201 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6202 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6203 isa<ConstantFPSDNode>(N0.getOperand(1)))
6204 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6205 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6206 N0.getOperand(1), N1));
6208 // No FP constant should be created after legalization as Instruction
6209 // Selection pass has hard time in dealing with FP constant.
6211 // We don't need test this condition for transformation like following, as
6212 // the DAG being transformed implies it is legal to take FP constant as
6215 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6217 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6219 // If allow, fold (fadd (fneg x), x) -> 0.0
6220 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6221 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6222 return DAG.getConstantFP(0.0, VT);
6224 // If allow, fold (fadd x, (fneg x)) -> 0.0
6225 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6226 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6227 return DAG.getConstantFP(0.0, VT);
6229 // In unsafe math mode, we can fold chains of FADD's of the same value
6230 // into multiplications. This transform is not safe in general because
6231 // we are reducing the number of rounding steps.
6232 if (DAG.getTarget().Options.UnsafeFPMath &&
6233 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6235 if (N0.getOpcode() == ISD::FMUL) {
6236 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6237 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6239 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6240 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6241 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6243 DAG.getConstantFP(1.0, VT));
6244 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6248 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6249 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6250 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6252 DAG.getConstantFP(1.0, VT));
6253 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6257 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6258 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6259 N1.getOperand(0) == N1.getOperand(1) &&
6260 N0.getOperand(1) == N1.getOperand(0)) {
6261 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6263 DAG.getConstantFP(2.0, VT));
6264 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6265 N0.getOperand(1), NewCFP);
6268 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6269 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6270 N1.getOperand(0) == N1.getOperand(1) &&
6271 N0.getOperand(0) == N1.getOperand(0)) {
6272 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6274 DAG.getConstantFP(2.0, VT));
6275 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6276 N0.getOperand(0), NewCFP);
6280 if (N1.getOpcode() == ISD::FMUL) {
6281 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6282 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6284 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6285 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6286 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6288 DAG.getConstantFP(1.0, VT));
6289 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6293 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6294 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6295 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6297 DAG.getConstantFP(1.0, VT));
6298 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6303 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6304 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6305 N0.getOperand(0) == N0.getOperand(1) &&
6306 N1.getOperand(1) == N0.getOperand(0)) {
6307 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6309 DAG.getConstantFP(2.0, VT));
6310 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6311 N1.getOperand(1), NewCFP);
6314 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6315 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6316 N0.getOperand(0) == N0.getOperand(1) &&
6317 N1.getOperand(0) == N0.getOperand(0)) {
6318 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6320 DAG.getConstantFP(2.0, VT));
6321 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6322 N1.getOperand(0), NewCFP);
6326 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6327 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6328 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6329 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6330 (N0.getOperand(0) == N1))
6331 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6332 N1, DAG.getConstantFP(3.0, VT));
6335 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6336 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6337 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6338 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6339 N1.getOperand(0) == N0)
6340 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6341 N0, DAG.getConstantFP(3.0, VT));
6344 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6345 if (AllowNewFpConst &&
6346 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6347 N0.getOperand(0) == N0.getOperand(1) &&
6348 N1.getOperand(0) == N1.getOperand(1) &&
6349 N0.getOperand(0) == N1.getOperand(0))
6350 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6352 DAG.getConstantFP(4.0, VT));
6355 // FADD -> FMA combines:
6356 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6357 DAG.getTarget().Options.UnsafeFPMath) &&
6358 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6359 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6361 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6362 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6363 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6364 N0.getOperand(0), N0.getOperand(1), N1);
6366 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6367 // Note: Commutes FADD operands.
6368 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6369 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6370 N1.getOperand(0), N1.getOperand(1), N0);
6376 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6377 SDValue N0 = N->getOperand(0);
6378 SDValue N1 = N->getOperand(1);
6379 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6380 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6381 EVT VT = N->getValueType(0);
6385 if (VT.isVector()) {
6386 SDValue FoldedVOp = SimplifyVBinOp(N);
6387 if (FoldedVOp.getNode()) return FoldedVOp;
6390 // fold (fsub c1, c2) -> c1-c2
6392 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6393 // fold (fsub A, 0) -> A
6394 if (DAG.getTarget().Options.UnsafeFPMath &&
6395 N1CFP && N1CFP->getValueAPF().isZero())
6397 // fold (fsub 0, B) -> -B
6398 if (DAG.getTarget().Options.UnsafeFPMath &&
6399 N0CFP && N0CFP->getValueAPF().isZero()) {
6400 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6401 return GetNegatedExpression(N1, DAG, LegalOperations);
6402 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6403 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6405 // fold (fsub A, (fneg B)) -> (fadd A, B)
6406 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6407 return DAG.getNode(ISD::FADD, dl, VT, N0,
6408 GetNegatedExpression(N1, DAG, LegalOperations));
6410 // If 'unsafe math' is enabled, fold
6411 // (fsub x, x) -> 0.0 &
6412 // (fsub x, (fadd x, y)) -> (fneg y) &
6413 // (fsub x, (fadd y, x)) -> (fneg y)
6414 if (DAG.getTarget().Options.UnsafeFPMath) {
6416 return DAG.getConstantFP(0.0f, VT);
6418 if (N1.getOpcode() == ISD::FADD) {
6419 SDValue N10 = N1->getOperand(0);
6420 SDValue N11 = N1->getOperand(1);
6422 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6423 &DAG.getTarget().Options))
6424 return GetNegatedExpression(N11, DAG, LegalOperations);
6426 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6427 &DAG.getTarget().Options))
6428 return GetNegatedExpression(N10, DAG, LegalOperations);
6432 // FSUB -> FMA combines:
6433 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6434 DAG.getTarget().Options.UnsafeFPMath) &&
6435 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6436 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6438 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6439 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6440 return DAG.getNode(ISD::FMA, dl, VT,
6441 N0.getOperand(0), N0.getOperand(1),
6442 DAG.getNode(ISD::FNEG, dl, VT, N1));
6444 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6445 // Note: Commutes FSUB operands.
6446 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6447 return DAG.getNode(ISD::FMA, dl, VT,
6448 DAG.getNode(ISD::FNEG, dl, VT,
6450 N1.getOperand(1), N0);
6452 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6453 if (N0.getOpcode() == ISD::FNEG &&
6454 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6455 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6456 SDValue N00 = N0.getOperand(0).getOperand(0);
6457 SDValue N01 = N0.getOperand(0).getOperand(1);
6458 return DAG.getNode(ISD::FMA, dl, VT,
6459 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6460 DAG.getNode(ISD::FNEG, dl, VT, N1));
6467 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6468 SDValue N0 = N->getOperand(0);
6469 SDValue N1 = N->getOperand(1);
6470 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6471 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6472 EVT VT = N->getValueType(0);
6473 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6476 if (VT.isVector()) {
6477 SDValue FoldedVOp = SimplifyVBinOp(N);
6478 if (FoldedVOp.getNode()) return FoldedVOp;
6481 // fold (fmul c1, c2) -> c1*c2
6483 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6484 // canonicalize constant to RHS
6485 if (N0CFP && !N1CFP)
6486 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6487 // fold (fmul A, 0) -> 0
6488 if (DAG.getTarget().Options.UnsafeFPMath &&
6489 N1CFP && N1CFP->getValueAPF().isZero())
6491 // fold (fmul A, 0) -> 0, vector edition.
6492 if (DAG.getTarget().Options.UnsafeFPMath &&
6493 ISD::isBuildVectorAllZeros(N1.getNode()))
6495 // fold (fmul A, 1.0) -> A
6496 if (N1CFP && N1CFP->isExactlyValue(1.0))
6498 // fold (fmul X, 2.0) -> (fadd X, X)
6499 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6500 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6501 // fold (fmul X, -1.0) -> (fneg X)
6502 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6503 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6504 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6506 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6507 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6508 &DAG.getTarget().Options)) {
6509 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6510 &DAG.getTarget().Options)) {
6511 // Both can be negated for free, check to see if at least one is cheaper
6513 if (LHSNeg == 2 || RHSNeg == 2)
6514 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6515 GetNegatedExpression(N0, DAG, LegalOperations),
6516 GetNegatedExpression(N1, DAG, LegalOperations));
6520 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6521 if (DAG.getTarget().Options.UnsafeFPMath &&
6522 N1CFP && N0.getOpcode() == ISD::FMUL &&
6523 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6524 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6525 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6526 N0.getOperand(1), N1));
6531 SDValue DAGCombiner::visitFMA(SDNode *N) {
6532 SDValue N0 = N->getOperand(0);
6533 SDValue N1 = N->getOperand(1);
6534 SDValue N2 = N->getOperand(2);
6535 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6536 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6537 EVT VT = N->getValueType(0);
6540 if (DAG.getTarget().Options.UnsafeFPMath) {
6541 if (N0CFP && N0CFP->isZero())
6543 if (N1CFP && N1CFP->isZero())
6546 if (N0CFP && N0CFP->isExactlyValue(1.0))
6547 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6548 if (N1CFP && N1CFP->isExactlyValue(1.0))
6549 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6551 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6552 if (N0CFP && !N1CFP)
6553 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6555 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6556 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6557 N2.getOpcode() == ISD::FMUL &&
6558 N0 == N2.getOperand(0) &&
6559 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6560 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6561 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6565 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6566 if (DAG.getTarget().Options.UnsafeFPMath &&
6567 N0.getOpcode() == ISD::FMUL && N1CFP &&
6568 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6569 return DAG.getNode(ISD::FMA, dl, VT,
6571 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6575 // (fma x, 1, y) -> (fadd x, y)
6576 // (fma x, -1, y) -> (fadd (fneg x), y)
6578 if (N1CFP->isExactlyValue(1.0))
6579 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6581 if (N1CFP->isExactlyValue(-1.0) &&
6582 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6583 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6584 AddToWorkList(RHSNeg.getNode());
6585 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6589 // (fma x, c, x) -> (fmul x, (c+1))
6590 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6591 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6592 DAG.getNode(ISD::FADD, dl, VT,
6593 N1, DAG.getConstantFP(1.0, VT)));
6595 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6596 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6597 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6598 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6599 DAG.getNode(ISD::FADD, dl, VT,
6600 N1, DAG.getConstantFP(-1.0, VT)));
6606 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6607 SDValue N0 = N->getOperand(0);
6608 SDValue N1 = N->getOperand(1);
6609 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6610 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6611 EVT VT = N->getValueType(0);
6612 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6615 if (VT.isVector()) {
6616 SDValue FoldedVOp = SimplifyVBinOp(N);
6617 if (FoldedVOp.getNode()) return FoldedVOp;
6620 // fold (fdiv c1, c2) -> c1/c2
6622 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6624 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6625 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6626 // Compute the reciprocal 1.0 / c2.
6627 APFloat N1APF = N1CFP->getValueAPF();
6628 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6629 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6630 // Only do the transform if the reciprocal is a legal fp immediate that
6631 // isn't too nasty (eg NaN, denormal, ...).
6632 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6633 (!LegalOperations ||
6634 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6635 // backend)... we should handle this gracefully after Legalize.
6636 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6637 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6638 TLI.isFPImmLegal(Recip, VT)))
6639 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6640 DAG.getConstantFP(Recip, VT));
6643 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6644 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6645 &DAG.getTarget().Options)) {
6646 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6647 &DAG.getTarget().Options)) {
6648 // Both can be negated for free, check to see if at least one is cheaper
6650 if (LHSNeg == 2 || RHSNeg == 2)
6651 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6652 GetNegatedExpression(N0, DAG, LegalOperations),
6653 GetNegatedExpression(N1, DAG, LegalOperations));
6660 SDValue DAGCombiner::visitFREM(SDNode *N) {
6661 SDValue N0 = N->getOperand(0);
6662 SDValue N1 = N->getOperand(1);
6663 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6664 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6665 EVT VT = N->getValueType(0);
6667 // fold (frem c1, c2) -> fmod(c1,c2)
6669 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6674 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6675 SDValue N0 = N->getOperand(0);
6676 SDValue N1 = N->getOperand(1);
6677 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6678 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6679 EVT VT = N->getValueType(0);
6681 if (N0CFP && N1CFP) // Constant fold
6682 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6685 const APFloat& V = N1CFP->getValueAPF();
6686 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6687 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6688 if (!V.isNegative()) {
6689 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6690 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6692 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6693 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6694 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6698 // copysign(fabs(x), y) -> copysign(x, y)
6699 // copysign(fneg(x), y) -> copysign(x, y)
6700 // copysign(copysign(x,z), y) -> copysign(x, y)
6701 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6702 N0.getOpcode() == ISD::FCOPYSIGN)
6703 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6704 N0.getOperand(0), N1);
6706 // copysign(x, abs(y)) -> abs(x)
6707 if (N1.getOpcode() == ISD::FABS)
6708 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6710 // copysign(x, copysign(y,z)) -> copysign(x, z)
6711 if (N1.getOpcode() == ISD::FCOPYSIGN)
6712 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6713 N0, N1.getOperand(1));
6715 // copysign(x, fp_extend(y)) -> copysign(x, y)
6716 // copysign(x, fp_round(y)) -> copysign(x, y)
6717 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6718 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6719 N0, N1.getOperand(0));
6724 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6725 SDValue N0 = N->getOperand(0);
6726 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6727 EVT VT = N->getValueType(0);
6728 EVT OpVT = N0.getValueType();
6730 // fold (sint_to_fp c1) -> c1fp
6732 // ...but only if the target supports immediate floating-point values
6733 (!LegalOperations ||
6734 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6735 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6737 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6738 // but UINT_TO_FP is legal on this target, try to convert.
6739 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6740 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6741 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6742 if (DAG.SignBitIsZero(N0))
6743 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6746 // The next optimizations are desirable only if SELECT_CC can be lowered.
6747 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6748 // having to say they don't support SELECT_CC on every type the DAG knows
6749 // about, since there is no way to mark an opcode illegal at all value types
6750 // (See also visitSELECT)
6751 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6752 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6753 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6755 (!LegalOperations ||
6756 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6758 { N0.getOperand(0), N0.getOperand(1),
6759 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6761 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6764 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6765 // (select_cc x, y, 1.0, 0.0,, cc)
6766 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6767 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6768 (!LegalOperations ||
6769 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6771 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6772 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6773 N0.getOperand(0).getOperand(2) };
6774 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6781 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6782 SDValue N0 = N->getOperand(0);
6783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6784 EVT VT = N->getValueType(0);
6785 EVT OpVT = N0.getValueType();
6787 // fold (uint_to_fp c1) -> c1fp
6789 // ...but only if the target supports immediate floating-point values
6790 (!LegalOperations ||
6791 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6792 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6794 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6795 // but SINT_TO_FP is legal on this target, try to convert.
6796 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6797 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6798 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6799 if (DAG.SignBitIsZero(N0))
6800 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6803 // The next optimizations are desirable only if SELECT_CC can be lowered.
6804 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6805 // having to say they don't support SELECT_CC on every type the DAG knows
6806 // about, since there is no way to mark an opcode illegal at all value types
6807 // (See also visitSELECT)
6808 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6809 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6811 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6812 (!LegalOperations ||
6813 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6815 { N0.getOperand(0), N0.getOperand(1),
6816 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6818 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6825 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6826 SDValue N0 = N->getOperand(0);
6827 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6828 EVT VT = N->getValueType(0);
6830 // fold (fp_to_sint c1fp) -> c1
6832 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6837 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6838 SDValue N0 = N->getOperand(0);
6839 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6840 EVT VT = N->getValueType(0);
6842 // fold (fp_to_uint c1fp) -> c1
6844 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6849 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6850 SDValue N0 = N->getOperand(0);
6851 SDValue N1 = N->getOperand(1);
6852 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6853 EVT VT = N->getValueType(0);
6855 // fold (fp_round c1fp) -> c1fp
6857 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6859 // fold (fp_round (fp_extend x)) -> x
6860 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6861 return N0.getOperand(0);
6863 // fold (fp_round (fp_round x)) -> (fp_round x)
6864 if (N0.getOpcode() == ISD::FP_ROUND) {
6865 // This is a value preserving truncation if both round's are.
6866 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6867 N0.getNode()->getConstantOperandVal(1) == 1;
6868 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6869 DAG.getIntPtrConstant(IsTrunc));
6872 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6873 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6874 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6875 N0.getOperand(0), N1);
6876 AddToWorkList(Tmp.getNode());
6877 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6878 Tmp, N0.getOperand(1));
6884 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6885 SDValue N0 = N->getOperand(0);
6886 EVT VT = N->getValueType(0);
6887 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6888 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6890 // fold (fp_round_inreg c1fp) -> c1fp
6891 if (N0CFP && isTypeLegal(EVT)) {
6892 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6893 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6899 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6900 SDValue N0 = N->getOperand(0);
6901 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6902 EVT VT = N->getValueType(0);
6904 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6905 if (N->hasOneUse() &&
6906 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6909 // fold (fp_extend c1fp) -> c1fp
6911 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6913 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6915 if (N0.getOpcode() == ISD::FP_ROUND
6916 && N0.getNode()->getConstantOperandVal(1) == 1) {
6917 SDValue In = N0.getOperand(0);
6918 if (In.getValueType() == VT) return In;
6919 if (VT.bitsLT(In.getValueType()))
6920 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6921 In, N0.getOperand(1));
6922 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6925 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6926 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6927 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6928 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6929 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6930 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6932 LN0->getBasePtr(), N0.getValueType(),
6933 LN0->getMemOperand());
6934 CombineTo(N, ExtLoad);
6935 CombineTo(N0.getNode(),
6936 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6937 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6938 ExtLoad.getValue(1));
6939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6945 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6946 SDValue N0 = N->getOperand(0);
6947 EVT VT = N->getValueType(0);
6949 if (VT.isVector()) {
6950 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6951 if (FoldedVOp.getNode()) return FoldedVOp;
6954 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6955 &DAG.getTarget().Options))
6956 return GetNegatedExpression(N0, DAG, LegalOperations);
6958 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6959 // constant pool values.
6960 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6962 N0.getNode()->hasOneUse() &&
6963 N0.getOperand(0).getValueType().isInteger()) {
6964 SDValue Int = N0.getOperand(0);
6965 EVT IntVT = Int.getValueType();
6966 if (IntVT.isInteger() && !IntVT.isVector()) {
6967 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6968 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6969 AddToWorkList(Int.getNode());
6970 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6975 // (fneg (fmul c, x)) -> (fmul -c, x)
6976 if (N0.getOpcode() == ISD::FMUL) {
6977 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6979 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6981 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6988 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6989 SDValue N0 = N->getOperand(0);
6990 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6991 EVT VT = N->getValueType(0);
6993 // fold (fceil c1) -> fceil(c1)
6995 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7000 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7001 SDValue N0 = N->getOperand(0);
7002 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7003 EVT VT = N->getValueType(0);
7005 // fold (ftrunc c1) -> ftrunc(c1)
7007 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7012 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7013 SDValue N0 = N->getOperand(0);
7014 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7015 EVT VT = N->getValueType(0);
7017 // fold (ffloor c1) -> ffloor(c1)
7019 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7024 SDValue DAGCombiner::visitFABS(SDNode *N) {
7025 SDValue N0 = N->getOperand(0);
7026 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7027 EVT VT = N->getValueType(0);
7029 if (VT.isVector()) {
7030 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7031 if (FoldedVOp.getNode()) return FoldedVOp;
7034 // fold (fabs c1) -> fabs(c1)
7036 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7037 // fold (fabs (fabs x)) -> (fabs x)
7038 if (N0.getOpcode() == ISD::FABS)
7039 return N->getOperand(0);
7040 // fold (fabs (fneg x)) -> (fabs x)
7041 // fold (fabs (fcopysign x, y)) -> (fabs x)
7042 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7043 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7045 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7046 // constant pool values.
7047 if (!TLI.isFAbsFree(VT) &&
7048 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7049 N0.getOperand(0).getValueType().isInteger() &&
7050 !N0.getOperand(0).getValueType().isVector()) {
7051 SDValue Int = N0.getOperand(0);
7052 EVT IntVT = Int.getValueType();
7053 if (IntVT.isInteger() && !IntVT.isVector()) {
7054 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7055 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7056 AddToWorkList(Int.getNode());
7057 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7058 N->getValueType(0), Int);
7065 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7066 SDValue Chain = N->getOperand(0);
7067 SDValue N1 = N->getOperand(1);
7068 SDValue N2 = N->getOperand(2);
7070 // If N is a constant we could fold this into a fallthrough or unconditional
7071 // branch. However that doesn't happen very often in normal code, because
7072 // Instcombine/SimplifyCFG should have handled the available opportunities.
7073 // If we did this folding here, it would be necessary to update the
7074 // MachineBasicBlock CFG, which is awkward.
7076 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7078 if (N1.getOpcode() == ISD::SETCC &&
7079 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7080 N1.getOperand(0).getValueType())) {
7081 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7082 Chain, N1.getOperand(2),
7083 N1.getOperand(0), N1.getOperand(1), N2);
7086 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7087 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7088 (N1.getOperand(0).hasOneUse() &&
7089 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7091 if (N1.getOpcode() == ISD::TRUNCATE) {
7092 // Look pass the truncate.
7093 Trunc = N1.getNode();
7094 N1 = N1.getOperand(0);
7097 // Match this pattern so that we can generate simpler code:
7100 // %b = and i32 %a, 2
7101 // %c = srl i32 %b, 1
7102 // brcond i32 %c ...
7107 // %b = and i32 %a, 2
7108 // %c = setcc eq %b, 0
7111 // This applies only when the AND constant value has one bit set and the
7112 // SRL constant is equal to the log2 of the AND constant. The back-end is
7113 // smart enough to convert the result into a TEST/JMP sequence.
7114 SDValue Op0 = N1.getOperand(0);
7115 SDValue Op1 = N1.getOperand(1);
7117 if (Op0.getOpcode() == ISD::AND &&
7118 Op1.getOpcode() == ISD::Constant) {
7119 SDValue AndOp1 = Op0.getOperand(1);
7121 if (AndOp1.getOpcode() == ISD::Constant) {
7122 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7124 if (AndConst.isPowerOf2() &&
7125 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7127 DAG.getSetCC(SDLoc(N),
7128 getSetCCResultType(Op0.getValueType()),
7129 Op0, DAG.getConstant(0, Op0.getValueType()),
7132 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7133 MVT::Other, Chain, SetCC, N2);
7134 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7135 // will convert it back to (X & C1) >> C2.
7136 CombineTo(N, NewBRCond, false);
7137 // Truncate is dead.
7139 removeFromWorkList(Trunc);
7140 DAG.DeleteNode(Trunc);
7142 // Replace the uses of SRL with SETCC
7143 WorkListRemover DeadNodes(*this);
7144 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7145 removeFromWorkList(N1.getNode());
7146 DAG.DeleteNode(N1.getNode());
7147 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7153 // Restore N1 if the above transformation doesn't match.
7154 N1 = N->getOperand(1);
7157 // Transform br(xor(x, y)) -> br(x != y)
7158 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7159 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7160 SDNode *TheXor = N1.getNode();
7161 SDValue Op0 = TheXor->getOperand(0);
7162 SDValue Op1 = TheXor->getOperand(1);
7163 if (Op0.getOpcode() == Op1.getOpcode()) {
7164 // Avoid missing important xor optimizations.
7165 SDValue Tmp = visitXOR(TheXor);
7166 if (Tmp.getNode()) {
7167 if (Tmp.getNode() != TheXor) {
7168 DEBUG(dbgs() << "\nReplacing.8 ";
7170 dbgs() << "\nWith: ";
7171 Tmp.getNode()->dump(&DAG);
7173 WorkListRemover DeadNodes(*this);
7174 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7175 removeFromWorkList(TheXor);
7176 DAG.DeleteNode(TheXor);
7177 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7178 MVT::Other, Chain, Tmp, N2);
7181 // visitXOR has changed XOR's operands or replaced the XOR completely,
7183 return SDValue(N, 0);
7187 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7189 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7190 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7191 Op0.getOpcode() == ISD::XOR) {
7192 TheXor = Op0.getNode();
7196 EVT SetCCVT = N1.getValueType();
7198 SetCCVT = getSetCCResultType(SetCCVT);
7199 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7202 Equal ? ISD::SETEQ : ISD::SETNE);
7203 // Replace the uses of XOR with SETCC
7204 WorkListRemover DeadNodes(*this);
7205 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7206 removeFromWorkList(N1.getNode());
7207 DAG.DeleteNode(N1.getNode());
7208 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7209 MVT::Other, Chain, SetCC, N2);
7216 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7218 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7219 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7220 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7222 // If N is a constant we could fold this into a fallthrough or unconditional
7223 // branch. However that doesn't happen very often in normal code, because
7224 // Instcombine/SimplifyCFG should have handled the available opportunities.
7225 // If we did this folding here, it would be necessary to update the
7226 // MachineBasicBlock CFG, which is awkward.
7228 // Use SimplifySetCC to simplify SETCC's.
7229 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7230 CondLHS, CondRHS, CC->get(), SDLoc(N),
7232 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7234 // fold to a simpler setcc
7235 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7236 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7237 N->getOperand(0), Simp.getOperand(2),
7238 Simp.getOperand(0), Simp.getOperand(1),
7244 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7245 /// uses N as its base pointer and that N may be folded in the load / store
7246 /// addressing mode.
7247 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7249 const TargetLowering &TLI) {
7251 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7252 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7254 VT = Use->getValueType(0);
7255 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7256 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7258 VT = ST->getValue().getValueType();
7262 TargetLowering::AddrMode AM;
7263 if (N->getOpcode() == ISD::ADD) {
7264 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7267 AM.BaseOffs = Offset->getSExtValue();
7271 } else if (N->getOpcode() == ISD::SUB) {
7272 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7275 AM.BaseOffs = -Offset->getSExtValue();
7282 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7285 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7286 /// pre-indexed load / store when the base pointer is an add or subtract
7287 /// and it has other uses besides the load / store. After the
7288 /// transformation, the new indexed load / store has effectively folded
7289 /// the add / subtract in and all of its other uses are redirected to the
7290 /// new load / store.
7291 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7292 if (Level < AfterLegalizeDAG)
7298 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7299 if (LD->isIndexed())
7301 VT = LD->getMemoryVT();
7302 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7303 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7305 Ptr = LD->getBasePtr();
7306 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7307 if (ST->isIndexed())
7309 VT = ST->getMemoryVT();
7310 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7311 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7313 Ptr = ST->getBasePtr();
7319 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7320 // out. There is no reason to make this a preinc/predec.
7321 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7322 Ptr.getNode()->hasOneUse())
7325 // Ask the target to do addressing mode selection.
7328 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7329 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7332 // Backends without true r+i pre-indexed forms may need to pass a
7333 // constant base with a variable offset so that constant coercion
7334 // will work with the patterns in canonical form.
7335 bool Swapped = false;
7336 if (isa<ConstantSDNode>(BasePtr)) {
7337 std::swap(BasePtr, Offset);
7341 // Don't create a indexed load / store with zero offset.
7342 if (isa<ConstantSDNode>(Offset) &&
7343 cast<ConstantSDNode>(Offset)->isNullValue())
7346 // Try turning it into a pre-indexed load / store except when:
7347 // 1) The new base ptr is a frame index.
7348 // 2) If N is a store and the new base ptr is either the same as or is a
7349 // predecessor of the value being stored.
7350 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7351 // that would create a cycle.
7352 // 4) All uses are load / store ops that use it as old base ptr.
7354 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7355 // (plus the implicit offset) to a register to preinc anyway.
7356 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7361 SDValue Val = cast<StoreSDNode>(N)->getValue();
7362 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7366 // If the offset is a constant, there may be other adds of constants that
7367 // can be folded with this one. We should do this to avoid having to keep
7368 // a copy of the original base pointer.
7369 SmallVector<SDNode *, 16> OtherUses;
7370 if (isa<ConstantSDNode>(Offset))
7371 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7372 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7374 if (Use == Ptr.getNode())
7377 if (Use->isPredecessorOf(N))
7380 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7385 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7386 if (Op1.getNode() == BasePtr.getNode())
7387 std::swap(Op0, Op1);
7388 assert(Op0.getNode() == BasePtr.getNode() &&
7389 "Use of ADD/SUB but not an operand");
7391 if (!isa<ConstantSDNode>(Op1)) {
7396 // FIXME: In some cases, we can be smarter about this.
7397 if (Op1.getValueType() != Offset.getValueType()) {
7402 OtherUses.push_back(Use);
7406 std::swap(BasePtr, Offset);
7408 // Now check for #3 and #4.
7409 bool RealUse = false;
7411 // Caches for hasPredecessorHelper
7412 SmallPtrSet<const SDNode *, 32> Visited;
7413 SmallVector<const SDNode *, 16> Worklist;
7415 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7416 E = Ptr.getNode()->use_end(); I != E; ++I) {
7420 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7423 // If Ptr may be folded in addressing mode of other use, then it's
7424 // not profitable to do this transformation.
7425 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7434 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7435 BasePtr, Offset, AM);
7437 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7438 BasePtr, Offset, AM);
7441 DEBUG(dbgs() << "\nReplacing.4 ";
7443 dbgs() << "\nWith: ";
7444 Result.getNode()->dump(&DAG);
7446 WorkListRemover DeadNodes(*this);
7448 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7451 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7454 // Finally, since the node is now dead, remove it from the graph.
7458 std::swap(BasePtr, Offset);
7460 // Replace other uses of BasePtr that can be updated to use Ptr
7461 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7462 unsigned OffsetIdx = 1;
7463 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7465 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7466 BasePtr.getNode() && "Expected BasePtr operand");
7468 // We need to replace ptr0 in the following expression:
7469 // x0 * offset0 + y0 * ptr0 = t0
7471 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7473 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7474 // indexed load/store and the expresion that needs to be re-written.
7476 // Therefore, we have:
7477 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7479 ConstantSDNode *CN =
7480 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7482 APInt Offset0 = CN->getAPIntValue();
7483 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7485 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7486 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7487 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7488 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7490 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7492 APInt CNV = Offset0;
7493 if (X0 < 0) CNV = -CNV;
7494 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7495 else CNV = CNV - Offset1;
7497 // We can now generate the new expression.
7498 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7499 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7501 SDValue NewUse = DAG.getNode(Opcode,
7502 SDLoc(OtherUses[i]),
7503 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7504 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7505 removeFromWorkList(OtherUses[i]);
7506 DAG.DeleteNode(OtherUses[i]);
7509 // Replace the uses of Ptr with uses of the updated base value.
7510 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7511 removeFromWorkList(Ptr.getNode());
7512 DAG.DeleteNode(Ptr.getNode());
7517 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7518 /// add / sub of the base pointer node into a post-indexed load / store.
7519 /// The transformation folded the add / subtract into the new indexed
7520 /// load / store effectively and all of its uses are redirected to the
7521 /// new load / store.
7522 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7523 if (Level < AfterLegalizeDAG)
7529 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7530 if (LD->isIndexed())
7532 VT = LD->getMemoryVT();
7533 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7534 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7536 Ptr = LD->getBasePtr();
7537 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7538 if (ST->isIndexed())
7540 VT = ST->getMemoryVT();
7541 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7542 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7544 Ptr = ST->getBasePtr();
7550 if (Ptr.getNode()->hasOneUse())
7553 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7554 E = Ptr.getNode()->use_end(); I != E; ++I) {
7557 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7562 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7563 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7564 // Don't create a indexed load / store with zero offset.
7565 if (isa<ConstantSDNode>(Offset) &&
7566 cast<ConstantSDNode>(Offset)->isNullValue())
7569 // Try turning it into a post-indexed load / store except when
7570 // 1) All uses are load / store ops that use it as base ptr (and
7571 // it may be folded as addressing mmode).
7572 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7573 // nor a successor of N. Otherwise, if Op is folded that would
7576 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7580 bool TryNext = false;
7581 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7582 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7584 if (Use == Ptr.getNode())
7587 // If all the uses are load / store addresses, then don't do the
7589 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7590 bool RealUse = false;
7591 for (SDNode::use_iterator III = Use->use_begin(),
7592 EEE = Use->use_end(); III != EEE; ++III) {
7593 SDNode *UseUse = *III;
7594 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7609 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7610 SDValue Result = isLoad
7611 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7612 BasePtr, Offset, AM)
7613 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7614 BasePtr, Offset, AM);
7617 DEBUG(dbgs() << "\nReplacing.5 ";
7619 dbgs() << "\nWith: ";
7620 Result.getNode()->dump(&DAG);
7622 WorkListRemover DeadNodes(*this);
7624 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7625 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7627 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7630 // Finally, since the node is now dead, remove it from the graph.
7633 // Replace the uses of Use with uses of the updated base value.
7634 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7635 Result.getValue(isLoad ? 1 : 0));
7636 removeFromWorkList(Op);
7646 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7647 LoadSDNode *LD = cast<LoadSDNode>(N);
7648 SDValue Chain = LD->getChain();
7649 SDValue Ptr = LD->getBasePtr();
7651 // If load is not volatile and there are no uses of the loaded value (and
7652 // the updated indexed value in case of indexed loads), change uses of the
7653 // chain value into uses of the chain input (i.e. delete the dead load).
7654 if (!LD->isVolatile()) {
7655 if (N->getValueType(1) == MVT::Other) {
7657 if (!N->hasAnyUseOfValue(0)) {
7658 // It's not safe to use the two value CombineTo variant here. e.g.
7659 // v1, chain2 = load chain1, loc
7660 // v2, chain3 = load chain2, loc
7662 // Now we replace use of chain2 with chain1. This makes the second load
7663 // isomorphic to the one we are deleting, and thus makes this load live.
7664 DEBUG(dbgs() << "\nReplacing.6 ";
7666 dbgs() << "\nWith chain: ";
7667 Chain.getNode()->dump(&DAG);
7669 WorkListRemover DeadNodes(*this);
7670 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7672 if (N->use_empty()) {
7673 removeFromWorkList(N);
7677 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7681 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7682 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7683 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7684 DEBUG(dbgs() << "\nReplacing.7 ";
7686 dbgs() << "\nWith: ";
7687 Undef.getNode()->dump(&DAG);
7688 dbgs() << " and 2 other values\n");
7689 WorkListRemover DeadNodes(*this);
7690 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7691 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7692 DAG.getUNDEF(N->getValueType(1)));
7693 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7694 removeFromWorkList(N);
7696 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7701 // If this load is directly stored, replace the load value with the stored
7703 // TODO: Handle store large -> read small portion.
7704 // TODO: Handle TRUNCSTORE/LOADEXT
7705 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7706 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7707 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7708 if (PrevST->getBasePtr() == Ptr &&
7709 PrevST->getValue().getValueType() == N->getValueType(0))
7710 return CombineTo(N, Chain.getOperand(1), Chain);
7714 // Try to infer better alignment information than the load already has.
7715 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7716 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7717 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7719 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7720 LD->getValueType(0),
7721 Chain, Ptr, LD->getPointerInfo(),
7723 LD->isVolatile(), LD->isNonTemporal(), Align,
7725 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7730 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7731 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7732 if (UseAA && LD->isUnindexed()) {
7733 // Walk up chain skipping non-aliasing memory nodes.
7734 SDValue BetterChain = FindBetterChain(N, Chain);
7736 // If there is a better chain.
7737 if (Chain != BetterChain) {
7740 // Replace the chain to void dependency.
7741 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7742 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7743 BetterChain, Ptr, LD->getMemOperand());
7745 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7746 LD->getValueType(0),
7747 BetterChain, Ptr, LD->getMemoryVT(),
7748 LD->getMemOperand());
7751 // Create token factor to keep old chain connected.
7752 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7753 MVT::Other, Chain, ReplLoad.getValue(1));
7755 // Make sure the new and old chains are cleaned up.
7756 AddToWorkList(Token.getNode());
7758 // Replace uses with load result and token factor. Don't add users
7760 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7764 // Try transforming N to an indexed load.
7765 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7766 return SDValue(N, 0);
7768 // Try to slice up N to more direct loads if the slices are mapped to
7769 // different register banks or pairing can take place.
7771 return SDValue(N, 0);
7777 /// \brief Helper structure used to slice a load in smaller loads.
7778 /// Basically a slice is obtained from the following sequence:
7779 /// Origin = load Ty1, Base
7780 /// Shift = srl Ty1 Origin, CstTy Amount
7781 /// Inst = trunc Shift to Ty2
7783 /// Then, it will be rewriten into:
7784 /// Slice = load SliceTy, Base + SliceOffset
7785 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7787 /// SliceTy is deduced from the number of bits that are actually used to
7789 struct LoadedSlice {
7790 /// \brief Helper structure used to compute the cost of a slice.
7792 /// Are we optimizing for code size.
7797 unsigned CrossRegisterBanksCopies;
7801 Cost(bool ForCodeSize = false)
7802 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7803 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7805 /// \brief Get the cost of one isolated slice.
7806 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7807 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7808 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7809 EVT TruncType = LS.Inst->getValueType(0);
7810 EVT LoadedType = LS.getLoadedType();
7811 if (TruncType != LoadedType &&
7812 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7816 /// \brief Account for slicing gain in the current cost.
7817 /// Slicing provide a few gains like removing a shift or a
7818 /// truncate. This method allows to grow the cost of the original
7819 /// load with the gain from this slice.
7820 void addSliceGain(const LoadedSlice &LS) {
7821 // Each slice saves a truncate.
7822 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7823 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7824 LS.Inst->getOperand(0).getValueType()))
7826 // If there is a shift amount, this slice gets rid of it.
7829 // If this slice can merge a cross register bank copy, account for it.
7830 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7831 ++CrossRegisterBanksCopies;
7834 Cost &operator+=(const Cost &RHS) {
7836 Truncates += RHS.Truncates;
7837 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7843 bool operator==(const Cost &RHS) const {
7844 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7845 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7846 ZExts == RHS.ZExts && Shift == RHS.Shift;
7849 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7851 bool operator<(const Cost &RHS) const {
7852 // Assume cross register banks copies are as expensive as loads.
7853 // FIXME: Do we want some more target hooks?
7854 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7855 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7856 // Unless we are optimizing for code size, consider the
7857 // expensive operation first.
7858 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7859 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7860 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7861 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7864 bool operator>(const Cost &RHS) const { return RHS < *this; }
7866 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7868 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7870 // The last instruction that represent the slice. This should be a
7871 // truncate instruction.
7873 // The original load instruction.
7875 // The right shift amount in bits from the original load.
7877 // The DAG from which Origin came from.
7878 // This is used to get some contextual information about legal types, etc.
7881 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7882 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7883 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7885 LoadedSlice(const LoadedSlice &LS)
7886 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7888 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7889 /// \return Result is \p BitWidth and has used bits set to 1 and
7890 /// not used bits set to 0.
7891 APInt getUsedBits() const {
7892 // Reproduce the trunc(lshr) sequence:
7893 // - Start from the truncated value.
7894 // - Zero extend to the desired bit width.
7896 assert(Origin && "No original load to compare against.");
7897 unsigned BitWidth = Origin->getValueSizeInBits(0);
7898 assert(Inst && "This slice is not bound to an instruction");
7899 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7900 "Extracted slice is bigger than the whole type!");
7901 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7902 UsedBits.setAllBits();
7903 UsedBits = UsedBits.zext(BitWidth);
7908 /// \brief Get the size of the slice to be loaded in bytes.
7909 unsigned getLoadedSize() const {
7910 unsigned SliceSize = getUsedBits().countPopulation();
7911 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7912 return SliceSize / 8;
7915 /// \brief Get the type that will be loaded for this slice.
7916 /// Note: This may not be the final type for the slice.
7917 EVT getLoadedType() const {
7918 assert(DAG && "Missing context");
7919 LLVMContext &Ctxt = *DAG->getContext();
7920 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7923 /// \brief Get the alignment of the load used for this slice.
7924 unsigned getAlignment() const {
7925 unsigned Alignment = Origin->getAlignment();
7926 unsigned Offset = getOffsetFromBase();
7928 Alignment = MinAlign(Alignment, Alignment + Offset);
7932 /// \brief Check if this slice can be rewritten with legal operations.
7933 bool isLegal() const {
7934 // An invalid slice is not legal.
7935 if (!Origin || !Inst || !DAG)
7938 // Offsets are for indexed load only, we do not handle that.
7939 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7942 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7944 // Check that the type is legal.
7945 EVT SliceType = getLoadedType();
7946 if (!TLI.isTypeLegal(SliceType))
7949 // Check that the load is legal for this type.
7950 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7953 // Check that the offset can be computed.
7954 // 1. Check its type.
7955 EVT PtrType = Origin->getBasePtr().getValueType();
7956 if (PtrType == MVT::Untyped || PtrType.isExtended())
7959 // 2. Check that it fits in the immediate.
7960 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7963 // 3. Check that the computation is legal.
7964 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7967 // Check that the zext is legal if it needs one.
7968 EVT TruncateType = Inst->getValueType(0);
7969 if (TruncateType != SliceType &&
7970 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7976 /// \brief Get the offset in bytes of this slice in the original chunk of
7978 /// \pre DAG != NULL.
7979 uint64_t getOffsetFromBase() const {
7980 assert(DAG && "Missing context.");
7982 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7983 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7984 uint64_t Offset = Shift / 8;
7985 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7986 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7987 "The size of the original loaded type is not a multiple of a"
7989 // If Offset is bigger than TySizeInBytes, it means we are loading all
7990 // zeros. This should have been optimized before in the process.
7991 assert(TySizeInBytes > Offset &&
7992 "Invalid shift amount for given loaded size");
7994 Offset = TySizeInBytes - Offset - getLoadedSize();
7998 /// \brief Generate the sequence of instructions to load the slice
7999 /// represented by this object and redirect the uses of this slice to
8000 /// this new sequence of instructions.
8001 /// \pre this->Inst && this->Origin are valid Instructions and this
8002 /// object passed the legal check: LoadedSlice::isLegal returned true.
8003 /// \return The last instruction of the sequence used to load the slice.
8004 SDValue loadSlice() const {
8005 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8006 const SDValue &OldBaseAddr = Origin->getBasePtr();
8007 SDValue BaseAddr = OldBaseAddr;
8008 // Get the offset in that chunk of bytes w.r.t. the endianess.
8009 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8010 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8012 // BaseAddr = BaseAddr + Offset.
8013 EVT ArithType = BaseAddr.getValueType();
8014 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8015 DAG->getConstant(Offset, ArithType));
8018 // Create the type of the loaded slice according to its size.
8019 EVT SliceType = getLoadedType();
8021 // Create the load for the slice.
8022 SDValue LastInst = DAG->getLoad(
8023 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8024 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8025 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8026 // If the final type is not the same as the loaded type, this means that
8027 // we have to pad with zero. Create a zero extend for that.
8028 EVT FinalType = Inst->getValueType(0);
8029 if (SliceType != FinalType)
8031 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8035 /// \brief Check if this slice can be merged with an expensive cross register
8036 /// bank copy. E.g.,
8038 /// f = bitcast i32 i to float
8039 bool canMergeExpensiveCrossRegisterBankCopy() const {
8040 if (!Inst || !Inst->hasOneUse())
8042 SDNode *Use = *Inst->use_begin();
8043 if (Use->getOpcode() != ISD::BITCAST)
8045 assert(DAG && "Missing context");
8046 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8047 EVT ResVT = Use->getValueType(0);
8048 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8049 const TargetRegisterClass *ArgRC =
8050 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8051 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8054 // At this point, we know that we perform a cross-register-bank copy.
8055 // Check if it is expensive.
8056 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8057 // Assume bitcasts are cheap, unless both register classes do not
8058 // explicitly share a common sub class.
8059 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8062 // Check if it will be merged with the load.
8063 // 1. Check the alignment constraint.
8064 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8065 ResVT.getTypeForEVT(*DAG->getContext()));
8067 if (RequiredAlignment > getAlignment())
8070 // 2. Check that the load is a legal operation for that type.
8071 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8074 // 3. Check that we do not have a zext in the way.
8075 if (Inst->getValueType(0) != getLoadedType())
8083 /// \brief Sorts LoadedSlice according to their offset.
8084 struct LoadedSliceSorter {
8085 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8086 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8087 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8091 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8092 /// \p UsedBits looks like 0..0 1..1 0..0.
8093 static bool areUsedBitsDense(const APInt &UsedBits) {
8094 // If all the bits are one, this is dense!
8095 if (UsedBits.isAllOnesValue())
8098 // Get rid of the unused bits on the right.
8099 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8100 // Get rid of the unused bits on the left.
8101 if (NarrowedUsedBits.countLeadingZeros())
8102 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8103 // Check that the chunk of bits is completely used.
8104 return NarrowedUsedBits.isAllOnesValue();
8107 /// \brief Check whether or not \p First and \p Second are next to each other
8108 /// in memory. This means that there is no hole between the bits loaded
8109 /// by \p First and the bits loaded by \p Second.
8110 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8111 const LoadedSlice &Second) {
8112 assert(First.Origin == Second.Origin && First.Origin &&
8113 "Unable to match different memory origins.");
8114 APInt UsedBits = First.getUsedBits();
8115 assert((UsedBits & Second.getUsedBits()) == 0 &&
8116 "Slices are not supposed to overlap.");
8117 UsedBits |= Second.getUsedBits();
8118 return areUsedBitsDense(UsedBits);
8121 /// \brief Adjust the \p GlobalLSCost according to the target
8122 /// paring capabilities and the layout of the slices.
8123 /// \pre \p GlobalLSCost should account for at least as many loads as
8124 /// there is in the slices in \p LoadedSlices.
8125 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8126 LoadedSlice::Cost &GlobalLSCost) {
8127 unsigned NumberOfSlices = LoadedSlices.size();
8128 // If there is less than 2 elements, no pairing is possible.
8129 if (NumberOfSlices < 2)
8132 // Sort the slices so that elements that are likely to be next to each
8133 // other in memory are next to each other in the list.
8134 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8135 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8136 // First (resp. Second) is the first (resp. Second) potentially candidate
8137 // to be placed in a paired load.
8138 const LoadedSlice *First = NULL;
8139 const LoadedSlice *Second = NULL;
8140 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8141 // Set the beginning of the pair.
8144 Second = &LoadedSlices[CurrSlice];
8146 // If First is NULL, it means we start a new pair.
8147 // Get to the next slice.
8151 EVT LoadedType = First->getLoadedType();
8153 // If the types of the slices are different, we cannot pair them.
8154 if (LoadedType != Second->getLoadedType())
8157 // Check if the target supplies paired loads for this type.
8158 unsigned RequiredAlignment = 0;
8159 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8160 // move to the next pair, this type is hopeless.
8164 // Check if we meet the alignment requirement.
8165 if (RequiredAlignment > First->getAlignment())
8168 // Check that both loads are next to each other in memory.
8169 if (!areSlicesNextToEachOther(*First, *Second))
8172 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8173 --GlobalLSCost.Loads;
8174 // Move to the next pair.
8179 /// \brief Check the profitability of all involved LoadedSlice.
8180 /// Currently, it is considered profitable if there is exactly two
8181 /// involved slices (1) which are (2) next to each other in memory, and
8182 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8184 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8185 /// the elements themselves.
8187 /// FIXME: When the cost model will be mature enough, we can relax
8188 /// constraints (1) and (2).
8189 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8190 const APInt &UsedBits, bool ForCodeSize) {
8191 unsigned NumberOfSlices = LoadedSlices.size();
8192 if (StressLoadSlicing)
8193 return NumberOfSlices > 1;
8196 if (NumberOfSlices != 2)
8200 if (!areUsedBitsDense(UsedBits))
8204 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8205 // The original code has one big load.
8207 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8208 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8209 // Accumulate the cost of all the slices.
8210 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8211 GlobalSlicingCost += SliceCost;
8213 // Account as cost in the original configuration the gain obtained
8214 // with the current slices.
8215 OrigCost.addSliceGain(LS);
8218 // If the target supports paired load, adjust the cost accordingly.
8219 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8220 return OrigCost > GlobalSlicingCost;
8223 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8224 /// operations, split it in the various pieces being extracted.
8226 /// This sort of thing is introduced by SROA.
8227 /// This slicing takes care not to insert overlapping loads.
8228 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8229 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8230 if (Level < AfterLegalizeDAG)
8233 LoadSDNode *LD = cast<LoadSDNode>(N);
8234 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8235 !LD->getValueType(0).isInteger())
8238 // Keep track of already used bits to detect overlapping values.
8239 // In that case, we will just abort the transformation.
8240 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8242 SmallVector<LoadedSlice, 4> LoadedSlices;
8244 // Check if this load is used as several smaller chunks of bits.
8245 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8246 // of computation for each trunc.
8247 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8248 UI != UIEnd; ++UI) {
8249 // Skip the uses of the chain.
8250 if (UI.getUse().getResNo() != 0)
8256 // Check if this is a trunc(lshr).
8257 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8258 isa<ConstantSDNode>(User->getOperand(1))) {
8259 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8260 User = *User->use_begin();
8263 // At this point, User is a Truncate, iff we encountered, trunc or
8265 if (User->getOpcode() != ISD::TRUNCATE)
8268 // The width of the type must be a power of 2 and greater than 8-bits.
8269 // Otherwise the load cannot be represented in LLVM IR.
8270 // Moreover, if we shifted with a non-8-bits multiple, the slice
8271 // will be across several bytes. We do not support that.
8272 unsigned Width = User->getValueSizeInBits(0);
8273 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8276 // Build the slice for this chain of computations.
8277 LoadedSlice LS(User, LD, Shift, &DAG);
8278 APInt CurrentUsedBits = LS.getUsedBits();
8280 // Check if this slice overlaps with another.
8281 if ((CurrentUsedBits & UsedBits) != 0)
8283 // Update the bits used globally.
8284 UsedBits |= CurrentUsedBits;
8286 // Check if the new slice would be legal.
8290 // Record the slice.
8291 LoadedSlices.push_back(LS);
8294 // Abort slicing if it does not seem to be profitable.
8295 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8300 // Rewrite each chain to use an independent load.
8301 // By construction, each chain can be represented by a unique load.
8303 // Prepare the argument for the new token factor for all the slices.
8304 SmallVector<SDValue, 8> ArgChains;
8305 for (SmallVectorImpl<LoadedSlice>::const_iterator
8306 LSIt = LoadedSlices.begin(),
8307 LSItEnd = LoadedSlices.end();
8308 LSIt != LSItEnd; ++LSIt) {
8309 SDValue SliceInst = LSIt->loadSlice();
8310 CombineTo(LSIt->Inst, SliceInst, true);
8311 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8312 SliceInst = SliceInst.getOperand(0);
8313 assert(SliceInst->getOpcode() == ISD::LOAD &&
8314 "It takes more than a zext to get to the loaded slice!!");
8315 ArgChains.push_back(SliceInst.getValue(1));
8318 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8319 &ArgChains[0], ArgChains.size());
8320 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8324 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8325 /// load is having specific bytes cleared out. If so, return the byte size
8326 /// being masked out and the shift amount.
8327 static std::pair<unsigned, unsigned>
8328 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8329 std::pair<unsigned, unsigned> Result(0, 0);
8331 // Check for the structure we're looking for.
8332 if (V->getOpcode() != ISD::AND ||
8333 !isa<ConstantSDNode>(V->getOperand(1)) ||
8334 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8337 // Check the chain and pointer.
8338 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8339 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8341 // The store should be chained directly to the load or be an operand of a
8343 if (LD == Chain.getNode())
8345 else if (Chain->getOpcode() != ISD::TokenFactor)
8346 return Result; // Fail.
8349 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8350 if (Chain->getOperand(i).getNode() == LD) {
8354 if (!isOk) return Result;
8357 // This only handles simple types.
8358 if (V.getValueType() != MVT::i16 &&
8359 V.getValueType() != MVT::i32 &&
8360 V.getValueType() != MVT::i64)
8363 // Check the constant mask. Invert it so that the bits being masked out are
8364 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8365 // follow the sign bit for uniformity.
8366 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8367 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8368 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8369 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8370 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8371 if (NotMaskLZ == 64) return Result; // All zero mask.
8373 // See if we have a continuous run of bits. If so, we have 0*1+0*
8374 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8377 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8378 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8379 NotMaskLZ -= 64-V.getValueSizeInBits();
8381 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8382 switch (MaskedBytes) {
8386 default: return Result; // All one mask, or 5-byte mask.
8389 // Verify that the first bit starts at a multiple of mask so that the access
8390 // is aligned the same as the access width.
8391 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8393 Result.first = MaskedBytes;
8394 Result.second = NotMaskTZ/8;
8399 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8400 /// provides a value as specified by MaskInfo. If so, replace the specified
8401 /// store with a narrower store of truncated IVal.
8403 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8404 SDValue IVal, StoreSDNode *St,
8406 unsigned NumBytes = MaskInfo.first;
8407 unsigned ByteShift = MaskInfo.second;
8408 SelectionDAG &DAG = DC->getDAG();
8410 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8411 // that uses this. If not, this is not a replacement.
8412 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8413 ByteShift*8, (ByteShift+NumBytes)*8);
8414 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8416 // Check that it is legal on the target to do this. It is legal if the new
8417 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8419 MVT VT = MVT::getIntegerVT(NumBytes*8);
8420 if (!DC->isTypeLegal(VT))
8423 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8424 // shifted by ByteShift and truncated down to NumBytes.
8426 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8427 DAG.getConstant(ByteShift*8,
8428 DC->getShiftAmountTy(IVal.getValueType())));
8430 // Figure out the offset for the store and the alignment of the access.
8432 unsigned NewAlign = St->getAlignment();
8434 if (DAG.getTargetLoweringInfo().isLittleEndian())
8435 StOffset = ByteShift;
8437 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8439 SDValue Ptr = St->getBasePtr();
8441 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8442 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8443 NewAlign = MinAlign(NewAlign, StOffset);
8446 // Truncate down to the new size.
8447 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8450 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8451 St->getPointerInfo().getWithOffset(StOffset),
8452 false, false, NewAlign).getNode();
8456 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8457 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8458 /// of the loaded bits, try narrowing the load and store if it would end up
8459 /// being a win for performance or code size.
8460 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8461 StoreSDNode *ST = cast<StoreSDNode>(N);
8462 if (ST->isVolatile())
8465 SDValue Chain = ST->getChain();
8466 SDValue Value = ST->getValue();
8467 SDValue Ptr = ST->getBasePtr();
8468 EVT VT = Value.getValueType();
8470 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8473 unsigned Opc = Value.getOpcode();
8475 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8476 // is a byte mask indicating a consecutive number of bytes, check to see if
8477 // Y is known to provide just those bytes. If so, we try to replace the
8478 // load + replace + store sequence with a single (narrower) store, which makes
8480 if (Opc == ISD::OR) {
8481 std::pair<unsigned, unsigned> MaskedLoad;
8482 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8483 if (MaskedLoad.first)
8484 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8485 Value.getOperand(1), ST,this))
8486 return SDValue(NewST, 0);
8488 // Or is commutative, so try swapping X and Y.
8489 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8490 if (MaskedLoad.first)
8491 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8492 Value.getOperand(0), ST,this))
8493 return SDValue(NewST, 0);
8496 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8497 Value.getOperand(1).getOpcode() != ISD::Constant)
8500 SDValue N0 = Value.getOperand(0);
8501 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8502 Chain == SDValue(N0.getNode(), 1)) {
8503 LoadSDNode *LD = cast<LoadSDNode>(N0);
8504 if (LD->getBasePtr() != Ptr ||
8505 LD->getPointerInfo().getAddrSpace() !=
8506 ST->getPointerInfo().getAddrSpace())
8509 // Find the type to narrow it the load / op / store to.
8510 SDValue N1 = Value.getOperand(1);
8511 unsigned BitWidth = N1.getValueSizeInBits();
8512 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8513 if (Opc == ISD::AND)
8514 Imm ^= APInt::getAllOnesValue(BitWidth);
8515 if (Imm == 0 || Imm.isAllOnesValue())
8517 unsigned ShAmt = Imm.countTrailingZeros();
8518 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8519 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8520 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8521 while (NewBW < BitWidth &&
8522 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8523 TLI.isNarrowingProfitable(VT, NewVT))) {
8524 NewBW = NextPowerOf2(NewBW);
8525 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8527 if (NewBW >= BitWidth)
8530 // If the lsb changed does not start at the type bitwidth boundary,
8531 // start at the previous one.
8533 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8534 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8535 std::min(BitWidth, ShAmt + NewBW));
8536 if ((Imm & Mask) == Imm) {
8537 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8538 if (Opc == ISD::AND)
8539 NewImm ^= APInt::getAllOnesValue(NewBW);
8540 uint64_t PtrOff = ShAmt / 8;
8541 // For big endian targets, we need to adjust the offset to the pointer to
8542 // load the correct bytes.
8543 if (TLI.isBigEndian())
8544 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8546 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8547 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8548 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8551 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8552 Ptr.getValueType(), Ptr,
8553 DAG.getConstant(PtrOff, Ptr.getValueType()));
8554 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8555 LD->getChain(), NewPtr,
8556 LD->getPointerInfo().getWithOffset(PtrOff),
8557 LD->isVolatile(), LD->isNonTemporal(),
8558 LD->isInvariant(), NewAlign,
8560 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8561 DAG.getConstant(NewImm, NewVT));
8562 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8564 ST->getPointerInfo().getWithOffset(PtrOff),
8565 false, false, NewAlign);
8567 AddToWorkList(NewPtr.getNode());
8568 AddToWorkList(NewLD.getNode());
8569 AddToWorkList(NewVal.getNode());
8570 WorkListRemover DeadNodes(*this);
8571 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8580 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8581 /// if the load value isn't used by any other operations, then consider
8582 /// transforming the pair to integer load / store operations if the target
8583 /// deems the transformation profitable.
8584 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8585 StoreSDNode *ST = cast<StoreSDNode>(N);
8586 SDValue Chain = ST->getChain();
8587 SDValue Value = ST->getValue();
8588 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8589 Value.hasOneUse() &&
8590 Chain == SDValue(Value.getNode(), 1)) {
8591 LoadSDNode *LD = cast<LoadSDNode>(Value);
8592 EVT VT = LD->getMemoryVT();
8593 if (!VT.isFloatingPoint() ||
8594 VT != ST->getMemoryVT() ||
8595 LD->isNonTemporal() ||
8596 ST->isNonTemporal() ||
8597 LD->getPointerInfo().getAddrSpace() != 0 ||
8598 ST->getPointerInfo().getAddrSpace() != 0)
8601 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8602 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8603 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8604 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8605 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8608 unsigned LDAlign = LD->getAlignment();
8609 unsigned STAlign = ST->getAlignment();
8610 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8611 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8612 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8615 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8616 LD->getChain(), LD->getBasePtr(),
8617 LD->getPointerInfo(),
8618 false, false, false, LDAlign);
8620 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8621 NewLD, ST->getBasePtr(),
8622 ST->getPointerInfo(),
8623 false, false, STAlign);
8625 AddToWorkList(NewLD.getNode());
8626 AddToWorkList(NewST.getNode());
8627 WorkListRemover DeadNodes(*this);
8628 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8636 /// Helper struct to parse and store a memory address as base + index + offset.
8637 /// We ignore sign extensions when it is safe to do so.
8638 /// The following two expressions are not equivalent. To differentiate we need
8639 /// to store whether there was a sign extension involved in the index
8641 /// (load (i64 add (i64 copyfromreg %c)
8642 /// (i64 signextend (add (i8 load %index)
8646 /// (load (i64 add (i64 copyfromreg %c)
8647 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8649 struct BaseIndexOffset {
8653 bool IsIndexSignExt;
8655 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8657 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8658 bool IsIndexSignExt) :
8659 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8661 bool equalBaseIndex(const BaseIndexOffset &Other) {
8662 return Other.Base == Base && Other.Index == Index &&
8663 Other.IsIndexSignExt == IsIndexSignExt;
8666 /// Parses tree in Ptr for base, index, offset addresses.
8667 static BaseIndexOffset match(SDValue Ptr) {
8668 bool IsIndexSignExt = false;
8670 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8671 // instruction, then it could be just the BASE or everything else we don't
8672 // know how to handle. Just use Ptr as BASE and give up.
8673 if (Ptr->getOpcode() != ISD::ADD)
8674 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8676 // We know that we have at least an ADD instruction. Try to pattern match
8677 // the simple case of BASE + OFFSET.
8678 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8679 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8680 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8684 // Inside a loop the current BASE pointer is calculated using an ADD and a
8685 // MUL instruction. In this case Ptr is the actual BASE pointer.
8686 // (i64 add (i64 %array_ptr)
8687 // (i64 mul (i64 %induction_var)
8688 // (i64 %element_size)))
8689 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8690 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8692 // Look at Base + Index + Offset cases.
8693 SDValue Base = Ptr->getOperand(0);
8694 SDValue IndexOffset = Ptr->getOperand(1);
8696 // Skip signextends.
8697 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8698 IndexOffset = IndexOffset->getOperand(0);
8699 IsIndexSignExt = true;
8702 // Either the case of Base + Index (no offset) or something else.
8703 if (IndexOffset->getOpcode() != ISD::ADD)
8704 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8706 // Now we have the case of Base + Index + offset.
8707 SDValue Index = IndexOffset->getOperand(0);
8708 SDValue Offset = IndexOffset->getOperand(1);
8710 if (!isa<ConstantSDNode>(Offset))
8711 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8713 // Ignore signextends.
8714 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8715 Index = Index->getOperand(0);
8716 IsIndexSignExt = true;
8717 } else IsIndexSignExt = false;
8719 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8720 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8724 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8725 /// is located in a sequence of memory operations connected by a chain.
8727 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8728 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8729 // Ptr to the mem node.
8730 LSBaseSDNode *MemNode;
8731 // Offset from the base ptr.
8732 int64_t OffsetFromBase;
8733 // What is the sequence number of this mem node.
8734 // Lowest mem operand in the DAG starts at zero.
8735 unsigned SequenceNum;
8738 /// Sorts store nodes in a link according to their offset from a shared
8740 struct ConsecutiveMemoryChainSorter {
8741 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8742 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8746 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8747 EVT MemVT = St->getMemoryVT();
8748 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8749 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8750 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8752 // Don't merge vectors into wider inputs.
8753 if (MemVT.isVector() || !MemVT.isSimple())
8756 // Perform an early exit check. Do not bother looking at stored values that
8757 // are not constants or loads.
8758 SDValue StoredVal = St->getValue();
8759 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8760 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8764 // Only look at ends of store sequences.
8765 SDValue Chain = SDValue(St, 1);
8766 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8769 // This holds the base pointer, index, and the offset in bytes from the base
8771 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8773 // We must have a base and an offset.
8774 if (!BasePtr.Base.getNode())
8777 // Do not handle stores to undef base pointers.
8778 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8781 // Save the LoadSDNodes that we find in the chain.
8782 // We need to make sure that these nodes do not interfere with
8783 // any of the store nodes.
8784 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8786 // Save the StoreSDNodes that we find in the chain.
8787 SmallVector<MemOpLink, 8> StoreNodes;
8789 // Walk up the chain and look for nodes with offsets from the same
8790 // base pointer. Stop when reaching an instruction with a different kind
8791 // or instruction which has a different base pointer.
8793 StoreSDNode *Index = St;
8795 // If the chain has more than one use, then we can't reorder the mem ops.
8796 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8799 // Find the base pointer and offset for this memory node.
8800 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8802 // Check that the base pointer is the same as the original one.
8803 if (!Ptr.equalBaseIndex(BasePtr))
8806 // Check that the alignment is the same.
8807 if (Index->getAlignment() != St->getAlignment())
8810 // The memory operands must not be volatile.
8811 if (Index->isVolatile() || Index->isIndexed())
8815 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8816 if (St->isTruncatingStore())
8819 // The stored memory type must be the same.
8820 if (Index->getMemoryVT() != MemVT)
8823 // We do not allow unaligned stores because we want to prevent overriding
8825 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8828 // We found a potential memory operand to merge.
8829 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8831 // Find the next memory operand in the chain. If the next operand in the
8832 // chain is a store then move up and continue the scan with the next
8833 // memory operand. If the next operand is a load save it and use alias
8834 // information to check if it interferes with anything.
8835 SDNode *NextInChain = Index->getChain().getNode();
8837 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8838 // We found a store node. Use it for the next iteration.
8841 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8842 if (Ldn->isVolatile()) {
8847 // Save the load node for later. Continue the scan.
8848 AliasLoadNodes.push_back(Ldn);
8849 NextInChain = Ldn->getChain().getNode();
8858 // Check if there is anything to merge.
8859 if (StoreNodes.size() < 2)
8862 // Sort the memory operands according to their distance from the base pointer.
8863 std::sort(StoreNodes.begin(), StoreNodes.end(),
8864 ConsecutiveMemoryChainSorter());
8866 // Scan the memory operations on the chain and find the first non-consecutive
8867 // store memory address.
8868 unsigned LastConsecutiveStore = 0;
8869 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8870 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8872 // Check that the addresses are consecutive starting from the second
8873 // element in the list of stores.
8875 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8876 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8881 // Check if this store interferes with any of the loads that we found.
8882 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8883 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8887 // We found a load that alias with this store. Stop the sequence.
8891 // Mark this node as useful.
8892 LastConsecutiveStore = i;
8895 // The node with the lowest store address.
8896 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8898 // Store the constants into memory as one consecutive store.
8900 unsigned LastLegalType = 0;
8901 unsigned LastLegalVectorType = 0;
8902 bool NonZero = false;
8903 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8904 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8905 SDValue StoredVal = St->getValue();
8907 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8908 NonZero |= !C->isNullValue();
8909 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8910 NonZero |= !C->getConstantFPValue()->isNullValue();
8916 // Find a legal type for the constant store.
8917 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8918 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8919 if (TLI.isTypeLegal(StoreTy))
8920 LastLegalType = i+1;
8921 // Or check whether a truncstore is legal.
8922 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8923 TargetLowering::TypePromoteInteger) {
8924 EVT LegalizedStoredValueTy =
8925 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8926 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8927 LastLegalType = i+1;
8930 // Find a legal type for the vector store.
8931 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8932 if (TLI.isTypeLegal(Ty))
8933 LastLegalVectorType = i + 1;
8936 // We only use vectors if the constant is known to be zero and the
8937 // function is not marked with the noimplicitfloat attribute.
8938 if (NonZero || NoVectors)
8939 LastLegalVectorType = 0;
8941 // Check if we found a legal integer type to store.
8942 if (LastLegalType == 0 && LastLegalVectorType == 0)
8945 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8946 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8948 // Make sure we have something to merge.
8952 unsigned EarliestNodeUsed = 0;
8953 for (unsigned i=0; i < NumElem; ++i) {
8954 // Find a chain for the new wide-store operand. Notice that some
8955 // of the store nodes that we found may not be selected for inclusion
8956 // in the wide store. The chain we use needs to be the chain of the
8957 // earliest store node which is *used* and replaced by the wide store.
8958 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8959 EarliestNodeUsed = i;
8962 // The earliest Node in the DAG.
8963 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8964 SDLoc DL(StoreNodes[0].MemNode);
8968 // Find a legal type for the vector store.
8969 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8970 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8971 StoredVal = DAG.getConstant(0, Ty);
8973 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8974 APInt StoreInt(StoreBW, 0);
8976 // Construct a single integer constant which is made of the smaller
8978 bool IsLE = TLI.isLittleEndian();
8979 for (unsigned i = 0; i < NumElem ; ++i) {
8980 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8981 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8982 SDValue Val = St->getValue();
8983 StoreInt<<=ElementSizeBytes*8;
8984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8985 StoreInt|=C->getAPIntValue().zext(StoreBW);
8986 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8987 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8989 assert(false && "Invalid constant element type");
8993 // Create the new Load and Store operations.
8994 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8995 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8998 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8999 FirstInChain->getBasePtr(),
9000 FirstInChain->getPointerInfo(),
9002 FirstInChain->getAlignment());
9004 // Replace the first store with the new store
9005 CombineTo(EarliestOp, NewStore);
9006 // Erase all other stores.
9007 for (unsigned i = 0; i < NumElem ; ++i) {
9008 if (StoreNodes[i].MemNode == EarliestOp)
9010 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9011 // ReplaceAllUsesWith will replace all uses that existed when it was
9012 // called, but graph optimizations may cause new ones to appear. For
9013 // example, the case in pr14333 looks like
9015 // St's chain -> St -> another store -> X
9017 // And the only difference from St to the other store is the chain.
9018 // When we change it's chain to be St's chain they become identical,
9019 // get CSEed and the net result is that X is now a use of St.
9020 // Since we know that St is redundant, just iterate.
9021 while (!St->use_empty())
9022 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9023 removeFromWorkList(St);
9030 // Below we handle the case of multiple consecutive stores that
9031 // come from multiple consecutive loads. We merge them into a single
9032 // wide load and a single wide store.
9034 // Look for load nodes which are used by the stored values.
9035 SmallVector<MemOpLink, 8> LoadNodes;
9037 // Find acceptable loads. Loads need to have the same chain (token factor),
9038 // must not be zext, volatile, indexed, and they must be consecutive.
9039 BaseIndexOffset LdBasePtr;
9040 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9041 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9042 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9045 // Loads must only have one use.
9046 if (!Ld->hasNUsesOfValue(1, 0))
9049 // Check that the alignment is the same as the stores.
9050 if (Ld->getAlignment() != St->getAlignment())
9053 // The memory operands must not be volatile.
9054 if (Ld->isVolatile() || Ld->isIndexed())
9057 // We do not accept ext loads.
9058 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9061 // The stored memory type must be the same.
9062 if (Ld->getMemoryVT() != MemVT)
9065 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9066 // If this is not the first ptr that we check.
9067 if (LdBasePtr.Base.getNode()) {
9068 // The base ptr must be the same.
9069 if (!LdPtr.equalBaseIndex(LdBasePtr))
9072 // Check that all other base pointers are the same as this one.
9076 // We found a potential memory operand to merge.
9077 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9080 if (LoadNodes.size() < 2)
9083 // Scan the memory operations on the chain and find the first non-consecutive
9084 // load memory address. These variables hold the index in the store node
9086 unsigned LastConsecutiveLoad = 0;
9087 // This variable refers to the size and not index in the array.
9088 unsigned LastLegalVectorType = 0;
9089 unsigned LastLegalIntegerType = 0;
9090 StartAddress = LoadNodes[0].OffsetFromBase;
9091 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9092 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9093 // All loads much share the same chain.
9094 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9097 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9098 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9100 LastConsecutiveLoad = i;
9102 // Find a legal type for the vector store.
9103 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9104 if (TLI.isTypeLegal(StoreTy))
9105 LastLegalVectorType = i + 1;
9107 // Find a legal type for the integer store.
9108 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9109 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9110 if (TLI.isTypeLegal(StoreTy))
9111 LastLegalIntegerType = i + 1;
9112 // Or check whether a truncstore and extload is legal.
9113 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9114 TargetLowering::TypePromoteInteger) {
9115 EVT LegalizedStoredValueTy =
9116 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9117 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9118 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9119 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9120 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9121 LastLegalIntegerType = i+1;
9125 // Only use vector types if the vector type is larger than the integer type.
9126 // If they are the same, use integers.
9127 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9128 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9130 // We add +1 here because the LastXXX variables refer to location while
9131 // the NumElem refers to array/index size.
9132 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9133 NumElem = std::min(LastLegalType, NumElem);
9138 // The earliest Node in the DAG.
9139 unsigned EarliestNodeUsed = 0;
9140 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9141 for (unsigned i=1; i<NumElem; ++i) {
9142 // Find a chain for the new wide-store operand. Notice that some
9143 // of the store nodes that we found may not be selected for inclusion
9144 // in the wide store. The chain we use needs to be the chain of the
9145 // earliest store node which is *used* and replaced by the wide store.
9146 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9147 EarliestNodeUsed = i;
9150 // Find if it is better to use vectors or integers to load and store
9154 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9156 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9157 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9160 SDLoc LoadDL(LoadNodes[0].MemNode);
9161 SDLoc StoreDL(StoreNodes[0].MemNode);
9163 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9164 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9165 FirstLoad->getChain(),
9166 FirstLoad->getBasePtr(),
9167 FirstLoad->getPointerInfo(),
9168 false, false, false,
9169 FirstLoad->getAlignment());
9171 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9172 FirstInChain->getBasePtr(),
9173 FirstInChain->getPointerInfo(), false, false,
9174 FirstInChain->getAlignment());
9176 // Replace one of the loads with the new load.
9177 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9178 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9179 SDValue(NewLoad.getNode(), 1));
9181 // Remove the rest of the load chains.
9182 for (unsigned i = 1; i < NumElem ; ++i) {
9183 // Replace all chain users of the old load nodes with the chain of the new
9185 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9186 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9189 // Replace the first store with the new store.
9190 CombineTo(EarliestOp, NewStore);
9191 // Erase all other stores.
9192 for (unsigned i = 0; i < NumElem ; ++i) {
9193 // Remove all Store nodes.
9194 if (StoreNodes[i].MemNode == EarliestOp)
9196 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9197 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9198 removeFromWorkList(St);
9205 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9206 StoreSDNode *ST = cast<StoreSDNode>(N);
9207 SDValue Chain = ST->getChain();
9208 SDValue Value = ST->getValue();
9209 SDValue Ptr = ST->getBasePtr();
9211 // If this is a store of a bit convert, store the input value if the
9212 // resultant store does not need a higher alignment than the original.
9213 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9214 ST->isUnindexed()) {
9215 unsigned OrigAlign = ST->getAlignment();
9216 EVT SVT = Value.getOperand(0).getValueType();
9217 unsigned Align = TLI.getDataLayout()->
9218 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9219 if (Align <= OrigAlign &&
9220 ((!LegalOperations && !ST->isVolatile()) ||
9221 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9222 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9223 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9224 ST->isNonTemporal(), OrigAlign,
9228 // Turn 'store undef, Ptr' -> nothing.
9229 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9232 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9233 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9234 // NOTE: If the original store is volatile, this transform must not increase
9235 // the number of stores. For example, on x86-32 an f64 can be stored in one
9236 // processor operation but an i64 (which is not legal) requires two. So the
9237 // transform should not be done in this case.
9238 if (Value.getOpcode() != ISD::TargetConstantFP) {
9240 switch (CFP->getSimpleValueType(0).SimpleTy) {
9241 default: llvm_unreachable("Unknown FP type");
9242 case MVT::f16: // We don't do this for these yet.
9248 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9249 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9250 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9251 bitcastToAPInt().getZExtValue(), MVT::i32);
9252 return DAG.getStore(Chain, SDLoc(N), Tmp,
9253 Ptr, ST->getMemOperand());
9257 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9258 !ST->isVolatile()) ||
9259 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9260 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9261 getZExtValue(), MVT::i64);
9262 return DAG.getStore(Chain, SDLoc(N), Tmp,
9263 Ptr, ST->getMemOperand());
9266 if (!ST->isVolatile() &&
9267 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9268 // Many FP stores are not made apparent until after legalize, e.g. for
9269 // argument passing. Since this is so common, custom legalize the
9270 // 64-bit integer store into two 32-bit stores.
9271 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9272 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9273 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9274 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9276 unsigned Alignment = ST->getAlignment();
9277 bool isVolatile = ST->isVolatile();
9278 bool isNonTemporal = ST->isNonTemporal();
9279 const MDNode *TBAAInfo = ST->getTBAAInfo();
9281 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9282 Ptr, ST->getPointerInfo(),
9283 isVolatile, isNonTemporal,
9284 ST->getAlignment(), TBAAInfo);
9285 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9286 DAG.getConstant(4, Ptr.getValueType()));
9287 Alignment = MinAlign(Alignment, 4U);
9288 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9289 Ptr, ST->getPointerInfo().getWithOffset(4),
9290 isVolatile, isNonTemporal,
9291 Alignment, TBAAInfo);
9292 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9301 // Try to infer better alignment information than the store already has.
9302 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9303 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9304 if (Align > ST->getAlignment())
9305 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9306 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9307 ST->isVolatile(), ST->isNonTemporal(), Align,
9312 // Try transforming a pair floating point load / store ops to integer
9313 // load / store ops.
9314 SDValue NewST = TransformFPLoadStorePair(N);
9315 if (NewST.getNode())
9318 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9319 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9320 if (UseAA && ST->isUnindexed()) {
9321 // Walk up chain skipping non-aliasing memory nodes.
9322 SDValue BetterChain = FindBetterChain(N, Chain);
9324 // If there is a better chain.
9325 if (Chain != BetterChain) {
9328 // Replace the chain to avoid dependency.
9329 if (ST->isTruncatingStore()) {
9330 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9331 ST->getMemoryVT(), ST->getMemOperand());
9333 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9334 ST->getMemOperand());
9337 // Create token to keep both nodes around.
9338 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9339 MVT::Other, Chain, ReplStore);
9341 // Make sure the new and old chains are cleaned up.
9342 AddToWorkList(Token.getNode());
9344 // Don't add users to work list.
9345 return CombineTo(N, Token, false);
9349 // Try transforming N to an indexed store.
9350 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9351 return SDValue(N, 0);
9353 // FIXME: is there such a thing as a truncating indexed store?
9354 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9355 Value.getValueType().isInteger()) {
9356 // See if we can simplify the input to this truncstore with knowledge that
9357 // only the low bits are being used. For example:
9358 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9360 GetDemandedBits(Value,
9361 APInt::getLowBitsSet(
9362 Value.getValueType().getScalarType().getSizeInBits(),
9363 ST->getMemoryVT().getScalarType().getSizeInBits()));
9364 AddToWorkList(Value.getNode());
9365 if (Shorter.getNode())
9366 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9367 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9369 // Otherwise, see if we can simplify the operation with
9370 // SimplifyDemandedBits, which only works if the value has a single use.
9371 if (SimplifyDemandedBits(Value,
9372 APInt::getLowBitsSet(
9373 Value.getValueType().getScalarType().getSizeInBits(),
9374 ST->getMemoryVT().getScalarType().getSizeInBits())))
9375 return SDValue(N, 0);
9378 // If this is a load followed by a store to the same location, then the store
9380 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9381 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9382 ST->isUnindexed() && !ST->isVolatile() &&
9383 // There can't be any side effects between the load and store, such as
9385 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9386 // The store is dead, remove it.
9391 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9392 // truncating store. We can do this even if this is already a truncstore.
9393 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9394 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9395 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9396 ST->getMemoryVT())) {
9397 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9398 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9401 // Only perform this optimization before the types are legal, because we
9402 // don't want to perform this optimization on every DAGCombine invocation.
9404 bool EverChanged = false;
9407 // There can be multiple store sequences on the same chain.
9408 // Keep trying to merge store sequences until we are unable to do so
9409 // or until we merge the last store on the chain.
9410 bool Changed = MergeConsecutiveStores(ST);
9411 EverChanged |= Changed;
9412 if (!Changed) break;
9413 } while (ST->getOpcode() != ISD::DELETED_NODE);
9416 return SDValue(N, 0);
9419 return ReduceLoadOpStoreWidth(N);
9422 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9423 SDValue InVec = N->getOperand(0);
9424 SDValue InVal = N->getOperand(1);
9425 SDValue EltNo = N->getOperand(2);
9428 // If the inserted element is an UNDEF, just use the input vector.
9429 if (InVal.getOpcode() == ISD::UNDEF)
9432 EVT VT = InVec.getValueType();
9434 // If we can't generate a legal BUILD_VECTOR, exit
9435 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9438 // Check that we know which element is being inserted
9439 if (!isa<ConstantSDNode>(EltNo))
9441 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9443 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9444 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9446 SmallVector<SDValue, 8> Ops;
9447 // Do not combine these two vectors if the output vector will not replace
9448 // the input vector.
9449 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9450 Ops.append(InVec.getNode()->op_begin(),
9451 InVec.getNode()->op_end());
9452 } else if (InVec.getOpcode() == ISD::UNDEF) {
9453 unsigned NElts = VT.getVectorNumElements();
9454 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9459 // Insert the element
9460 if (Elt < Ops.size()) {
9461 // All the operands of BUILD_VECTOR must have the same type;
9462 // we enforce that here.
9463 EVT OpVT = Ops[0].getValueType();
9464 if (InVal.getValueType() != OpVT)
9465 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9466 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9467 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9471 // Return the new vector
9472 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9473 VT, &Ops[0], Ops.size());
9476 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9477 // (vextract (scalar_to_vector val, 0) -> val
9478 SDValue InVec = N->getOperand(0);
9479 EVT VT = InVec.getValueType();
9480 EVT NVT = N->getValueType(0);
9482 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9483 // Check if the result type doesn't match the inserted element type. A
9484 // SCALAR_TO_VECTOR may truncate the inserted element and the
9485 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9486 SDValue InOp = InVec.getOperand(0);
9487 if (InOp.getValueType() != NVT) {
9488 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9489 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9494 SDValue EltNo = N->getOperand(1);
9495 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9497 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9498 // We only perform this optimization before the op legalization phase because
9499 // we may introduce new vector instructions which are not backed by TD
9500 // patterns. For example on AVX, extracting elements from a wide vector
9501 // without using extract_subvector.
9502 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9503 && ConstEltNo && !LegalOperations) {
9504 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9505 int NumElem = VT.getVectorNumElements();
9506 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9507 // Find the new index to extract from.
9508 int OrigElt = SVOp->getMaskElt(Elt);
9510 // Extracting an undef index is undef.
9512 return DAG.getUNDEF(NVT);
9514 // Select the right vector half to extract from.
9515 if (OrigElt < NumElem) {
9516 InVec = InVec->getOperand(0);
9518 InVec = InVec->getOperand(1);
9522 EVT IndexTy = TLI.getVectorIdxTy();
9523 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9524 InVec, DAG.getConstant(OrigElt, IndexTy));
9527 // Perform only after legalization to ensure build_vector / vector_shuffle
9528 // optimizations have already been done.
9529 if (!LegalOperations) return SDValue();
9531 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9532 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9533 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9536 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9537 bool NewLoad = false;
9538 bool BCNumEltsChanged = false;
9539 EVT ExtVT = VT.getVectorElementType();
9542 // If the result of load has to be truncated, then it's not necessarily
9544 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9547 if (InVec.getOpcode() == ISD::BITCAST) {
9548 // Don't duplicate a load with other uses.
9549 if (!InVec.hasOneUse())
9552 EVT BCVT = InVec.getOperand(0).getValueType();
9553 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9555 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9556 BCNumEltsChanged = true;
9557 InVec = InVec.getOperand(0);
9558 ExtVT = BCVT.getVectorElementType();
9562 LoadSDNode *LN0 = NULL;
9563 const ShuffleVectorSDNode *SVN = NULL;
9564 if (ISD::isNormalLoad(InVec.getNode())) {
9565 LN0 = cast<LoadSDNode>(InVec);
9566 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9567 InVec.getOperand(0).getValueType() == ExtVT &&
9568 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9569 // Don't duplicate a load with other uses.
9570 if (!InVec.hasOneUse())
9573 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9574 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9575 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9577 // (load $addr+1*size)
9579 // Don't duplicate a load with other uses.
9580 if (!InVec.hasOneUse())
9583 // If the bit convert changed the number of elements, it is unsafe
9584 // to examine the mask.
9585 if (BCNumEltsChanged)
9588 // Select the input vector, guarding against out of range extract vector.
9589 unsigned NumElems = VT.getVectorNumElements();
9590 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9591 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9593 if (InVec.getOpcode() == ISD::BITCAST) {
9594 // Don't duplicate a load with other uses.
9595 if (!InVec.hasOneUse())
9598 InVec = InVec.getOperand(0);
9600 if (ISD::isNormalLoad(InVec.getNode())) {
9601 LN0 = cast<LoadSDNode>(InVec);
9602 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9606 // Make sure we found a non-volatile load and the extractelement is
9608 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9611 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9613 return DAG.getUNDEF(LVT);
9615 unsigned Align = LN0->getAlignment();
9617 // Check the resultant load doesn't need a higher alignment than the
9621 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9623 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9629 SDValue NewPtr = LN0->getBasePtr();
9630 unsigned PtrOff = 0;
9633 PtrOff = LVT.getSizeInBits() * Elt / 8;
9634 EVT PtrType = NewPtr.getValueType();
9635 if (TLI.isBigEndian())
9636 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9637 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9638 DAG.getConstant(PtrOff, PtrType));
9641 // The replacement we need to do here is a little tricky: we need to
9642 // replace an extractelement of a load with a load.
9643 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9644 // Note that this replacement assumes that the extractvalue is the only
9645 // use of the load; that's okay because we don't want to perform this
9646 // transformation in other cases anyway.
9649 if (NVT.bitsGT(LVT)) {
9650 // If the result type of vextract is wider than the load, then issue an
9651 // extending load instead.
9652 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9653 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9654 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9655 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9656 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9657 Align, LN0->getTBAAInfo());
9658 Chain = Load.getValue(1);
9660 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9661 LN0->getPointerInfo().getWithOffset(PtrOff),
9662 LN0->isVolatile(), LN0->isNonTemporal(),
9663 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9664 Chain = Load.getValue(1);
9665 if (NVT.bitsLT(LVT))
9666 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9668 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9670 WorkListRemover DeadNodes(*this);
9671 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9672 SDValue To[] = { Load, Chain };
9673 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9674 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9675 // worklist explicitly as well.
9676 AddToWorkList(Load.getNode());
9677 AddUsersToWorkList(Load.getNode()); // Add users too
9678 // Make sure to revisit this node to clean it up; it will usually be dead.
9680 return SDValue(N, 0);
9686 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9687 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9688 // We perform this optimization post type-legalization because
9689 // the type-legalizer often scalarizes integer-promoted vectors.
9690 // Performing this optimization before may create bit-casts which
9691 // will be type-legalized to complex code sequences.
9692 // We perform this optimization only before the operation legalizer because we
9693 // may introduce illegal operations.
9694 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9697 unsigned NumInScalars = N->getNumOperands();
9699 EVT VT = N->getValueType(0);
9701 // Check to see if this is a BUILD_VECTOR of a bunch of values
9702 // which come from any_extend or zero_extend nodes. If so, we can create
9703 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9704 // optimizations. We do not handle sign-extend because we can't fill the sign
9706 EVT SourceType = MVT::Other;
9707 bool AllAnyExt = true;
9709 for (unsigned i = 0; i != NumInScalars; ++i) {
9710 SDValue In = N->getOperand(i);
9711 // Ignore undef inputs.
9712 if (In.getOpcode() == ISD::UNDEF) continue;
9714 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9715 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9717 // Abort if the element is not an extension.
9718 if (!ZeroExt && !AnyExt) {
9719 SourceType = MVT::Other;
9723 // The input is a ZeroExt or AnyExt. Check the original type.
9724 EVT InTy = In.getOperand(0).getValueType();
9726 // Check that all of the widened source types are the same.
9727 if (SourceType == MVT::Other)
9730 else if (InTy != SourceType) {
9731 // Multiple income types. Abort.
9732 SourceType = MVT::Other;
9736 // Check if all of the extends are ANY_EXTENDs.
9737 AllAnyExt &= AnyExt;
9740 // In order to have valid types, all of the inputs must be extended from the
9741 // same source type and all of the inputs must be any or zero extend.
9742 // Scalar sizes must be a power of two.
9743 EVT OutScalarTy = VT.getScalarType();
9744 bool ValidTypes = SourceType != MVT::Other &&
9745 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9746 isPowerOf2_32(SourceType.getSizeInBits());
9748 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9749 // turn into a single shuffle instruction.
9753 bool isLE = TLI.isLittleEndian();
9754 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9755 assert(ElemRatio > 1 && "Invalid element size ratio");
9756 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9757 DAG.getConstant(0, SourceType);
9759 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9760 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9762 // Populate the new build_vector
9763 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9764 SDValue Cast = N->getOperand(i);
9765 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9766 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9767 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9769 if (Cast.getOpcode() == ISD::UNDEF)
9770 In = DAG.getUNDEF(SourceType);
9772 In = Cast->getOperand(0);
9773 unsigned Index = isLE ? (i * ElemRatio) :
9774 (i * ElemRatio + (ElemRatio - 1));
9776 assert(Index < Ops.size() && "Invalid index");
9780 // The type of the new BUILD_VECTOR node.
9781 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9782 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9783 "Invalid vector size");
9784 // Check if the new vector type is legal.
9785 if (!isTypeLegal(VecVT)) return SDValue();
9787 // Make the new BUILD_VECTOR.
9788 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9790 // The new BUILD_VECTOR node has the potential to be further optimized.
9791 AddToWorkList(BV.getNode());
9792 // Bitcast to the desired type.
9793 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9796 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9797 EVT VT = N->getValueType(0);
9799 unsigned NumInScalars = N->getNumOperands();
9802 EVT SrcVT = MVT::Other;
9803 unsigned Opcode = ISD::DELETED_NODE;
9804 unsigned NumDefs = 0;
9806 for (unsigned i = 0; i != NumInScalars; ++i) {
9807 SDValue In = N->getOperand(i);
9808 unsigned Opc = In.getOpcode();
9810 if (Opc == ISD::UNDEF)
9813 // If all scalar values are floats and converted from integers.
9814 if (Opcode == ISD::DELETED_NODE &&
9815 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9822 EVT InVT = In.getOperand(0).getValueType();
9824 // If all scalar values are typed differently, bail out. It's chosen to
9825 // simplify BUILD_VECTOR of integer types.
9826 if (SrcVT == MVT::Other)
9833 // If the vector has just one element defined, it's not worth to fold it into
9834 // a vectorized one.
9838 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9839 && "Should only handle conversion from integer to float.");
9840 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9842 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9844 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9847 SmallVector<SDValue, 8> Opnds;
9848 for (unsigned i = 0; i != NumInScalars; ++i) {
9849 SDValue In = N->getOperand(i);
9851 if (In.getOpcode() == ISD::UNDEF)
9852 Opnds.push_back(DAG.getUNDEF(SrcVT));
9854 Opnds.push_back(In.getOperand(0));
9856 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9857 &Opnds[0], Opnds.size());
9858 AddToWorkList(BV.getNode());
9860 return DAG.getNode(Opcode, dl, VT, BV);
9863 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9864 unsigned NumInScalars = N->getNumOperands();
9866 EVT VT = N->getValueType(0);
9868 // A vector built entirely of undefs is undef.
9869 if (ISD::allOperandsUndef(N))
9870 return DAG.getUNDEF(VT);
9872 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9876 V = reduceBuildVecConvertToConvertBuildVec(N);
9880 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9881 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9882 // at most two distinct vectors, turn this into a shuffle node.
9884 // May only combine to shuffle after legalize if shuffle is legal.
9885 if (LegalOperations &&
9886 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9889 SDValue VecIn1, VecIn2;
9890 for (unsigned i = 0; i != NumInScalars; ++i) {
9891 // Ignore undef inputs.
9892 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9894 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9895 // constant index, bail out.
9896 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9897 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9898 VecIn1 = VecIn2 = SDValue(0, 0);
9902 // We allow up to two distinct input vectors.
9903 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9904 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9907 if (VecIn1.getNode() == 0) {
9908 VecIn1 = ExtractedFromVec;
9909 } else if (VecIn2.getNode() == 0) {
9910 VecIn2 = ExtractedFromVec;
9913 VecIn1 = VecIn2 = SDValue(0, 0);
9918 // If everything is good, we can make a shuffle operation.
9919 if (VecIn1.getNode()) {
9920 SmallVector<int, 8> Mask;
9921 for (unsigned i = 0; i != NumInScalars; ++i) {
9922 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9927 // If extracting from the first vector, just use the index directly.
9928 SDValue Extract = N->getOperand(i);
9929 SDValue ExtVal = Extract.getOperand(1);
9930 if (Extract.getOperand(0) == VecIn1) {
9931 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9932 if (ExtIndex > VT.getVectorNumElements())
9935 Mask.push_back(ExtIndex);
9939 // Otherwise, use InIdx + VecSize
9940 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9941 Mask.push_back(Idx+NumInScalars);
9944 // We can't generate a shuffle node with mismatched input and output types.
9945 // Attempt to transform a single input vector to the correct type.
9946 if ((VT != VecIn1.getValueType())) {
9947 // We don't support shuffeling between TWO values of different types.
9948 if (VecIn2.getNode() != 0)
9951 // We only support widening of vectors which are half the size of the
9952 // output registers. For example XMM->YMM widening on X86 with AVX.
9953 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9956 // If the input vector type has a different base type to the output
9957 // vector type, bail out.
9958 if (VecIn1.getValueType().getVectorElementType() !=
9959 VT.getVectorElementType())
9962 // Widen the input vector by adding undef values.
9963 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9964 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9967 // If VecIn2 is unused then change it to undef.
9968 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9970 // Check that we were able to transform all incoming values to the same
9972 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9973 VecIn1.getValueType() != VT)
9976 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9977 if (!isTypeLegal(VT))
9980 // Return the new VECTOR_SHUFFLE node.
9984 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9990 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9991 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9992 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9993 // inputs come from at most two distinct vectors, turn this into a shuffle
9996 // If we only have one input vector, we don't need to do any concatenation.
9997 if (N->getNumOperands() == 1)
9998 return N->getOperand(0);
10000 // Check if all of the operands are undefs.
10001 EVT VT = N->getValueType(0);
10002 if (ISD::allOperandsUndef(N))
10003 return DAG.getUNDEF(VT);
10005 // Optimize concat_vectors where one of the vectors is undef.
10006 if (N->getNumOperands() == 2 &&
10007 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10008 SDValue In = N->getOperand(0);
10009 assert(In.getValueType().isVector() && "Must concat vectors");
10011 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10012 if (In->getOpcode() == ISD::BITCAST &&
10013 !In->getOperand(0)->getValueType(0).isVector()) {
10014 SDValue Scalar = In->getOperand(0);
10015 EVT SclTy = Scalar->getValueType(0);
10017 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10020 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10021 VT.getSizeInBits() / SclTy.getSizeInBits());
10022 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10025 SDLoc dl = SDLoc(N);
10026 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10027 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10031 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10032 // nodes often generate nop CONCAT_VECTOR nodes.
10033 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10034 // place the incoming vectors at the exact same location.
10035 SDValue SingleSource = SDValue();
10036 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10038 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10039 SDValue Op = N->getOperand(i);
10041 if (Op.getOpcode() == ISD::UNDEF)
10044 // Check if this is the identity extract:
10045 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10048 // Find the single incoming vector for the extract_subvector.
10049 if (SingleSource.getNode()) {
10050 if (Op.getOperand(0) != SingleSource)
10053 SingleSource = Op.getOperand(0);
10055 // Check the source type is the same as the type of the result.
10056 // If not, this concat may extend the vector, so we can not
10057 // optimize it away.
10058 if (SingleSource.getValueType() != N->getValueType(0))
10062 unsigned IdentityIndex = i * PartNumElem;
10063 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10064 // The extract index must be constant.
10068 // Check that we are reading from the identity index.
10069 if (CS->getZExtValue() != IdentityIndex)
10073 if (SingleSource.getNode())
10074 return SingleSource;
10079 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10080 EVT NVT = N->getValueType(0);
10081 SDValue V = N->getOperand(0);
10083 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10085 // (extract_subvec (concat V1, V2, ...), i)
10088 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10090 if (V->getOperand(0).getValueType() != NVT)
10092 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10093 unsigned NumElems = NVT.getVectorNumElements();
10094 assert((Idx % NumElems) == 0 &&
10095 "IDX in concat is not a multiple of the result vector length.");
10096 return V->getOperand(Idx / NumElems);
10100 if (V->getOpcode() == ISD::BITCAST)
10101 V = V.getOperand(0);
10103 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10105 // Handle only simple case where vector being inserted and vector
10106 // being extracted are of same type, and are half size of larger vectors.
10107 EVT BigVT = V->getOperand(0).getValueType();
10108 EVT SmallVT = V->getOperand(1).getValueType();
10109 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10112 // Only handle cases where both indexes are constants with the same type.
10113 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10114 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10116 if (InsIdx && ExtIdx &&
10117 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10118 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10120 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10122 // indices are equal or bit offsets are equal => V1
10123 // otherwise => (extract_subvec V1, ExtIdx)
10124 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10125 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10126 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10127 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10128 DAG.getNode(ISD::BITCAST, dl,
10129 N->getOperand(0).getValueType(),
10130 V->getOperand(0)), N->getOperand(1));
10137 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10138 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10139 EVT VT = N->getValueType(0);
10140 unsigned NumElts = VT.getVectorNumElements();
10142 SDValue N0 = N->getOperand(0);
10143 SDValue N1 = N->getOperand(1);
10144 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10146 SmallVector<SDValue, 4> Ops;
10147 EVT ConcatVT = N0.getOperand(0).getValueType();
10148 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10149 unsigned NumConcats = NumElts / NumElemsPerConcat;
10151 // Look at every vector that's inserted. We're looking for exact
10152 // subvector-sized copies from a concatenated vector
10153 for (unsigned I = 0; I != NumConcats; ++I) {
10154 // Make sure we're dealing with a copy.
10155 unsigned Begin = I * NumElemsPerConcat;
10156 bool AllUndef = true, NoUndef = true;
10157 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10158 if (SVN->getMaskElt(J) >= 0)
10165 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10168 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10169 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10172 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10173 if (FirstElt < N0.getNumOperands())
10174 Ops.push_back(N0.getOperand(FirstElt));
10176 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10178 } else if (AllUndef) {
10179 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10180 } else { // Mixed with general masks and undefs, can't do optimization.
10185 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10189 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10190 EVT VT = N->getValueType(0);
10191 unsigned NumElts = VT.getVectorNumElements();
10193 SDValue N0 = N->getOperand(0);
10194 SDValue N1 = N->getOperand(1);
10196 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10198 // Canonicalize shuffle undef, undef -> undef
10199 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10200 return DAG.getUNDEF(VT);
10202 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10204 // Canonicalize shuffle v, v -> v, undef
10206 SmallVector<int, 8> NewMask;
10207 for (unsigned i = 0; i != NumElts; ++i) {
10208 int Idx = SVN->getMaskElt(i);
10209 if (Idx >= (int)NumElts) Idx -= NumElts;
10210 NewMask.push_back(Idx);
10212 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10216 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10217 if (N0.getOpcode() == ISD::UNDEF) {
10218 SmallVector<int, 8> NewMask;
10219 for (unsigned i = 0; i != NumElts; ++i) {
10220 int Idx = SVN->getMaskElt(i);
10222 if (Idx >= (int)NumElts)
10225 Idx = -1; // remove reference to lhs
10227 NewMask.push_back(Idx);
10229 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10233 // Remove references to rhs if it is undef
10234 if (N1.getOpcode() == ISD::UNDEF) {
10235 bool Changed = false;
10236 SmallVector<int, 8> NewMask;
10237 for (unsigned i = 0; i != NumElts; ++i) {
10238 int Idx = SVN->getMaskElt(i);
10239 if (Idx >= (int)NumElts) {
10243 NewMask.push_back(Idx);
10246 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10249 // If it is a splat, check if the argument vector is another splat or a
10250 // build_vector with all scalar elements the same.
10251 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10252 SDNode *V = N0.getNode();
10254 // If this is a bit convert that changes the element type of the vector but
10255 // not the number of vector elements, look through it. Be careful not to
10256 // look though conversions that change things like v4f32 to v2f64.
10257 if (V->getOpcode() == ISD::BITCAST) {
10258 SDValue ConvInput = V->getOperand(0);
10259 if (ConvInput.getValueType().isVector() &&
10260 ConvInput.getValueType().getVectorNumElements() == NumElts)
10261 V = ConvInput.getNode();
10264 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10265 assert(V->getNumOperands() == NumElts &&
10266 "BUILD_VECTOR has wrong number of operands");
10268 bool AllSame = true;
10269 for (unsigned i = 0; i != NumElts; ++i) {
10270 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10271 Base = V->getOperand(i);
10275 // Splat of <u, u, u, u>, return <u, u, u, u>
10276 if (!Base.getNode())
10278 for (unsigned i = 0; i != NumElts; ++i) {
10279 if (V->getOperand(i) != Base) {
10284 // Splat of <x, x, x, x>, return <x, x, x, x>
10290 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10291 Level < AfterLegalizeVectorOps &&
10292 (N1.getOpcode() == ISD::UNDEF ||
10293 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10294 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10295 SDValue V = partitionShuffleOfConcats(N, DAG);
10301 // If this shuffle node is simply a swizzle of another shuffle node,
10302 // and it reverses the swizzle of the previous shuffle then we can
10303 // optimize shuffle(shuffle(x, undef), undef) -> x.
10304 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10305 N1.getOpcode() == ISD::UNDEF) {
10307 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10309 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10310 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10313 // The incoming shuffle must be of the same type as the result of the
10314 // current shuffle.
10315 assert(OtherSV->getOperand(0).getValueType() == VT &&
10316 "Shuffle types don't match");
10318 for (unsigned i = 0; i != NumElts; ++i) {
10319 int Idx = SVN->getMaskElt(i);
10320 assert(Idx < (int)NumElts && "Index references undef operand");
10321 // Next, this index comes from the first value, which is the incoming
10322 // shuffle. Adopt the incoming index.
10324 Idx = OtherSV->getMaskElt(Idx);
10326 // The combined shuffle must map each index to itself.
10327 if (Idx >= 0 && (unsigned)Idx != i)
10331 return OtherSV->getOperand(0);
10337 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10338 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10339 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10340 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10341 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10342 EVT VT = N->getValueType(0);
10344 SDValue LHS = N->getOperand(0);
10345 SDValue RHS = N->getOperand(1);
10346 if (N->getOpcode() == ISD::AND) {
10347 if (RHS.getOpcode() == ISD::BITCAST)
10348 RHS = RHS.getOperand(0);
10349 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10350 SmallVector<int, 8> Indices;
10351 unsigned NumElts = RHS.getNumOperands();
10352 for (unsigned i = 0; i != NumElts; ++i) {
10353 SDValue Elt = RHS.getOperand(i);
10354 if (!isa<ConstantSDNode>(Elt))
10357 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10358 Indices.push_back(i);
10359 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10360 Indices.push_back(NumElts);
10365 // Let's see if the target supports this vector_shuffle.
10366 EVT RVT = RHS.getValueType();
10367 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10370 // Return the new VECTOR_SHUFFLE node.
10371 EVT EltVT = RVT.getVectorElementType();
10372 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10373 DAG.getConstant(0, EltVT));
10374 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10375 RVT, &ZeroOps[0], ZeroOps.size());
10376 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10377 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10378 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10385 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10386 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10387 assert(N->getValueType(0).isVector() &&
10388 "SimplifyVBinOp only works on vectors!");
10390 SDValue LHS = N->getOperand(0);
10391 SDValue RHS = N->getOperand(1);
10392 SDValue Shuffle = XformToShuffleWithZero(N);
10393 if (Shuffle.getNode()) return Shuffle;
10395 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10397 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10398 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10399 // Check if both vectors are constants. If not bail out.
10400 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10401 cast<BuildVectorSDNode>(RHS)->isConstant()))
10404 SmallVector<SDValue, 8> Ops;
10405 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10406 SDValue LHSOp = LHS.getOperand(i);
10407 SDValue RHSOp = RHS.getOperand(i);
10409 // Can't fold divide by zero.
10410 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10411 N->getOpcode() == ISD::FDIV) {
10412 if ((RHSOp.getOpcode() == ISD::Constant &&
10413 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10414 (RHSOp.getOpcode() == ISD::ConstantFP &&
10415 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10419 EVT VT = LHSOp.getValueType();
10420 EVT RVT = RHSOp.getValueType();
10422 // Integer BUILD_VECTOR operands may have types larger than the element
10423 // size (e.g., when the element type is not legal). Prior to type
10424 // legalization, the types may not match between the two BUILD_VECTORS.
10425 // Truncate one of the operands to make them match.
10426 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10427 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10429 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10433 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10435 if (FoldOp.getOpcode() != ISD::UNDEF &&
10436 FoldOp.getOpcode() != ISD::Constant &&
10437 FoldOp.getOpcode() != ISD::ConstantFP)
10439 Ops.push_back(FoldOp);
10440 AddToWorkList(FoldOp.getNode());
10443 if (Ops.size() == LHS.getNumOperands())
10444 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10445 LHS.getValueType(), &Ops[0], Ops.size());
10451 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10452 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10453 assert(N->getValueType(0).isVector() &&
10454 "SimplifyVUnaryOp only works on vectors!");
10456 SDValue N0 = N->getOperand(0);
10458 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10461 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10462 SmallVector<SDValue, 8> Ops;
10463 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10464 SDValue Op = N0.getOperand(i);
10465 if (Op.getOpcode() != ISD::UNDEF &&
10466 Op.getOpcode() != ISD::ConstantFP)
10468 EVT EltVT = Op.getValueType();
10469 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10470 if (FoldOp.getOpcode() != ISD::UNDEF &&
10471 FoldOp.getOpcode() != ISD::ConstantFP)
10473 Ops.push_back(FoldOp);
10474 AddToWorkList(FoldOp.getNode());
10477 if (Ops.size() != N0.getNumOperands())
10480 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10481 N0.getValueType(), &Ops[0], Ops.size());
10484 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10485 SDValue N1, SDValue N2){
10486 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10488 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10489 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10491 // If we got a simplified select_cc node back from SimplifySelectCC, then
10492 // break it down into a new SETCC node, and a new SELECT node, and then return
10493 // the SELECT node, since we were called with a SELECT node.
10494 if (SCC.getNode()) {
10495 // Check to see if we got a select_cc back (to turn into setcc/select).
10496 // Otherwise, just return whatever node we got back, like fabs.
10497 if (SCC.getOpcode() == ISD::SELECT_CC) {
10498 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10500 SCC.getOperand(0), SCC.getOperand(1),
10501 SCC.getOperand(4));
10502 AddToWorkList(SETCC.getNode());
10503 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10504 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10512 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10513 /// are the two values being selected between, see if we can simplify the
10514 /// select. Callers of this should assume that TheSelect is deleted if this
10515 /// returns true. As such, they should return the appropriate thing (e.g. the
10516 /// node) back to the top-level of the DAG combiner loop to avoid it being
10518 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10521 // Cannot simplify select with vector condition
10522 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10524 // If this is a select from two identical things, try to pull the operation
10525 // through the select.
10526 if (LHS.getOpcode() != RHS.getOpcode() ||
10527 !LHS.hasOneUse() || !RHS.hasOneUse())
10530 // If this is a load and the token chain is identical, replace the select
10531 // of two loads with a load through a select of the address to load from.
10532 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10533 // constants have been dropped into the constant pool.
10534 if (LHS.getOpcode() == ISD::LOAD) {
10535 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10536 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10538 // Token chains must be identical.
10539 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10540 // Do not let this transformation reduce the number of volatile loads.
10541 LLD->isVolatile() || RLD->isVolatile() ||
10542 // If this is an EXTLOAD, the VT's must match.
10543 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10544 // If this is an EXTLOAD, the kind of extension must match.
10545 (LLD->getExtensionType() != RLD->getExtensionType() &&
10546 // The only exception is if one of the extensions is anyext.
10547 LLD->getExtensionType() != ISD::EXTLOAD &&
10548 RLD->getExtensionType() != ISD::EXTLOAD) ||
10549 // FIXME: this discards src value information. This is
10550 // over-conservative. It would be beneficial to be able to remember
10551 // both potential memory locations. Since we are discarding
10552 // src value info, don't do the transformation if the memory
10553 // locations are not in the default address space.
10554 LLD->getPointerInfo().getAddrSpace() != 0 ||
10555 RLD->getPointerInfo().getAddrSpace() != 0 ||
10556 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10557 LLD->getBasePtr().getValueType()))
10560 // Check that the select condition doesn't reach either load. If so,
10561 // folding this will induce a cycle into the DAG. If not, this is safe to
10562 // xform, so create a select of the addresses.
10564 if (TheSelect->getOpcode() == ISD::SELECT) {
10565 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10566 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10567 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10569 // The loads must not depend on one another.
10570 if (LLD->isPredecessorOf(RLD) ||
10571 RLD->isPredecessorOf(LLD))
10573 Addr = DAG.getSelect(SDLoc(TheSelect),
10574 LLD->getBasePtr().getValueType(),
10575 TheSelect->getOperand(0), LLD->getBasePtr(),
10576 RLD->getBasePtr());
10577 } else { // Otherwise SELECT_CC
10578 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10579 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10581 if ((LLD->hasAnyUseOfValue(1) &&
10582 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10583 (RLD->hasAnyUseOfValue(1) &&
10584 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10587 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10588 LLD->getBasePtr().getValueType(),
10589 TheSelect->getOperand(0),
10590 TheSelect->getOperand(1),
10591 LLD->getBasePtr(), RLD->getBasePtr(),
10592 TheSelect->getOperand(4));
10596 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10597 Load = DAG.getLoad(TheSelect->getValueType(0),
10599 // FIXME: Discards pointer and TBAA info.
10600 LLD->getChain(), Addr, MachinePointerInfo(),
10601 LLD->isVolatile(), LLD->isNonTemporal(),
10602 LLD->isInvariant(), LLD->getAlignment());
10604 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10605 RLD->getExtensionType() : LLD->getExtensionType(),
10607 TheSelect->getValueType(0),
10608 // FIXME: Discards pointer and TBAA info.
10609 LLD->getChain(), Addr, MachinePointerInfo(),
10610 LLD->getMemoryVT(), LLD->isVolatile(),
10611 LLD->isNonTemporal(), LLD->getAlignment());
10614 // Users of the select now use the result of the load.
10615 CombineTo(TheSelect, Load);
10617 // Users of the old loads now use the new load's chain. We know the
10618 // old-load value is dead now.
10619 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10620 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10627 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10628 /// where 'cond' is the comparison specified by CC.
10629 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10630 SDValue N2, SDValue N3,
10631 ISD::CondCode CC, bool NotExtCompare) {
10632 // (x ? y : y) -> y.
10633 if (N2 == N3) return N2;
10635 EVT VT = N2.getValueType();
10636 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10637 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10638 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10640 // Determine if the condition we're dealing with is constant
10641 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10642 N0, N1, CC, DL, false);
10643 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10644 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10646 // fold select_cc true, x, y -> x
10647 if (SCCC && !SCCC->isNullValue())
10649 // fold select_cc false, x, y -> y
10650 if (SCCC && SCCC->isNullValue())
10653 // Check to see if we can simplify the select into an fabs node
10654 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10655 // Allow either -0.0 or 0.0
10656 if (CFP->getValueAPF().isZero()) {
10657 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10658 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10659 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10660 N2 == N3.getOperand(0))
10661 return DAG.getNode(ISD::FABS, DL, VT, N0);
10663 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10664 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10665 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10666 N2.getOperand(0) == N3)
10667 return DAG.getNode(ISD::FABS, DL, VT, N3);
10671 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10672 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10673 // in it. This is a win when the constant is not otherwise available because
10674 // it replaces two constant pool loads with one. We only do this if the FP
10675 // type is known to be legal, because if it isn't, then we are before legalize
10676 // types an we want the other legalization to happen first (e.g. to avoid
10677 // messing with soft float) and if the ConstantFP is not legal, because if
10678 // it is legal, we may not need to store the FP constant in a constant pool.
10679 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10680 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10681 if (TLI.isTypeLegal(N2.getValueType()) &&
10682 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10683 TargetLowering::Legal) &&
10684 // If both constants have multiple uses, then we won't need to do an
10685 // extra load, they are likely around in registers for other users.
10686 (TV->hasOneUse() || FV->hasOneUse())) {
10687 Constant *Elts[] = {
10688 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10689 const_cast<ConstantFP*>(TV->getConstantFPValue())
10691 Type *FPTy = Elts[0]->getType();
10692 const DataLayout &TD = *TLI.getDataLayout();
10694 // Create a ConstantArray of the two constants.
10695 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10696 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10697 TD.getPrefTypeAlignment(FPTy));
10698 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10700 // Get the offsets to the 0 and 1 element of the array so that we can
10701 // select between them.
10702 SDValue Zero = DAG.getIntPtrConstant(0);
10703 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10704 SDValue One = DAG.getIntPtrConstant(EltSize);
10706 SDValue Cond = DAG.getSetCC(DL,
10707 getSetCCResultType(N0.getValueType()),
10709 AddToWorkList(Cond.getNode());
10710 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10712 AddToWorkList(CstOffset.getNode());
10713 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10715 AddToWorkList(CPIdx.getNode());
10716 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10717 MachinePointerInfo::getConstantPool(), false,
10718 false, false, Alignment);
10723 // Check to see if we can perform the "gzip trick", transforming
10724 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10725 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10726 (N1C->isNullValue() || // (a < 0) ? b : 0
10727 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10728 EVT XType = N0.getValueType();
10729 EVT AType = N2.getValueType();
10730 if (XType.bitsGE(AType)) {
10731 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10732 // single-bit constant.
10733 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10734 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10735 ShCtV = XType.getSizeInBits()-ShCtV-1;
10736 SDValue ShCt = DAG.getConstant(ShCtV,
10737 getShiftAmountTy(N0.getValueType()));
10738 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10740 AddToWorkList(Shift.getNode());
10742 if (XType.bitsGT(AType)) {
10743 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10744 AddToWorkList(Shift.getNode());
10747 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10750 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10752 DAG.getConstant(XType.getSizeInBits()-1,
10753 getShiftAmountTy(N0.getValueType())));
10754 AddToWorkList(Shift.getNode());
10756 if (XType.bitsGT(AType)) {
10757 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10758 AddToWorkList(Shift.getNode());
10761 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10765 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10766 // where y is has a single bit set.
10767 // A plaintext description would be, we can turn the SELECT_CC into an AND
10768 // when the condition can be materialized as an all-ones register. Any
10769 // single bit-test can be materialized as an all-ones register with
10770 // shift-left and shift-right-arith.
10771 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10772 N0->getValueType(0) == VT &&
10773 N1C && N1C->isNullValue() &&
10774 N2C && N2C->isNullValue()) {
10775 SDValue AndLHS = N0->getOperand(0);
10776 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10777 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10778 // Shift the tested bit over the sign bit.
10779 APInt AndMask = ConstAndRHS->getAPIntValue();
10781 DAG.getConstant(AndMask.countLeadingZeros(),
10782 getShiftAmountTy(AndLHS.getValueType()));
10783 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10785 // Now arithmetic right shift it all the way over, so the result is either
10786 // all-ones, or zero.
10788 DAG.getConstant(AndMask.getBitWidth()-1,
10789 getShiftAmountTy(Shl.getValueType()));
10790 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10792 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10796 // fold select C, 16, 0 -> shl C, 4
10797 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10798 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10799 TargetLowering::ZeroOrOneBooleanContent) {
10801 // If the caller doesn't want us to simplify this into a zext of a compare,
10803 if (NotExtCompare && N2C->getAPIntValue() == 1)
10806 // Get a SetCC of the condition
10807 // NOTE: Don't create a SETCC if it's not legal on this target.
10808 if (!LegalOperations ||
10809 TLI.isOperationLegal(ISD::SETCC,
10810 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10812 // cast from setcc result type to select result type
10814 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10816 if (N2.getValueType().bitsLT(SCC.getValueType()))
10817 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10818 N2.getValueType());
10820 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10821 N2.getValueType(), SCC);
10823 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10824 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10825 N2.getValueType(), SCC);
10828 AddToWorkList(SCC.getNode());
10829 AddToWorkList(Temp.getNode());
10831 if (N2C->getAPIntValue() == 1)
10834 // shl setcc result by log2 n2c
10835 return DAG.getNode(
10836 ISD::SHL, DL, N2.getValueType(), Temp,
10837 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10838 getShiftAmountTy(Temp.getValueType())));
10842 // Check to see if this is the equivalent of setcc
10843 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10844 // otherwise, go ahead with the folds.
10845 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10846 EVT XType = N0.getValueType();
10847 if (!LegalOperations ||
10848 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10849 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10850 if (Res.getValueType() != VT)
10851 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10855 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10856 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10857 (!LegalOperations ||
10858 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10859 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10860 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10861 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10862 getShiftAmountTy(Ctlz.getValueType())));
10864 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10865 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10866 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10867 XType, DAG.getConstant(0, XType), N0);
10868 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10869 return DAG.getNode(ISD::SRL, DL, XType,
10870 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10871 DAG.getConstant(XType.getSizeInBits()-1,
10872 getShiftAmountTy(XType)));
10874 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10875 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10876 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10877 DAG.getConstant(XType.getSizeInBits()-1,
10878 getShiftAmountTy(N0.getValueType())));
10879 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10883 // Check to see if this is an integer abs.
10884 // select_cc setg[te] X, 0, X, -X ->
10885 // select_cc setgt X, -1, X, -X ->
10886 // select_cc setl[te] X, 0, -X, X ->
10887 // select_cc setlt X, 1, -X, X ->
10888 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10890 ConstantSDNode *SubC = NULL;
10891 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10892 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10893 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10894 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10895 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10896 (N1C->isOne() && CC == ISD::SETLT)) &&
10897 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10898 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10900 EVT XType = N0.getValueType();
10901 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10902 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10904 DAG.getConstant(XType.getSizeInBits()-1,
10905 getShiftAmountTy(N0.getValueType())));
10906 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10908 AddToWorkList(Shift.getNode());
10909 AddToWorkList(Add.getNode());
10910 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10917 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10918 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10919 SDValue N1, ISD::CondCode Cond,
10920 SDLoc DL, bool foldBooleans) {
10921 TargetLowering::DAGCombinerInfo
10922 DagCombineInfo(DAG, Level, false, this);
10923 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10926 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10927 /// return a DAG expression to select that will generate the same value by
10928 /// multiplying by a magic number. See:
10929 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10930 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10931 std::vector<SDNode*> Built;
10932 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10934 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10936 AddToWorkList(*ii);
10940 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10941 /// return a DAG expression to select that will generate the same value by
10942 /// multiplying by a magic number. See:
10943 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10944 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10945 std::vector<SDNode*> Built;
10946 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10948 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10950 AddToWorkList(*ii);
10954 /// FindBaseOffset - Return true if base is a frame index, which is known not
10955 // to alias with anything but itself. Provides base object and offset as
10957 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10958 const GlobalValue *&GV, const void *&CV) {
10959 // Assume it is a primitive operation.
10960 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10962 // If it's an adding a simple constant then integrate the offset.
10963 if (Base.getOpcode() == ISD::ADD) {
10964 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10965 Base = Base.getOperand(0);
10966 Offset += C->getZExtValue();
10970 // Return the underlying GlobalValue, and update the Offset. Return false
10971 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10972 // by multiple nodes with different offsets.
10973 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10974 GV = G->getGlobal();
10975 Offset += G->getOffset();
10979 // Return the underlying Constant value, and update the Offset. Return false
10980 // for ConstantSDNodes since the same constant pool entry may be represented
10981 // by multiple nodes with different offsets.
10982 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10983 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10984 : (const void *)C->getConstVal();
10985 Offset += C->getOffset();
10988 // If it's any of the following then it can't alias with anything but itself.
10989 return isa<FrameIndexSDNode>(Base);
10992 /// isAlias - Return true if there is any possibility that the two addresses
10994 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10995 const Value *SrcValue1, int SrcValueOffset1,
10996 unsigned SrcValueAlign1,
10997 const MDNode *TBAAInfo1,
10998 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10999 const Value *SrcValue2, int SrcValueOffset2,
11000 unsigned SrcValueAlign2,
11001 const MDNode *TBAAInfo2) const {
11002 // If they are the same then they must be aliases.
11003 if (Ptr1 == Ptr2) return true;
11005 // If they are both volatile then they cannot be reordered.
11006 if (IsVolatile1 && IsVolatile2) return true;
11008 // Gather base node and offset information.
11009 SDValue Base1, Base2;
11010 int64_t Offset1, Offset2;
11011 const GlobalValue *GV1, *GV2;
11012 const void *CV1, *CV2;
11013 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11014 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11016 // If they have a same base address then check to see if they overlap.
11017 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11018 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11020 // It is possible for different frame indices to alias each other, mostly
11021 // when tail call optimization reuses return address slots for arguments.
11022 // To catch this case, look up the actual index of frame indices to compute
11023 // the real alias relationship.
11024 if (isFrameIndex1 && isFrameIndex2) {
11025 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11026 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11027 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11028 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11031 // Otherwise, if we know what the bases are, and they aren't identical, then
11032 // we know they cannot alias.
11033 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11036 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11037 // compared to the size and offset of the access, we may be able to prove they
11038 // do not alias. This check is conservative for now to catch cases created by
11039 // splitting vector types.
11040 if ((SrcValueAlign1 == SrcValueAlign2) &&
11041 (SrcValueOffset1 != SrcValueOffset2) &&
11042 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11043 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11044 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11046 // There is no overlap between these relatively aligned accesses of similar
11047 // size, return no alias.
11048 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11052 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11053 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11054 if (UseAA && SrcValue1 && SrcValue2) {
11055 // Use alias analysis information.
11056 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11057 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11058 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11059 AliasAnalysis::AliasResult AAResult =
11060 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
11061 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
11062 if (AAResult == AliasAnalysis::NoAlias)
11066 // Otherwise we have to assume they alias.
11070 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11071 SDValue Ptr0, Ptr1;
11072 int64_t Size0, Size1;
11073 bool IsVolatile0, IsVolatile1;
11074 const Value *SrcValue0, *SrcValue1;
11075 int SrcValueOffset0, SrcValueOffset1;
11076 unsigned SrcValueAlign0, SrcValueAlign1;
11077 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11078 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11079 SrcValueAlign0, SrcTBAAInfo0);
11080 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11081 SrcValueAlign1, SrcTBAAInfo1);
11082 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11083 SrcValueAlign0, SrcTBAAInfo0,
11084 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11085 SrcValueAlign1, SrcTBAAInfo1);
11088 /// FindAliasInfo - Extracts the relevant alias information from the memory
11089 /// node. Returns true if the operand was a nonvolatile load.
11090 bool DAGCombiner::FindAliasInfo(SDNode *N,
11091 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11092 const Value *&SrcValue,
11093 int &SrcValueOffset,
11094 unsigned &SrcValueAlign,
11095 const MDNode *&TBAAInfo) const {
11096 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11098 Ptr = LS->getBasePtr();
11099 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11100 IsVolatile = LS->isVolatile();
11101 SrcValue = LS->getSrcValue();
11102 SrcValueOffset = LS->getSrcValueOffset();
11103 SrcValueAlign = LS->getOriginalAlignment();
11104 TBAAInfo = LS->getTBAAInfo();
11105 return isa<LoadSDNode>(LS) && !IsVolatile;
11108 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11109 /// looking for aliasing nodes and adding them to the Aliases vector.
11110 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11111 SmallVectorImpl<SDValue> &Aliases) {
11112 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11113 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11115 // Get alias information for node.
11119 const Value *SrcValue;
11120 int SrcValueOffset;
11121 unsigned SrcValueAlign;
11122 const MDNode *SrcTBAAInfo;
11123 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11124 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11127 Chains.push_back(OriginalChain);
11128 unsigned Depth = 0;
11130 // Look at each chain and determine if it is an alias. If so, add it to the
11131 // aliases list. If not, then continue up the chain looking for the next
11133 while (!Chains.empty()) {
11134 SDValue Chain = Chains.back();
11137 // For TokenFactor nodes, look at each operand and only continue up the
11138 // chain until we find two aliases. If we've seen two aliases, assume we'll
11139 // find more and revert to original chain since the xform is unlikely to be
11142 // FIXME: The depth check could be made to return the last non-aliasing
11143 // chain we found before we hit a tokenfactor rather than the original
11145 if (Depth > 6 || Aliases.size() == 2) {
11147 Aliases.push_back(OriginalChain);
11151 // Don't bother if we've been before.
11152 if (!Visited.insert(Chain.getNode()))
11155 switch (Chain.getOpcode()) {
11156 case ISD::EntryToken:
11157 // Entry token is ideal chain operand, but handled in FindBetterChain.
11162 // Get alias information for Chain.
11166 const Value *OpSrcValue;
11167 int OpSrcValueOffset;
11168 unsigned OpSrcValueAlign;
11169 const MDNode *OpSrcTBAAInfo;
11170 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11171 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11175 // If chain is alias then stop here.
11176 if (!(IsLoad && IsOpLoad) &&
11177 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11178 SrcValueAlign, SrcTBAAInfo,
11179 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11180 OpSrcValueAlign, OpSrcTBAAInfo)) {
11181 Aliases.push_back(Chain);
11183 // Look further up the chain.
11184 Chains.push_back(Chain.getOperand(0));
11190 case ISD::TokenFactor:
11191 // We have to check each of the operands of the token factor for "small"
11192 // token factors, so we queue them up. Adding the operands to the queue
11193 // (stack) in reverse order maintains the original order and increases the
11194 // likelihood that getNode will find a matching token factor (CSE.)
11195 if (Chain.getNumOperands() > 16) {
11196 Aliases.push_back(Chain);
11199 for (unsigned n = Chain.getNumOperands(); n;)
11200 Chains.push_back(Chain.getOperand(--n));
11205 // For all other instructions we will just have to take what we can get.
11206 Aliases.push_back(Chain);
11211 // We need to be careful here to also search for aliases through the
11212 // value operand of a store, etc. Consider the following situation:
11214 // L1 = load Token1, %52
11215 // S1 = store Token1, L1, %51
11216 // L2 = load Token1, %52+8
11217 // S2 = store Token1, L2, %51+8
11218 // Token2 = Token(S1, S2)
11219 // L3 = load Token2, %53
11220 // S3 = store Token2, L3, %52
11221 // L4 = load Token2, %53+8
11222 // S4 = store Token2, L4, %52+8
11223 // If we search for aliases of S3 (which loads address %52), and we look
11224 // only through the chain, then we'll miss the trivial dependence on L1
11225 // (which also loads from %52). We then might change all loads and
11226 // stores to use Token1 as their chain operand, which could result in
11227 // copying %53 into %52 before copying %52 into %51 (which should
11230 // The problem is, however, that searching for such data dependencies
11231 // can become expensive, and the cost is not directly related to the
11232 // chain depth. Instead, we'll rule out such configurations here by
11233 // insisting that we've visited all chain users (except for users
11234 // of the original chain, which is not necessary). When doing this,
11235 // we need to look through nodes we don't care about (otherwise, things
11236 // like register copies will interfere with trivial cases).
11238 SmallVector<const SDNode *, 16> Worklist;
11239 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11240 IE = Visited.end(); I != IE; ++I)
11241 if (*I != OriginalChain.getNode())
11242 Worklist.push_back(*I);
11244 while (!Worklist.empty()) {
11245 const SDNode *M = Worklist.pop_back_val();
11247 // We have already visited M, and want to make sure we've visited any uses
11248 // of M that we care about. For uses that we've not visisted, and don't
11249 // care about, queue them to the worklist.
11251 for (SDNode::use_iterator UI = M->use_begin(),
11252 UIE = M->use_end(); UI != UIE; ++UI)
11253 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11254 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11255 // We've not visited this use, and we care about it (it could have an
11256 // ordering dependency with the original node).
11258 Aliases.push_back(OriginalChain);
11262 // We've not visited this use, but we don't care about it. Mark it as
11263 // visited and enqueue it to the worklist.
11264 Worklist.push_back(*UI);
11269 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11270 /// for a better chain (aliasing node.)
11271 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11272 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11274 // Accumulate all the aliases to this node.
11275 GatherAllAliases(N, OldChain, Aliases);
11277 // If no operands then chain to entry token.
11278 if (Aliases.size() == 0)
11279 return DAG.getEntryNode();
11281 // If a single operand then chain to it. We don't need to revisit it.
11282 if (Aliases.size() == 1)
11285 // Construct a custom tailored token factor.
11286 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11287 &Aliases[0], Aliases.size());
11290 // SelectionDAG::Combine - This is the entry point for the file.
11292 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11293 CodeGenOpt::Level OptLevel) {
11294 /// run - This is the main entry point to this class.
11296 DAGCombiner(*this, AA, OptLevel).Run(Level);