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.isOperationLegal(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 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3217 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3218 N0.getOperand(0), N1),
3219 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3221 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3222 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3223 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3224 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3226 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3227 LL.getValueType().isInteger()) {
3228 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3229 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3230 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3231 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3232 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3233 LR.getValueType(), LL, RL);
3234 AddToWorkList(ORNode.getNode());
3235 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3237 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3238 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3239 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3240 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3241 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3242 LR.getValueType(), LL, RL);
3243 AddToWorkList(ANDNode.getNode());
3244 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3247 // canonicalize equivalent to ll == rl
3248 if (LL == RR && LR == RL) {
3249 Op1 = ISD::getSetCCSwappedOperands(Op1);
3252 if (LL == RL && LR == RR) {
3253 bool isInteger = LL.getValueType().isInteger();
3254 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3255 if (Result != ISD::SETCC_INVALID &&
3256 (!LegalOperations ||
3257 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3258 TLI.isOperationLegal(ISD::SETCC,
3259 getSetCCResultType(N0.getValueType())))))
3260 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3265 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3266 if (N0.getOpcode() == N1.getOpcode()) {
3267 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3268 if (Tmp.getNode()) return Tmp;
3271 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3272 if (N0.getOpcode() == ISD::AND &&
3273 N1.getOpcode() == ISD::AND &&
3274 N0.getOperand(1).getOpcode() == ISD::Constant &&
3275 N1.getOperand(1).getOpcode() == ISD::Constant &&
3276 // Don't increase # computations.
3277 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3278 // We can only do this xform if we know that bits from X that are set in C2
3279 // but not in C1 are already zero. Likewise for Y.
3280 const APInt &LHSMask =
3281 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3282 const APInt &RHSMask =
3283 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3285 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3286 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3287 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3288 N0.getOperand(0), N1.getOperand(0));
3289 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3290 DAG.getConstant(LHSMask | RHSMask, VT));
3294 // See if this is some rotate idiom.
3295 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3296 return SDValue(Rot, 0);
3298 // Simplify the operands using demanded-bits information.
3299 if (!VT.isVector() &&
3300 SimplifyDemandedBits(SDValue(N, 0)))
3301 return SDValue(N, 0);
3306 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3307 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3308 if (Op.getOpcode() == ISD::AND) {
3309 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3310 Mask = Op.getOperand(1);
3311 Op = Op.getOperand(0);
3317 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3325 // Return true if we can prove that, whenever Neg and Pos are both in the
3326 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3327 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3329 // (or (shift1 X, Neg), (shift2 X, Pos))
3331 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3332 // shift1 by Neg. The range [0, OpSize) means that we only need to consider
3333 // shift amounts with defined behavior.
3334 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3335 // If OpSize is a power of 2 then:
3337 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3338 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3340 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3341 // for the stronger condition:
3343 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3345 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3346 // we can just replace Neg with Neg' for the rest of the function.
3348 // In other cases we check for the even stronger condition:
3350 // Neg == OpSize - Pos [B]
3352 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3353 // behavior if Pos == 0 (and consequently Neg == OpSize).
3355 // We could actually use [A] whenever OpSize is a power of 2, but the
3356 // only extra cases that it would match are those uninteresting ones
3357 // where Neg and Pos are never in range at the same time. E.g. for
3358 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3359 // as well as (sub 32, Pos), but:
3361 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3363 // always invokes undefined behavior for 32-bit X.
3365 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3366 unsigned LoBits = 0;
3367 if (Neg.getOpcode() == ISD::AND &&
3368 isPowerOf2_64(OpSize) &&
3369 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3370 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3371 Neg = Neg.getOperand(0);
3372 LoBits = Log2_64(OpSize);
3375 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3376 if (Neg.getOpcode() != ISD::SUB)
3378 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3381 SDValue NegOp1 = Neg.getOperand(1);
3383 // The condition we need is now:
3385 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3387 // If NegOp1 == Pos then we need:
3389 // OpSize & Mask == NegC & Mask
3391 // (because "x & Mask" is a truncation and distributes through subtraction).
3394 Width = NegC->getAPIntValue();
3395 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3396 // Then the condition we want to prove becomes:
3398 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3400 // which, again because "x & Mask" is a truncation, becomes:
3402 // NegC & Mask == (OpSize - PosC) & Mask
3403 // OpSize & Mask == (NegC + PosC) & Mask
3404 else if (Pos.getOpcode() == ISD::ADD &&
3405 Pos.getOperand(0) == NegOp1 &&
3406 Pos.getOperand(1).getOpcode() == ISD::Constant)
3407 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3408 NegC->getAPIntValue());
3412 // Now we just need to check that OpSize & Mask == Width & Mask.
3414 return Width.getLoBits(LoBits) == 0;
3415 return Width == OpSize;
3418 // A subroutine of MatchRotate used once we have found an OR of two opposite
3419 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3420 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3421 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3422 // Neg with outer conversions stripped away.
3423 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3424 SDValue Neg, SDValue InnerPos,
3425 SDValue InnerNeg, unsigned PosOpcode,
3426 unsigned NegOpcode, SDLoc DL) {
3427 // fold (or (shl x, (*ext y)),
3428 // (srl x, (*ext (sub 32, y)))) ->
3429 // (rotl x, y) or (rotr x, (sub 32, y))
3431 // fold (or (shl x, (*ext (sub 32, y))),
3432 // (srl x, (*ext y))) ->
3433 // (rotr x, y) or (rotl x, (sub 32, y))
3434 EVT VT = Shifted.getValueType();
3435 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3436 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3437 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3438 HasPos ? Pos : Neg).getNode();
3441 // fold (or (shl (*ext x), (*ext y)),
3442 // (srl (*ext x), (*ext (sub 32, y)))) ->
3443 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3445 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3446 // (srl (*ext x), (*ext y))) ->
3447 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3448 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3449 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3450 SDValue InnerShifted = Shifted.getOperand(0);
3451 EVT InnerVT = InnerShifted.getValueType();
3452 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3453 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3454 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3455 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3456 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3457 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3465 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3466 // idioms for rotate, and if the target supports rotation instructions, generate
3468 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3469 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3470 EVT VT = LHS.getValueType();
3471 if (!TLI.isTypeLegal(VT)) return 0;
3473 // The target must have at least one rotate flavor.
3474 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3475 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3476 if (!HasROTL && !HasROTR) return 0;
3478 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3479 SDValue LHSShift; // The shift.
3480 SDValue LHSMask; // AND value if any.
3481 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3482 return 0; // Not part of a rotate.
3484 SDValue RHSShift; // The shift.
3485 SDValue RHSMask; // AND value if any.
3486 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3487 return 0; // Not part of a rotate.
3489 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3490 return 0; // Not shifting the same value.
3492 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3493 return 0; // Shifts must disagree.
3495 // Canonicalize shl to left side in a shl/srl pair.
3496 if (RHSShift.getOpcode() == ISD::SHL) {
3497 std::swap(LHS, RHS);
3498 std::swap(LHSShift, RHSShift);
3499 std::swap(LHSMask , RHSMask );
3502 unsigned OpSizeInBits = VT.getSizeInBits();
3503 SDValue LHSShiftArg = LHSShift.getOperand(0);
3504 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3505 SDValue RHSShiftArg = RHSShift.getOperand(0);
3506 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3508 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3509 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3510 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3511 RHSShiftAmt.getOpcode() == ISD::Constant) {
3512 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3513 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3514 if ((LShVal + RShVal) != OpSizeInBits)
3517 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3518 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3520 // If there is an AND of either shifted operand, apply it to the result.
3521 if (LHSMask.getNode() || RHSMask.getNode()) {
3522 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3524 if (LHSMask.getNode()) {
3525 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3526 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3528 if (RHSMask.getNode()) {
3529 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3530 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3533 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3536 return Rot.getNode();
3539 // If there is a mask here, and we have a variable shift, we can't be sure
3540 // that we're masking out the right stuff.
3541 if (LHSMask.getNode() || RHSMask.getNode())
3544 // If the shift amount is sign/zext/any-extended just peel it off.
3545 SDValue LExtOp0 = LHSShiftAmt;
3546 SDValue RExtOp0 = RHSShiftAmt;
3547 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3548 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3549 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3550 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3551 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3552 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3553 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3554 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3555 LExtOp0 = LHSShiftAmt.getOperand(0);
3556 RExtOp0 = RHSShiftAmt.getOperand(0);
3559 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3560 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3564 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3565 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3572 SDValue DAGCombiner::visitXOR(SDNode *N) {
3573 SDValue N0 = N->getOperand(0);
3574 SDValue N1 = N->getOperand(1);
3575 SDValue LHS, RHS, CC;
3576 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3577 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3578 EVT VT = N0.getValueType();
3581 if (VT.isVector()) {
3582 SDValue FoldedVOp = SimplifyVBinOp(N);
3583 if (FoldedVOp.getNode()) return FoldedVOp;
3585 // fold (xor x, 0) -> x, vector edition
3586 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3588 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3592 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3593 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3594 return DAG.getConstant(0, VT);
3595 // fold (xor x, undef) -> undef
3596 if (N0.getOpcode() == ISD::UNDEF)
3598 if (N1.getOpcode() == ISD::UNDEF)
3600 // fold (xor c1, c2) -> c1^c2
3602 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3603 // canonicalize constant to RHS
3605 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3606 // fold (xor x, 0) -> x
3607 if (N1C && N1C->isNullValue())
3610 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3611 if (RXOR.getNode() != 0)
3614 // fold !(x cc y) -> (x !cc y)
3615 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3616 bool isInt = LHS.getValueType().isInteger();
3617 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3620 if (!LegalOperations ||
3621 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3622 switch (N0.getOpcode()) {
3624 llvm_unreachable("Unhandled SetCC Equivalent!");
3626 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3627 case ISD::SELECT_CC:
3628 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3629 N0.getOperand(3), NotCC);
3634 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3635 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3636 N0.getNode()->hasOneUse() &&
3637 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3638 SDValue V = N0.getOperand(0);
3639 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3640 DAG.getConstant(1, V.getValueType()));
3641 AddToWorkList(V.getNode());
3642 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3645 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3646 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3647 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3648 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3649 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3650 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3651 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3652 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3653 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3654 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3657 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3658 if (N1C && N1C->isAllOnesValue() &&
3659 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3660 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3661 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3662 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3663 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3664 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3665 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3666 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3669 // fold (xor (and x, y), y) -> (and (not x), y)
3670 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3671 N0->getOperand(1) == N1) {
3672 SDValue X = N0->getOperand(0);
3673 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3674 AddToWorkList(NotX.getNode());
3675 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3677 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3678 if (N1C && N0.getOpcode() == ISD::XOR) {
3679 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3680 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3682 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3683 DAG.getConstant(N1C->getAPIntValue() ^
3684 N00C->getAPIntValue(), VT));
3686 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3687 DAG.getConstant(N1C->getAPIntValue() ^
3688 N01C->getAPIntValue(), VT));
3690 // fold (xor x, x) -> 0
3692 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3694 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3695 if (N0.getOpcode() == N1.getOpcode()) {
3696 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3697 if (Tmp.getNode()) return Tmp;
3700 // Simplify the expression using non-local knowledge.
3701 if (!VT.isVector() &&
3702 SimplifyDemandedBits(SDValue(N, 0)))
3703 return SDValue(N, 0);
3708 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3709 /// the shift amount is a constant.
3710 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3711 SDNode *LHS = N->getOperand(0).getNode();
3712 if (!LHS->hasOneUse()) return SDValue();
3714 // We want to pull some binops through shifts, so that we have (and (shift))
3715 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3716 // thing happens with address calculations, so it's important to canonicalize
3718 bool HighBitSet = false; // Can we transform this if the high bit is set?
3720 switch (LHS->getOpcode()) {
3721 default: return SDValue();
3724 HighBitSet = false; // We can only transform sra if the high bit is clear.
3727 HighBitSet = true; // We can only transform sra if the high bit is set.
3730 if (N->getOpcode() != ISD::SHL)
3731 return SDValue(); // only shl(add) not sr[al](add).
3732 HighBitSet = false; // We can only transform sra if the high bit is clear.
3736 // We require the RHS of the binop to be a constant as well.
3737 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3738 if (!BinOpCst) return SDValue();
3740 // FIXME: disable this unless the input to the binop is a shift by a constant.
3741 // If it is not a shift, it pessimizes some common cases like:
3743 // void foo(int *X, int i) { X[i & 1235] = 1; }
3744 // int bar(int *X, int i) { return X[i & 255]; }
3745 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3746 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3747 BinOpLHSVal->getOpcode() != ISD::SRA &&
3748 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3749 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3752 EVT VT = N->getValueType(0);
3754 // If this is a signed shift right, and the high bit is modified by the
3755 // logical operation, do not perform the transformation. The highBitSet
3756 // boolean indicates the value of the high bit of the constant which would
3757 // cause it to be modified for this operation.
3758 if (N->getOpcode() == ISD::SRA) {
3759 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3760 if (BinOpRHSSignSet != HighBitSet)
3764 // Fold the constants, shifting the binop RHS by the shift amount.
3765 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3767 LHS->getOperand(1), N->getOperand(1));
3769 // Create the new shift.
3770 SDValue NewShift = DAG.getNode(N->getOpcode(),
3771 SDLoc(LHS->getOperand(0)),
3772 VT, LHS->getOperand(0), N->getOperand(1));
3774 // Create the new binop.
3775 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3778 SDValue DAGCombiner::visitSHL(SDNode *N) {
3779 SDValue N0 = N->getOperand(0);
3780 SDValue N1 = N->getOperand(1);
3781 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3782 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3783 EVT VT = N0.getValueType();
3784 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3787 if (VT.isVector()) {
3788 SDValue FoldedVOp = SimplifyVBinOp(N);
3789 if (FoldedVOp.getNode()) return FoldedVOp;
3792 // fold (shl c1, c2) -> c1<<c2
3794 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3795 // fold (shl 0, x) -> 0
3796 if (N0C && N0C->isNullValue())
3798 // fold (shl x, c >= size(x)) -> undef
3799 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3800 return DAG.getUNDEF(VT);
3801 // fold (shl x, 0) -> x
3802 if (N1C && N1C->isNullValue())
3804 // fold (shl undef, x) -> 0
3805 if (N0.getOpcode() == ISD::UNDEF)
3806 return DAG.getConstant(0, VT);
3807 // if (shl x, c) is known to be zero, return 0
3808 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3809 APInt::getAllOnesValue(OpSizeInBits)))
3810 return DAG.getConstant(0, VT);
3811 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3812 if (N1.getOpcode() == ISD::TRUNCATE &&
3813 N1.getOperand(0).getOpcode() == ISD::AND &&
3814 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3815 SDValue N101 = N1.getOperand(0).getOperand(1);
3816 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3817 EVT TruncVT = N1.getValueType();
3818 SDValue N100 = N1.getOperand(0).getOperand(0);
3819 APInt TruncC = N101C->getAPIntValue();
3820 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3821 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3822 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3823 DAG.getNode(ISD::TRUNCATE,
3826 DAG.getConstant(TruncC, TruncVT)));
3830 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3831 return SDValue(N, 0);
3833 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3834 if (N1C && N0.getOpcode() == ISD::SHL &&
3835 N0.getOperand(1).getOpcode() == ISD::Constant) {
3836 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3837 uint64_t c2 = N1C->getZExtValue();
3838 if (c1 + c2 >= OpSizeInBits)
3839 return DAG.getConstant(0, VT);
3840 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3841 DAG.getConstant(c1 + c2, N1.getValueType()));
3844 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3845 // For this to be valid, the second form must not preserve any of the bits
3846 // that are shifted out by the inner shift in the first form. This means
3847 // the outer shift size must be >= the number of bits added by the ext.
3848 // As a corollary, we don't care what kind of ext it is.
3849 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3850 N0.getOpcode() == ISD::ANY_EXTEND ||
3851 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3852 N0.getOperand(0).getOpcode() == ISD::SHL &&
3853 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3855 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3856 uint64_t c2 = N1C->getZExtValue();
3857 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3858 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3859 if (c2 >= OpSizeInBits - InnerShiftSize) {
3860 if (c1 + c2 >= OpSizeInBits)
3861 return DAG.getConstant(0, VT);
3862 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3863 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3864 N0.getOperand(0)->getOperand(0)),
3865 DAG.getConstant(c1 + c2, N1.getValueType()));
3869 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3870 // Only fold this if the inner zext has no other uses to avoid increasing
3871 // the total number of instructions.
3872 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3873 N0.getOperand(0).getOpcode() == ISD::SRL &&
3874 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3876 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3877 if (c1 < VT.getSizeInBits()) {
3878 uint64_t c2 = N1C->getZExtValue();
3880 SDValue NewOp0 = N0.getOperand(0);
3881 EVT CountVT = NewOp0.getOperand(1).getValueType();
3882 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3883 NewOp0, DAG.getConstant(c2, CountVT));
3884 AddToWorkList(NewSHL.getNode());
3885 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3890 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3891 // (and (srl x, (sub c1, c2), MASK)
3892 // Only fold this if the inner shift has no other uses -- if it does, folding
3893 // this will increase the total number of instructions.
3894 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3895 N0.getOperand(1).getOpcode() == ISD::Constant) {
3896 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3897 if (c1 < VT.getSizeInBits()) {
3898 uint64_t c2 = N1C->getZExtValue();
3899 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3900 VT.getSizeInBits() - c1);
3903 Mask = Mask.shl(c2-c1);
3904 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3905 DAG.getConstant(c2-c1, N1.getValueType()));
3907 Mask = Mask.lshr(c1-c2);
3908 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3909 DAG.getConstant(c1-c2, N1.getValueType()));
3911 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3912 DAG.getConstant(Mask, VT));
3915 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3916 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3917 SDValue HiBitsMask =
3918 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3919 VT.getSizeInBits() -
3920 N1C->getZExtValue()),
3922 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3927 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3928 if (NewSHL.getNode())
3935 SDValue DAGCombiner::visitSRA(SDNode *N) {
3936 SDValue N0 = N->getOperand(0);
3937 SDValue N1 = N->getOperand(1);
3938 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3940 EVT VT = N0.getValueType();
3941 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3944 if (VT.isVector()) {
3945 SDValue FoldedVOp = SimplifyVBinOp(N);
3946 if (FoldedVOp.getNode()) return FoldedVOp;
3949 // fold (sra c1, c2) -> (sra c1, c2)
3951 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3952 // fold (sra 0, x) -> 0
3953 if (N0C && N0C->isNullValue())
3955 // fold (sra -1, x) -> -1
3956 if (N0C && N0C->isAllOnesValue())
3958 // fold (sra x, (setge c, size(x))) -> undef
3959 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3960 return DAG.getUNDEF(VT);
3961 // fold (sra x, 0) -> x
3962 if (N1C && N1C->isNullValue())
3964 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3966 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3967 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3968 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3970 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3971 ExtVT, VT.getVectorNumElements());
3972 if ((!LegalOperations ||
3973 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3974 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3975 N0.getOperand(0), DAG.getValueType(ExtVT));
3978 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3979 if (N1C && N0.getOpcode() == ISD::SRA) {
3980 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3981 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3982 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3983 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3984 DAG.getConstant(Sum, N1C->getValueType(0)));
3988 // fold (sra (shl X, m), (sub result_size, n))
3989 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3990 // result_size - n != m.
3991 // If truncate is free for the target sext(shl) is likely to result in better
3993 if (N0.getOpcode() == ISD::SHL) {
3994 // Get the two constanst of the shifts, CN0 = m, CN = n.
3995 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3997 // Determine what the truncate's result bitsize and type would be.
3999 EVT::getIntegerVT(*DAG.getContext(),
4000 OpSizeInBits - N1C->getZExtValue());
4001 // Determine the residual right-shift amount.
4002 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4004 // If the shift is not a no-op (in which case this should be just a sign
4005 // extend already), the truncated to type is legal, sign_extend is legal
4006 // on that type, and the truncate to that type is both legal and free,
4007 // perform the transform.
4008 if ((ShiftAmt > 0) &&
4009 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4010 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4011 TLI.isTruncateFree(VT, TruncVT)) {
4013 SDValue Amt = DAG.getConstant(ShiftAmt,
4014 getShiftAmountTy(N0.getOperand(0).getValueType()));
4015 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4016 N0.getOperand(0), Amt);
4017 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4019 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4020 N->getValueType(0), Trunc);
4025 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4026 if (N1.getOpcode() == ISD::TRUNCATE &&
4027 N1.getOperand(0).getOpcode() == ISD::AND &&
4028 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4029 SDValue N101 = N1.getOperand(0).getOperand(1);
4030 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4031 EVT TruncVT = N1.getValueType();
4032 SDValue N100 = N1.getOperand(0).getOperand(0);
4033 APInt TruncC = N101C->getAPIntValue();
4034 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
4035 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4036 DAG.getNode(ISD::AND, SDLoc(N),
4038 DAG.getNode(ISD::TRUNCATE,
4041 DAG.getConstant(TruncC, TruncVT)));
4045 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4046 // if c1 is equal to the number of bits the trunc removes
4047 if (N0.getOpcode() == ISD::TRUNCATE &&
4048 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4049 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4050 N0.getOperand(0).hasOneUse() &&
4051 N0.getOperand(0).getOperand(1).hasOneUse() &&
4052 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4053 EVT LargeVT = N0.getOperand(0).getValueType();
4054 ConstantSDNode *LargeShiftAmt =
4055 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4057 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4058 LargeShiftAmt->getZExtValue()) {
4060 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4061 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4062 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4063 N0.getOperand(0).getOperand(0), Amt);
4064 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4068 // Simplify, based on bits shifted out of the LHS.
4069 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4070 return SDValue(N, 0);
4073 // If the sign bit is known to be zero, switch this to a SRL.
4074 if (DAG.SignBitIsZero(N0))
4075 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4078 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4079 if (NewSRA.getNode())
4086 SDValue DAGCombiner::visitSRL(SDNode *N) {
4087 SDValue N0 = N->getOperand(0);
4088 SDValue N1 = N->getOperand(1);
4089 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4090 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4091 EVT VT = N0.getValueType();
4092 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4095 if (VT.isVector()) {
4096 SDValue FoldedVOp = SimplifyVBinOp(N);
4097 if (FoldedVOp.getNode()) return FoldedVOp;
4100 // fold (srl c1, c2) -> c1 >>u c2
4102 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4103 // fold (srl 0, x) -> 0
4104 if (N0C && N0C->isNullValue())
4106 // fold (srl x, c >= size(x)) -> undef
4107 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4108 return DAG.getUNDEF(VT);
4109 // fold (srl x, 0) -> x
4110 if (N1C && N1C->isNullValue())
4112 // if (srl x, c) is known to be zero, return 0
4113 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4114 APInt::getAllOnesValue(OpSizeInBits)))
4115 return DAG.getConstant(0, VT);
4117 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4118 if (N1C && N0.getOpcode() == ISD::SRL &&
4119 N0.getOperand(1).getOpcode() == ISD::Constant) {
4120 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4121 uint64_t c2 = N1C->getZExtValue();
4122 if (c1 + c2 >= OpSizeInBits)
4123 return DAG.getConstant(0, VT);
4124 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4125 DAG.getConstant(c1 + c2, N1.getValueType()));
4128 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4129 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4130 N0.getOperand(0).getOpcode() == ISD::SRL &&
4131 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4133 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4134 uint64_t c2 = N1C->getZExtValue();
4135 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4136 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4137 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4138 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4139 if (c1 + OpSizeInBits == InnerShiftSize) {
4140 if (c1 + c2 >= InnerShiftSize)
4141 return DAG.getConstant(0, VT);
4142 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4143 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4144 N0.getOperand(0)->getOperand(0),
4145 DAG.getConstant(c1 + c2, ShiftCountVT)));
4149 // fold (srl (shl x, c), c) -> (and x, cst2)
4150 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4151 N0.getValueSizeInBits() <= 64) {
4152 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4153 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4154 DAG.getConstant(~0ULL >> ShAmt, VT));
4157 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4158 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4159 // Shifting in all undef bits?
4160 EVT SmallVT = N0.getOperand(0).getValueType();
4161 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4162 return DAG.getUNDEF(VT);
4164 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4165 uint64_t ShiftAmt = N1C->getZExtValue();
4166 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4168 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4169 AddToWorkList(SmallShift.getNode());
4170 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4171 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4172 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4173 DAG.getConstant(Mask, VT));
4177 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4178 // bit, which is unmodified by sra.
4179 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4180 if (N0.getOpcode() == ISD::SRA)
4181 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4184 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4185 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4186 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4187 APInt KnownZero, KnownOne;
4188 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4190 // If any of the input bits are KnownOne, then the input couldn't be all
4191 // zeros, thus the result of the srl will always be zero.
4192 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4194 // If all of the bits input the to ctlz node are known to be zero, then
4195 // the result of the ctlz is "32" and the result of the shift is one.
4196 APInt UnknownBits = ~KnownZero;
4197 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4199 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4200 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4201 // Okay, we know that only that the single bit specified by UnknownBits
4202 // could be set on input to the CTLZ node. If this bit is set, the SRL
4203 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4204 // to an SRL/XOR pair, which is likely to simplify more.
4205 unsigned ShAmt = UnknownBits.countTrailingZeros();
4206 SDValue Op = N0.getOperand(0);
4209 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4210 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4211 AddToWorkList(Op.getNode());
4214 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4215 Op, DAG.getConstant(1, VT));
4219 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4220 if (N1.getOpcode() == ISD::TRUNCATE &&
4221 N1.getOperand(0).getOpcode() == ISD::AND &&
4222 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4223 SDValue N101 = N1.getOperand(0).getOperand(1);
4224 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4225 EVT TruncVT = N1.getValueType();
4226 SDValue N100 = N1.getOperand(0).getOperand(0);
4227 APInt TruncC = N101C->getAPIntValue();
4228 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4229 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4230 DAG.getNode(ISD::AND, SDLoc(N),
4232 DAG.getNode(ISD::TRUNCATE,
4235 DAG.getConstant(TruncC, TruncVT)));
4239 // fold operands of srl based on knowledge that the low bits are not
4241 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4242 return SDValue(N, 0);
4245 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4246 if (NewSRL.getNode())
4250 // Attempt to convert a srl of a load into a narrower zero-extending load.
4251 SDValue NarrowLoad = ReduceLoadWidth(N);
4252 if (NarrowLoad.getNode())
4255 // Here is a common situation. We want to optimize:
4258 // %b = and i32 %a, 2
4259 // %c = srl i32 %b, 1
4260 // brcond i32 %c ...
4266 // %c = setcc eq %b, 0
4269 // However when after the source operand of SRL is optimized into AND, the SRL
4270 // itself may not be optimized further. Look for it and add the BRCOND into
4272 if (N->hasOneUse()) {
4273 SDNode *Use = *N->use_begin();
4274 if (Use->getOpcode() == ISD::BRCOND)
4276 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4277 // Also look pass the truncate.
4278 Use = *Use->use_begin();
4279 if (Use->getOpcode() == ISD::BRCOND)
4287 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4288 SDValue N0 = N->getOperand(0);
4289 EVT VT = N->getValueType(0);
4291 // fold (ctlz c1) -> c2
4292 if (isa<ConstantSDNode>(N0))
4293 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4297 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4298 SDValue N0 = N->getOperand(0);
4299 EVT VT = N->getValueType(0);
4301 // fold (ctlz_zero_undef c1) -> c2
4302 if (isa<ConstantSDNode>(N0))
4303 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4307 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4308 SDValue N0 = N->getOperand(0);
4309 EVT VT = N->getValueType(0);
4311 // fold (cttz c1) -> c2
4312 if (isa<ConstantSDNode>(N0))
4313 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4317 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4318 SDValue N0 = N->getOperand(0);
4319 EVT VT = N->getValueType(0);
4321 // fold (cttz_zero_undef c1) -> c2
4322 if (isa<ConstantSDNode>(N0))
4323 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4327 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4328 SDValue N0 = N->getOperand(0);
4329 EVT VT = N->getValueType(0);
4331 // fold (ctpop c1) -> c2
4332 if (isa<ConstantSDNode>(N0))
4333 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4337 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4338 SDValue N0 = N->getOperand(0);
4339 SDValue N1 = N->getOperand(1);
4340 SDValue N2 = N->getOperand(2);
4341 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4342 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4343 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4344 EVT VT = N->getValueType(0);
4345 EVT VT0 = N0.getValueType();
4347 // fold (select C, X, X) -> X
4350 // fold (select true, X, Y) -> X
4351 if (N0C && !N0C->isNullValue())
4353 // fold (select false, X, Y) -> Y
4354 if (N0C && N0C->isNullValue())
4356 // fold (select C, 1, X) -> (or C, X)
4357 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4358 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4359 // fold (select C, 0, 1) -> (xor C, 1)
4360 if (VT.isInteger() &&
4363 TLI.getBooleanContents(false) ==
4364 TargetLowering::ZeroOrOneBooleanContent)) &&
4365 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4368 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4369 N0, DAG.getConstant(1, VT0));
4370 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4371 N0, DAG.getConstant(1, VT0));
4372 AddToWorkList(XORNode.getNode());
4374 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4375 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4377 // fold (select C, 0, X) -> (and (not C), X)
4378 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4379 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4380 AddToWorkList(NOTNode.getNode());
4381 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4383 // fold (select C, X, 1) -> (or (not C), X)
4384 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4385 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4386 AddToWorkList(NOTNode.getNode());
4387 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4389 // fold (select C, X, 0) -> (and C, X)
4390 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4391 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4392 // fold (select X, X, Y) -> (or X, Y)
4393 // fold (select X, 1, Y) -> (or X, Y)
4394 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4395 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4396 // fold (select X, Y, X) -> (and X, Y)
4397 // fold (select X, Y, 0) -> (and X, Y)
4398 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4401 // If we can fold this based on the true/false value, do so.
4402 if (SimplifySelectOps(N, N1, N2))
4403 return SDValue(N, 0); // Don't revisit N.
4405 // fold selects based on a setcc into other things, such as min/max/abs
4406 if (N0.getOpcode() == ISD::SETCC) {
4408 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4409 // having to say they don't support SELECT_CC on every type the DAG knows
4410 // about, since there is no way to mark an opcode illegal at all value types
4411 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4412 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4413 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4414 N0.getOperand(0), N0.getOperand(1),
4415 N1, N2, N0.getOperand(2));
4416 return SimplifySelect(SDLoc(N), N0, N1, N2);
4423 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4426 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4428 // Split the inputs.
4429 SDValue Lo, Hi, LL, LH, RL, RH;
4430 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4431 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4433 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4434 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4436 return std::make_pair(Lo, Hi);
4439 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4440 SDValue N0 = N->getOperand(0);
4441 SDValue N1 = N->getOperand(1);
4442 SDValue N2 = N->getOperand(2);
4445 // Canonicalize integer abs.
4446 // vselect (setg[te] X, 0), X, -X ->
4447 // vselect (setgt X, -1), X, -X ->
4448 // vselect (setl[te] X, 0), -X, X ->
4449 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4450 if (N0.getOpcode() == ISD::SETCC) {
4451 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4452 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4454 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4456 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4457 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4458 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4459 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4460 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4461 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4462 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4465 EVT VT = LHS.getValueType();
4466 SDValue Shift = DAG.getNode(
4467 ISD::SRA, DL, VT, LHS,
4468 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4469 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4470 AddToWorkList(Shift.getNode());
4471 AddToWorkList(Add.getNode());
4472 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4476 // If the VSELECT result requires splitting and the mask is provided by a
4477 // SETCC, then split both nodes and its operands before legalization. This
4478 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4479 // and enables future optimizations (e.g. min/max pattern matching on X86).
4480 if (N0.getOpcode() == ISD::SETCC) {
4481 EVT VT = N->getValueType(0);
4483 // Check if any splitting is required.
4484 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4485 TargetLowering::TypeSplitVector)
4488 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4489 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4490 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4491 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4493 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4494 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4496 // Add the new VSELECT nodes to the work list in case they need to be split
4498 AddToWorkList(Lo.getNode());
4499 AddToWorkList(Hi.getNode());
4501 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4504 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4505 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4507 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4508 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4514 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4515 SDValue N0 = N->getOperand(0);
4516 SDValue N1 = N->getOperand(1);
4517 SDValue N2 = N->getOperand(2);
4518 SDValue N3 = N->getOperand(3);
4519 SDValue N4 = N->getOperand(4);
4520 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4522 // fold select_cc lhs, rhs, x, x, cc -> x
4526 // Determine if the condition we're dealing with is constant
4527 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4528 N0, N1, CC, SDLoc(N), false);
4529 if (SCC.getNode()) {
4530 AddToWorkList(SCC.getNode());
4532 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4533 if (!SCCC->isNullValue())
4534 return N2; // cond always true -> true val
4536 return N3; // cond always false -> false val
4539 // Fold to a simpler select_cc
4540 if (SCC.getOpcode() == ISD::SETCC)
4541 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4542 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4546 // If we can fold this based on the true/false value, do so.
4547 if (SimplifySelectOps(N, N2, N3))
4548 return SDValue(N, 0); // Don't revisit N.
4550 // fold select_cc into other things, such as min/max/abs
4551 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4554 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4555 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4556 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4560 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4561 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4562 // transformation. Returns true if extension are possible and the above
4563 // mentioned transformation is profitable.
4564 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4566 SmallVectorImpl<SDNode *> &ExtendNodes,
4567 const TargetLowering &TLI) {
4568 bool HasCopyToRegUses = false;
4569 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4570 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4571 UE = N0.getNode()->use_end();
4576 if (UI.getUse().getResNo() != N0.getResNo())
4578 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4579 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4580 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4581 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4582 // Sign bits will be lost after a zext.
4585 for (unsigned i = 0; i != 2; ++i) {
4586 SDValue UseOp = User->getOperand(i);
4589 if (!isa<ConstantSDNode>(UseOp))
4594 ExtendNodes.push_back(User);
4597 // If truncates aren't free and there are users we can't
4598 // extend, it isn't worthwhile.
4601 // Remember if this value is live-out.
4602 if (User->getOpcode() == ISD::CopyToReg)
4603 HasCopyToRegUses = true;
4606 if (HasCopyToRegUses) {
4607 bool BothLiveOut = false;
4608 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4610 SDUse &Use = UI.getUse();
4611 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4617 // Both unextended and extended values are live out. There had better be
4618 // a good reason for the transformation.
4619 return ExtendNodes.size();
4624 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4625 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4626 ISD::NodeType ExtType) {
4627 // Extend SetCC uses if necessary.
4628 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4629 SDNode *SetCC = SetCCs[i];
4630 SmallVector<SDValue, 4> Ops;
4632 for (unsigned j = 0; j != 2; ++j) {
4633 SDValue SOp = SetCC->getOperand(j);
4635 Ops.push_back(ExtLoad);
4637 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4640 Ops.push_back(SetCC->getOperand(2));
4641 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4642 &Ops[0], Ops.size()));
4646 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4647 SDValue N0 = N->getOperand(0);
4648 EVT VT = N->getValueType(0);
4650 // fold (sext c1) -> c1
4651 if (isa<ConstantSDNode>(N0))
4652 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4654 // fold (sext (sext x)) -> (sext x)
4655 // fold (sext (aext x)) -> (sext x)
4656 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4657 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4660 if (N0.getOpcode() == ISD::TRUNCATE) {
4661 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4662 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4663 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4664 if (NarrowLoad.getNode()) {
4665 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4666 if (NarrowLoad.getNode() != N0.getNode()) {
4667 CombineTo(N0.getNode(), NarrowLoad);
4668 // CombineTo deleted the truncate, if needed, but not what's under it.
4671 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4674 // See if the value being truncated is already sign extended. If so, just
4675 // eliminate the trunc/sext pair.
4676 SDValue Op = N0.getOperand(0);
4677 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4678 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4679 unsigned DestBits = VT.getScalarType().getSizeInBits();
4680 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4682 if (OpBits == DestBits) {
4683 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4684 // bits, it is already ready.
4685 if (NumSignBits > DestBits-MidBits)
4687 } else if (OpBits < DestBits) {
4688 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4689 // bits, just sext from i32.
4690 if (NumSignBits > OpBits-MidBits)
4691 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4693 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4694 // bits, just truncate to i32.
4695 if (NumSignBits > OpBits-MidBits)
4696 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4699 // fold (sext (truncate x)) -> (sextinreg x).
4700 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4701 N0.getValueType())) {
4702 if (OpBits < DestBits)
4703 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4704 else if (OpBits > DestBits)
4705 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4706 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4707 DAG.getValueType(N0.getValueType()));
4711 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4712 // None of the supported targets knows how to perform load and sign extend
4713 // on vectors in one instruction. We only perform this transformation on
4715 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4716 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4717 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4718 bool DoXform = true;
4719 SmallVector<SDNode*, 4> SetCCs;
4720 if (!N0.hasOneUse())
4721 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4723 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4724 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4726 LN0->getBasePtr(), N0.getValueType(),
4727 LN0->getMemOperand());
4728 CombineTo(N, ExtLoad);
4729 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4730 N0.getValueType(), ExtLoad);
4731 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4732 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4734 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4738 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4739 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4740 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4741 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4742 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4743 EVT MemVT = LN0->getMemoryVT();
4744 if ((!LegalOperations && !LN0->isVolatile()) ||
4745 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4746 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4748 LN0->getBasePtr(), MemVT,
4749 LN0->getMemOperand());
4750 CombineTo(N, ExtLoad);
4751 CombineTo(N0.getNode(),
4752 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4753 N0.getValueType(), ExtLoad),
4754 ExtLoad.getValue(1));
4755 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4759 // fold (sext (and/or/xor (load x), cst)) ->
4760 // (and/or/xor (sextload x), (sext cst))
4761 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4762 N0.getOpcode() == ISD::XOR) &&
4763 isa<LoadSDNode>(N0.getOperand(0)) &&
4764 N0.getOperand(1).getOpcode() == ISD::Constant &&
4765 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4766 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4767 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4768 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4769 bool DoXform = true;
4770 SmallVector<SDNode*, 4> SetCCs;
4771 if (!N0.hasOneUse())
4772 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4775 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4776 LN0->getChain(), LN0->getBasePtr(),
4778 LN0->getMemOperand());
4779 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4780 Mask = Mask.sext(VT.getSizeInBits());
4781 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4782 ExtLoad, DAG.getConstant(Mask, VT));
4783 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4784 SDLoc(N0.getOperand(0)),
4785 N0.getOperand(0).getValueType(), ExtLoad);
4787 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4788 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4795 if (N0.getOpcode() == ISD::SETCC) {
4796 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4797 // Only do this before legalize for now.
4798 if (VT.isVector() && !LegalOperations &&
4799 TLI.getBooleanContents(true) ==
4800 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4801 EVT N0VT = N0.getOperand(0).getValueType();
4802 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4803 // of the same size as the compared operands. Only optimize sext(setcc())
4804 // if this is the case.
4805 EVT SVT = getSetCCResultType(N0VT);
4807 // We know that the # elements of the results is the same as the
4808 // # elements of the compare (and the # elements of the compare result
4809 // for that matter). Check to see that they are the same size. If so,
4810 // we know that the element size of the sext'd result matches the
4811 // element size of the compare operands.
4812 if (VT.getSizeInBits() == SVT.getSizeInBits())
4813 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4815 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4817 // If the desired elements are smaller or larger than the source
4818 // elements we can use a matching integer vector type and then
4819 // truncate/sign extend
4820 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4821 if (SVT == MatchingVectorType) {
4822 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4823 N0.getOperand(0), N0.getOperand(1),
4824 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4825 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4829 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4830 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4832 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4834 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4835 NegOne, DAG.getConstant(0, VT),
4836 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4837 if (SCC.getNode()) return SCC;
4838 if (!VT.isVector() &&
4839 (!LegalOperations ||
4840 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4841 return DAG.getSelect(SDLoc(N), VT,
4842 DAG.getSetCC(SDLoc(N),
4843 getSetCCResultType(VT),
4844 N0.getOperand(0), N0.getOperand(1),
4845 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4846 NegOne, DAG.getConstant(0, VT));
4850 // fold (sext x) -> (zext x) if the sign bit is known zero.
4851 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4852 DAG.SignBitIsZero(N0))
4853 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4858 // isTruncateOf - If N is a truncate of some other value, return true, record
4859 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4860 // This function computes KnownZero to avoid a duplicated call to
4861 // ComputeMaskedBits in the caller.
4862 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4865 if (N->getOpcode() == ISD::TRUNCATE) {
4866 Op = N->getOperand(0);
4867 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4871 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4872 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4875 SDValue Op0 = N->getOperand(0);
4876 SDValue Op1 = N->getOperand(1);
4877 assert(Op0.getValueType() == Op1.getValueType());
4879 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4880 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4881 if (COp0 && COp0->isNullValue())
4883 else if (COp1 && COp1->isNullValue())
4888 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4890 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4896 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4897 SDValue N0 = N->getOperand(0);
4898 EVT VT = N->getValueType(0);
4900 // fold (zext c1) -> c1
4901 if (isa<ConstantSDNode>(N0))
4902 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4903 // fold (zext (zext x)) -> (zext x)
4904 // fold (zext (aext x)) -> (zext x)
4905 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4906 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4909 // fold (zext (truncate x)) -> (zext x) or
4910 // (zext (truncate x)) -> (truncate x)
4911 // This is valid when the truncated bits of x are already zero.
4912 // FIXME: We should extend this to work for vectors too.
4915 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4916 APInt TruncatedBits =
4917 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4918 APInt(Op.getValueSizeInBits(), 0) :
4919 APInt::getBitsSet(Op.getValueSizeInBits(),
4920 N0.getValueSizeInBits(),
4921 std::min(Op.getValueSizeInBits(),
4922 VT.getSizeInBits()));
4923 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4924 if (VT.bitsGT(Op.getValueType()))
4925 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4926 if (VT.bitsLT(Op.getValueType()))
4927 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4933 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4934 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4935 if (N0.getOpcode() == ISD::TRUNCATE) {
4936 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4937 if (NarrowLoad.getNode()) {
4938 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4939 if (NarrowLoad.getNode() != N0.getNode()) {
4940 CombineTo(N0.getNode(), NarrowLoad);
4941 // CombineTo deleted the truncate, if needed, but not what's under it.
4944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4948 // fold (zext (truncate x)) -> (and x, mask)
4949 if (N0.getOpcode() == ISD::TRUNCATE &&
4950 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4952 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4953 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4954 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4955 if (NarrowLoad.getNode()) {
4956 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4957 if (NarrowLoad.getNode() != N0.getNode()) {
4958 CombineTo(N0.getNode(), NarrowLoad);
4959 // CombineTo deleted the truncate, if needed, but not what's under it.
4962 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4965 SDValue Op = N0.getOperand(0);
4966 if (Op.getValueType().bitsLT(VT)) {
4967 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4968 AddToWorkList(Op.getNode());
4969 } else if (Op.getValueType().bitsGT(VT)) {
4970 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4971 AddToWorkList(Op.getNode());
4973 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4974 N0.getValueType().getScalarType());
4977 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4978 // if either of the casts is not free.
4979 if (N0.getOpcode() == ISD::AND &&
4980 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4981 N0.getOperand(1).getOpcode() == ISD::Constant &&
4982 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4983 N0.getValueType()) ||
4984 !TLI.isZExtFree(N0.getValueType(), VT))) {
4985 SDValue X = N0.getOperand(0).getOperand(0);
4986 if (X.getValueType().bitsLT(VT)) {
4987 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4988 } else if (X.getValueType().bitsGT(VT)) {
4989 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4991 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4992 Mask = Mask.zext(VT.getSizeInBits());
4993 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4994 X, DAG.getConstant(Mask, VT));
4997 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4998 // None of the supported targets knows how to perform load and vector_zext
4999 // on vectors in one instruction. We only perform this transformation on
5001 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5002 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5003 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5004 bool DoXform = true;
5005 SmallVector<SDNode*, 4> SetCCs;
5006 if (!N0.hasOneUse())
5007 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5009 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5010 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5012 LN0->getBasePtr(), N0.getValueType(),
5013 LN0->getMemOperand());
5014 CombineTo(N, ExtLoad);
5015 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5016 N0.getValueType(), ExtLoad);
5017 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5019 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5021 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5025 // fold (zext (and/or/xor (load x), cst)) ->
5026 // (and/or/xor (zextload x), (zext cst))
5027 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5028 N0.getOpcode() == ISD::XOR) &&
5029 isa<LoadSDNode>(N0.getOperand(0)) &&
5030 N0.getOperand(1).getOpcode() == ISD::Constant &&
5031 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5032 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5033 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5034 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5035 bool DoXform = true;
5036 SmallVector<SDNode*, 4> SetCCs;
5037 if (!N0.hasOneUse())
5038 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5041 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5042 LN0->getChain(), LN0->getBasePtr(),
5044 LN0->getMemOperand());
5045 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5046 Mask = Mask.zext(VT.getSizeInBits());
5047 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5048 ExtLoad, DAG.getConstant(Mask, VT));
5049 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5050 SDLoc(N0.getOperand(0)),
5051 N0.getOperand(0).getValueType(), ExtLoad);
5053 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5054 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5056 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5061 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5062 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5063 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5064 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5065 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5066 EVT MemVT = LN0->getMemoryVT();
5067 if ((!LegalOperations && !LN0->isVolatile()) ||
5068 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5069 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5071 LN0->getBasePtr(), MemVT,
5072 LN0->getMemOperand());
5073 CombineTo(N, ExtLoad);
5074 CombineTo(N0.getNode(),
5075 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5077 ExtLoad.getValue(1));
5078 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5082 if (N0.getOpcode() == ISD::SETCC) {
5083 if (!LegalOperations && VT.isVector() &&
5084 N0.getValueType().getVectorElementType() == MVT::i1) {
5085 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5086 // Only do this before legalize for now.
5087 EVT N0VT = N0.getOperand(0).getValueType();
5088 EVT EltVT = VT.getVectorElementType();
5089 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5090 DAG.getConstant(1, EltVT));
5091 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5092 // We know that the # elements of the results is the same as the
5093 // # elements of the compare (and the # elements of the compare result
5094 // for that matter). Check to see that they are the same size. If so,
5095 // we know that the element size of the sext'd result matches the
5096 // element size of the compare operands.
5097 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5098 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5100 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5101 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5102 &OneOps[0], OneOps.size()));
5104 // If the desired elements are smaller or larger than the source
5105 // elements we can use a matching integer vector type and then
5106 // truncate/sign extend
5107 EVT MatchingElementType =
5108 EVT::getIntegerVT(*DAG.getContext(),
5109 N0VT.getScalarType().getSizeInBits());
5110 EVT MatchingVectorType =
5111 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5112 N0VT.getVectorNumElements());
5114 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5116 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5117 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5118 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5119 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5120 &OneOps[0], OneOps.size()));
5123 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5125 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5126 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5127 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5128 if (SCC.getNode()) return SCC;
5131 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5132 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5133 isa<ConstantSDNode>(N0.getOperand(1)) &&
5134 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5136 SDValue ShAmt = N0.getOperand(1);
5137 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5138 if (N0.getOpcode() == ISD::SHL) {
5139 SDValue InnerZExt = N0.getOperand(0);
5140 // If the original shl may be shifting out bits, do not perform this
5142 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5143 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5144 if (ShAmtVal > KnownZeroBits)
5150 // Ensure that the shift amount is wide enough for the shifted value.
5151 if (VT.getSizeInBits() >= 256)
5152 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5154 return DAG.getNode(N0.getOpcode(), DL, VT,
5155 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5162 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5163 SDValue N0 = N->getOperand(0);
5164 EVT VT = N->getValueType(0);
5166 // fold (aext c1) -> c1
5167 if (isa<ConstantSDNode>(N0))
5168 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5169 // fold (aext (aext x)) -> (aext x)
5170 // fold (aext (zext x)) -> (zext x)
5171 // fold (aext (sext x)) -> (sext x)
5172 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5173 N0.getOpcode() == ISD::ZERO_EXTEND ||
5174 N0.getOpcode() == ISD::SIGN_EXTEND)
5175 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5177 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5178 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5179 if (N0.getOpcode() == ISD::TRUNCATE) {
5180 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5181 if (NarrowLoad.getNode()) {
5182 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5183 if (NarrowLoad.getNode() != N0.getNode()) {
5184 CombineTo(N0.getNode(), NarrowLoad);
5185 // CombineTo deleted the truncate, if needed, but not what's under it.
5188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5192 // fold (aext (truncate x))
5193 if (N0.getOpcode() == ISD::TRUNCATE) {
5194 SDValue TruncOp = N0.getOperand(0);
5195 if (TruncOp.getValueType() == VT)
5196 return TruncOp; // x iff x size == zext size.
5197 if (TruncOp.getValueType().bitsGT(VT))
5198 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5199 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5202 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5203 // if the trunc is not free.
5204 if (N0.getOpcode() == ISD::AND &&
5205 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5206 N0.getOperand(1).getOpcode() == ISD::Constant &&
5207 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5208 N0.getValueType())) {
5209 SDValue X = N0.getOperand(0).getOperand(0);
5210 if (X.getValueType().bitsLT(VT)) {
5211 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5212 } else if (X.getValueType().bitsGT(VT)) {
5213 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5215 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5216 Mask = Mask.zext(VT.getSizeInBits());
5217 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5218 X, DAG.getConstant(Mask, VT));
5221 // fold (aext (load x)) -> (aext (truncate (extload x)))
5222 // None of the supported targets knows how to perform load and any_ext
5223 // on vectors in one instruction. We only perform this transformation on
5225 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5226 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5227 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5228 bool DoXform = true;
5229 SmallVector<SDNode*, 4> SetCCs;
5230 if (!N0.hasOneUse())
5231 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5233 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5234 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5236 LN0->getBasePtr(), N0.getValueType(),
5237 LN0->getMemOperand());
5238 CombineTo(N, ExtLoad);
5239 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5240 N0.getValueType(), ExtLoad);
5241 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5242 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5244 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5248 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5249 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5250 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5251 if (N0.getOpcode() == ISD::LOAD &&
5252 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5254 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5255 EVT MemVT = LN0->getMemoryVT();
5256 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5257 VT, LN0->getChain(), LN0->getBasePtr(),
5258 MemVT, LN0->getMemOperand());
5259 CombineTo(N, ExtLoad);
5260 CombineTo(N0.getNode(),
5261 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5262 N0.getValueType(), ExtLoad),
5263 ExtLoad.getValue(1));
5264 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5267 if (N0.getOpcode() == ISD::SETCC) {
5268 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5269 // Only do this before legalize for now.
5270 if (VT.isVector() && !LegalOperations) {
5271 EVT N0VT = N0.getOperand(0).getValueType();
5272 // We know that the # elements of the results is the same as the
5273 // # elements of the compare (and the # elements of the compare result
5274 // for that matter). Check to see that they are the same size. If so,
5275 // we know that the element size of the sext'd result matches the
5276 // element size of the compare operands.
5277 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5278 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5280 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5281 // If the desired elements are smaller or larger than the source
5282 // elements we can use a matching integer vector type and then
5283 // truncate/sign extend
5285 EVT MatchingElementType =
5286 EVT::getIntegerVT(*DAG.getContext(),
5287 N0VT.getScalarType().getSizeInBits());
5288 EVT MatchingVectorType =
5289 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5290 N0VT.getVectorNumElements());
5292 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5294 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5295 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5299 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5301 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5302 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5303 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5311 /// GetDemandedBits - See if the specified operand can be simplified with the
5312 /// knowledge that only the bits specified by Mask are used. If so, return the
5313 /// simpler operand, otherwise return a null SDValue.
5314 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5315 switch (V.getOpcode()) {
5317 case ISD::Constant: {
5318 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5319 assert(CV != 0 && "Const value should be ConstSDNode.");
5320 const APInt &CVal = CV->getAPIntValue();
5321 APInt NewVal = CVal & Mask;
5323 return DAG.getConstant(NewVal, V.getValueType());
5328 // If the LHS or RHS don't contribute bits to the or, drop them.
5329 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5330 return V.getOperand(1);
5331 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5332 return V.getOperand(0);
5335 // Only look at single-use SRLs.
5336 if (!V.getNode()->hasOneUse())
5338 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5339 // See if we can recursively simplify the LHS.
5340 unsigned Amt = RHSC->getZExtValue();
5342 // Watch out for shift count overflow though.
5343 if (Amt >= Mask.getBitWidth()) break;
5344 APInt NewMask = Mask << Amt;
5345 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5346 if (SimplifyLHS.getNode())
5347 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5348 SimplifyLHS, V.getOperand(1));
5354 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5355 /// bits and then truncated to a narrower type and where N is a multiple
5356 /// of number of bits of the narrower type, transform it to a narrower load
5357 /// from address + N / num of bits of new type. If the result is to be
5358 /// extended, also fold the extension to form a extending load.
5359 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5360 unsigned Opc = N->getOpcode();
5362 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5363 SDValue N0 = N->getOperand(0);
5364 EVT VT = N->getValueType(0);
5367 // This transformation isn't valid for vector loads.
5371 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5373 if (Opc == ISD::SIGN_EXTEND_INREG) {
5374 ExtType = ISD::SEXTLOAD;
5375 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5376 } else if (Opc == ISD::SRL) {
5377 // Another special-case: SRL is basically zero-extending a narrower value.
5378 ExtType = ISD::ZEXTLOAD;
5380 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5381 if (!N01) return SDValue();
5382 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5383 VT.getSizeInBits() - N01->getZExtValue());
5385 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5388 unsigned EVTBits = ExtVT.getSizeInBits();
5390 // Do not generate loads of non-round integer types since these can
5391 // be expensive (and would be wrong if the type is not byte sized).
5392 if (!ExtVT.isRound())
5396 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5397 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5398 ShAmt = N01->getZExtValue();
5399 // Is the shift amount a multiple of size of VT?
5400 if ((ShAmt & (EVTBits-1)) == 0) {
5401 N0 = N0.getOperand(0);
5402 // Is the load width a multiple of size of VT?
5403 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5407 // At this point, we must have a load or else we can't do the transform.
5408 if (!isa<LoadSDNode>(N0)) return SDValue();
5410 // Because a SRL must be assumed to *need* to zero-extend the high bits
5411 // (as opposed to anyext the high bits), we can't combine the zextload
5412 // lowering of SRL and an sextload.
5413 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5416 // If the shift amount is larger than the input type then we're not
5417 // accessing any of the loaded bytes. If the load was a zextload/extload
5418 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5419 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5424 // If the load is shifted left (and the result isn't shifted back right),
5425 // we can fold the truncate through the shift.
5426 unsigned ShLeftAmt = 0;
5427 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5428 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5429 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5430 ShLeftAmt = N01->getZExtValue();
5431 N0 = N0.getOperand(0);
5435 // If we haven't found a load, we can't narrow it. Don't transform one with
5436 // multiple uses, this would require adding a new load.
5437 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5440 // Don't change the width of a volatile load.
5441 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5442 if (LN0->isVolatile())
5445 // Verify that we are actually reducing a load width here.
5446 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5449 // For the transform to be legal, the load must produce only two values
5450 // (the value loaded and the chain). Don't transform a pre-increment
5451 // load, for example, which produces an extra value. Otherwise the
5452 // transformation is not equivalent, and the downstream logic to replace
5453 // uses gets things wrong.
5454 if (LN0->getNumValues() > 2)
5457 // If the load that we're shrinking is an extload and we're not just
5458 // discarding the extension we can't simply shrink the load. Bail.
5459 // TODO: It would be possible to merge the extensions in some cases.
5460 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5461 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5464 EVT PtrType = N0.getOperand(1).getValueType();
5466 if (PtrType == MVT::Untyped || PtrType.isExtended())
5467 // It's not possible to generate a constant of extended or untyped type.
5470 // For big endian targets, we need to adjust the offset to the pointer to
5471 // load the correct bytes.
5472 if (TLI.isBigEndian()) {
5473 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5474 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5475 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5478 uint64_t PtrOff = ShAmt / 8;
5479 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5480 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5481 PtrType, LN0->getBasePtr(),
5482 DAG.getConstant(PtrOff, PtrType));
5483 AddToWorkList(NewPtr.getNode());
5486 if (ExtType == ISD::NON_EXTLOAD)
5487 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5488 LN0->getPointerInfo().getWithOffset(PtrOff),
5489 LN0->isVolatile(), LN0->isNonTemporal(),
5490 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5492 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5493 LN0->getPointerInfo().getWithOffset(PtrOff),
5494 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5495 NewAlign, LN0->getTBAAInfo());
5497 // Replace the old load's chain with the new load's chain.
5498 WorkListRemover DeadNodes(*this);
5499 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5501 // Shift the result left, if we've swallowed a left shift.
5502 SDValue Result = Load;
5503 if (ShLeftAmt != 0) {
5504 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5505 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5507 // If the shift amount is as large as the result size (but, presumably,
5508 // no larger than the source) then the useful bits of the result are
5509 // zero; we can't simply return the shortened shift, because the result
5510 // of that operation is undefined.
5511 if (ShLeftAmt >= VT.getSizeInBits())
5512 Result = DAG.getConstant(0, VT);
5514 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5515 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5518 // Return the new loaded value.
5522 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5523 SDValue N0 = N->getOperand(0);
5524 SDValue N1 = N->getOperand(1);
5525 EVT VT = N->getValueType(0);
5526 EVT EVT = cast<VTSDNode>(N1)->getVT();
5527 unsigned VTBits = VT.getScalarType().getSizeInBits();
5528 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5530 // fold (sext_in_reg c1) -> c1
5531 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5532 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5534 // If the input is already sign extended, just drop the extension.
5535 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5538 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5539 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5540 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5541 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5542 N0.getOperand(0), N1);
5544 // fold (sext_in_reg (sext x)) -> (sext x)
5545 // fold (sext_in_reg (aext x)) -> (sext x)
5546 // if x is small enough.
5547 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5548 SDValue N00 = N0.getOperand(0);
5549 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5550 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5551 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5554 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5555 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5556 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5558 // fold operands of sext_in_reg based on knowledge that the top bits are not
5560 if (SimplifyDemandedBits(SDValue(N, 0)))
5561 return SDValue(N, 0);
5563 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5564 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5565 SDValue NarrowLoad = ReduceLoadWidth(N);
5566 if (NarrowLoad.getNode())
5569 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5570 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5571 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5572 if (N0.getOpcode() == ISD::SRL) {
5573 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5574 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5575 // We can turn this into an SRA iff the input to the SRL is already sign
5577 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5578 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5579 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5580 N0.getOperand(0), N0.getOperand(1));
5584 // fold (sext_inreg (extload x)) -> (sextload x)
5585 if (ISD::isEXTLoad(N0.getNode()) &&
5586 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5587 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5588 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5589 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5590 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5591 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5593 LN0->getBasePtr(), EVT,
5594 LN0->getMemOperand());
5595 CombineTo(N, ExtLoad);
5596 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5597 AddToWorkList(ExtLoad.getNode());
5598 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5600 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5601 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5603 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5604 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5605 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5606 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5607 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5609 LN0->getBasePtr(), EVT,
5610 LN0->getMemOperand());
5611 CombineTo(N, ExtLoad);
5612 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5613 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5616 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5617 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5618 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5619 N0.getOperand(1), false);
5620 if (BSwap.getNode() != 0)
5621 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5625 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5626 // into a build_vector.
5627 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5628 SmallVector<SDValue, 8> Elts;
5629 unsigned NumElts = N0->getNumOperands();
5630 unsigned ShAmt = VTBits - EVTBits;
5632 for (unsigned i = 0; i != NumElts; ++i) {
5633 SDValue Op = N0->getOperand(i);
5634 if (Op->getOpcode() == ISD::UNDEF) {
5639 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5640 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5641 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5642 Op.getValueType()));
5645 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5651 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5652 SDValue N0 = N->getOperand(0);
5653 EVT VT = N->getValueType(0);
5654 bool isLE = TLI.isLittleEndian();
5657 if (N0.getValueType() == N->getValueType(0))
5659 // fold (truncate c1) -> c1
5660 if (isa<ConstantSDNode>(N0))
5661 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5662 // fold (truncate (truncate x)) -> (truncate x)
5663 if (N0.getOpcode() == ISD::TRUNCATE)
5664 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5665 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5666 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5667 N0.getOpcode() == ISD::SIGN_EXTEND ||
5668 N0.getOpcode() == ISD::ANY_EXTEND) {
5669 if (N0.getOperand(0).getValueType().bitsLT(VT))
5670 // if the source is smaller than the dest, we still need an extend
5671 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5673 if (N0.getOperand(0).getValueType().bitsGT(VT))
5674 // if the source is larger than the dest, than we just need the truncate
5675 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5676 // if the source and dest are the same type, we can drop both the extend
5677 // and the truncate.
5678 return N0.getOperand(0);
5681 // Fold extract-and-trunc into a narrow extract. For example:
5682 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5683 // i32 y = TRUNCATE(i64 x)
5685 // v16i8 b = BITCAST (v2i64 val)
5686 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5688 // Note: We only run this optimization after type legalization (which often
5689 // creates this pattern) and before operation legalization after which
5690 // we need to be more careful about the vector instructions that we generate.
5691 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5692 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5694 EVT VecTy = N0.getOperand(0).getValueType();
5695 EVT ExTy = N0.getValueType();
5696 EVT TrTy = N->getValueType(0);
5698 unsigned NumElem = VecTy.getVectorNumElements();
5699 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5701 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5702 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5704 SDValue EltNo = N0->getOperand(1);
5705 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5706 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5707 EVT IndexTy = TLI.getVectorIdxTy();
5708 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5710 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5711 NVT, N0.getOperand(0));
5713 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5715 DAG.getConstant(Index, IndexTy));
5719 // Fold a series of buildvector, bitcast, and truncate if possible.
5721 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5722 // (2xi32 (buildvector x, y)).
5723 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5724 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5725 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5726 N0.getOperand(0).hasOneUse()) {
5728 SDValue BuildVect = N0.getOperand(0);
5729 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5730 EVT TruncVecEltTy = VT.getVectorElementType();
5732 // Check that the element types match.
5733 if (BuildVectEltTy == TruncVecEltTy) {
5734 // Now we only need to compute the offset of the truncated elements.
5735 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5736 unsigned TruncVecNumElts = VT.getVectorNumElements();
5737 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5739 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5740 "Invalid number of elements");
5742 SmallVector<SDValue, 8> Opnds;
5743 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5744 Opnds.push_back(BuildVect.getOperand(i));
5746 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5751 // See if we can simplify the input to this truncate through knowledge that
5752 // only the low bits are being used.
5753 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5754 // Currently we only perform this optimization on scalars because vectors
5755 // may have different active low bits.
5756 if (!VT.isVector()) {
5758 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5759 VT.getSizeInBits()));
5760 if (Shorter.getNode())
5761 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5763 // fold (truncate (load x)) -> (smaller load x)
5764 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5765 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5766 SDValue Reduced = ReduceLoadWidth(N);
5767 if (Reduced.getNode())
5769 // Handle the case where the load remains an extending load even
5770 // after truncation.
5771 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5772 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5773 if (!LN0->isVolatile() &&
5774 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5775 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5776 VT, LN0->getChain(), LN0->getBasePtr(),
5778 LN0->getMemOperand());
5779 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5784 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5785 // where ... are all 'undef'.
5786 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5787 SmallVector<EVT, 8> VTs;
5790 unsigned NumDefs = 0;
5792 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5793 SDValue X = N0.getOperand(i);
5794 if (X.getOpcode() != ISD::UNDEF) {
5799 // Stop if more than one members are non-undef.
5802 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5803 VT.getVectorElementType(),
5804 X.getValueType().getVectorNumElements()));
5808 return DAG.getUNDEF(VT);
5811 assert(V.getNode() && "The single defined operand is empty!");
5812 SmallVector<SDValue, 8> Opnds;
5813 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5815 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5818 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5819 AddToWorkList(NV.getNode());
5820 Opnds.push_back(NV);
5822 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5823 &Opnds[0], Opnds.size());
5827 // Simplify the operands using demanded-bits information.
5828 if (!VT.isVector() &&
5829 SimplifyDemandedBits(SDValue(N, 0)))
5830 return SDValue(N, 0);
5835 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5836 SDValue Elt = N->getOperand(i);
5837 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5838 return Elt.getNode();
5839 return Elt.getOperand(Elt.getResNo()).getNode();
5842 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5843 /// if load locations are consecutive.
5844 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5845 assert(N->getOpcode() == ISD::BUILD_PAIR);
5847 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5848 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5849 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5850 LD1->getPointerInfo().getAddrSpace() !=
5851 LD2->getPointerInfo().getAddrSpace())
5853 EVT LD1VT = LD1->getValueType(0);
5855 if (ISD::isNON_EXTLoad(LD2) &&
5857 // If both are volatile this would reduce the number of volatile loads.
5858 // If one is volatile it might be ok, but play conservative and bail out.
5859 !LD1->isVolatile() &&
5860 !LD2->isVolatile() &&
5861 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5862 unsigned Align = LD1->getAlignment();
5863 unsigned NewAlign = TLI.getDataLayout()->
5864 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5866 if (NewAlign <= Align &&
5867 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5868 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5869 LD1->getBasePtr(), LD1->getPointerInfo(),
5870 false, false, false, Align);
5876 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5877 SDValue N0 = N->getOperand(0);
5878 EVT VT = N->getValueType(0);
5880 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5881 // Only do this before legalize, since afterward the target may be depending
5882 // on the bitconvert.
5883 // First check to see if this is all constant.
5885 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5887 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
5889 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5890 assert(!DestEltVT.isVector() &&
5891 "Element type of vector ValueType must not be vector!");
5893 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5896 // If the input is a constant, let getNode fold it.
5897 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5898 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5899 if (Res.getNode() != N) {
5900 if (!LegalOperations ||
5901 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5904 // Folding it resulted in an illegal node, and it's too late to
5905 // do that. Clean up the old node and forego the transformation.
5906 // Ideally this won't happen very often, because instcombine
5907 // and the earlier dagcombine runs (where illegal nodes are
5908 // permitted) should have folded most of them already.
5909 DAG.DeleteNode(Res.getNode());
5913 // (conv (conv x, t1), t2) -> (conv x, t2)
5914 if (N0.getOpcode() == ISD::BITCAST)
5915 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5918 // fold (conv (load x)) -> (load (conv*)x)
5919 // If the resultant load doesn't need a higher alignment than the original!
5920 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5921 // Do not change the width of a volatile load.
5922 !cast<LoadSDNode>(N0)->isVolatile() &&
5923 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5924 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5925 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5926 unsigned Align = TLI.getDataLayout()->
5927 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5928 unsigned OrigAlign = LN0->getAlignment();
5930 if (Align <= OrigAlign) {
5931 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5932 LN0->getBasePtr(), LN0->getPointerInfo(),
5933 LN0->isVolatile(), LN0->isNonTemporal(),
5934 LN0->isInvariant(), OrigAlign,
5935 LN0->getTBAAInfo());
5937 CombineTo(N0.getNode(),
5938 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5939 N0.getValueType(), Load),
5945 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5946 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5947 // This often reduces constant pool loads.
5948 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5949 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5950 N0.getNode()->hasOneUse() && VT.isInteger() &&
5951 !VT.isVector() && !N0.getValueType().isVector()) {
5952 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5954 AddToWorkList(NewConv.getNode());
5956 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5957 if (N0.getOpcode() == ISD::FNEG)
5958 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5959 NewConv, DAG.getConstant(SignBit, VT));
5960 assert(N0.getOpcode() == ISD::FABS);
5961 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5962 NewConv, DAG.getConstant(~SignBit, VT));
5965 // fold (bitconvert (fcopysign cst, x)) ->
5966 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5967 // Note that we don't handle (copysign x, cst) because this can always be
5968 // folded to an fneg or fabs.
5969 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5970 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5971 VT.isInteger() && !VT.isVector()) {
5972 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5973 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5974 if (isTypeLegal(IntXVT)) {
5975 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5976 IntXVT, N0.getOperand(1));
5977 AddToWorkList(X.getNode());
5979 // If X has a different width than the result/lhs, sext it or truncate it.
5980 unsigned VTWidth = VT.getSizeInBits();
5981 if (OrigXWidth < VTWidth) {
5982 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5983 AddToWorkList(X.getNode());
5984 } else if (OrigXWidth > VTWidth) {
5985 // To get the sign bit in the right place, we have to shift it right
5986 // before truncating.
5987 X = DAG.getNode(ISD::SRL, SDLoc(X),
5988 X.getValueType(), X,
5989 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5990 AddToWorkList(X.getNode());
5991 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5992 AddToWorkList(X.getNode());
5995 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5996 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5997 X, DAG.getConstant(SignBit, VT));
5998 AddToWorkList(X.getNode());
6000 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6001 VT, N0.getOperand(0));
6002 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6003 Cst, DAG.getConstant(~SignBit, VT));
6004 AddToWorkList(Cst.getNode());
6006 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6010 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6011 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6012 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6013 if (CombineLD.getNode())
6020 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6021 EVT VT = N->getValueType(0);
6022 return CombineConsecutiveLoads(N, VT);
6025 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6026 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6027 /// destination element value type.
6028 SDValue DAGCombiner::
6029 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6030 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6032 // If this is already the right type, we're done.
6033 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6035 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6036 unsigned DstBitSize = DstEltVT.getSizeInBits();
6038 // If this is a conversion of N elements of one type to N elements of another
6039 // type, convert each element. This handles FP<->INT cases.
6040 if (SrcBitSize == DstBitSize) {
6041 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6042 BV->getValueType(0).getVectorNumElements());
6044 // Due to the FP element handling below calling this routine recursively,
6045 // we can end up with a scalar-to-vector node here.
6046 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6047 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6048 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6049 DstEltVT, BV->getOperand(0)));
6051 SmallVector<SDValue, 8> Ops;
6052 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6053 SDValue Op = BV->getOperand(i);
6054 // If the vector element type is not legal, the BUILD_VECTOR operands
6055 // are promoted and implicitly truncated. Make that explicit here.
6056 if (Op.getValueType() != SrcEltVT)
6057 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6058 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6060 AddToWorkList(Ops.back().getNode());
6062 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6063 &Ops[0], Ops.size());
6066 // Otherwise, we're growing or shrinking the elements. To avoid having to
6067 // handle annoying details of growing/shrinking FP values, we convert them to
6069 if (SrcEltVT.isFloatingPoint()) {
6070 // Convert the input float vector to a int vector where the elements are the
6072 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6073 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6074 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6078 // Now we know the input is an integer vector. If the output is a FP type,
6079 // convert to integer first, then to FP of the right size.
6080 if (DstEltVT.isFloatingPoint()) {
6081 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6082 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6083 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6085 // Next, convert to FP elements of the same size.
6086 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6089 // Okay, we know the src/dst types are both integers of differing types.
6090 // Handling growing first.
6091 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6092 if (SrcBitSize < DstBitSize) {
6093 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6095 SmallVector<SDValue, 8> Ops;
6096 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6097 i += NumInputsPerOutput) {
6098 bool isLE = TLI.isLittleEndian();
6099 APInt NewBits = APInt(DstBitSize, 0);
6100 bool EltIsUndef = true;
6101 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6102 // Shift the previously computed bits over.
6103 NewBits <<= SrcBitSize;
6104 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6105 if (Op.getOpcode() == ISD::UNDEF) continue;
6108 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6109 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6113 Ops.push_back(DAG.getUNDEF(DstEltVT));
6115 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6118 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6119 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6120 &Ops[0], Ops.size());
6123 // Finally, this must be the case where we are shrinking elements: each input
6124 // turns into multiple outputs.
6125 bool isS2V = ISD::isScalarToVector(BV);
6126 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6127 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6128 NumOutputsPerInput*BV->getNumOperands());
6129 SmallVector<SDValue, 8> Ops;
6131 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6132 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6133 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6134 Ops.push_back(DAG.getUNDEF(DstEltVT));
6138 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6139 getAPIntValue().zextOrTrunc(SrcBitSize);
6141 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6142 APInt ThisVal = OpVal.trunc(DstBitSize);
6143 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6144 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6145 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6146 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6148 OpVal = OpVal.lshr(DstBitSize);
6151 // For big endian targets, swap the order of the pieces of each element.
6152 if (TLI.isBigEndian())
6153 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6156 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6157 &Ops[0], Ops.size());
6160 SDValue DAGCombiner::visitFADD(SDNode *N) {
6161 SDValue N0 = N->getOperand(0);
6162 SDValue N1 = N->getOperand(1);
6163 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6164 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6165 EVT VT = N->getValueType(0);
6168 if (VT.isVector()) {
6169 SDValue FoldedVOp = SimplifyVBinOp(N);
6170 if (FoldedVOp.getNode()) return FoldedVOp;
6173 // fold (fadd c1, c2) -> c1 + c2
6175 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6176 // canonicalize constant to RHS
6177 if (N0CFP && !N1CFP)
6178 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6179 // fold (fadd A, 0) -> A
6180 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6181 N1CFP->getValueAPF().isZero())
6183 // fold (fadd A, (fneg B)) -> (fsub A, B)
6184 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6185 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6186 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6187 GetNegatedExpression(N1, DAG, LegalOperations));
6188 // fold (fadd (fneg A), B) -> (fsub B, A)
6189 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6190 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6191 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6192 GetNegatedExpression(N0, DAG, LegalOperations));
6194 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6195 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6196 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6197 isa<ConstantFPSDNode>(N0.getOperand(1)))
6198 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6199 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6200 N0.getOperand(1), N1));
6202 // No FP constant should be created after legalization as Instruction
6203 // Selection pass has hard time in dealing with FP constant.
6205 // We don't need test this condition for transformation like following, as
6206 // the DAG being transformed implies it is legal to take FP constant as
6209 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6211 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6213 // If allow, fold (fadd (fneg x), x) -> 0.0
6214 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6215 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6216 return DAG.getConstantFP(0.0, VT);
6218 // If allow, fold (fadd x, (fneg x)) -> 0.0
6219 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6220 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6221 return DAG.getConstantFP(0.0, VT);
6223 // In unsafe math mode, we can fold chains of FADD's of the same value
6224 // into multiplications. This transform is not safe in general because
6225 // we are reducing the number of rounding steps.
6226 if (DAG.getTarget().Options.UnsafeFPMath &&
6227 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6229 if (N0.getOpcode() == ISD::FMUL) {
6230 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6231 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6233 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6234 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6235 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6237 DAG.getConstantFP(1.0, VT));
6238 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6242 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6243 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6244 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6246 DAG.getConstantFP(1.0, VT));
6247 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6251 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6252 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6253 N1.getOperand(0) == N1.getOperand(1) &&
6254 N0.getOperand(1) == N1.getOperand(0)) {
6255 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6257 DAG.getConstantFP(2.0, VT));
6258 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6259 N0.getOperand(1), NewCFP);
6262 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6263 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6264 N1.getOperand(0) == N1.getOperand(1) &&
6265 N0.getOperand(0) == N1.getOperand(0)) {
6266 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6268 DAG.getConstantFP(2.0, VT));
6269 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6270 N0.getOperand(0), NewCFP);
6274 if (N1.getOpcode() == ISD::FMUL) {
6275 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6276 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6278 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6279 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6280 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6282 DAG.getConstantFP(1.0, VT));
6283 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6287 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6288 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6289 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6291 DAG.getConstantFP(1.0, VT));
6292 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6297 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6298 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6299 N0.getOperand(0) == N0.getOperand(1) &&
6300 N1.getOperand(1) == N0.getOperand(0)) {
6301 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6303 DAG.getConstantFP(2.0, VT));
6304 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6305 N1.getOperand(1), NewCFP);
6308 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6309 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6310 N0.getOperand(0) == N0.getOperand(1) &&
6311 N1.getOperand(0) == N0.getOperand(0)) {
6312 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6314 DAG.getConstantFP(2.0, VT));
6315 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6316 N1.getOperand(0), NewCFP);
6320 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6321 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6322 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6323 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6324 (N0.getOperand(0) == N1))
6325 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6326 N1, DAG.getConstantFP(3.0, VT));
6329 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6330 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6331 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6332 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6333 N1.getOperand(0) == N0)
6334 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6335 N0, DAG.getConstantFP(3.0, VT));
6338 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6339 if (AllowNewFpConst &&
6340 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6341 N0.getOperand(0) == N0.getOperand(1) &&
6342 N1.getOperand(0) == N1.getOperand(1) &&
6343 N0.getOperand(0) == N1.getOperand(0))
6344 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6346 DAG.getConstantFP(4.0, VT));
6349 // FADD -> FMA combines:
6350 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6351 DAG.getTarget().Options.UnsafeFPMath) &&
6352 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6353 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6355 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6356 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6357 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6358 N0.getOperand(0), N0.getOperand(1), N1);
6360 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6361 // Note: Commutes FADD operands.
6362 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6363 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6364 N1.getOperand(0), N1.getOperand(1), N0);
6370 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6371 SDValue N0 = N->getOperand(0);
6372 SDValue N1 = N->getOperand(1);
6373 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6374 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6375 EVT VT = N->getValueType(0);
6379 if (VT.isVector()) {
6380 SDValue FoldedVOp = SimplifyVBinOp(N);
6381 if (FoldedVOp.getNode()) return FoldedVOp;
6384 // fold (fsub c1, c2) -> c1-c2
6386 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6387 // fold (fsub A, 0) -> A
6388 if (DAG.getTarget().Options.UnsafeFPMath &&
6389 N1CFP && N1CFP->getValueAPF().isZero())
6391 // fold (fsub 0, B) -> -B
6392 if (DAG.getTarget().Options.UnsafeFPMath &&
6393 N0CFP && N0CFP->getValueAPF().isZero()) {
6394 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6395 return GetNegatedExpression(N1, DAG, LegalOperations);
6396 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6397 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6399 // fold (fsub A, (fneg B)) -> (fadd A, B)
6400 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6401 return DAG.getNode(ISD::FADD, dl, VT, N0,
6402 GetNegatedExpression(N1, DAG, LegalOperations));
6404 // If 'unsafe math' is enabled, fold
6405 // (fsub x, x) -> 0.0 &
6406 // (fsub x, (fadd x, y)) -> (fneg y) &
6407 // (fsub x, (fadd y, x)) -> (fneg y)
6408 if (DAG.getTarget().Options.UnsafeFPMath) {
6410 return DAG.getConstantFP(0.0f, VT);
6412 if (N1.getOpcode() == ISD::FADD) {
6413 SDValue N10 = N1->getOperand(0);
6414 SDValue N11 = N1->getOperand(1);
6416 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6417 &DAG.getTarget().Options))
6418 return GetNegatedExpression(N11, DAG, LegalOperations);
6420 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6421 &DAG.getTarget().Options))
6422 return GetNegatedExpression(N10, DAG, LegalOperations);
6426 // FSUB -> FMA combines:
6427 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6428 DAG.getTarget().Options.UnsafeFPMath) &&
6429 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6430 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6432 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6433 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6434 return DAG.getNode(ISD::FMA, dl, VT,
6435 N0.getOperand(0), N0.getOperand(1),
6436 DAG.getNode(ISD::FNEG, dl, VT, N1));
6438 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6439 // Note: Commutes FSUB operands.
6440 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6441 return DAG.getNode(ISD::FMA, dl, VT,
6442 DAG.getNode(ISD::FNEG, dl, VT,
6444 N1.getOperand(1), N0);
6446 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6447 if (N0.getOpcode() == ISD::FNEG &&
6448 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6449 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6450 SDValue N00 = N0.getOperand(0).getOperand(0);
6451 SDValue N01 = N0.getOperand(0).getOperand(1);
6452 return DAG.getNode(ISD::FMA, dl, VT,
6453 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6454 DAG.getNode(ISD::FNEG, dl, VT, N1));
6461 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6462 SDValue N0 = N->getOperand(0);
6463 SDValue N1 = N->getOperand(1);
6464 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6465 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6466 EVT VT = N->getValueType(0);
6467 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6470 if (VT.isVector()) {
6471 SDValue FoldedVOp = SimplifyVBinOp(N);
6472 if (FoldedVOp.getNode()) return FoldedVOp;
6475 // fold (fmul c1, c2) -> c1*c2
6477 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6478 // canonicalize constant to RHS
6479 if (N0CFP && !N1CFP)
6480 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6481 // fold (fmul A, 0) -> 0
6482 if (DAG.getTarget().Options.UnsafeFPMath &&
6483 N1CFP && N1CFP->getValueAPF().isZero())
6485 // fold (fmul A, 0) -> 0, vector edition.
6486 if (DAG.getTarget().Options.UnsafeFPMath &&
6487 ISD::isBuildVectorAllZeros(N1.getNode()))
6489 // fold (fmul A, 1.0) -> A
6490 if (N1CFP && N1CFP->isExactlyValue(1.0))
6492 // fold (fmul X, 2.0) -> (fadd X, X)
6493 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6494 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6495 // fold (fmul X, -1.0) -> (fneg X)
6496 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6497 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6498 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6500 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6501 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6502 &DAG.getTarget().Options)) {
6503 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6504 &DAG.getTarget().Options)) {
6505 // Both can be negated for free, check to see if at least one is cheaper
6507 if (LHSNeg == 2 || RHSNeg == 2)
6508 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6509 GetNegatedExpression(N0, DAG, LegalOperations),
6510 GetNegatedExpression(N1, DAG, LegalOperations));
6514 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6515 if (DAG.getTarget().Options.UnsafeFPMath &&
6516 N1CFP && N0.getOpcode() == ISD::FMUL &&
6517 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6518 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6519 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6520 N0.getOperand(1), N1));
6525 SDValue DAGCombiner::visitFMA(SDNode *N) {
6526 SDValue N0 = N->getOperand(0);
6527 SDValue N1 = N->getOperand(1);
6528 SDValue N2 = N->getOperand(2);
6529 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6530 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6531 EVT VT = N->getValueType(0);
6534 if (DAG.getTarget().Options.UnsafeFPMath) {
6535 if (N0CFP && N0CFP->isZero())
6537 if (N1CFP && N1CFP->isZero())
6540 if (N0CFP && N0CFP->isExactlyValue(1.0))
6541 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6542 if (N1CFP && N1CFP->isExactlyValue(1.0))
6543 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6545 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6546 if (N0CFP && !N1CFP)
6547 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6549 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6550 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6551 N2.getOpcode() == ISD::FMUL &&
6552 N0 == N2.getOperand(0) &&
6553 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6554 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6555 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6559 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6560 if (DAG.getTarget().Options.UnsafeFPMath &&
6561 N0.getOpcode() == ISD::FMUL && N1CFP &&
6562 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6563 return DAG.getNode(ISD::FMA, dl, VT,
6565 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6569 // (fma x, 1, y) -> (fadd x, y)
6570 // (fma x, -1, y) -> (fadd (fneg x), y)
6572 if (N1CFP->isExactlyValue(1.0))
6573 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6575 if (N1CFP->isExactlyValue(-1.0) &&
6576 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6577 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6578 AddToWorkList(RHSNeg.getNode());
6579 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6583 // (fma x, c, x) -> (fmul x, (c+1))
6584 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6585 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6586 DAG.getNode(ISD::FADD, dl, VT,
6587 N1, DAG.getConstantFP(1.0, VT)));
6589 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6590 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6591 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6592 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6593 DAG.getNode(ISD::FADD, dl, VT,
6594 N1, DAG.getConstantFP(-1.0, VT)));
6600 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6601 SDValue N0 = N->getOperand(0);
6602 SDValue N1 = N->getOperand(1);
6603 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6604 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6605 EVT VT = N->getValueType(0);
6606 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6609 if (VT.isVector()) {
6610 SDValue FoldedVOp = SimplifyVBinOp(N);
6611 if (FoldedVOp.getNode()) return FoldedVOp;
6614 // fold (fdiv c1, c2) -> c1/c2
6616 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6618 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6619 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6620 // Compute the reciprocal 1.0 / c2.
6621 APFloat N1APF = N1CFP->getValueAPF();
6622 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6623 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6624 // Only do the transform if the reciprocal is a legal fp immediate that
6625 // isn't too nasty (eg NaN, denormal, ...).
6626 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6627 (!LegalOperations ||
6628 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6629 // backend)... we should handle this gracefully after Legalize.
6630 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6631 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6632 TLI.isFPImmLegal(Recip, VT)))
6633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6634 DAG.getConstantFP(Recip, VT));
6637 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6638 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6639 &DAG.getTarget().Options)) {
6640 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6641 &DAG.getTarget().Options)) {
6642 // Both can be negated for free, check to see if at least one is cheaper
6644 if (LHSNeg == 2 || RHSNeg == 2)
6645 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6646 GetNegatedExpression(N0, DAG, LegalOperations),
6647 GetNegatedExpression(N1, DAG, LegalOperations));
6654 SDValue DAGCombiner::visitFREM(SDNode *N) {
6655 SDValue N0 = N->getOperand(0);
6656 SDValue N1 = N->getOperand(1);
6657 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6658 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6659 EVT VT = N->getValueType(0);
6661 // fold (frem c1, c2) -> fmod(c1,c2)
6663 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6668 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6669 SDValue N0 = N->getOperand(0);
6670 SDValue N1 = N->getOperand(1);
6671 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6672 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6673 EVT VT = N->getValueType(0);
6675 if (N0CFP && N1CFP) // Constant fold
6676 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6679 const APFloat& V = N1CFP->getValueAPF();
6680 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6681 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6682 if (!V.isNegative()) {
6683 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6684 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6686 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6687 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6688 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6692 // copysign(fabs(x), y) -> copysign(x, y)
6693 // copysign(fneg(x), y) -> copysign(x, y)
6694 // copysign(copysign(x,z), y) -> copysign(x, y)
6695 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6696 N0.getOpcode() == ISD::FCOPYSIGN)
6697 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6698 N0.getOperand(0), N1);
6700 // copysign(x, abs(y)) -> abs(x)
6701 if (N1.getOpcode() == ISD::FABS)
6702 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6704 // copysign(x, copysign(y,z)) -> copysign(x, z)
6705 if (N1.getOpcode() == ISD::FCOPYSIGN)
6706 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6707 N0, N1.getOperand(1));
6709 // copysign(x, fp_extend(y)) -> copysign(x, y)
6710 // copysign(x, fp_round(y)) -> copysign(x, y)
6711 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6712 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6713 N0, N1.getOperand(0));
6718 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6719 SDValue N0 = N->getOperand(0);
6720 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6721 EVT VT = N->getValueType(0);
6722 EVT OpVT = N0.getValueType();
6724 // fold (sint_to_fp c1) -> c1fp
6726 // ...but only if the target supports immediate floating-point values
6727 (!LegalOperations ||
6728 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6729 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6731 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6732 // but UINT_TO_FP is legal on this target, try to convert.
6733 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6734 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6735 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6736 if (DAG.SignBitIsZero(N0))
6737 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6740 // The next optimizations are desireable only if SELECT_CC can be lowered.
6741 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6742 // having to say they don't support SELECT_CC on every type the DAG knows
6743 // about, since there is no way to mark an opcode illegal at all value types
6744 // (See also visitSELECT)
6745 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6746 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6747 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6749 (!LegalOperations ||
6750 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6752 { N0.getOperand(0), N0.getOperand(1),
6753 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6755 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6758 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6759 // (select_cc x, y, 1.0, 0.0,, cc)
6760 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6761 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6762 (!LegalOperations ||
6763 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6765 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6766 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6767 N0.getOperand(0).getOperand(2) };
6768 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6775 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6776 SDValue N0 = N->getOperand(0);
6777 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6778 EVT VT = N->getValueType(0);
6779 EVT OpVT = N0.getValueType();
6781 // fold (uint_to_fp c1) -> c1fp
6783 // ...but only if the target supports immediate floating-point values
6784 (!LegalOperations ||
6785 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6786 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6788 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6789 // but SINT_TO_FP is legal on this target, try to convert.
6790 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6791 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6792 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6793 if (DAG.SignBitIsZero(N0))
6794 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6797 // The next optimizations are desireable only if SELECT_CC can be lowered.
6798 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6799 // having to say they don't support SELECT_CC on every type the DAG knows
6800 // about, since there is no way to mark an opcode illegal at all value types
6801 // (See also visitSELECT)
6802 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6803 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6805 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6806 (!LegalOperations ||
6807 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6809 { N0.getOperand(0), N0.getOperand(1),
6810 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6812 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6819 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6820 SDValue N0 = N->getOperand(0);
6821 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6822 EVT VT = N->getValueType(0);
6824 // fold (fp_to_sint c1fp) -> c1
6826 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6831 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6832 SDValue N0 = N->getOperand(0);
6833 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6834 EVT VT = N->getValueType(0);
6836 // fold (fp_to_uint c1fp) -> c1
6838 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6843 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6844 SDValue N0 = N->getOperand(0);
6845 SDValue N1 = N->getOperand(1);
6846 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6847 EVT VT = N->getValueType(0);
6849 // fold (fp_round c1fp) -> c1fp
6851 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6853 // fold (fp_round (fp_extend x)) -> x
6854 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6855 return N0.getOperand(0);
6857 // fold (fp_round (fp_round x)) -> (fp_round x)
6858 if (N0.getOpcode() == ISD::FP_ROUND) {
6859 // This is a value preserving truncation if both round's are.
6860 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6861 N0.getNode()->getConstantOperandVal(1) == 1;
6862 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6863 DAG.getIntPtrConstant(IsTrunc));
6866 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6867 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6868 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6869 N0.getOperand(0), N1);
6870 AddToWorkList(Tmp.getNode());
6871 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6872 Tmp, N0.getOperand(1));
6878 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6879 SDValue N0 = N->getOperand(0);
6880 EVT VT = N->getValueType(0);
6881 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6882 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6884 // fold (fp_round_inreg c1fp) -> c1fp
6885 if (N0CFP && isTypeLegal(EVT)) {
6886 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6887 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6893 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6894 SDValue N0 = N->getOperand(0);
6895 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6896 EVT VT = N->getValueType(0);
6898 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6899 if (N->hasOneUse() &&
6900 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6903 // fold (fp_extend c1fp) -> c1fp
6905 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6907 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6909 if (N0.getOpcode() == ISD::FP_ROUND
6910 && N0.getNode()->getConstantOperandVal(1) == 1) {
6911 SDValue In = N0.getOperand(0);
6912 if (In.getValueType() == VT) return In;
6913 if (VT.bitsLT(In.getValueType()))
6914 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6915 In, N0.getOperand(1));
6916 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6919 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6920 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6921 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6922 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6923 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6924 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6926 LN0->getBasePtr(), N0.getValueType(),
6927 LN0->getMemOperand());
6928 CombineTo(N, ExtLoad);
6929 CombineTo(N0.getNode(),
6930 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6931 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6932 ExtLoad.getValue(1));
6933 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6939 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6940 SDValue N0 = N->getOperand(0);
6941 EVT VT = N->getValueType(0);
6943 if (VT.isVector()) {
6944 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6945 if (FoldedVOp.getNode()) return FoldedVOp;
6948 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6949 &DAG.getTarget().Options))
6950 return GetNegatedExpression(N0, DAG, LegalOperations);
6952 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6953 // constant pool values.
6954 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6956 N0.getNode()->hasOneUse() &&
6957 N0.getOperand(0).getValueType().isInteger()) {
6958 SDValue Int = N0.getOperand(0);
6959 EVT IntVT = Int.getValueType();
6960 if (IntVT.isInteger() && !IntVT.isVector()) {
6961 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6962 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6963 AddToWorkList(Int.getNode());
6964 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6969 // (fneg (fmul c, x)) -> (fmul -c, x)
6970 if (N0.getOpcode() == ISD::FMUL) {
6971 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6973 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6975 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6982 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6983 SDValue N0 = N->getOperand(0);
6984 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6985 EVT VT = N->getValueType(0);
6987 // fold (fceil c1) -> fceil(c1)
6989 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6994 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6995 SDValue N0 = N->getOperand(0);
6996 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6997 EVT VT = N->getValueType(0);
6999 // fold (ftrunc c1) -> ftrunc(c1)
7001 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7006 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7007 SDValue N0 = N->getOperand(0);
7008 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7009 EVT VT = N->getValueType(0);
7011 // fold (ffloor c1) -> ffloor(c1)
7013 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7018 SDValue DAGCombiner::visitFABS(SDNode *N) {
7019 SDValue N0 = N->getOperand(0);
7020 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7021 EVT VT = N->getValueType(0);
7023 if (VT.isVector()) {
7024 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7025 if (FoldedVOp.getNode()) return FoldedVOp;
7028 // fold (fabs c1) -> fabs(c1)
7030 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7031 // fold (fabs (fabs x)) -> (fabs x)
7032 if (N0.getOpcode() == ISD::FABS)
7033 return N->getOperand(0);
7034 // fold (fabs (fneg x)) -> (fabs x)
7035 // fold (fabs (fcopysign x, y)) -> (fabs x)
7036 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7037 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7039 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7040 // constant pool values.
7041 if (!TLI.isFAbsFree(VT) &&
7042 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7043 N0.getOperand(0).getValueType().isInteger() &&
7044 !N0.getOperand(0).getValueType().isVector()) {
7045 SDValue Int = N0.getOperand(0);
7046 EVT IntVT = Int.getValueType();
7047 if (IntVT.isInteger() && !IntVT.isVector()) {
7048 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7049 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7050 AddToWorkList(Int.getNode());
7051 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7052 N->getValueType(0), Int);
7059 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7060 SDValue Chain = N->getOperand(0);
7061 SDValue N1 = N->getOperand(1);
7062 SDValue N2 = N->getOperand(2);
7064 // If N is a constant we could fold this into a fallthrough or unconditional
7065 // branch. However that doesn't happen very often in normal code, because
7066 // Instcombine/SimplifyCFG should have handled the available opportunities.
7067 // If we did this folding here, it would be necessary to update the
7068 // MachineBasicBlock CFG, which is awkward.
7070 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7072 if (N1.getOpcode() == ISD::SETCC &&
7073 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7074 N1.getOperand(0).getValueType())) {
7075 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7076 Chain, N1.getOperand(2),
7077 N1.getOperand(0), N1.getOperand(1), N2);
7080 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7081 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7082 (N1.getOperand(0).hasOneUse() &&
7083 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7085 if (N1.getOpcode() == ISD::TRUNCATE) {
7086 // Look pass the truncate.
7087 Trunc = N1.getNode();
7088 N1 = N1.getOperand(0);
7091 // Match this pattern so that we can generate simpler code:
7094 // %b = and i32 %a, 2
7095 // %c = srl i32 %b, 1
7096 // brcond i32 %c ...
7101 // %b = and i32 %a, 2
7102 // %c = setcc eq %b, 0
7105 // This applies only when the AND constant value has one bit set and the
7106 // SRL constant is equal to the log2 of the AND constant. The back-end is
7107 // smart enough to convert the result into a TEST/JMP sequence.
7108 SDValue Op0 = N1.getOperand(0);
7109 SDValue Op1 = N1.getOperand(1);
7111 if (Op0.getOpcode() == ISD::AND &&
7112 Op1.getOpcode() == ISD::Constant) {
7113 SDValue AndOp1 = Op0.getOperand(1);
7115 if (AndOp1.getOpcode() == ISD::Constant) {
7116 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7118 if (AndConst.isPowerOf2() &&
7119 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7121 DAG.getSetCC(SDLoc(N),
7122 getSetCCResultType(Op0.getValueType()),
7123 Op0, DAG.getConstant(0, Op0.getValueType()),
7126 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7127 MVT::Other, Chain, SetCC, N2);
7128 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7129 // will convert it back to (X & C1) >> C2.
7130 CombineTo(N, NewBRCond, false);
7131 // Truncate is dead.
7133 removeFromWorkList(Trunc);
7134 DAG.DeleteNode(Trunc);
7136 // Replace the uses of SRL with SETCC
7137 WorkListRemover DeadNodes(*this);
7138 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7139 removeFromWorkList(N1.getNode());
7140 DAG.DeleteNode(N1.getNode());
7141 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7147 // Restore N1 if the above transformation doesn't match.
7148 N1 = N->getOperand(1);
7151 // Transform br(xor(x, y)) -> br(x != y)
7152 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7153 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7154 SDNode *TheXor = N1.getNode();
7155 SDValue Op0 = TheXor->getOperand(0);
7156 SDValue Op1 = TheXor->getOperand(1);
7157 if (Op0.getOpcode() == Op1.getOpcode()) {
7158 // Avoid missing important xor optimizations.
7159 SDValue Tmp = visitXOR(TheXor);
7160 if (Tmp.getNode()) {
7161 if (Tmp.getNode() != TheXor) {
7162 DEBUG(dbgs() << "\nReplacing.8 ";
7164 dbgs() << "\nWith: ";
7165 Tmp.getNode()->dump(&DAG);
7167 WorkListRemover DeadNodes(*this);
7168 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7169 removeFromWorkList(TheXor);
7170 DAG.DeleteNode(TheXor);
7171 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7172 MVT::Other, Chain, Tmp, N2);
7175 // visitXOR has changed XOR's operands or replaced the XOR completely,
7177 return SDValue(N, 0);
7181 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7183 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7184 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7185 Op0.getOpcode() == ISD::XOR) {
7186 TheXor = Op0.getNode();
7190 EVT SetCCVT = N1.getValueType();
7192 SetCCVT = getSetCCResultType(SetCCVT);
7193 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7196 Equal ? ISD::SETEQ : ISD::SETNE);
7197 // Replace the uses of XOR with SETCC
7198 WorkListRemover DeadNodes(*this);
7199 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7200 removeFromWorkList(N1.getNode());
7201 DAG.DeleteNode(N1.getNode());
7202 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7203 MVT::Other, Chain, SetCC, N2);
7210 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7212 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7213 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7214 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7216 // If N is a constant we could fold this into a fallthrough or unconditional
7217 // branch. However that doesn't happen very often in normal code, because
7218 // Instcombine/SimplifyCFG should have handled the available opportunities.
7219 // If we did this folding here, it would be necessary to update the
7220 // MachineBasicBlock CFG, which is awkward.
7222 // Use SimplifySetCC to simplify SETCC's.
7223 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7224 CondLHS, CondRHS, CC->get(), SDLoc(N),
7226 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7228 // fold to a simpler setcc
7229 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7230 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7231 N->getOperand(0), Simp.getOperand(2),
7232 Simp.getOperand(0), Simp.getOperand(1),
7238 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7239 /// uses N as its base pointer and that N may be folded in the load / store
7240 /// addressing mode.
7241 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7243 const TargetLowering &TLI) {
7245 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7246 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7248 VT = Use->getValueType(0);
7249 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7250 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7252 VT = ST->getValue().getValueType();
7256 TargetLowering::AddrMode AM;
7257 if (N->getOpcode() == ISD::ADD) {
7258 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7261 AM.BaseOffs = Offset->getSExtValue();
7265 } else if (N->getOpcode() == ISD::SUB) {
7266 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7269 AM.BaseOffs = -Offset->getSExtValue();
7276 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7279 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7280 /// pre-indexed load / store when the base pointer is an add or subtract
7281 /// and it has other uses besides the load / store. After the
7282 /// transformation, the new indexed load / store has effectively folded
7283 /// the add / subtract in and all of its other uses are redirected to the
7284 /// new load / store.
7285 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7286 if (Level < AfterLegalizeDAG)
7292 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7293 if (LD->isIndexed())
7295 VT = LD->getMemoryVT();
7296 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7297 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7299 Ptr = LD->getBasePtr();
7300 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7301 if (ST->isIndexed())
7303 VT = ST->getMemoryVT();
7304 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7305 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7307 Ptr = ST->getBasePtr();
7313 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7314 // out. There is no reason to make this a preinc/predec.
7315 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7316 Ptr.getNode()->hasOneUse())
7319 // Ask the target to do addressing mode selection.
7322 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7323 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7326 // Backends without true r+i pre-indexed forms may need to pass a
7327 // constant base with a variable offset so that constant coercion
7328 // will work with the patterns in canonical form.
7329 bool Swapped = false;
7330 if (isa<ConstantSDNode>(BasePtr)) {
7331 std::swap(BasePtr, Offset);
7335 // Don't create a indexed load / store with zero offset.
7336 if (isa<ConstantSDNode>(Offset) &&
7337 cast<ConstantSDNode>(Offset)->isNullValue())
7340 // Try turning it into a pre-indexed load / store except when:
7341 // 1) The new base ptr is a frame index.
7342 // 2) If N is a store and the new base ptr is either the same as or is a
7343 // predecessor of the value being stored.
7344 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7345 // that would create a cycle.
7346 // 4) All uses are load / store ops that use it as old base ptr.
7348 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7349 // (plus the implicit offset) to a register to preinc anyway.
7350 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7355 SDValue Val = cast<StoreSDNode>(N)->getValue();
7356 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7360 // If the offset is a constant, there may be other adds of constants that
7361 // can be folded with this one. We should do this to avoid having to keep
7362 // a copy of the original base pointer.
7363 SmallVector<SDNode *, 16> OtherUses;
7364 if (isa<ConstantSDNode>(Offset))
7365 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7366 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7368 if (Use == Ptr.getNode())
7371 if (Use->isPredecessorOf(N))
7374 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7379 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7380 if (Op1.getNode() == BasePtr.getNode())
7381 std::swap(Op0, Op1);
7382 assert(Op0.getNode() == BasePtr.getNode() &&
7383 "Use of ADD/SUB but not an operand");
7385 if (!isa<ConstantSDNode>(Op1)) {
7390 // FIXME: In some cases, we can be smarter about this.
7391 if (Op1.getValueType() != Offset.getValueType()) {
7396 OtherUses.push_back(Use);
7400 std::swap(BasePtr, Offset);
7402 // Now check for #3 and #4.
7403 bool RealUse = false;
7405 // Caches for hasPredecessorHelper
7406 SmallPtrSet<const SDNode *, 32> Visited;
7407 SmallVector<const SDNode *, 16> Worklist;
7409 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7410 E = Ptr.getNode()->use_end(); I != E; ++I) {
7414 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7417 // If Ptr may be folded in addressing mode of other use, then it's
7418 // not profitable to do this transformation.
7419 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7428 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7429 BasePtr, Offset, AM);
7431 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7432 BasePtr, Offset, AM);
7435 DEBUG(dbgs() << "\nReplacing.4 ";
7437 dbgs() << "\nWith: ";
7438 Result.getNode()->dump(&DAG);
7440 WorkListRemover DeadNodes(*this);
7442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7448 // Finally, since the node is now dead, remove it from the graph.
7452 std::swap(BasePtr, Offset);
7454 // Replace other uses of BasePtr that can be updated to use Ptr
7455 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7456 unsigned OffsetIdx = 1;
7457 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7459 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7460 BasePtr.getNode() && "Expected BasePtr operand");
7462 // We need to replace ptr0 in the following expression:
7463 // x0 * offset0 + y0 * ptr0 = t0
7465 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7467 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7468 // indexed load/store and the expresion that needs to be re-written.
7470 // Therefore, we have:
7471 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7473 ConstantSDNode *CN =
7474 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7476 APInt Offset0 = CN->getAPIntValue();
7477 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7479 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7480 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7481 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7482 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7484 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7486 APInt CNV = Offset0;
7487 if (X0 < 0) CNV = -CNV;
7488 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7489 else CNV = CNV - Offset1;
7491 // We can now generate the new expression.
7492 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7493 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7495 SDValue NewUse = DAG.getNode(Opcode,
7496 SDLoc(OtherUses[i]),
7497 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7498 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7499 removeFromWorkList(OtherUses[i]);
7500 DAG.DeleteNode(OtherUses[i]);
7503 // Replace the uses of Ptr with uses of the updated base value.
7504 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7505 removeFromWorkList(Ptr.getNode());
7506 DAG.DeleteNode(Ptr.getNode());
7511 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7512 /// add / sub of the base pointer node into a post-indexed load / store.
7513 /// The transformation folded the add / subtract into the new indexed
7514 /// load / store effectively and all of its uses are redirected to the
7515 /// new load / store.
7516 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7517 if (Level < AfterLegalizeDAG)
7523 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7524 if (LD->isIndexed())
7526 VT = LD->getMemoryVT();
7527 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7528 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7530 Ptr = LD->getBasePtr();
7531 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7532 if (ST->isIndexed())
7534 VT = ST->getMemoryVT();
7535 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7536 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7538 Ptr = ST->getBasePtr();
7544 if (Ptr.getNode()->hasOneUse())
7547 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7548 E = Ptr.getNode()->use_end(); I != E; ++I) {
7551 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7556 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7557 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7558 // Don't create a indexed load / store with zero offset.
7559 if (isa<ConstantSDNode>(Offset) &&
7560 cast<ConstantSDNode>(Offset)->isNullValue())
7563 // Try turning it into a post-indexed load / store except when
7564 // 1) All uses are load / store ops that use it as base ptr (and
7565 // it may be folded as addressing mmode).
7566 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7567 // nor a successor of N. Otherwise, if Op is folded that would
7570 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7574 bool TryNext = false;
7575 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7576 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7578 if (Use == Ptr.getNode())
7581 // If all the uses are load / store addresses, then don't do the
7583 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7584 bool RealUse = false;
7585 for (SDNode::use_iterator III = Use->use_begin(),
7586 EEE = Use->use_end(); III != EEE; ++III) {
7587 SDNode *UseUse = *III;
7588 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7603 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7604 SDValue Result = isLoad
7605 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7606 BasePtr, Offset, AM)
7607 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7608 BasePtr, Offset, AM);
7611 DEBUG(dbgs() << "\nReplacing.5 ";
7613 dbgs() << "\nWith: ";
7614 Result.getNode()->dump(&DAG);
7616 WorkListRemover DeadNodes(*this);
7618 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7619 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7621 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7624 // Finally, since the node is now dead, remove it from the graph.
7627 // Replace the uses of Use with uses of the updated base value.
7628 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7629 Result.getValue(isLoad ? 1 : 0));
7630 removeFromWorkList(Op);
7640 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7641 LoadSDNode *LD = cast<LoadSDNode>(N);
7642 SDValue Chain = LD->getChain();
7643 SDValue Ptr = LD->getBasePtr();
7645 // If load is not volatile and there are no uses of the loaded value (and
7646 // the updated indexed value in case of indexed loads), change uses of the
7647 // chain value into uses of the chain input (i.e. delete the dead load).
7648 if (!LD->isVolatile()) {
7649 if (N->getValueType(1) == MVT::Other) {
7651 if (!N->hasAnyUseOfValue(0)) {
7652 // It's not safe to use the two value CombineTo variant here. e.g.
7653 // v1, chain2 = load chain1, loc
7654 // v2, chain3 = load chain2, loc
7656 // Now we replace use of chain2 with chain1. This makes the second load
7657 // isomorphic to the one we are deleting, and thus makes this load live.
7658 DEBUG(dbgs() << "\nReplacing.6 ";
7660 dbgs() << "\nWith chain: ";
7661 Chain.getNode()->dump(&DAG);
7663 WorkListRemover DeadNodes(*this);
7664 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7666 if (N->use_empty()) {
7667 removeFromWorkList(N);
7671 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7675 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7676 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7677 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7678 DEBUG(dbgs() << "\nReplacing.7 ";
7680 dbgs() << "\nWith: ";
7681 Undef.getNode()->dump(&DAG);
7682 dbgs() << " and 2 other values\n");
7683 WorkListRemover DeadNodes(*this);
7684 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7685 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7686 DAG.getUNDEF(N->getValueType(1)));
7687 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7688 removeFromWorkList(N);
7690 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7695 // If this load is directly stored, replace the load value with the stored
7697 // TODO: Handle store large -> read small portion.
7698 // TODO: Handle TRUNCSTORE/LOADEXT
7699 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7700 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7701 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7702 if (PrevST->getBasePtr() == Ptr &&
7703 PrevST->getValue().getValueType() == N->getValueType(0))
7704 return CombineTo(N, Chain.getOperand(1), Chain);
7708 // Try to infer better alignment information than the load already has.
7709 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7710 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7711 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7713 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7714 LD->getValueType(0),
7715 Chain, Ptr, LD->getPointerInfo(),
7717 LD->isVolatile(), LD->isNonTemporal(), Align,
7719 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7724 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7725 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7727 // Walk up chain skipping non-aliasing memory nodes.
7728 SDValue BetterChain = FindBetterChain(N, Chain);
7730 // If there is a better chain.
7731 if (Chain != BetterChain) {
7734 // Replace the chain to void dependency.
7735 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7736 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7737 BetterChain, Ptr, LD->getMemOperand());
7739 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7740 LD->getValueType(0),
7741 BetterChain, Ptr, LD->getMemoryVT(),
7742 LD->getMemOperand());
7745 // Create token factor to keep old chain connected.
7746 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7747 MVT::Other, Chain, ReplLoad.getValue(1));
7749 // Make sure the new and old chains are cleaned up.
7750 AddToWorkList(Token.getNode());
7752 // Replace uses with load result and token factor. Don't add users
7754 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7758 // Try transforming N to an indexed load.
7759 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7760 return SDValue(N, 0);
7762 // Try to slice up N to more direct loads if the slices are mapped to
7763 // different register banks or pairing can take place.
7765 return SDValue(N, 0);
7771 /// \brief Helper structure used to slice a load in smaller loads.
7772 /// Basically a slice is obtained from the following sequence:
7773 /// Origin = load Ty1, Base
7774 /// Shift = srl Ty1 Origin, CstTy Amount
7775 /// Inst = trunc Shift to Ty2
7777 /// Then, it will be rewriten into:
7778 /// Slice = load SliceTy, Base + SliceOffset
7779 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7781 /// SliceTy is deduced from the number of bits that are actually used to
7783 struct LoadedSlice {
7784 /// \brief Helper structure used to compute the cost of a slice.
7786 /// Are we optimizing for code size.
7791 unsigned CrossRegisterBanksCopies;
7795 Cost(bool ForCodeSize = false)
7796 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7797 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7799 /// \brief Get the cost of one isolated slice.
7800 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7801 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7802 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7803 EVT TruncType = LS.Inst->getValueType(0);
7804 EVT LoadedType = LS.getLoadedType();
7805 if (TruncType != LoadedType &&
7806 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7810 /// \brief Account for slicing gain in the current cost.
7811 /// Slicing provide a few gains like removing a shift or a
7812 /// truncate. This method allows to grow the cost of the original
7813 /// load with the gain from this slice.
7814 void addSliceGain(const LoadedSlice &LS) {
7815 // Each slice saves a truncate.
7816 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7817 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7818 LS.Inst->getOperand(0).getValueType()))
7820 // If there is a shift amount, this slice gets rid of it.
7823 // If this slice can merge a cross register bank copy, account for it.
7824 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7825 ++CrossRegisterBanksCopies;
7828 Cost &operator+=(const Cost &RHS) {
7830 Truncates += RHS.Truncates;
7831 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7837 bool operator==(const Cost &RHS) const {
7838 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7839 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7840 ZExts == RHS.ZExts && Shift == RHS.Shift;
7843 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7845 bool operator<(const Cost &RHS) const {
7846 // Assume cross register banks copies are as expensive as loads.
7847 // FIXME: Do we want some more target hooks?
7848 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7849 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7850 // Unless we are optimizing for code size, consider the
7851 // expensive operation first.
7852 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7853 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7854 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7855 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7858 bool operator>(const Cost &RHS) const { return RHS < *this; }
7860 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7862 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7864 // The last instruction that represent the slice. This should be a
7865 // truncate instruction.
7867 // The original load instruction.
7869 // The right shift amount in bits from the original load.
7871 // The DAG from which Origin came from.
7872 // This is used to get some contextual information about legal types, etc.
7875 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7876 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7877 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7879 LoadedSlice(const LoadedSlice &LS)
7880 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7882 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7883 /// \return Result is \p BitWidth and has used bits set to 1 and
7884 /// not used bits set to 0.
7885 APInt getUsedBits() const {
7886 // Reproduce the trunc(lshr) sequence:
7887 // - Start from the truncated value.
7888 // - Zero extend to the desired bit width.
7890 assert(Origin && "No original load to compare against.");
7891 unsigned BitWidth = Origin->getValueSizeInBits(0);
7892 assert(Inst && "This slice is not bound to an instruction");
7893 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7894 "Extracted slice is bigger than the whole type!");
7895 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7896 UsedBits.setAllBits();
7897 UsedBits = UsedBits.zext(BitWidth);
7902 /// \brief Get the size of the slice to be loaded in bytes.
7903 unsigned getLoadedSize() const {
7904 unsigned SliceSize = getUsedBits().countPopulation();
7905 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7906 return SliceSize / 8;
7909 /// \brief Get the type that will be loaded for this slice.
7910 /// Note: This may not be the final type for the slice.
7911 EVT getLoadedType() const {
7912 assert(DAG && "Missing context");
7913 LLVMContext &Ctxt = *DAG->getContext();
7914 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7917 /// \brief Get the alignment of the load used for this slice.
7918 unsigned getAlignment() const {
7919 unsigned Alignment = Origin->getAlignment();
7920 unsigned Offset = getOffsetFromBase();
7922 Alignment = MinAlign(Alignment, Alignment + Offset);
7926 /// \brief Check if this slice can be rewritten with legal operations.
7927 bool isLegal() const {
7928 // An invalid slice is not legal.
7929 if (!Origin || !Inst || !DAG)
7932 // Offsets are for indexed load only, we do not handle that.
7933 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7936 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7938 // Check that the type is legal.
7939 EVT SliceType = getLoadedType();
7940 if (!TLI.isTypeLegal(SliceType))
7943 // Check that the load is legal for this type.
7944 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7947 // Check that the offset can be computed.
7948 // 1. Check its type.
7949 EVT PtrType = Origin->getBasePtr().getValueType();
7950 if (PtrType == MVT::Untyped || PtrType.isExtended())
7953 // 2. Check that it fits in the immediate.
7954 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7957 // 3. Check that the computation is legal.
7958 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7961 // Check that the zext is legal if it needs one.
7962 EVT TruncateType = Inst->getValueType(0);
7963 if (TruncateType != SliceType &&
7964 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7970 /// \brief Get the offset in bytes of this slice in the original chunk of
7972 /// \pre DAG != NULL.
7973 uint64_t getOffsetFromBase() const {
7974 assert(DAG && "Missing context.");
7976 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7977 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7978 uint64_t Offset = Shift / 8;
7979 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7980 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7981 "The size of the original loaded type is not a multiple of a"
7983 // If Offset is bigger than TySizeInBytes, it means we are loading all
7984 // zeros. This should have been optimized before in the process.
7985 assert(TySizeInBytes > Offset &&
7986 "Invalid shift amount for given loaded size");
7988 Offset = TySizeInBytes - Offset - getLoadedSize();
7992 /// \brief Generate the sequence of instructions to load the slice
7993 /// represented by this object and redirect the uses of this slice to
7994 /// this new sequence of instructions.
7995 /// \pre this->Inst && this->Origin are valid Instructions and this
7996 /// object passed the legal check: LoadedSlice::isLegal returned true.
7997 /// \return The last instruction of the sequence used to load the slice.
7998 SDValue loadSlice() const {
7999 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8000 const SDValue &OldBaseAddr = Origin->getBasePtr();
8001 SDValue BaseAddr = OldBaseAddr;
8002 // Get the offset in that chunk of bytes w.r.t. the endianess.
8003 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8004 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8006 // BaseAddr = BaseAddr + Offset.
8007 EVT ArithType = BaseAddr.getValueType();
8008 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8009 DAG->getConstant(Offset, ArithType));
8012 // Create the type of the loaded slice according to its size.
8013 EVT SliceType = getLoadedType();
8015 // Create the load for the slice.
8016 SDValue LastInst = DAG->getLoad(
8017 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8018 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8019 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8020 // If the final type is not the same as the loaded type, this means that
8021 // we have to pad with zero. Create a zero extend for that.
8022 EVT FinalType = Inst->getValueType(0);
8023 if (SliceType != FinalType)
8025 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8029 /// \brief Check if this slice can be merged with an expensive cross register
8030 /// bank copy. E.g.,
8032 /// f = bitcast i32 i to float
8033 bool canMergeExpensiveCrossRegisterBankCopy() const {
8034 if (!Inst || !Inst->hasOneUse())
8036 SDNode *Use = *Inst->use_begin();
8037 if (Use->getOpcode() != ISD::BITCAST)
8039 assert(DAG && "Missing context");
8040 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8041 EVT ResVT = Use->getValueType(0);
8042 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8043 const TargetRegisterClass *ArgRC =
8044 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8045 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8048 // At this point, we know that we perform a cross-register-bank copy.
8049 // Check if it is expensive.
8050 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8051 // Assume bitcasts are cheap, unless both register classes do not
8052 // explicitly share a common sub class.
8053 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8056 // Check if it will be merged with the load.
8057 // 1. Check the alignment constraint.
8058 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8059 ResVT.getTypeForEVT(*DAG->getContext()));
8061 if (RequiredAlignment > getAlignment())
8064 // 2. Check that the load is a legal operation for that type.
8065 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8068 // 3. Check that we do not have a zext in the way.
8069 if (Inst->getValueType(0) != getLoadedType())
8077 /// \brief Sorts LoadedSlice according to their offset.
8078 struct LoadedSliceSorter {
8079 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8080 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8081 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8085 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8086 /// \p UsedBits looks like 0..0 1..1 0..0.
8087 static bool areUsedBitsDense(const APInt &UsedBits) {
8088 // If all the bits are one, this is dense!
8089 if (UsedBits.isAllOnesValue())
8092 // Get rid of the unused bits on the right.
8093 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8094 // Get rid of the unused bits on the left.
8095 if (NarrowedUsedBits.countLeadingZeros())
8096 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8097 // Check that the chunk of bits is completely used.
8098 return NarrowedUsedBits.isAllOnesValue();
8101 /// \brief Check whether or not \p First and \p Second are next to each other
8102 /// in memory. This means that there is no hole between the bits loaded
8103 /// by \p First and the bits loaded by \p Second.
8104 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8105 const LoadedSlice &Second) {
8106 assert(First.Origin == Second.Origin && First.Origin &&
8107 "Unable to match different memory origins.");
8108 APInt UsedBits = First.getUsedBits();
8109 assert((UsedBits & Second.getUsedBits()) == 0 &&
8110 "Slices are not supposed to overlap.");
8111 UsedBits |= Second.getUsedBits();
8112 return areUsedBitsDense(UsedBits);
8115 /// \brief Adjust the \p GlobalLSCost according to the target
8116 /// paring capabilities and the layout of the slices.
8117 /// \pre \p GlobalLSCost should account for at least as many loads as
8118 /// there is in the slices in \p LoadedSlices.
8119 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8120 LoadedSlice::Cost &GlobalLSCost) {
8121 unsigned NumberOfSlices = LoadedSlices.size();
8122 // If there is less than 2 elements, no pairing is possible.
8123 if (NumberOfSlices < 2)
8126 // Sort the slices so that elements that are likely to be next to each
8127 // other in memory are next to each other in the list.
8128 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8129 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8130 // First (resp. Second) is the first (resp. Second) potentially candidate
8131 // to be placed in a paired load.
8132 const LoadedSlice *First = NULL;
8133 const LoadedSlice *Second = NULL;
8134 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8135 // Set the beginning of the pair.
8138 Second = &LoadedSlices[CurrSlice];
8140 // If First is NULL, it means we start a new pair.
8141 // Get to the next slice.
8145 EVT LoadedType = First->getLoadedType();
8147 // If the types of the slices are different, we cannot pair them.
8148 if (LoadedType != Second->getLoadedType())
8151 // Check if the target supplies paired loads for this type.
8152 unsigned RequiredAlignment = 0;
8153 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8154 // move to the next pair, this type is hopeless.
8158 // Check if we meet the alignment requirement.
8159 if (RequiredAlignment > First->getAlignment())
8162 // Check that both loads are next to each other in memory.
8163 if (!areSlicesNextToEachOther(*First, *Second))
8166 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8167 --GlobalLSCost.Loads;
8168 // Move to the next pair.
8173 /// \brief Check the profitability of all involved LoadedSlice.
8174 /// Currently, it is considered profitable if there is exactly two
8175 /// involved slices (1) which are (2) next to each other in memory, and
8176 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8178 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8179 /// the elements themselves.
8181 /// FIXME: When the cost model will be mature enough, we can relax
8182 /// constraints (1) and (2).
8183 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8184 const APInt &UsedBits, bool ForCodeSize) {
8185 unsigned NumberOfSlices = LoadedSlices.size();
8186 if (StressLoadSlicing)
8187 return NumberOfSlices > 1;
8190 if (NumberOfSlices != 2)
8194 if (!areUsedBitsDense(UsedBits))
8198 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8199 // The original code has one big load.
8201 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8202 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8203 // Accumulate the cost of all the slices.
8204 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8205 GlobalSlicingCost += SliceCost;
8207 // Account as cost in the original configuration the gain obtained
8208 // with the current slices.
8209 OrigCost.addSliceGain(LS);
8212 // If the target supports paired load, adjust the cost accordingly.
8213 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8214 return OrigCost > GlobalSlicingCost;
8217 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8218 /// operations, split it in the various pieces being extracted.
8220 /// This sort of thing is introduced by SROA.
8221 /// This slicing takes care not to insert overlapping loads.
8222 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8223 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8224 if (Level < AfterLegalizeDAG)
8227 LoadSDNode *LD = cast<LoadSDNode>(N);
8228 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8229 !LD->getValueType(0).isInteger())
8232 // Keep track of already used bits to detect overlapping values.
8233 // In that case, we will just abort the transformation.
8234 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8236 SmallVector<LoadedSlice, 4> LoadedSlices;
8238 // Check if this load is used as several smaller chunks of bits.
8239 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8240 // of computation for each trunc.
8241 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8242 UI != UIEnd; ++UI) {
8243 // Skip the uses of the chain.
8244 if (UI.getUse().getResNo() != 0)
8250 // Check if this is a trunc(lshr).
8251 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8252 isa<ConstantSDNode>(User->getOperand(1))) {
8253 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8254 User = *User->use_begin();
8257 // At this point, User is a Truncate, iff we encountered, trunc or
8259 if (User->getOpcode() != ISD::TRUNCATE)
8262 // The width of the type must be a power of 2 and greater than 8-bits.
8263 // Otherwise the load cannot be represented in LLVM IR.
8264 // Moreover, if we shifted with a non-8-bits multiple, the slice
8265 // will be accross several bytes. We do not support that.
8266 unsigned Width = User->getValueSizeInBits(0);
8267 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8270 // Build the slice for this chain of computations.
8271 LoadedSlice LS(User, LD, Shift, &DAG);
8272 APInt CurrentUsedBits = LS.getUsedBits();
8274 // Check if this slice overlaps with another.
8275 if ((CurrentUsedBits & UsedBits) != 0)
8277 // Update the bits used globally.
8278 UsedBits |= CurrentUsedBits;
8280 // Check if the new slice would be legal.
8284 // Record the slice.
8285 LoadedSlices.push_back(LS);
8288 // Abort slicing if it does not seem to be profitable.
8289 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8294 // Rewrite each chain to use an independent load.
8295 // By construction, each chain can be represented by a unique load.
8297 // Prepare the argument for the new token factor for all the slices.
8298 SmallVector<SDValue, 8> ArgChains;
8299 for (SmallVectorImpl<LoadedSlice>::const_iterator
8300 LSIt = LoadedSlices.begin(),
8301 LSItEnd = LoadedSlices.end();
8302 LSIt != LSItEnd; ++LSIt) {
8303 SDValue SliceInst = LSIt->loadSlice();
8304 CombineTo(LSIt->Inst, SliceInst, true);
8305 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8306 SliceInst = SliceInst.getOperand(0);
8307 assert(SliceInst->getOpcode() == ISD::LOAD &&
8308 "It takes more than a zext to get to the loaded slice!!");
8309 ArgChains.push_back(SliceInst.getValue(1));
8312 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8313 &ArgChains[0], ArgChains.size());
8314 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8318 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8319 /// load is having specific bytes cleared out. If so, return the byte size
8320 /// being masked out and the shift amount.
8321 static std::pair<unsigned, unsigned>
8322 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8323 std::pair<unsigned, unsigned> Result(0, 0);
8325 // Check for the structure we're looking for.
8326 if (V->getOpcode() != ISD::AND ||
8327 !isa<ConstantSDNode>(V->getOperand(1)) ||
8328 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8331 // Check the chain and pointer.
8332 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8333 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8335 // The store should be chained directly to the load or be an operand of a
8337 if (LD == Chain.getNode())
8339 else if (Chain->getOpcode() != ISD::TokenFactor)
8340 return Result; // Fail.
8343 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8344 if (Chain->getOperand(i).getNode() == LD) {
8348 if (!isOk) return Result;
8351 // This only handles simple types.
8352 if (V.getValueType() != MVT::i16 &&
8353 V.getValueType() != MVT::i32 &&
8354 V.getValueType() != MVT::i64)
8357 // Check the constant mask. Invert it so that the bits being masked out are
8358 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8359 // follow the sign bit for uniformity.
8360 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8361 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8362 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8363 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8364 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8365 if (NotMaskLZ == 64) return Result; // All zero mask.
8367 // See if we have a continuous run of bits. If so, we have 0*1+0*
8368 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8371 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8372 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8373 NotMaskLZ -= 64-V.getValueSizeInBits();
8375 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8376 switch (MaskedBytes) {
8380 default: return Result; // All one mask, or 5-byte mask.
8383 // Verify that the first bit starts at a multiple of mask so that the access
8384 // is aligned the same as the access width.
8385 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8387 Result.first = MaskedBytes;
8388 Result.second = NotMaskTZ/8;
8393 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8394 /// provides a value as specified by MaskInfo. If so, replace the specified
8395 /// store with a narrower store of truncated IVal.
8397 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8398 SDValue IVal, StoreSDNode *St,
8400 unsigned NumBytes = MaskInfo.first;
8401 unsigned ByteShift = MaskInfo.second;
8402 SelectionDAG &DAG = DC->getDAG();
8404 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8405 // that uses this. If not, this is not a replacement.
8406 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8407 ByteShift*8, (ByteShift+NumBytes)*8);
8408 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8410 // Check that it is legal on the target to do this. It is legal if the new
8411 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8413 MVT VT = MVT::getIntegerVT(NumBytes*8);
8414 if (!DC->isTypeLegal(VT))
8417 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8418 // shifted by ByteShift and truncated down to NumBytes.
8420 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8421 DAG.getConstant(ByteShift*8,
8422 DC->getShiftAmountTy(IVal.getValueType())));
8424 // Figure out the offset for the store and the alignment of the access.
8426 unsigned NewAlign = St->getAlignment();
8428 if (DAG.getTargetLoweringInfo().isLittleEndian())
8429 StOffset = ByteShift;
8431 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8433 SDValue Ptr = St->getBasePtr();
8435 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8436 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8437 NewAlign = MinAlign(NewAlign, StOffset);
8440 // Truncate down to the new size.
8441 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8444 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8445 St->getPointerInfo().getWithOffset(StOffset),
8446 false, false, NewAlign).getNode();
8450 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8451 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8452 /// of the loaded bits, try narrowing the load and store if it would end up
8453 /// being a win for performance or code size.
8454 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8455 StoreSDNode *ST = cast<StoreSDNode>(N);
8456 if (ST->isVolatile())
8459 SDValue Chain = ST->getChain();
8460 SDValue Value = ST->getValue();
8461 SDValue Ptr = ST->getBasePtr();
8462 EVT VT = Value.getValueType();
8464 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8467 unsigned Opc = Value.getOpcode();
8469 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8470 // is a byte mask indicating a consecutive number of bytes, check to see if
8471 // Y is known to provide just those bytes. If so, we try to replace the
8472 // load + replace + store sequence with a single (narrower) store, which makes
8474 if (Opc == ISD::OR) {
8475 std::pair<unsigned, unsigned> MaskedLoad;
8476 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8477 if (MaskedLoad.first)
8478 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8479 Value.getOperand(1), ST,this))
8480 return SDValue(NewST, 0);
8482 // Or is commutative, so try swapping X and Y.
8483 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8484 if (MaskedLoad.first)
8485 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8486 Value.getOperand(0), ST,this))
8487 return SDValue(NewST, 0);
8490 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8491 Value.getOperand(1).getOpcode() != ISD::Constant)
8494 SDValue N0 = Value.getOperand(0);
8495 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8496 Chain == SDValue(N0.getNode(), 1)) {
8497 LoadSDNode *LD = cast<LoadSDNode>(N0);
8498 if (LD->getBasePtr() != Ptr ||
8499 LD->getPointerInfo().getAddrSpace() !=
8500 ST->getPointerInfo().getAddrSpace())
8503 // Find the type to narrow it the load / op / store to.
8504 SDValue N1 = Value.getOperand(1);
8505 unsigned BitWidth = N1.getValueSizeInBits();
8506 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8507 if (Opc == ISD::AND)
8508 Imm ^= APInt::getAllOnesValue(BitWidth);
8509 if (Imm == 0 || Imm.isAllOnesValue())
8511 unsigned ShAmt = Imm.countTrailingZeros();
8512 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8513 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8514 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8515 while (NewBW < BitWidth &&
8516 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8517 TLI.isNarrowingProfitable(VT, NewVT))) {
8518 NewBW = NextPowerOf2(NewBW);
8519 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8521 if (NewBW >= BitWidth)
8524 // If the lsb changed does not start at the type bitwidth boundary,
8525 // start at the previous one.
8527 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8528 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8529 std::min(BitWidth, ShAmt + NewBW));
8530 if ((Imm & Mask) == Imm) {
8531 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8532 if (Opc == ISD::AND)
8533 NewImm ^= APInt::getAllOnesValue(NewBW);
8534 uint64_t PtrOff = ShAmt / 8;
8535 // For big endian targets, we need to adjust the offset to the pointer to
8536 // load the correct bytes.
8537 if (TLI.isBigEndian())
8538 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8540 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8541 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8542 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8545 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8546 Ptr.getValueType(), Ptr,
8547 DAG.getConstant(PtrOff, Ptr.getValueType()));
8548 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8549 LD->getChain(), NewPtr,
8550 LD->getPointerInfo().getWithOffset(PtrOff),
8551 LD->isVolatile(), LD->isNonTemporal(),
8552 LD->isInvariant(), NewAlign,
8554 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8555 DAG.getConstant(NewImm, NewVT));
8556 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8558 ST->getPointerInfo().getWithOffset(PtrOff),
8559 false, false, NewAlign);
8561 AddToWorkList(NewPtr.getNode());
8562 AddToWorkList(NewLD.getNode());
8563 AddToWorkList(NewVal.getNode());
8564 WorkListRemover DeadNodes(*this);
8565 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8574 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8575 /// if the load value isn't used by any other operations, then consider
8576 /// transforming the pair to integer load / store operations if the target
8577 /// deems the transformation profitable.
8578 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8579 StoreSDNode *ST = cast<StoreSDNode>(N);
8580 SDValue Chain = ST->getChain();
8581 SDValue Value = ST->getValue();
8582 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8583 Value.hasOneUse() &&
8584 Chain == SDValue(Value.getNode(), 1)) {
8585 LoadSDNode *LD = cast<LoadSDNode>(Value);
8586 EVT VT = LD->getMemoryVT();
8587 if (!VT.isFloatingPoint() ||
8588 VT != ST->getMemoryVT() ||
8589 LD->isNonTemporal() ||
8590 ST->isNonTemporal() ||
8591 LD->getPointerInfo().getAddrSpace() != 0 ||
8592 ST->getPointerInfo().getAddrSpace() != 0)
8595 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8596 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8597 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8598 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8599 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8602 unsigned LDAlign = LD->getAlignment();
8603 unsigned STAlign = ST->getAlignment();
8604 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8605 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8606 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8609 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8610 LD->getChain(), LD->getBasePtr(),
8611 LD->getPointerInfo(),
8612 false, false, false, LDAlign);
8614 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8615 NewLD, ST->getBasePtr(),
8616 ST->getPointerInfo(),
8617 false, false, STAlign);
8619 AddToWorkList(NewLD.getNode());
8620 AddToWorkList(NewST.getNode());
8621 WorkListRemover DeadNodes(*this);
8622 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8630 /// Helper struct to parse and store a memory address as base + index + offset.
8631 /// We ignore sign extensions when it is safe to do so.
8632 /// The following two expressions are not equivalent. To differentiate we need
8633 /// to store whether there was a sign extension involved in the index
8635 /// (load (i64 add (i64 copyfromreg %c)
8636 /// (i64 signextend (add (i8 load %index)
8640 /// (load (i64 add (i64 copyfromreg %c)
8641 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8643 struct BaseIndexOffset {
8647 bool IsIndexSignExt;
8649 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8651 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8652 bool IsIndexSignExt) :
8653 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8655 bool equalBaseIndex(const BaseIndexOffset &Other) {
8656 return Other.Base == Base && Other.Index == Index &&
8657 Other.IsIndexSignExt == IsIndexSignExt;
8660 /// Parses tree in Ptr for base, index, offset addresses.
8661 static BaseIndexOffset match(SDValue Ptr) {
8662 bool IsIndexSignExt = false;
8664 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8665 // instruction, then it could be just the BASE or everything else we don't
8666 // know how to handle. Just use Ptr as BASE and give up.
8667 if (Ptr->getOpcode() != ISD::ADD)
8668 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8670 // We know that we have at least an ADD instruction. Try to pattern match
8671 // the simple case of BASE + OFFSET.
8672 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8673 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8674 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8678 // Inside a loop the current BASE pointer is calculated using an ADD and a
8679 // MUL instruction. In this case Ptr is the actual BASE pointer.
8680 // (i64 add (i64 %array_ptr)
8681 // (i64 mul (i64 %induction_var)
8682 // (i64 %element_size)))
8683 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8684 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8686 // Look at Base + Index + Offset cases.
8687 SDValue Base = Ptr->getOperand(0);
8688 SDValue IndexOffset = Ptr->getOperand(1);
8690 // Skip signextends.
8691 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8692 IndexOffset = IndexOffset->getOperand(0);
8693 IsIndexSignExt = true;
8696 // Either the case of Base + Index (no offset) or something else.
8697 if (IndexOffset->getOpcode() != ISD::ADD)
8698 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8700 // Now we have the case of Base + Index + offset.
8701 SDValue Index = IndexOffset->getOperand(0);
8702 SDValue Offset = IndexOffset->getOperand(1);
8704 if (!isa<ConstantSDNode>(Offset))
8705 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8707 // Ignore signextends.
8708 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8709 Index = Index->getOperand(0);
8710 IsIndexSignExt = true;
8711 } else IsIndexSignExt = false;
8713 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8714 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8718 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8719 /// is located in a sequence of memory operations connected by a chain.
8721 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8722 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8723 // Ptr to the mem node.
8724 LSBaseSDNode *MemNode;
8725 // Offset from the base ptr.
8726 int64_t OffsetFromBase;
8727 // What is the sequence number of this mem node.
8728 // Lowest mem operand in the DAG starts at zero.
8729 unsigned SequenceNum;
8732 /// Sorts store nodes in a link according to their offset from a shared
8734 struct ConsecutiveMemoryChainSorter {
8735 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8736 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8740 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8741 EVT MemVT = St->getMemoryVT();
8742 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8743 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8744 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8746 // Don't merge vectors into wider inputs.
8747 if (MemVT.isVector() || !MemVT.isSimple())
8750 // Perform an early exit check. Do not bother looking at stored values that
8751 // are not constants or loads.
8752 SDValue StoredVal = St->getValue();
8753 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8754 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8758 // Only look at ends of store sequences.
8759 SDValue Chain = SDValue(St, 1);
8760 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8763 // This holds the base pointer, index, and the offset in bytes from the base
8765 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8767 // We must have a base and an offset.
8768 if (!BasePtr.Base.getNode())
8771 // Do not handle stores to undef base pointers.
8772 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8775 // Save the LoadSDNodes that we find in the chain.
8776 // We need to make sure that these nodes do not interfere with
8777 // any of the store nodes.
8778 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8780 // Save the StoreSDNodes that we find in the chain.
8781 SmallVector<MemOpLink, 8> StoreNodes;
8783 // Walk up the chain and look for nodes with offsets from the same
8784 // base pointer. Stop when reaching an instruction with a different kind
8785 // or instruction which has a different base pointer.
8787 StoreSDNode *Index = St;
8789 // If the chain has more than one use, then we can't reorder the mem ops.
8790 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8793 // Find the base pointer and offset for this memory node.
8794 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8796 // Check that the base pointer is the same as the original one.
8797 if (!Ptr.equalBaseIndex(BasePtr))
8800 // Check that the alignment is the same.
8801 if (Index->getAlignment() != St->getAlignment())
8804 // The memory operands must not be volatile.
8805 if (Index->isVolatile() || Index->isIndexed())
8809 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8810 if (St->isTruncatingStore())
8813 // The stored memory type must be the same.
8814 if (Index->getMemoryVT() != MemVT)
8817 // We do not allow unaligned stores because we want to prevent overriding
8819 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8822 // We found a potential memory operand to merge.
8823 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8825 // Find the next memory operand in the chain. If the next operand in the
8826 // chain is a store then move up and continue the scan with the next
8827 // memory operand. If the next operand is a load save it and use alias
8828 // information to check if it interferes with anything.
8829 SDNode *NextInChain = Index->getChain().getNode();
8831 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8832 // We found a store node. Use it for the next iteration.
8835 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8836 if (Ldn->isVolatile()) {
8841 // Save the load node for later. Continue the scan.
8842 AliasLoadNodes.push_back(Ldn);
8843 NextInChain = Ldn->getChain().getNode();
8852 // Check if there is anything to merge.
8853 if (StoreNodes.size() < 2)
8856 // Sort the memory operands according to their distance from the base pointer.
8857 std::sort(StoreNodes.begin(), StoreNodes.end(),
8858 ConsecutiveMemoryChainSorter());
8860 // Scan the memory operations on the chain and find the first non-consecutive
8861 // store memory address.
8862 unsigned LastConsecutiveStore = 0;
8863 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8864 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8866 // Check that the addresses are consecutive starting from the second
8867 // element in the list of stores.
8869 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8870 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8875 // Check if this store interferes with any of the loads that we found.
8876 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8877 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8881 // We found a load that alias with this store. Stop the sequence.
8885 // Mark this node as useful.
8886 LastConsecutiveStore = i;
8889 // The node with the lowest store address.
8890 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8892 // Store the constants into memory as one consecutive store.
8894 unsigned LastLegalType = 0;
8895 unsigned LastLegalVectorType = 0;
8896 bool NonZero = false;
8897 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8898 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8899 SDValue StoredVal = St->getValue();
8901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8902 NonZero |= !C->isNullValue();
8903 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8904 NonZero |= !C->getConstantFPValue()->isNullValue();
8910 // Find a legal type for the constant store.
8911 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8912 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8913 if (TLI.isTypeLegal(StoreTy))
8914 LastLegalType = i+1;
8915 // Or check whether a truncstore is legal.
8916 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8917 TargetLowering::TypePromoteInteger) {
8918 EVT LegalizedStoredValueTy =
8919 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8920 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8921 LastLegalType = i+1;
8924 // Find a legal type for the vector store.
8925 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8926 if (TLI.isTypeLegal(Ty))
8927 LastLegalVectorType = i + 1;
8930 // We only use vectors if the constant is known to be zero and the
8931 // function is not marked with the noimplicitfloat attribute.
8932 if (NonZero || NoVectors)
8933 LastLegalVectorType = 0;
8935 // Check if we found a legal integer type to store.
8936 if (LastLegalType == 0 && LastLegalVectorType == 0)
8939 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8940 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8942 // Make sure we have something to merge.
8946 unsigned EarliestNodeUsed = 0;
8947 for (unsigned i=0; i < NumElem; ++i) {
8948 // Find a chain for the new wide-store operand. Notice that some
8949 // of the store nodes that we found may not be selected for inclusion
8950 // in the wide store. The chain we use needs to be the chain of the
8951 // earliest store node which is *used* and replaced by the wide store.
8952 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8953 EarliestNodeUsed = i;
8956 // The earliest Node in the DAG.
8957 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8958 SDLoc DL(StoreNodes[0].MemNode);
8962 // Find a legal type for the vector store.
8963 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8964 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8965 StoredVal = DAG.getConstant(0, Ty);
8967 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8968 APInt StoreInt(StoreBW, 0);
8970 // Construct a single integer constant which is made of the smaller
8972 bool IsLE = TLI.isLittleEndian();
8973 for (unsigned i = 0; i < NumElem ; ++i) {
8974 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8975 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8976 SDValue Val = St->getValue();
8977 StoreInt<<=ElementSizeBytes*8;
8978 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8979 StoreInt|=C->getAPIntValue().zext(StoreBW);
8980 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8981 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8983 assert(false && "Invalid constant element type");
8987 // Create the new Load and Store operations.
8988 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8989 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8992 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8993 FirstInChain->getBasePtr(),
8994 FirstInChain->getPointerInfo(),
8996 FirstInChain->getAlignment());
8998 // Replace the first store with the new store
8999 CombineTo(EarliestOp, NewStore);
9000 // Erase all other stores.
9001 for (unsigned i = 0; i < NumElem ; ++i) {
9002 if (StoreNodes[i].MemNode == EarliestOp)
9004 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9005 // ReplaceAllUsesWith will replace all uses that existed when it was
9006 // called, but graph optimizations may cause new ones to appear. For
9007 // example, the case in pr14333 looks like
9009 // St's chain -> St -> another store -> X
9011 // And the only difference from St to the other store is the chain.
9012 // When we change it's chain to be St's chain they become identical,
9013 // get CSEed and the net result is that X is now a use of St.
9014 // Since we know that St is redundant, just iterate.
9015 while (!St->use_empty())
9016 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9017 removeFromWorkList(St);
9024 // Below we handle the case of multiple consecutive stores that
9025 // come from multiple consecutive loads. We merge them into a single
9026 // wide load and a single wide store.
9028 // Look for load nodes which are used by the stored values.
9029 SmallVector<MemOpLink, 8> LoadNodes;
9031 // Find acceptable loads. Loads need to have the same chain (token factor),
9032 // must not be zext, volatile, indexed, and they must be consecutive.
9033 BaseIndexOffset LdBasePtr;
9034 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9035 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9036 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9039 // Loads must only have one use.
9040 if (!Ld->hasNUsesOfValue(1, 0))
9043 // Check that the alignment is the same as the stores.
9044 if (Ld->getAlignment() != St->getAlignment())
9047 // The memory operands must not be volatile.
9048 if (Ld->isVolatile() || Ld->isIndexed())
9051 // We do not accept ext loads.
9052 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9055 // The stored memory type must be the same.
9056 if (Ld->getMemoryVT() != MemVT)
9059 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9060 // If this is not the first ptr that we check.
9061 if (LdBasePtr.Base.getNode()) {
9062 // The base ptr must be the same.
9063 if (!LdPtr.equalBaseIndex(LdBasePtr))
9066 // Check that all other base pointers are the same as this one.
9070 // We found a potential memory operand to merge.
9071 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9074 if (LoadNodes.size() < 2)
9077 // Scan the memory operations on the chain and find the first non-consecutive
9078 // load memory address. These variables hold the index in the store node
9080 unsigned LastConsecutiveLoad = 0;
9081 // This variable refers to the size and not index in the array.
9082 unsigned LastLegalVectorType = 0;
9083 unsigned LastLegalIntegerType = 0;
9084 StartAddress = LoadNodes[0].OffsetFromBase;
9085 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9086 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9087 // All loads much share the same chain.
9088 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9091 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9092 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9094 LastConsecutiveLoad = i;
9096 // Find a legal type for the vector store.
9097 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9098 if (TLI.isTypeLegal(StoreTy))
9099 LastLegalVectorType = i + 1;
9101 // Find a legal type for the integer store.
9102 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9103 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9104 if (TLI.isTypeLegal(StoreTy))
9105 LastLegalIntegerType = i + 1;
9106 // Or check whether a truncstore and extload is legal.
9107 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9108 TargetLowering::TypePromoteInteger) {
9109 EVT LegalizedStoredValueTy =
9110 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9111 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9112 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9113 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9114 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9115 LastLegalIntegerType = i+1;
9119 // Only use vector types if the vector type is larger than the integer type.
9120 // If they are the same, use integers.
9121 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9122 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9124 // We add +1 here because the LastXXX variables refer to location while
9125 // the NumElem refers to array/index size.
9126 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9127 NumElem = std::min(LastLegalType, NumElem);
9132 // The earliest Node in the DAG.
9133 unsigned EarliestNodeUsed = 0;
9134 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9135 for (unsigned i=1; i<NumElem; ++i) {
9136 // Find a chain for the new wide-store operand. Notice that some
9137 // of the store nodes that we found may not be selected for inclusion
9138 // in the wide store. The chain we use needs to be the chain of the
9139 // earliest store node which is *used* and replaced by the wide store.
9140 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9141 EarliestNodeUsed = i;
9144 // Find if it is better to use vectors or integers to load and store
9148 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9150 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9151 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9154 SDLoc LoadDL(LoadNodes[0].MemNode);
9155 SDLoc StoreDL(StoreNodes[0].MemNode);
9157 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9158 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9159 FirstLoad->getChain(),
9160 FirstLoad->getBasePtr(),
9161 FirstLoad->getPointerInfo(),
9162 false, false, false,
9163 FirstLoad->getAlignment());
9165 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9166 FirstInChain->getBasePtr(),
9167 FirstInChain->getPointerInfo(), false, false,
9168 FirstInChain->getAlignment());
9170 // Replace one of the loads with the new load.
9171 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9172 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9173 SDValue(NewLoad.getNode(), 1));
9175 // Remove the rest of the load chains.
9176 for (unsigned i = 1; i < NumElem ; ++i) {
9177 // Replace all chain users of the old load nodes with the chain of the new
9179 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9180 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9183 // Replace the first store with the new store.
9184 CombineTo(EarliestOp, NewStore);
9185 // Erase all other stores.
9186 for (unsigned i = 0; i < NumElem ; ++i) {
9187 // Remove all Store nodes.
9188 if (StoreNodes[i].MemNode == EarliestOp)
9190 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9191 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9192 removeFromWorkList(St);
9199 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9200 StoreSDNode *ST = cast<StoreSDNode>(N);
9201 SDValue Chain = ST->getChain();
9202 SDValue Value = ST->getValue();
9203 SDValue Ptr = ST->getBasePtr();
9205 // If this is a store of a bit convert, store the input value if the
9206 // resultant store does not need a higher alignment than the original.
9207 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9208 ST->isUnindexed()) {
9209 unsigned OrigAlign = ST->getAlignment();
9210 EVT SVT = Value.getOperand(0).getValueType();
9211 unsigned Align = TLI.getDataLayout()->
9212 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9213 if (Align <= OrigAlign &&
9214 ((!LegalOperations && !ST->isVolatile()) ||
9215 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9216 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9217 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9218 ST->isNonTemporal(), OrigAlign,
9222 // Turn 'store undef, Ptr' -> nothing.
9223 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9226 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9227 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9228 // NOTE: If the original store is volatile, this transform must not increase
9229 // the number of stores. For example, on x86-32 an f64 can be stored in one
9230 // processor operation but an i64 (which is not legal) requires two. So the
9231 // transform should not be done in this case.
9232 if (Value.getOpcode() != ISD::TargetConstantFP) {
9234 switch (CFP->getSimpleValueType(0).SimpleTy) {
9235 default: llvm_unreachable("Unknown FP type");
9236 case MVT::f16: // We don't do this for these yet.
9242 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9243 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9244 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9245 bitcastToAPInt().getZExtValue(), MVT::i32);
9246 return DAG.getStore(Chain, SDLoc(N), Tmp,
9247 Ptr, ST->getMemOperand());
9251 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9252 !ST->isVolatile()) ||
9253 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9254 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9255 getZExtValue(), MVT::i64);
9256 return DAG.getStore(Chain, SDLoc(N), Tmp,
9257 Ptr, ST->getMemOperand());
9260 if (!ST->isVolatile() &&
9261 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9262 // Many FP stores are not made apparent until after legalize, e.g. for
9263 // argument passing. Since this is so common, custom legalize the
9264 // 64-bit integer store into two 32-bit stores.
9265 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9266 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9267 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9268 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9270 unsigned Alignment = ST->getAlignment();
9271 bool isVolatile = ST->isVolatile();
9272 bool isNonTemporal = ST->isNonTemporal();
9273 const MDNode *TBAAInfo = ST->getTBAAInfo();
9275 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9276 Ptr, ST->getPointerInfo(),
9277 isVolatile, isNonTemporal,
9278 ST->getAlignment(), TBAAInfo);
9279 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9280 DAG.getConstant(4, Ptr.getValueType()));
9281 Alignment = MinAlign(Alignment, 4U);
9282 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9283 Ptr, ST->getPointerInfo().getWithOffset(4),
9284 isVolatile, isNonTemporal,
9285 Alignment, TBAAInfo);
9286 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9295 // Try to infer better alignment information than the store already has.
9296 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9297 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9298 if (Align > ST->getAlignment())
9299 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9300 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9301 ST->isVolatile(), ST->isNonTemporal(), Align,
9306 // Try transforming a pair floating point load / store ops to integer
9307 // load / store ops.
9308 SDValue NewST = TransformFPLoadStorePair(N);
9309 if (NewST.getNode())
9312 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9313 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9315 // Walk up chain skipping non-aliasing memory nodes.
9316 SDValue BetterChain = FindBetterChain(N, Chain);
9318 // If there is a better chain.
9319 if (Chain != BetterChain) {
9322 // Replace the chain to avoid dependency.
9323 if (ST->isTruncatingStore()) {
9324 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9325 ST->getMemoryVT(), ST->getMemOperand());
9327 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9328 ST->getMemOperand());
9331 // Create token to keep both nodes around.
9332 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9333 MVT::Other, Chain, ReplStore);
9335 // Make sure the new and old chains are cleaned up.
9336 AddToWorkList(Token.getNode());
9338 // Don't add users to work list.
9339 return CombineTo(N, Token, false);
9343 // Try transforming N to an indexed store.
9344 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9345 return SDValue(N, 0);
9347 // FIXME: is there such a thing as a truncating indexed store?
9348 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9349 Value.getValueType().isInteger()) {
9350 // See if we can simplify the input to this truncstore with knowledge that
9351 // only the low bits are being used. For example:
9352 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9354 GetDemandedBits(Value,
9355 APInt::getLowBitsSet(
9356 Value.getValueType().getScalarType().getSizeInBits(),
9357 ST->getMemoryVT().getScalarType().getSizeInBits()));
9358 AddToWorkList(Value.getNode());
9359 if (Shorter.getNode())
9360 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9361 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9363 // Otherwise, see if we can simplify the operation with
9364 // SimplifyDemandedBits, which only works if the value has a single use.
9365 if (SimplifyDemandedBits(Value,
9366 APInt::getLowBitsSet(
9367 Value.getValueType().getScalarType().getSizeInBits(),
9368 ST->getMemoryVT().getScalarType().getSizeInBits())))
9369 return SDValue(N, 0);
9372 // If this is a load followed by a store to the same location, then the store
9374 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9375 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9376 ST->isUnindexed() && !ST->isVolatile() &&
9377 // There can't be any side effects between the load and store, such as
9379 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9380 // The store is dead, remove it.
9385 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9386 // truncating store. We can do this even if this is already a truncstore.
9387 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9388 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9389 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9390 ST->getMemoryVT())) {
9391 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9392 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9395 // Only perform this optimization before the types are legal, because we
9396 // don't want to perform this optimization on every DAGCombine invocation.
9398 bool EverChanged = false;
9401 // There can be multiple store sequences on the same chain.
9402 // Keep trying to merge store sequences until we are unable to do so
9403 // or until we merge the last store on the chain.
9404 bool Changed = MergeConsecutiveStores(ST);
9405 EverChanged |= Changed;
9406 if (!Changed) break;
9407 } while (ST->getOpcode() != ISD::DELETED_NODE);
9410 return SDValue(N, 0);
9413 return ReduceLoadOpStoreWidth(N);
9416 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9417 SDValue InVec = N->getOperand(0);
9418 SDValue InVal = N->getOperand(1);
9419 SDValue EltNo = N->getOperand(2);
9422 // If the inserted element is an UNDEF, just use the input vector.
9423 if (InVal.getOpcode() == ISD::UNDEF)
9426 EVT VT = InVec.getValueType();
9428 // If we can't generate a legal BUILD_VECTOR, exit
9429 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9432 // Check that we know which element is being inserted
9433 if (!isa<ConstantSDNode>(EltNo))
9435 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9437 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9438 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9440 SmallVector<SDValue, 8> Ops;
9441 // Do not combine these two vectors if the output vector will not replace
9442 // the input vector.
9443 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9444 Ops.append(InVec.getNode()->op_begin(),
9445 InVec.getNode()->op_end());
9446 } else if (InVec.getOpcode() == ISD::UNDEF) {
9447 unsigned NElts = VT.getVectorNumElements();
9448 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9453 // Insert the element
9454 if (Elt < Ops.size()) {
9455 // All the operands of BUILD_VECTOR must have the same type;
9456 // we enforce that here.
9457 EVT OpVT = Ops[0].getValueType();
9458 if (InVal.getValueType() != OpVT)
9459 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9460 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9461 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9465 // Return the new vector
9466 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9467 VT, &Ops[0], Ops.size());
9470 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9471 // (vextract (scalar_to_vector val, 0) -> val
9472 SDValue InVec = N->getOperand(0);
9473 EVT VT = InVec.getValueType();
9474 EVT NVT = N->getValueType(0);
9476 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9477 // Check if the result type doesn't match the inserted element type. A
9478 // SCALAR_TO_VECTOR may truncate the inserted element and the
9479 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9480 SDValue InOp = InVec.getOperand(0);
9481 if (InOp.getValueType() != NVT) {
9482 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9483 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9488 SDValue EltNo = N->getOperand(1);
9489 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9491 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9492 // We only perform this optimization before the op legalization phase because
9493 // we may introduce new vector instructions which are not backed by TD
9494 // patterns. For example on AVX, extracting elements from a wide vector
9495 // without using extract_subvector.
9496 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9497 && ConstEltNo && !LegalOperations) {
9498 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9499 int NumElem = VT.getVectorNumElements();
9500 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9501 // Find the new index to extract from.
9502 int OrigElt = SVOp->getMaskElt(Elt);
9504 // Extracting an undef index is undef.
9506 return DAG.getUNDEF(NVT);
9508 // Select the right vector half to extract from.
9509 if (OrigElt < NumElem) {
9510 InVec = InVec->getOperand(0);
9512 InVec = InVec->getOperand(1);
9516 EVT IndexTy = TLI.getVectorIdxTy();
9517 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9518 InVec, DAG.getConstant(OrigElt, IndexTy));
9521 // Perform only after legalization to ensure build_vector / vector_shuffle
9522 // optimizations have already been done.
9523 if (!LegalOperations) return SDValue();
9525 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9526 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9527 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9530 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9531 bool NewLoad = false;
9532 bool BCNumEltsChanged = false;
9533 EVT ExtVT = VT.getVectorElementType();
9536 // If the result of load has to be truncated, then it's not necessarily
9538 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9541 if (InVec.getOpcode() == ISD::BITCAST) {
9542 // Don't duplicate a load with other uses.
9543 if (!InVec.hasOneUse())
9546 EVT BCVT = InVec.getOperand(0).getValueType();
9547 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9549 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9550 BCNumEltsChanged = true;
9551 InVec = InVec.getOperand(0);
9552 ExtVT = BCVT.getVectorElementType();
9556 LoadSDNode *LN0 = NULL;
9557 const ShuffleVectorSDNode *SVN = NULL;
9558 if (ISD::isNormalLoad(InVec.getNode())) {
9559 LN0 = cast<LoadSDNode>(InVec);
9560 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9561 InVec.getOperand(0).getValueType() == ExtVT &&
9562 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9563 // Don't duplicate a load with other uses.
9564 if (!InVec.hasOneUse())
9567 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9568 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9569 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9571 // (load $addr+1*size)
9573 // Don't duplicate a load with other uses.
9574 if (!InVec.hasOneUse())
9577 // If the bit convert changed the number of elements, it is unsafe
9578 // to examine the mask.
9579 if (BCNumEltsChanged)
9582 // Select the input vector, guarding against out of range extract vector.
9583 unsigned NumElems = VT.getVectorNumElements();
9584 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9585 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9587 if (InVec.getOpcode() == ISD::BITCAST) {
9588 // Don't duplicate a load with other uses.
9589 if (!InVec.hasOneUse())
9592 InVec = InVec.getOperand(0);
9594 if (ISD::isNormalLoad(InVec.getNode())) {
9595 LN0 = cast<LoadSDNode>(InVec);
9596 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9600 // Make sure we found a non-volatile load and the extractelement is
9602 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9605 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9607 return DAG.getUNDEF(LVT);
9609 unsigned Align = LN0->getAlignment();
9611 // Check the resultant load doesn't need a higher alignment than the
9615 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9617 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9623 SDValue NewPtr = LN0->getBasePtr();
9624 unsigned PtrOff = 0;
9627 PtrOff = LVT.getSizeInBits() * Elt / 8;
9628 EVT PtrType = NewPtr.getValueType();
9629 if (TLI.isBigEndian())
9630 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9631 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9632 DAG.getConstant(PtrOff, PtrType));
9635 // The replacement we need to do here is a little tricky: we need to
9636 // replace an extractelement of a load with a load.
9637 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9638 // Note that this replacement assumes that the extractvalue is the only
9639 // use of the load; that's okay because we don't want to perform this
9640 // transformation in other cases anyway.
9643 if (NVT.bitsGT(LVT)) {
9644 // If the result type of vextract is wider than the load, then issue an
9645 // extending load instead.
9646 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9647 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9648 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9649 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9650 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9651 Align, LN0->getTBAAInfo());
9652 Chain = Load.getValue(1);
9654 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9655 LN0->getPointerInfo().getWithOffset(PtrOff),
9656 LN0->isVolatile(), LN0->isNonTemporal(),
9657 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9658 Chain = Load.getValue(1);
9659 if (NVT.bitsLT(LVT))
9660 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9662 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9664 WorkListRemover DeadNodes(*this);
9665 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9666 SDValue To[] = { Load, Chain };
9667 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9668 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9669 // worklist explicitly as well.
9670 AddToWorkList(Load.getNode());
9671 AddUsersToWorkList(Load.getNode()); // Add users too
9672 // Make sure to revisit this node to clean it up; it will usually be dead.
9674 return SDValue(N, 0);
9680 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9681 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9682 // We perform this optimization post type-legalization because
9683 // the type-legalizer often scalarizes integer-promoted vectors.
9684 // Performing this optimization before may create bit-casts which
9685 // will be type-legalized to complex code sequences.
9686 // We perform this optimization only before the operation legalizer because we
9687 // may introduce illegal operations.
9688 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9691 unsigned NumInScalars = N->getNumOperands();
9693 EVT VT = N->getValueType(0);
9695 // Check to see if this is a BUILD_VECTOR of a bunch of values
9696 // which come from any_extend or zero_extend nodes. If so, we can create
9697 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9698 // optimizations. We do not handle sign-extend because we can't fill the sign
9700 EVT SourceType = MVT::Other;
9701 bool AllAnyExt = true;
9703 for (unsigned i = 0; i != NumInScalars; ++i) {
9704 SDValue In = N->getOperand(i);
9705 // Ignore undef inputs.
9706 if (In.getOpcode() == ISD::UNDEF) continue;
9708 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9709 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9711 // Abort if the element is not an extension.
9712 if (!ZeroExt && !AnyExt) {
9713 SourceType = MVT::Other;
9717 // The input is a ZeroExt or AnyExt. Check the original type.
9718 EVT InTy = In.getOperand(0).getValueType();
9720 // Check that all of the widened source types are the same.
9721 if (SourceType == MVT::Other)
9724 else if (InTy != SourceType) {
9725 // Multiple income types. Abort.
9726 SourceType = MVT::Other;
9730 // Check if all of the extends are ANY_EXTENDs.
9731 AllAnyExt &= AnyExt;
9734 // In order to have valid types, all of the inputs must be extended from the
9735 // same source type and all of the inputs must be any or zero extend.
9736 // Scalar sizes must be a power of two.
9737 EVT OutScalarTy = VT.getScalarType();
9738 bool ValidTypes = SourceType != MVT::Other &&
9739 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9740 isPowerOf2_32(SourceType.getSizeInBits());
9742 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9743 // turn into a single shuffle instruction.
9747 bool isLE = TLI.isLittleEndian();
9748 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9749 assert(ElemRatio > 1 && "Invalid element size ratio");
9750 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9751 DAG.getConstant(0, SourceType);
9753 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9754 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9756 // Populate the new build_vector
9757 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9758 SDValue Cast = N->getOperand(i);
9759 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9760 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9761 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9763 if (Cast.getOpcode() == ISD::UNDEF)
9764 In = DAG.getUNDEF(SourceType);
9766 In = Cast->getOperand(0);
9767 unsigned Index = isLE ? (i * ElemRatio) :
9768 (i * ElemRatio + (ElemRatio - 1));
9770 assert(Index < Ops.size() && "Invalid index");
9774 // The type of the new BUILD_VECTOR node.
9775 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9776 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9777 "Invalid vector size");
9778 // Check if the new vector type is legal.
9779 if (!isTypeLegal(VecVT)) return SDValue();
9781 // Make the new BUILD_VECTOR.
9782 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9784 // The new BUILD_VECTOR node has the potential to be further optimized.
9785 AddToWorkList(BV.getNode());
9786 // Bitcast to the desired type.
9787 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9790 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9791 EVT VT = N->getValueType(0);
9793 unsigned NumInScalars = N->getNumOperands();
9796 EVT SrcVT = MVT::Other;
9797 unsigned Opcode = ISD::DELETED_NODE;
9798 unsigned NumDefs = 0;
9800 for (unsigned i = 0; i != NumInScalars; ++i) {
9801 SDValue In = N->getOperand(i);
9802 unsigned Opc = In.getOpcode();
9804 if (Opc == ISD::UNDEF)
9807 // If all scalar values are floats and converted from integers.
9808 if (Opcode == ISD::DELETED_NODE &&
9809 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9816 EVT InVT = In.getOperand(0).getValueType();
9818 // If all scalar values are typed differently, bail out. It's chosen to
9819 // simplify BUILD_VECTOR of integer types.
9820 if (SrcVT == MVT::Other)
9827 // If the vector has just one element defined, it's not worth to fold it into
9828 // a vectorized one.
9832 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9833 && "Should only handle conversion from integer to float.");
9834 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9836 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9838 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9841 SmallVector<SDValue, 8> Opnds;
9842 for (unsigned i = 0; i != NumInScalars; ++i) {
9843 SDValue In = N->getOperand(i);
9845 if (In.getOpcode() == ISD::UNDEF)
9846 Opnds.push_back(DAG.getUNDEF(SrcVT));
9848 Opnds.push_back(In.getOperand(0));
9850 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9851 &Opnds[0], Opnds.size());
9852 AddToWorkList(BV.getNode());
9854 return DAG.getNode(Opcode, dl, VT, BV);
9857 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9858 unsigned NumInScalars = N->getNumOperands();
9860 EVT VT = N->getValueType(0);
9862 // A vector built entirely of undefs is undef.
9863 if (ISD::allOperandsUndef(N))
9864 return DAG.getUNDEF(VT);
9866 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9870 V = reduceBuildVecConvertToConvertBuildVec(N);
9874 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9875 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9876 // at most two distinct vectors, turn this into a shuffle node.
9878 // May only combine to shuffle after legalize if shuffle is legal.
9879 if (LegalOperations &&
9880 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9883 SDValue VecIn1, VecIn2;
9884 for (unsigned i = 0; i != NumInScalars; ++i) {
9885 // Ignore undef inputs.
9886 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9888 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9889 // constant index, bail out.
9890 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9891 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9892 VecIn1 = VecIn2 = SDValue(0, 0);
9896 // We allow up to two distinct input vectors.
9897 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9898 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9901 if (VecIn1.getNode() == 0) {
9902 VecIn1 = ExtractedFromVec;
9903 } else if (VecIn2.getNode() == 0) {
9904 VecIn2 = ExtractedFromVec;
9907 VecIn1 = VecIn2 = SDValue(0, 0);
9912 // If everything is good, we can make a shuffle operation.
9913 if (VecIn1.getNode()) {
9914 SmallVector<int, 8> Mask;
9915 for (unsigned i = 0; i != NumInScalars; ++i) {
9916 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9921 // If extracting from the first vector, just use the index directly.
9922 SDValue Extract = N->getOperand(i);
9923 SDValue ExtVal = Extract.getOperand(1);
9924 if (Extract.getOperand(0) == VecIn1) {
9925 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9926 if (ExtIndex > VT.getVectorNumElements())
9929 Mask.push_back(ExtIndex);
9933 // Otherwise, use InIdx + VecSize
9934 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9935 Mask.push_back(Idx+NumInScalars);
9938 // We can't generate a shuffle node with mismatched input and output types.
9939 // Attempt to transform a single input vector to the correct type.
9940 if ((VT != VecIn1.getValueType())) {
9941 // We don't support shuffeling between TWO values of different types.
9942 if (VecIn2.getNode() != 0)
9945 // We only support widening of vectors which are half the size of the
9946 // output registers. For example XMM->YMM widening on X86 with AVX.
9947 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9950 // If the input vector type has a different base type to the output
9951 // vector type, bail out.
9952 if (VecIn1.getValueType().getVectorElementType() !=
9953 VT.getVectorElementType())
9956 // Widen the input vector by adding undef values.
9957 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9958 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9961 // If VecIn2 is unused then change it to undef.
9962 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9964 // Check that we were able to transform all incoming values to the same
9966 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9967 VecIn1.getValueType() != VT)
9970 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9971 if (!isTypeLegal(VT))
9974 // Return the new VECTOR_SHUFFLE node.
9978 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9984 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9985 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9986 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9987 // inputs come from at most two distinct vectors, turn this into a shuffle
9990 // If we only have one input vector, we don't need to do any concatenation.
9991 if (N->getNumOperands() == 1)
9992 return N->getOperand(0);
9994 // Check if all of the operands are undefs.
9995 EVT VT = N->getValueType(0);
9996 if (ISD::allOperandsUndef(N))
9997 return DAG.getUNDEF(VT);
9999 // Optimize concat_vectors where one of the vectors is undef.
10000 if (N->getNumOperands() == 2 &&
10001 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10002 SDValue In = N->getOperand(0);
10003 assert(In.getValueType().isVector() && "Must concat vectors");
10005 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10006 if (In->getOpcode() == ISD::BITCAST &&
10007 !In->getOperand(0)->getValueType(0).isVector()) {
10008 SDValue Scalar = In->getOperand(0);
10009 EVT SclTy = Scalar->getValueType(0);
10011 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10014 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10015 VT.getSizeInBits() / SclTy.getSizeInBits());
10016 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10019 SDLoc dl = SDLoc(N);
10020 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10021 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10025 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10026 // nodes often generate nop CONCAT_VECTOR nodes.
10027 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10028 // place the incoming vectors at the exact same location.
10029 SDValue SingleSource = SDValue();
10030 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10032 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10033 SDValue Op = N->getOperand(i);
10035 if (Op.getOpcode() == ISD::UNDEF)
10038 // Check if this is the identity extract:
10039 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10042 // Find the single incoming vector for the extract_subvector.
10043 if (SingleSource.getNode()) {
10044 if (Op.getOperand(0) != SingleSource)
10047 SingleSource = Op.getOperand(0);
10049 // Check the source type is the same as the type of the result.
10050 // If not, this concat may extend the vector, so we can not
10051 // optimize it away.
10052 if (SingleSource.getValueType() != N->getValueType(0))
10056 unsigned IdentityIndex = i * PartNumElem;
10057 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10058 // The extract index must be constant.
10062 // Check that we are reading from the identity index.
10063 if (CS->getZExtValue() != IdentityIndex)
10067 if (SingleSource.getNode())
10068 return SingleSource;
10073 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10074 EVT NVT = N->getValueType(0);
10075 SDValue V = N->getOperand(0);
10077 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10079 // (extract_subvec (concat V1, V2, ...), i)
10082 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10084 if (V->getOperand(0).getValueType() != NVT)
10086 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10087 unsigned NumElems = NVT.getVectorNumElements();
10088 assert((Idx % NumElems) == 0 &&
10089 "IDX in concat is not a multiple of the result vector length.");
10090 return V->getOperand(Idx / NumElems);
10094 if (V->getOpcode() == ISD::BITCAST)
10095 V = V.getOperand(0);
10097 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10099 // Handle only simple case where vector being inserted and vector
10100 // being extracted are of same type, and are half size of larger vectors.
10101 EVT BigVT = V->getOperand(0).getValueType();
10102 EVT SmallVT = V->getOperand(1).getValueType();
10103 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10106 // Only handle cases where both indexes are constants with the same type.
10107 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10108 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10110 if (InsIdx && ExtIdx &&
10111 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10112 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10114 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10116 // indices are equal or bit offsets are equal => V1
10117 // otherwise => (extract_subvec V1, ExtIdx)
10118 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10119 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10120 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10121 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10122 DAG.getNode(ISD::BITCAST, dl,
10123 N->getOperand(0).getValueType(),
10124 V->getOperand(0)), N->getOperand(1));
10131 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10132 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10133 EVT VT = N->getValueType(0);
10134 unsigned NumElts = VT.getVectorNumElements();
10136 SDValue N0 = N->getOperand(0);
10137 SDValue N1 = N->getOperand(1);
10138 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10140 SmallVector<SDValue, 4> Ops;
10141 EVT ConcatVT = N0.getOperand(0).getValueType();
10142 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10143 unsigned NumConcats = NumElts / NumElemsPerConcat;
10145 // Look at every vector that's inserted. We're looking for exact
10146 // subvector-sized copies from a concatenated vector
10147 for (unsigned I = 0; I != NumConcats; ++I) {
10148 // Make sure we're dealing with a copy.
10149 unsigned Begin = I * NumElemsPerConcat;
10150 bool AllUndef = true, NoUndef = true;
10151 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10152 if (SVN->getMaskElt(J) >= 0)
10159 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10162 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10163 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10166 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10167 if (FirstElt < N0.getNumOperands())
10168 Ops.push_back(N0.getOperand(FirstElt));
10170 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10172 } else if (AllUndef) {
10173 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10174 } else { // Mixed with general masks and undefs, can't do optimization.
10179 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10183 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10184 EVT VT = N->getValueType(0);
10185 unsigned NumElts = VT.getVectorNumElements();
10187 SDValue N0 = N->getOperand(0);
10188 SDValue N1 = N->getOperand(1);
10190 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10192 // Canonicalize shuffle undef, undef -> undef
10193 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10194 return DAG.getUNDEF(VT);
10196 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10198 // Canonicalize shuffle v, v -> v, undef
10200 SmallVector<int, 8> NewMask;
10201 for (unsigned i = 0; i != NumElts; ++i) {
10202 int Idx = SVN->getMaskElt(i);
10203 if (Idx >= (int)NumElts) Idx -= NumElts;
10204 NewMask.push_back(Idx);
10206 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10210 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10211 if (N0.getOpcode() == ISD::UNDEF) {
10212 SmallVector<int, 8> NewMask;
10213 for (unsigned i = 0; i != NumElts; ++i) {
10214 int Idx = SVN->getMaskElt(i);
10216 if (Idx >= (int)NumElts)
10219 Idx = -1; // remove reference to lhs
10221 NewMask.push_back(Idx);
10223 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10227 // Remove references to rhs if it is undef
10228 if (N1.getOpcode() == ISD::UNDEF) {
10229 bool Changed = false;
10230 SmallVector<int, 8> NewMask;
10231 for (unsigned i = 0; i != NumElts; ++i) {
10232 int Idx = SVN->getMaskElt(i);
10233 if (Idx >= (int)NumElts) {
10237 NewMask.push_back(Idx);
10240 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10243 // If it is a splat, check if the argument vector is another splat or a
10244 // build_vector with all scalar elements the same.
10245 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10246 SDNode *V = N0.getNode();
10248 // If this is a bit convert that changes the element type of the vector but
10249 // not the number of vector elements, look through it. Be careful not to
10250 // look though conversions that change things like v4f32 to v2f64.
10251 if (V->getOpcode() == ISD::BITCAST) {
10252 SDValue ConvInput = V->getOperand(0);
10253 if (ConvInput.getValueType().isVector() &&
10254 ConvInput.getValueType().getVectorNumElements() == NumElts)
10255 V = ConvInput.getNode();
10258 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10259 assert(V->getNumOperands() == NumElts &&
10260 "BUILD_VECTOR has wrong number of operands");
10262 bool AllSame = true;
10263 for (unsigned i = 0; i != NumElts; ++i) {
10264 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10265 Base = V->getOperand(i);
10269 // Splat of <u, u, u, u>, return <u, u, u, u>
10270 if (!Base.getNode())
10272 for (unsigned i = 0; i != NumElts; ++i) {
10273 if (V->getOperand(i) != Base) {
10278 // Splat of <x, x, x, x>, return <x, x, x, x>
10284 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10285 Level < AfterLegalizeVectorOps &&
10286 (N1.getOpcode() == ISD::UNDEF ||
10287 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10288 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10289 SDValue V = partitionShuffleOfConcats(N, DAG);
10295 // If this shuffle node is simply a swizzle of another shuffle node,
10296 // and it reverses the swizzle of the previous shuffle then we can
10297 // optimize shuffle(shuffle(x, undef), undef) -> x.
10298 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10299 N1.getOpcode() == ISD::UNDEF) {
10301 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10303 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10304 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10307 // The incoming shuffle must be of the same type as the result of the
10308 // current shuffle.
10309 assert(OtherSV->getOperand(0).getValueType() == VT &&
10310 "Shuffle types don't match");
10312 for (unsigned i = 0; i != NumElts; ++i) {
10313 int Idx = SVN->getMaskElt(i);
10314 assert(Idx < (int)NumElts && "Index references undef operand");
10315 // Next, this index comes from the first value, which is the incoming
10316 // shuffle. Adopt the incoming index.
10318 Idx = OtherSV->getMaskElt(Idx);
10320 // The combined shuffle must map each index to itself.
10321 if (Idx >= 0 && (unsigned)Idx != i)
10325 return OtherSV->getOperand(0);
10331 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10332 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10333 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10334 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10335 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10336 EVT VT = N->getValueType(0);
10338 SDValue LHS = N->getOperand(0);
10339 SDValue RHS = N->getOperand(1);
10340 if (N->getOpcode() == ISD::AND) {
10341 if (RHS.getOpcode() == ISD::BITCAST)
10342 RHS = RHS.getOperand(0);
10343 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10344 SmallVector<int, 8> Indices;
10345 unsigned NumElts = RHS.getNumOperands();
10346 for (unsigned i = 0; i != NumElts; ++i) {
10347 SDValue Elt = RHS.getOperand(i);
10348 if (!isa<ConstantSDNode>(Elt))
10351 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10352 Indices.push_back(i);
10353 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10354 Indices.push_back(NumElts);
10359 // Let's see if the target supports this vector_shuffle.
10360 EVT RVT = RHS.getValueType();
10361 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10364 // Return the new VECTOR_SHUFFLE node.
10365 EVT EltVT = RVT.getVectorElementType();
10366 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10367 DAG.getConstant(0, EltVT));
10368 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10369 RVT, &ZeroOps[0], ZeroOps.size());
10370 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10371 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10372 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10379 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10380 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10381 assert(N->getValueType(0).isVector() &&
10382 "SimplifyVBinOp only works on vectors!");
10384 SDValue LHS = N->getOperand(0);
10385 SDValue RHS = N->getOperand(1);
10386 SDValue Shuffle = XformToShuffleWithZero(N);
10387 if (Shuffle.getNode()) return Shuffle;
10389 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10391 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10392 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10393 // Check if both vectors are constants. If not bail out.
10394 if (!cast<BuildVectorSDNode>(LHS)->isConstant() &&
10395 !cast<BuildVectorSDNode>(RHS)->isConstant())
10398 SmallVector<SDValue, 8> Ops;
10399 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10400 SDValue LHSOp = LHS.getOperand(i);
10401 SDValue RHSOp = RHS.getOperand(i);
10403 // Can't fold divide by zero.
10404 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10405 N->getOpcode() == ISD::FDIV) {
10406 if ((RHSOp.getOpcode() == ISD::Constant &&
10407 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10408 (RHSOp.getOpcode() == ISD::ConstantFP &&
10409 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10413 EVT VT = LHSOp.getValueType();
10414 EVT RVT = RHSOp.getValueType();
10416 // Integer BUILD_VECTOR operands may have types larger than the element
10417 // size (e.g., when the element type is not legal). Prior to type
10418 // legalization, the types may not match between the two BUILD_VECTORS.
10419 // Truncate one of the operands to make them match.
10420 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10421 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10423 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10427 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10429 if (FoldOp.getOpcode() != ISD::UNDEF &&
10430 FoldOp.getOpcode() != ISD::Constant &&
10431 FoldOp.getOpcode() != ISD::ConstantFP)
10433 Ops.push_back(FoldOp);
10434 AddToWorkList(FoldOp.getNode());
10437 if (Ops.size() == LHS.getNumOperands())
10438 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10439 LHS.getValueType(), &Ops[0], Ops.size());
10445 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10446 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10447 assert(N->getValueType(0).isVector() &&
10448 "SimplifyVUnaryOp only works on vectors!");
10450 SDValue N0 = N->getOperand(0);
10452 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10455 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10456 SmallVector<SDValue, 8> Ops;
10457 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10458 SDValue Op = N0.getOperand(i);
10459 if (Op.getOpcode() != ISD::UNDEF &&
10460 Op.getOpcode() != ISD::ConstantFP)
10462 EVT EltVT = Op.getValueType();
10463 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10464 if (FoldOp.getOpcode() != ISD::UNDEF &&
10465 FoldOp.getOpcode() != ISD::ConstantFP)
10467 Ops.push_back(FoldOp);
10468 AddToWorkList(FoldOp.getNode());
10471 if (Ops.size() != N0.getNumOperands())
10474 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10475 N0.getValueType(), &Ops[0], Ops.size());
10478 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10479 SDValue N1, SDValue N2){
10480 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10482 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10483 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10485 // If we got a simplified select_cc node back from SimplifySelectCC, then
10486 // break it down into a new SETCC node, and a new SELECT node, and then return
10487 // the SELECT node, since we were called with a SELECT node.
10488 if (SCC.getNode()) {
10489 // Check to see if we got a select_cc back (to turn into setcc/select).
10490 // Otherwise, just return whatever node we got back, like fabs.
10491 if (SCC.getOpcode() == ISD::SELECT_CC) {
10492 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10494 SCC.getOperand(0), SCC.getOperand(1),
10495 SCC.getOperand(4));
10496 AddToWorkList(SETCC.getNode());
10497 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10498 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10506 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10507 /// are the two values being selected between, see if we can simplify the
10508 /// select. Callers of this should assume that TheSelect is deleted if this
10509 /// returns true. As such, they should return the appropriate thing (e.g. the
10510 /// node) back to the top-level of the DAG combiner loop to avoid it being
10512 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10515 // Cannot simplify select with vector condition
10516 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10518 // If this is a select from two identical things, try to pull the operation
10519 // through the select.
10520 if (LHS.getOpcode() != RHS.getOpcode() ||
10521 !LHS.hasOneUse() || !RHS.hasOneUse())
10524 // If this is a load and the token chain is identical, replace the select
10525 // of two loads with a load through a select of the address to load from.
10526 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10527 // constants have been dropped into the constant pool.
10528 if (LHS.getOpcode() == ISD::LOAD) {
10529 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10530 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10532 // Token chains must be identical.
10533 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10534 // Do not let this transformation reduce the number of volatile loads.
10535 LLD->isVolatile() || RLD->isVolatile() ||
10536 // If this is an EXTLOAD, the VT's must match.
10537 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10538 // If this is an EXTLOAD, the kind of extension must match.
10539 (LLD->getExtensionType() != RLD->getExtensionType() &&
10540 // The only exception is if one of the extensions is anyext.
10541 LLD->getExtensionType() != ISD::EXTLOAD &&
10542 RLD->getExtensionType() != ISD::EXTLOAD) ||
10543 // FIXME: this discards src value information. This is
10544 // over-conservative. It would be beneficial to be able to remember
10545 // both potential memory locations. Since we are discarding
10546 // src value info, don't do the transformation if the memory
10547 // locations are not in the default address space.
10548 LLD->getPointerInfo().getAddrSpace() != 0 ||
10549 RLD->getPointerInfo().getAddrSpace() != 0 ||
10550 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10551 LLD->getBasePtr().getValueType()))
10554 // Check that the select condition doesn't reach either load. If so,
10555 // folding this will induce a cycle into the DAG. If not, this is safe to
10556 // xform, so create a select of the addresses.
10558 if (TheSelect->getOpcode() == ISD::SELECT) {
10559 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10560 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10561 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10563 // The loads must not depend on one another.
10564 if (LLD->isPredecessorOf(RLD) ||
10565 RLD->isPredecessorOf(LLD))
10567 Addr = DAG.getSelect(SDLoc(TheSelect),
10568 LLD->getBasePtr().getValueType(),
10569 TheSelect->getOperand(0), LLD->getBasePtr(),
10570 RLD->getBasePtr());
10571 } else { // Otherwise SELECT_CC
10572 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10573 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10575 if ((LLD->hasAnyUseOfValue(1) &&
10576 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10577 (RLD->hasAnyUseOfValue(1) &&
10578 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10581 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10582 LLD->getBasePtr().getValueType(),
10583 TheSelect->getOperand(0),
10584 TheSelect->getOperand(1),
10585 LLD->getBasePtr(), RLD->getBasePtr(),
10586 TheSelect->getOperand(4));
10590 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10591 Load = DAG.getLoad(TheSelect->getValueType(0),
10593 // FIXME: Discards pointer and TBAA info.
10594 LLD->getChain(), Addr, MachinePointerInfo(),
10595 LLD->isVolatile(), LLD->isNonTemporal(),
10596 LLD->isInvariant(), LLD->getAlignment());
10598 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10599 RLD->getExtensionType() : LLD->getExtensionType(),
10601 TheSelect->getValueType(0),
10602 // FIXME: Discards pointer and TBAA info.
10603 LLD->getChain(), Addr, MachinePointerInfo(),
10604 LLD->getMemoryVT(), LLD->isVolatile(),
10605 LLD->isNonTemporal(), LLD->getAlignment());
10608 // Users of the select now use the result of the load.
10609 CombineTo(TheSelect, Load);
10611 // Users of the old loads now use the new load's chain. We know the
10612 // old-load value is dead now.
10613 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10614 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10621 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10622 /// where 'cond' is the comparison specified by CC.
10623 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10624 SDValue N2, SDValue N3,
10625 ISD::CondCode CC, bool NotExtCompare) {
10626 // (x ? y : y) -> y.
10627 if (N2 == N3) return N2;
10629 EVT VT = N2.getValueType();
10630 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10631 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10632 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10634 // Determine if the condition we're dealing with is constant
10635 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10636 N0, N1, CC, DL, false);
10637 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10638 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10640 // fold select_cc true, x, y -> x
10641 if (SCCC && !SCCC->isNullValue())
10643 // fold select_cc false, x, y -> y
10644 if (SCCC && SCCC->isNullValue())
10647 // Check to see if we can simplify the select into an fabs node
10648 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10649 // Allow either -0.0 or 0.0
10650 if (CFP->getValueAPF().isZero()) {
10651 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10652 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10653 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10654 N2 == N3.getOperand(0))
10655 return DAG.getNode(ISD::FABS, DL, VT, N0);
10657 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10658 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10659 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10660 N2.getOperand(0) == N3)
10661 return DAG.getNode(ISD::FABS, DL, VT, N3);
10665 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10666 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10667 // in it. This is a win when the constant is not otherwise available because
10668 // it replaces two constant pool loads with one. We only do this if the FP
10669 // type is known to be legal, because if it isn't, then we are before legalize
10670 // types an we want the other legalization to happen first (e.g. to avoid
10671 // messing with soft float) and if the ConstantFP is not legal, because if
10672 // it is legal, we may not need to store the FP constant in a constant pool.
10673 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10674 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10675 if (TLI.isTypeLegal(N2.getValueType()) &&
10676 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10677 TargetLowering::Legal) &&
10678 // If both constants have multiple uses, then we won't need to do an
10679 // extra load, they are likely around in registers for other users.
10680 (TV->hasOneUse() || FV->hasOneUse())) {
10681 Constant *Elts[] = {
10682 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10683 const_cast<ConstantFP*>(TV->getConstantFPValue())
10685 Type *FPTy = Elts[0]->getType();
10686 const DataLayout &TD = *TLI.getDataLayout();
10688 // Create a ConstantArray of the two constants.
10689 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10690 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10691 TD.getPrefTypeAlignment(FPTy));
10692 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10694 // Get the offsets to the 0 and 1 element of the array so that we can
10695 // select between them.
10696 SDValue Zero = DAG.getIntPtrConstant(0);
10697 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10698 SDValue One = DAG.getIntPtrConstant(EltSize);
10700 SDValue Cond = DAG.getSetCC(DL,
10701 getSetCCResultType(N0.getValueType()),
10703 AddToWorkList(Cond.getNode());
10704 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10706 AddToWorkList(CstOffset.getNode());
10707 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10709 AddToWorkList(CPIdx.getNode());
10710 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10711 MachinePointerInfo::getConstantPool(), false,
10712 false, false, Alignment);
10717 // Check to see if we can perform the "gzip trick", transforming
10718 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10719 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10720 (N1C->isNullValue() || // (a < 0) ? b : 0
10721 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10722 EVT XType = N0.getValueType();
10723 EVT AType = N2.getValueType();
10724 if (XType.bitsGE(AType)) {
10725 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10726 // single-bit constant.
10727 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10728 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10729 ShCtV = XType.getSizeInBits()-ShCtV-1;
10730 SDValue ShCt = DAG.getConstant(ShCtV,
10731 getShiftAmountTy(N0.getValueType()));
10732 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10734 AddToWorkList(Shift.getNode());
10736 if (XType.bitsGT(AType)) {
10737 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10738 AddToWorkList(Shift.getNode());
10741 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10744 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10746 DAG.getConstant(XType.getSizeInBits()-1,
10747 getShiftAmountTy(N0.getValueType())));
10748 AddToWorkList(Shift.getNode());
10750 if (XType.bitsGT(AType)) {
10751 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10752 AddToWorkList(Shift.getNode());
10755 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10759 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10760 // where y is has a single bit set.
10761 // A plaintext description would be, we can turn the SELECT_CC into an AND
10762 // when the condition can be materialized as an all-ones register. Any
10763 // single bit-test can be materialized as an all-ones register with
10764 // shift-left and shift-right-arith.
10765 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10766 N0->getValueType(0) == VT &&
10767 N1C && N1C->isNullValue() &&
10768 N2C && N2C->isNullValue()) {
10769 SDValue AndLHS = N0->getOperand(0);
10770 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10771 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10772 // Shift the tested bit over the sign bit.
10773 APInt AndMask = ConstAndRHS->getAPIntValue();
10775 DAG.getConstant(AndMask.countLeadingZeros(),
10776 getShiftAmountTy(AndLHS.getValueType()));
10777 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10779 // Now arithmetic right shift it all the way over, so the result is either
10780 // all-ones, or zero.
10782 DAG.getConstant(AndMask.getBitWidth()-1,
10783 getShiftAmountTy(Shl.getValueType()));
10784 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10786 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10790 // fold select C, 16, 0 -> shl C, 4
10791 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10792 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10793 TargetLowering::ZeroOrOneBooleanContent) {
10795 // If the caller doesn't want us to simplify this into a zext of a compare,
10797 if (NotExtCompare && N2C->getAPIntValue() == 1)
10800 // Get a SetCC of the condition
10801 // NOTE: Don't create a SETCC if it's not legal on this target.
10802 if (!LegalOperations ||
10803 TLI.isOperationLegal(ISD::SETCC,
10804 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10806 // cast from setcc result type to select result type
10808 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10810 if (N2.getValueType().bitsLT(SCC.getValueType()))
10811 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10812 N2.getValueType());
10814 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10815 N2.getValueType(), SCC);
10817 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10818 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10819 N2.getValueType(), SCC);
10822 AddToWorkList(SCC.getNode());
10823 AddToWorkList(Temp.getNode());
10825 if (N2C->getAPIntValue() == 1)
10828 // shl setcc result by log2 n2c
10829 return DAG.getNode(
10830 ISD::SHL, DL, N2.getValueType(), Temp,
10831 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10832 getShiftAmountTy(Temp.getValueType())));
10836 // Check to see if this is the equivalent of setcc
10837 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10838 // otherwise, go ahead with the folds.
10839 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10840 EVT XType = N0.getValueType();
10841 if (!LegalOperations ||
10842 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10843 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10844 if (Res.getValueType() != VT)
10845 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10849 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10850 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10851 (!LegalOperations ||
10852 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10853 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10854 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10855 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10856 getShiftAmountTy(Ctlz.getValueType())));
10858 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10859 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10860 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10861 XType, DAG.getConstant(0, XType), N0);
10862 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10863 return DAG.getNode(ISD::SRL, DL, XType,
10864 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10865 DAG.getConstant(XType.getSizeInBits()-1,
10866 getShiftAmountTy(XType)));
10868 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10869 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10870 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10871 DAG.getConstant(XType.getSizeInBits()-1,
10872 getShiftAmountTy(N0.getValueType())));
10873 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10877 // Check to see if this is an integer abs.
10878 // select_cc setg[te] X, 0, X, -X ->
10879 // select_cc setgt X, -1, X, -X ->
10880 // select_cc setl[te] X, 0, -X, X ->
10881 // select_cc setlt X, 1, -X, X ->
10882 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10884 ConstantSDNode *SubC = NULL;
10885 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10886 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10887 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10888 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10889 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10890 (N1C->isOne() && CC == ISD::SETLT)) &&
10891 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10892 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10894 EVT XType = N0.getValueType();
10895 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10896 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10898 DAG.getConstant(XType.getSizeInBits()-1,
10899 getShiftAmountTy(N0.getValueType())));
10900 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10902 AddToWorkList(Shift.getNode());
10903 AddToWorkList(Add.getNode());
10904 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10911 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10912 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10913 SDValue N1, ISD::CondCode Cond,
10914 SDLoc DL, bool foldBooleans) {
10915 TargetLowering::DAGCombinerInfo
10916 DagCombineInfo(DAG, Level, false, this);
10917 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10920 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10921 /// return a DAG expression to select that will generate the same value by
10922 /// multiplying by a magic number. See:
10923 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10924 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10925 std::vector<SDNode*> Built;
10926 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10928 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10930 AddToWorkList(*ii);
10934 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10935 /// return a DAG expression to select that will generate the same value by
10936 /// multiplying by a magic number. See:
10937 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10938 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10939 std::vector<SDNode*> Built;
10940 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10942 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10944 AddToWorkList(*ii);
10948 /// FindBaseOffset - Return true if base is a frame index, which is known not
10949 // to alias with anything but itself. Provides base object and offset as
10951 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10952 const GlobalValue *&GV, const void *&CV) {
10953 // Assume it is a primitive operation.
10954 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10956 // If it's an adding a simple constant then integrate the offset.
10957 if (Base.getOpcode() == ISD::ADD) {
10958 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10959 Base = Base.getOperand(0);
10960 Offset += C->getZExtValue();
10964 // Return the underlying GlobalValue, and update the Offset. Return false
10965 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10966 // by multiple nodes with different offsets.
10967 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10968 GV = G->getGlobal();
10969 Offset += G->getOffset();
10973 // Return the underlying Constant value, and update the Offset. Return false
10974 // for ConstantSDNodes since the same constant pool entry may be represented
10975 // by multiple nodes with different offsets.
10976 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10977 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10978 : (const void *)C->getConstVal();
10979 Offset += C->getOffset();
10982 // If it's any of the following then it can't alias with anything but itself.
10983 return isa<FrameIndexSDNode>(Base);
10986 /// isAlias - Return true if there is any possibility that the two addresses
10988 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10989 const Value *SrcValue1, int SrcValueOffset1,
10990 unsigned SrcValueAlign1,
10991 const MDNode *TBAAInfo1,
10992 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10993 const Value *SrcValue2, int SrcValueOffset2,
10994 unsigned SrcValueAlign2,
10995 const MDNode *TBAAInfo2) const {
10996 // If they are the same then they must be aliases.
10997 if (Ptr1 == Ptr2) return true;
10999 // If they are both volatile then they cannot be reordered.
11000 if (IsVolatile1 && IsVolatile2) return true;
11002 // Gather base node and offset information.
11003 SDValue Base1, Base2;
11004 int64_t Offset1, Offset2;
11005 const GlobalValue *GV1, *GV2;
11006 const void *CV1, *CV2;
11007 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11008 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11010 // If they have a same base address then check to see if they overlap.
11011 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11012 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11014 // It is possible for different frame indices to alias each other, mostly
11015 // when tail call optimization reuses return address slots for arguments.
11016 // To catch this case, look up the actual index of frame indices to compute
11017 // the real alias relationship.
11018 if (isFrameIndex1 && isFrameIndex2) {
11019 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11020 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11021 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11022 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11025 // Otherwise, if we know what the bases are, and they aren't identical, then
11026 // we know they cannot alias.
11027 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11030 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11031 // compared to the size and offset of the access, we may be able to prove they
11032 // do not alias. This check is conservative for now to catch cases created by
11033 // splitting vector types.
11034 if ((SrcValueAlign1 == SrcValueAlign2) &&
11035 (SrcValueOffset1 != SrcValueOffset2) &&
11036 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11037 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11038 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11040 // There is no overlap between these relatively aligned accesses of similar
11041 // size, return no alias.
11042 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11046 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11047 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11048 if (UseAA && SrcValue1 && SrcValue2) {
11049 // Use alias analysis information.
11050 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11051 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11052 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11053 AliasAnalysis::AliasResult AAResult =
11054 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
11055 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
11056 if (AAResult == AliasAnalysis::NoAlias)
11060 // Otherwise we have to assume they alias.
11064 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11065 SDValue Ptr0, Ptr1;
11066 int64_t Size0, Size1;
11067 bool IsVolatile0, IsVolatile1;
11068 const Value *SrcValue0, *SrcValue1;
11069 int SrcValueOffset0, SrcValueOffset1;
11070 unsigned SrcValueAlign0, SrcValueAlign1;
11071 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11072 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11073 SrcValueAlign0, SrcTBAAInfo0);
11074 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11075 SrcValueAlign1, SrcTBAAInfo1);
11076 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11077 SrcValueAlign0, SrcTBAAInfo0,
11078 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11079 SrcValueAlign1, SrcTBAAInfo1);
11082 /// FindAliasInfo - Extracts the relevant alias information from the memory
11083 /// node. Returns true if the operand was a nonvolatile load.
11084 bool DAGCombiner::FindAliasInfo(SDNode *N,
11085 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11086 const Value *&SrcValue,
11087 int &SrcValueOffset,
11088 unsigned &SrcValueAlign,
11089 const MDNode *&TBAAInfo) const {
11090 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11092 Ptr = LS->getBasePtr();
11093 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11094 IsVolatile = LS->isVolatile();
11095 SrcValue = LS->getSrcValue();
11096 SrcValueOffset = LS->getSrcValueOffset();
11097 SrcValueAlign = LS->getOriginalAlignment();
11098 TBAAInfo = LS->getTBAAInfo();
11099 return isa<LoadSDNode>(LS) && !IsVolatile;
11102 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11103 /// looking for aliasing nodes and adding them to the Aliases vector.
11104 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11105 SmallVectorImpl<SDValue> &Aliases) {
11106 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11107 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11109 // Get alias information for node.
11113 const Value *SrcValue;
11114 int SrcValueOffset;
11115 unsigned SrcValueAlign;
11116 const MDNode *SrcTBAAInfo;
11117 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11118 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11121 Chains.push_back(OriginalChain);
11122 unsigned Depth = 0;
11124 // Look at each chain and determine if it is an alias. If so, add it to the
11125 // aliases list. If not, then continue up the chain looking for the next
11127 while (!Chains.empty()) {
11128 SDValue Chain = Chains.back();
11131 // For TokenFactor nodes, look at each operand and only continue up the
11132 // chain until we find two aliases. If we've seen two aliases, assume we'll
11133 // find more and revert to original chain since the xform is unlikely to be
11136 // FIXME: The depth check could be made to return the last non-aliasing
11137 // chain we found before we hit a tokenfactor rather than the original
11139 if (Depth > 6 || Aliases.size() == 2) {
11141 Aliases.push_back(OriginalChain);
11145 // Don't bother if we've been before.
11146 if (!Visited.insert(Chain.getNode()))
11149 switch (Chain.getOpcode()) {
11150 case ISD::EntryToken:
11151 // Entry token is ideal chain operand, but handled in FindBetterChain.
11156 // Get alias information for Chain.
11160 const Value *OpSrcValue;
11161 int OpSrcValueOffset;
11162 unsigned OpSrcValueAlign;
11163 const MDNode *OpSrcTBAAInfo;
11164 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11165 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11169 // If chain is alias then stop here.
11170 if (!(IsLoad && IsOpLoad) &&
11171 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11172 SrcValueAlign, SrcTBAAInfo,
11173 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11174 OpSrcValueAlign, OpSrcTBAAInfo)) {
11175 Aliases.push_back(Chain);
11177 // Look further up the chain.
11178 Chains.push_back(Chain.getOperand(0));
11184 case ISD::TokenFactor:
11185 // We have to check each of the operands of the token factor for "small"
11186 // token factors, so we queue them up. Adding the operands to the queue
11187 // (stack) in reverse order maintains the original order and increases the
11188 // likelihood that getNode will find a matching token factor (CSE.)
11189 if (Chain.getNumOperands() > 16) {
11190 Aliases.push_back(Chain);
11193 for (unsigned n = Chain.getNumOperands(); n;)
11194 Chains.push_back(Chain.getOperand(--n));
11199 // For all other instructions we will just have to take what we can get.
11200 Aliases.push_back(Chain);
11206 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11207 /// for a better chain (aliasing node.)
11208 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11209 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11211 // Accumulate all the aliases to this node.
11212 GatherAllAliases(N, OldChain, Aliases);
11214 // If no operands then chain to entry token.
11215 if (Aliases.size() == 0)
11216 return DAG.getEntryNode();
11218 // If a single operand then chain to it. We don't need to revisit it.
11219 if (Aliases.size() == 1)
11222 // Construct a custom tailored token factor.
11223 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11224 &Aliases[0], Aliases.size());
11227 // SelectionDAG::Combine - This is the entry point for the file.
11229 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11230 CodeGenOpt::Level OptLevel) {
11231 /// run - This is the main entry point to this class.
11233 DAGCombiner(*this, AA, OptLevel).Run(Level);