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 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
611 SDValue N0, SDValue N1) {
612 EVT VT = N0.getValueType();
613 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
614 if (isa<ConstantSDNode>(N1)) {
615 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
617 DAG.FoldConstantArithmetic(Opc, VT,
618 cast<ConstantSDNode>(N0.getOperand(1)),
619 cast<ConstantSDNode>(N1));
620 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
622 if (N0.hasOneUse()) {
623 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
624 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
625 N0.getOperand(0), N1);
626 AddToWorkList(OpNode.getNode());
627 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
631 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
632 if (isa<ConstantSDNode>(N0)) {
633 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
635 DAG.FoldConstantArithmetic(Opc, VT,
636 cast<ConstantSDNode>(N1.getOperand(1)),
637 cast<ConstantSDNode>(N0));
638 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
640 if (N1.hasOneUse()) {
641 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
642 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
643 N1.getOperand(0), N0);
644 AddToWorkList(OpNode.getNode());
645 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
652 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
654 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
656 DEBUG(dbgs() << "\nReplacing.1 ";
658 dbgs() << "\nWith: ";
659 To[0].getNode()->dump(&DAG);
660 dbgs() << " and " << NumTo-1 << " other values\n";
661 for (unsigned i = 0, e = NumTo; i != e; ++i)
662 assert((!To[i].getNode() ||
663 N->getValueType(i) == To[i].getValueType()) &&
664 "Cannot combine value to value of different type!"));
665 WorkListRemover DeadNodes(*this);
666 DAG.ReplaceAllUsesWith(N, To);
668 // Push the new nodes and any users onto the worklist
669 for (unsigned i = 0, e = NumTo; i != e; ++i) {
670 if (To[i].getNode()) {
671 AddToWorkList(To[i].getNode());
672 AddUsersToWorkList(To[i].getNode());
677 // Finally, if the node is now dead, remove it from the graph. The node
678 // may not be dead if the replacement process recursively simplified to
679 // something else needing this node.
680 if (N->use_empty()) {
681 // Nodes can be reintroduced into the worklist. Make sure we do not
682 // process a node that has been replaced.
683 removeFromWorkList(N);
685 // Finally, since the node is now dead, remove it from the graph.
688 return SDValue(N, 0);
692 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
693 // Replace all uses. If any nodes become isomorphic to other nodes and
694 // are deleted, make sure to remove them from our worklist.
695 WorkListRemover DeadNodes(*this);
696 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
698 // Push the new node and any (possibly new) users onto the worklist.
699 AddToWorkList(TLO.New.getNode());
700 AddUsersToWorkList(TLO.New.getNode());
702 // Finally, if the node is now dead, remove it from the graph. The node
703 // may not be dead if the replacement process recursively simplified to
704 // something else needing this node.
705 if (TLO.Old.getNode()->use_empty()) {
706 removeFromWorkList(TLO.Old.getNode());
708 // If the operands of this node are only used by the node, they will now
709 // be dead. Make sure to visit them first to delete dead nodes early.
710 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
711 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
712 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
714 DAG.DeleteNode(TLO.Old.getNode());
718 /// SimplifyDemandedBits - Check the specified integer node value to see if
719 /// it can be simplified or if things it uses can be simplified by bit
720 /// propagation. If so, return true.
721 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
722 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
723 APInt KnownZero, KnownOne;
724 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
728 AddToWorkList(Op.getNode());
730 // Replace the old value with the new one.
732 DEBUG(dbgs() << "\nReplacing.2 ";
733 TLO.Old.getNode()->dump(&DAG);
734 dbgs() << "\nWith: ";
735 TLO.New.getNode()->dump(&DAG);
738 CommitTargetLoweringOpt(TLO);
742 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
744 EVT VT = Load->getValueType(0);
745 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
747 DEBUG(dbgs() << "\nReplacing.9 ";
749 dbgs() << "\nWith: ";
750 Trunc.getNode()->dump(&DAG);
752 WorkListRemover DeadNodes(*this);
753 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
754 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
755 removeFromWorkList(Load);
756 DAG.DeleteNode(Load);
757 AddToWorkList(Trunc.getNode());
760 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
763 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
764 EVT MemVT = LD->getMemoryVT();
765 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
766 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
768 : LD->getExtensionType();
770 return DAG.getExtLoad(ExtType, dl, PVT,
771 LD->getChain(), LD->getBasePtr(),
772 MemVT, LD->getMemOperand());
775 unsigned Opc = Op.getOpcode();
778 case ISD::AssertSext:
779 return DAG.getNode(ISD::AssertSext, dl, PVT,
780 SExtPromoteOperand(Op.getOperand(0), PVT),
782 case ISD::AssertZext:
783 return DAG.getNode(ISD::AssertZext, dl, PVT,
784 ZExtPromoteOperand(Op.getOperand(0), PVT),
786 case ISD::Constant: {
788 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
789 return DAG.getNode(ExtOpc, dl, PVT, Op);
793 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
795 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
798 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
799 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
801 EVT OldVT = Op.getValueType();
803 bool Replace = false;
804 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
805 if (NewOp.getNode() == 0)
807 AddToWorkList(NewOp.getNode());
810 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
811 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
812 DAG.getValueType(OldVT));
815 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
816 EVT OldVT = Op.getValueType();
818 bool Replace = false;
819 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
820 if (NewOp.getNode() == 0)
822 AddToWorkList(NewOp.getNode());
825 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
826 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
829 /// PromoteIntBinOp - Promote the specified integer binary operation if the
830 /// target indicates it is beneficial. e.g. On x86, it's usually better to
831 /// promote i16 operations to i32 since i16 instructions are longer.
832 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
833 if (!LegalOperations)
836 EVT VT = Op.getValueType();
837 if (VT.isVector() || !VT.isInteger())
840 // If operation type is 'undesirable', e.g. i16 on x86, consider
842 unsigned Opc = Op.getOpcode();
843 if (TLI.isTypeDesirableForOp(Opc, VT))
847 // Consult target whether it is a good idea to promote this operation and
848 // what's the right type to promote it to.
849 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
850 assert(PVT != VT && "Don't know what type to promote to!");
852 bool Replace0 = false;
853 SDValue N0 = Op.getOperand(0);
854 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
855 if (NN0.getNode() == 0)
858 bool Replace1 = false;
859 SDValue N1 = Op.getOperand(1);
864 NN1 = PromoteOperand(N1, PVT, Replace1);
865 if (NN1.getNode() == 0)
869 AddToWorkList(NN0.getNode());
871 AddToWorkList(NN1.getNode());
874 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
876 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
878 DEBUG(dbgs() << "\nPromoting ";
879 Op.getNode()->dump(&DAG));
881 return DAG.getNode(ISD::TRUNCATE, dl, VT,
882 DAG.getNode(Opc, dl, PVT, NN0, NN1));
887 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
888 /// target indicates it is beneficial. e.g. On x86, it's usually better to
889 /// promote i16 operations to i32 since i16 instructions are longer.
890 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
891 if (!LegalOperations)
894 EVT VT = Op.getValueType();
895 if (VT.isVector() || !VT.isInteger())
898 // If operation type is 'undesirable', e.g. i16 on x86, consider
900 unsigned Opc = Op.getOpcode();
901 if (TLI.isTypeDesirableForOp(Opc, VT))
905 // Consult target whether it is a good idea to promote this operation and
906 // what's the right type to promote it to.
907 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908 assert(PVT != VT && "Don't know what type to promote to!");
910 bool Replace = false;
911 SDValue N0 = Op.getOperand(0);
913 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
914 else if (Opc == ISD::SRL)
915 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
917 N0 = PromoteOperand(N0, PVT, Replace);
918 if (N0.getNode() == 0)
921 AddToWorkList(N0.getNode());
923 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
925 DEBUG(dbgs() << "\nPromoting ";
926 Op.getNode()->dump(&DAG));
928 return DAG.getNode(ISD::TRUNCATE, dl, VT,
929 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
934 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
935 if (!LegalOperations)
938 EVT VT = Op.getValueType();
939 if (VT.isVector() || !VT.isInteger())
942 // If operation type is 'undesirable', e.g. i16 on x86, consider
944 unsigned Opc = Op.getOpcode();
945 if (TLI.isTypeDesirableForOp(Opc, VT))
949 // Consult target whether it is a good idea to promote this operation and
950 // what's the right type to promote it to.
951 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
952 assert(PVT != VT && "Don't know what type to promote to!");
953 // fold (aext (aext x)) -> (aext x)
954 // fold (aext (zext x)) -> (zext x)
955 // fold (aext (sext x)) -> (sext x)
956 DEBUG(dbgs() << "\nPromoting ";
957 Op.getNode()->dump(&DAG));
958 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
963 bool DAGCombiner::PromoteLoad(SDValue Op) {
964 if (!LegalOperations)
967 EVT VT = Op.getValueType();
968 if (VT.isVector() || !VT.isInteger())
971 // If operation type is 'undesirable', e.g. i16 on x86, consider
973 unsigned Opc = Op.getOpcode();
974 if (TLI.isTypeDesirableForOp(Opc, VT))
978 // Consult target whether it is a good idea to promote this operation and
979 // what's the right type to promote it to.
980 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
981 assert(PVT != VT && "Don't know what type to promote to!");
984 SDNode *N = Op.getNode();
985 LoadSDNode *LD = cast<LoadSDNode>(N);
986 EVT MemVT = LD->getMemoryVT();
987 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
988 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
990 : LD->getExtensionType();
991 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
992 LD->getChain(), LD->getBasePtr(),
993 MemVT, LD->getMemOperand());
994 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
996 DEBUG(dbgs() << "\nPromoting ";
999 Result.getNode()->dump(&DAG);
1001 WorkListRemover DeadNodes(*this);
1002 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1003 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1004 removeFromWorkList(N);
1006 AddToWorkList(Result.getNode());
1013 //===----------------------------------------------------------------------===//
1014 // Main DAG Combiner implementation
1015 //===----------------------------------------------------------------------===//
1017 void DAGCombiner::Run(CombineLevel AtLevel) {
1018 // set the instance variables, so that the various visit routines may use it.
1020 LegalOperations = Level >= AfterLegalizeVectorOps;
1021 LegalTypes = Level >= AfterLegalizeTypes;
1023 // Add all the dag nodes to the worklist.
1024 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1025 E = DAG.allnodes_end(); I != E; ++I)
1028 // Create a dummy node (which is not added to allnodes), that adds a reference
1029 // to the root node, preventing it from being deleted, and tracking any
1030 // changes of the root.
1031 HandleSDNode Dummy(DAG.getRoot());
1033 // The root of the dag may dangle to deleted nodes until the dag combiner is
1034 // done. Set it to null to avoid confusion.
1035 DAG.setRoot(SDValue());
1037 // while the worklist isn't empty, find a node and
1038 // try and combine it.
1039 while (!WorkListContents.empty()) {
1041 // The WorkListOrder holds the SDNodes in order, but it may contain
1043 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1044 // worklist *should* contain, and check the node we want to visit is should
1045 // actually be visited.
1047 N = WorkListOrder.pop_back_val();
1048 } while (!WorkListContents.erase(N));
1050 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1051 // N is deleted from the DAG, since they too may now be dead or may have a
1052 // reduced number of uses, allowing other xforms.
1053 if (N->use_empty() && N != &Dummy) {
1054 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1055 AddToWorkList(N->getOperand(i).getNode());
1061 SDValue RV = combine(N);
1063 if (RV.getNode() == 0)
1068 // If we get back the same node we passed in, rather than a new node or
1069 // zero, we know that the node must have defined multiple values and
1070 // CombineTo was used. Since CombineTo takes care of the worklist
1071 // mechanics for us, we have no work to do in this case.
1072 if (RV.getNode() == N)
1075 assert(N->getOpcode() != ISD::DELETED_NODE &&
1076 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1077 "Node was deleted but visit returned new node!");
1079 DEBUG(dbgs() << "\nReplacing.3 ";
1081 dbgs() << "\nWith: ";
1082 RV.getNode()->dump(&DAG);
1085 // Transfer debug value.
1086 DAG.TransferDbgValues(SDValue(N, 0), RV);
1087 WorkListRemover DeadNodes(*this);
1088 if (N->getNumValues() == RV.getNode()->getNumValues())
1089 DAG.ReplaceAllUsesWith(N, RV.getNode());
1091 assert(N->getValueType(0) == RV.getValueType() &&
1092 N->getNumValues() == 1 && "Type mismatch");
1094 DAG.ReplaceAllUsesWith(N, &OpV);
1097 // Push the new node and any users onto the worklist
1098 AddToWorkList(RV.getNode());
1099 AddUsersToWorkList(RV.getNode());
1101 // Add any uses of the old node to the worklist in case this node is the
1102 // last one that uses them. They may become dead after this node is
1104 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1105 AddToWorkList(N->getOperand(i).getNode());
1107 // Finally, if the node is now dead, remove it from the graph. The node
1108 // may not be dead if the replacement process recursively simplified to
1109 // something else needing this node.
1110 if (N->use_empty()) {
1111 // Nodes can be reintroduced into the worklist. Make sure we do not
1112 // process a node that has been replaced.
1113 removeFromWorkList(N);
1115 // Finally, since the node is now dead, remove it from the graph.
1120 // If the root changed (e.g. it was a dead load, update the root).
1121 DAG.setRoot(Dummy.getValue());
1122 DAG.RemoveDeadNodes();
1125 SDValue DAGCombiner::visit(SDNode *N) {
1126 switch (N->getOpcode()) {
1128 case ISD::TokenFactor: return visitTokenFactor(N);
1129 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1130 case ISD::ADD: return visitADD(N);
1131 case ISD::SUB: return visitSUB(N);
1132 case ISD::ADDC: return visitADDC(N);
1133 case ISD::SUBC: return visitSUBC(N);
1134 case ISD::ADDE: return visitADDE(N);
1135 case ISD::SUBE: return visitSUBE(N);
1136 case ISD::MUL: return visitMUL(N);
1137 case ISD::SDIV: return visitSDIV(N);
1138 case ISD::UDIV: return visitUDIV(N);
1139 case ISD::SREM: return visitSREM(N);
1140 case ISD::UREM: return visitUREM(N);
1141 case ISD::MULHU: return visitMULHU(N);
1142 case ISD::MULHS: return visitMULHS(N);
1143 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1144 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1145 case ISD::SMULO: return visitSMULO(N);
1146 case ISD::UMULO: return visitUMULO(N);
1147 case ISD::SDIVREM: return visitSDIVREM(N);
1148 case ISD::UDIVREM: return visitUDIVREM(N);
1149 case ISD::AND: return visitAND(N);
1150 case ISD::OR: return visitOR(N);
1151 case ISD::XOR: return visitXOR(N);
1152 case ISD::SHL: return visitSHL(N);
1153 case ISD::SRA: return visitSRA(N);
1154 case ISD::SRL: return visitSRL(N);
1155 case ISD::CTLZ: return visitCTLZ(N);
1156 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1157 case ISD::CTTZ: return visitCTTZ(N);
1158 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1159 case ISD::CTPOP: return visitCTPOP(N);
1160 case ISD::SELECT: return visitSELECT(N);
1161 case ISD::VSELECT: return visitVSELECT(N);
1162 case ISD::SELECT_CC: return visitSELECT_CC(N);
1163 case ISD::SETCC: return visitSETCC(N);
1164 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1165 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1166 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1167 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1168 case ISD::TRUNCATE: return visitTRUNCATE(N);
1169 case ISD::BITCAST: return visitBITCAST(N);
1170 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1171 case ISD::FADD: return visitFADD(N);
1172 case ISD::FSUB: return visitFSUB(N);
1173 case ISD::FMUL: return visitFMUL(N);
1174 case ISD::FMA: return visitFMA(N);
1175 case ISD::FDIV: return visitFDIV(N);
1176 case ISD::FREM: return visitFREM(N);
1177 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1178 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1179 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1180 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1181 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1182 case ISD::FP_ROUND: return visitFP_ROUND(N);
1183 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1184 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1185 case ISD::FNEG: return visitFNEG(N);
1186 case ISD::FABS: return visitFABS(N);
1187 case ISD::FFLOOR: return visitFFLOOR(N);
1188 case ISD::FCEIL: return visitFCEIL(N);
1189 case ISD::FTRUNC: return visitFTRUNC(N);
1190 case ISD::BRCOND: return visitBRCOND(N);
1191 case ISD::BR_CC: return visitBR_CC(N);
1192 case ISD::LOAD: return visitLOAD(N);
1193 case ISD::STORE: return visitSTORE(N);
1194 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1195 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1196 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1197 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1198 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1199 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1204 SDValue DAGCombiner::combine(SDNode *N) {
1205 SDValue RV = visit(N);
1207 // If nothing happened, try a target-specific DAG combine.
1208 if (RV.getNode() == 0) {
1209 assert(N->getOpcode() != ISD::DELETED_NODE &&
1210 "Node was deleted but visit returned NULL!");
1212 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1213 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1215 // Expose the DAG combiner to the target combiner impls.
1216 TargetLowering::DAGCombinerInfo
1217 DagCombineInfo(DAG, Level, false, this);
1219 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1223 // If nothing happened still, try promoting the operation.
1224 if (RV.getNode() == 0) {
1225 switch (N->getOpcode()) {
1233 RV = PromoteIntBinOp(SDValue(N, 0));
1238 RV = PromoteIntShiftOp(SDValue(N, 0));
1240 case ISD::SIGN_EXTEND:
1241 case ISD::ZERO_EXTEND:
1242 case ISD::ANY_EXTEND:
1243 RV = PromoteExtend(SDValue(N, 0));
1246 if (PromoteLoad(SDValue(N, 0)))
1252 // If N is a commutative binary node, try commuting it to enable more
1254 if (RV.getNode() == 0 &&
1255 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1256 N->getNumValues() == 1) {
1257 SDValue N0 = N->getOperand(0);
1258 SDValue N1 = N->getOperand(1);
1260 // Constant operands are canonicalized to RHS.
1261 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1262 SDValue Ops[] = { N1, N0 };
1263 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1266 return SDValue(CSENode, 0);
1273 /// getInputChainForNode - Given a node, return its input chain if it has one,
1274 /// otherwise return a null sd operand.
1275 static SDValue getInputChainForNode(SDNode *N) {
1276 if (unsigned NumOps = N->getNumOperands()) {
1277 if (N->getOperand(0).getValueType() == MVT::Other)
1278 return N->getOperand(0);
1279 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1280 return N->getOperand(NumOps-1);
1281 for (unsigned i = 1; i < NumOps-1; ++i)
1282 if (N->getOperand(i).getValueType() == MVT::Other)
1283 return N->getOperand(i);
1288 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1289 // If N has two operands, where one has an input chain equal to the other,
1290 // the 'other' chain is redundant.
1291 if (N->getNumOperands() == 2) {
1292 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1293 return N->getOperand(0);
1294 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1295 return N->getOperand(1);
1298 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1299 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1300 SmallPtrSet<SDNode*, 16> SeenOps;
1301 bool Changed = false; // If we should replace this token factor.
1303 // Start out with this token factor.
1306 // Iterate through token factors. The TFs grows when new token factors are
1308 for (unsigned i = 0; i < TFs.size(); ++i) {
1309 SDNode *TF = TFs[i];
1311 // Check each of the operands.
1312 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1313 SDValue Op = TF->getOperand(i);
1315 switch (Op.getOpcode()) {
1316 case ISD::EntryToken:
1317 // Entry tokens don't need to be added to the list. They are
1322 case ISD::TokenFactor:
1323 if (Op.hasOneUse() &&
1324 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1325 // Queue up for processing.
1326 TFs.push_back(Op.getNode());
1327 // Clean up in case the token factor is removed.
1328 AddToWorkList(Op.getNode());
1335 // Only add if it isn't already in the list.
1336 if (SeenOps.insert(Op.getNode()))
1347 // If we've change things around then replace token factor.
1350 // The entry token is the only possible outcome.
1351 Result = DAG.getEntryNode();
1353 // New and improved token factor.
1354 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1355 MVT::Other, &Ops[0], Ops.size());
1358 // Don't add users to work list.
1359 return CombineTo(N, Result, false);
1365 /// MERGE_VALUES can always be eliminated.
1366 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1367 WorkListRemover DeadNodes(*this);
1368 // Replacing results may cause a different MERGE_VALUES to suddenly
1369 // be CSE'd with N, and carry its uses with it. Iterate until no
1370 // uses remain, to ensure that the node can be safely deleted.
1371 // First add the users of this node to the work list so that they
1372 // can be tried again once they have new operands.
1373 AddUsersToWorkList(N);
1375 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1376 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1377 } while (!N->use_empty());
1378 removeFromWorkList(N);
1380 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1384 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1385 SelectionDAG &DAG) {
1386 EVT VT = N0.getValueType();
1387 SDValue N00 = N0.getOperand(0);
1388 SDValue N01 = N0.getOperand(1);
1389 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1391 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1392 isa<ConstantSDNode>(N00.getOperand(1))) {
1393 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1394 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1395 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1396 N00.getOperand(0), N01),
1397 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1398 N00.getOperand(1), N01));
1399 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1405 SDValue DAGCombiner::visitADD(SDNode *N) {
1406 SDValue N0 = N->getOperand(0);
1407 SDValue N1 = N->getOperand(1);
1408 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1409 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1410 EVT VT = N0.getValueType();
1413 if (VT.isVector()) {
1414 SDValue FoldedVOp = SimplifyVBinOp(N);
1415 if (FoldedVOp.getNode()) return FoldedVOp;
1417 // fold (add x, 0) -> x, vector edition
1418 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1420 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1424 // fold (add x, undef) -> undef
1425 if (N0.getOpcode() == ISD::UNDEF)
1427 if (N1.getOpcode() == ISD::UNDEF)
1429 // fold (add c1, c2) -> c1+c2
1431 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1432 // canonicalize constant to RHS
1434 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1435 // fold (add x, 0) -> x
1436 if (N1C && N1C->isNullValue())
1438 // fold (add Sym, c) -> Sym+c
1439 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1440 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1441 GA->getOpcode() == ISD::GlobalAddress)
1442 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1444 (uint64_t)N1C->getSExtValue());
1445 // fold ((c1-A)+c2) -> (c1+c2)-A
1446 if (N1C && N0.getOpcode() == ISD::SUB)
1447 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1448 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1449 DAG.getConstant(N1C->getAPIntValue()+
1450 N0C->getAPIntValue(), VT),
1453 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1454 if (RADD.getNode() != 0)
1456 // fold ((0-A) + B) -> B-A
1457 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1458 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1459 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1460 // fold (A + (0-B)) -> A-B
1461 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1462 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1463 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1464 // fold (A+(B-A)) -> B
1465 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1466 return N1.getOperand(0);
1467 // fold ((B-A)+A) -> B
1468 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1469 return N0.getOperand(0);
1470 // fold (A+(B-(A+C))) to (B-C)
1471 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1472 N0 == N1.getOperand(1).getOperand(0))
1473 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1474 N1.getOperand(1).getOperand(1));
1475 // fold (A+(B-(C+A))) to (B-C)
1476 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1477 N0 == N1.getOperand(1).getOperand(1))
1478 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1479 N1.getOperand(1).getOperand(0));
1480 // fold (A+((B-A)+or-C)) to (B+or-C)
1481 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1482 N1.getOperand(0).getOpcode() == ISD::SUB &&
1483 N0 == N1.getOperand(0).getOperand(1))
1484 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1485 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1487 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1488 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1489 SDValue N00 = N0.getOperand(0);
1490 SDValue N01 = N0.getOperand(1);
1491 SDValue N10 = N1.getOperand(0);
1492 SDValue N11 = N1.getOperand(1);
1494 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1495 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1496 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1497 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1500 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1501 return SDValue(N, 0);
1503 // fold (a+b) -> (a|b) iff a and b share no bits.
1504 if (VT.isInteger() && !VT.isVector()) {
1505 APInt LHSZero, LHSOne;
1506 APInt RHSZero, RHSOne;
1507 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1509 if (LHSZero.getBoolValue()) {
1510 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1512 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1513 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1514 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1515 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1519 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1520 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1521 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1522 if (Result.getNode()) return Result;
1524 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1525 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1526 if (Result.getNode()) return Result;
1529 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1530 if (N1.getOpcode() == ISD::SHL &&
1531 N1.getOperand(0).getOpcode() == ISD::SUB)
1532 if (ConstantSDNode *C =
1533 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1534 if (C->getAPIntValue() == 0)
1535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1536 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1537 N1.getOperand(0).getOperand(1),
1539 if (N0.getOpcode() == ISD::SHL &&
1540 N0.getOperand(0).getOpcode() == ISD::SUB)
1541 if (ConstantSDNode *C =
1542 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1543 if (C->getAPIntValue() == 0)
1544 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1545 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1546 N0.getOperand(0).getOperand(1),
1549 if (N1.getOpcode() == ISD::AND) {
1550 SDValue AndOp0 = N1.getOperand(0);
1551 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1552 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1553 unsigned DestBits = VT.getScalarType().getSizeInBits();
1555 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1556 // and similar xforms where the inner op is either ~0 or 0.
1557 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1559 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1563 // add (sext i1), X -> sub X, (zext i1)
1564 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1565 N0.getOperand(0).getValueType() == MVT::i1 &&
1566 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1568 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1569 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1575 SDValue DAGCombiner::visitADDC(SDNode *N) {
1576 SDValue N0 = N->getOperand(0);
1577 SDValue N1 = N->getOperand(1);
1578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1580 EVT VT = N0.getValueType();
1582 // If the flag result is dead, turn this into an ADD.
1583 if (!N->hasAnyUseOfValue(1))
1584 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1585 DAG.getNode(ISD::CARRY_FALSE,
1586 SDLoc(N), MVT::Glue));
1588 // canonicalize constant to RHS.
1590 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1592 // fold (addc x, 0) -> x + no carry out
1593 if (N1C && N1C->isNullValue())
1594 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1595 SDLoc(N), MVT::Glue));
1597 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1598 APInt LHSZero, LHSOne;
1599 APInt RHSZero, RHSOne;
1600 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1602 if (LHSZero.getBoolValue()) {
1603 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1605 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1606 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1607 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1608 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1609 DAG.getNode(ISD::CARRY_FALSE,
1610 SDLoc(N), MVT::Glue));
1616 SDValue DAGCombiner::visitADDE(SDNode *N) {
1617 SDValue N0 = N->getOperand(0);
1618 SDValue N1 = N->getOperand(1);
1619 SDValue CarryIn = N->getOperand(2);
1620 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1621 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1623 // canonicalize constant to RHS
1625 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1628 // fold (adde x, y, false) -> (addc x, y)
1629 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1630 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1635 // Since it may not be valid to emit a fold to zero for vector initializers
1636 // check if we can before folding.
1637 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1639 bool LegalOperations, bool LegalTypes) {
1641 return DAG.getConstant(0, VT);
1642 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1643 return DAG.getConstant(0, VT);
1647 SDValue DAGCombiner::visitSUB(SDNode *N) {
1648 SDValue N0 = N->getOperand(0);
1649 SDValue N1 = N->getOperand(1);
1650 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1651 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1652 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1653 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1654 EVT VT = N0.getValueType();
1657 if (VT.isVector()) {
1658 SDValue FoldedVOp = SimplifyVBinOp(N);
1659 if (FoldedVOp.getNode()) return FoldedVOp;
1661 // fold (sub x, 0) -> x, vector edition
1662 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1666 // fold (sub x, x) -> 0
1667 // FIXME: Refactor this and xor and other similar operations together.
1669 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1670 // fold (sub c1, c2) -> c1-c2
1672 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1673 // fold (sub x, c) -> (add x, -c)
1675 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1676 DAG.getConstant(-N1C->getAPIntValue(), VT));
1677 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1678 if (N0C && N0C->isAllOnesValue())
1679 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1680 // fold A-(A-B) -> B
1681 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1682 return N1.getOperand(1);
1683 // fold (A+B)-A -> B
1684 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1685 return N0.getOperand(1);
1686 // fold (A+B)-B -> A
1687 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1688 return N0.getOperand(0);
1689 // fold C2-(A+C1) -> (C2-C1)-A
1690 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1691 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1693 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1696 // fold ((A+(B+or-C))-B) -> A+or-C
1697 if (N0.getOpcode() == ISD::ADD &&
1698 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1699 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1700 N0.getOperand(1).getOperand(0) == N1)
1701 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1702 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1703 // fold ((A+(C+B))-B) -> A+C
1704 if (N0.getOpcode() == ISD::ADD &&
1705 N0.getOperand(1).getOpcode() == ISD::ADD &&
1706 N0.getOperand(1).getOperand(1) == N1)
1707 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1708 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1709 // fold ((A-(B-C))-C) -> A-B
1710 if (N0.getOpcode() == ISD::SUB &&
1711 N0.getOperand(1).getOpcode() == ISD::SUB &&
1712 N0.getOperand(1).getOperand(1) == N1)
1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1714 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1716 // If either operand of a sub is undef, the result is undef
1717 if (N0.getOpcode() == ISD::UNDEF)
1719 if (N1.getOpcode() == ISD::UNDEF)
1722 // If the relocation model supports it, consider symbol offsets.
1723 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1724 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1725 // fold (sub Sym, c) -> Sym-c
1726 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1727 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1729 (uint64_t)N1C->getSExtValue());
1730 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1731 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1732 if (GA->getGlobal() == GB->getGlobal())
1733 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1740 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1741 SDValue N0 = N->getOperand(0);
1742 SDValue N1 = N->getOperand(1);
1743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1745 EVT VT = N0.getValueType();
1747 // If the flag result is dead, turn this into an SUB.
1748 if (!N->hasAnyUseOfValue(1))
1749 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1750 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1753 // fold (subc x, x) -> 0 + no borrow
1755 return CombineTo(N, DAG.getConstant(0, VT),
1756 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1759 // fold (subc x, 0) -> x + no borrow
1760 if (N1C && N1C->isNullValue())
1761 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1764 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1765 if (N0C && N0C->isAllOnesValue())
1766 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1767 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1773 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1774 SDValue N0 = N->getOperand(0);
1775 SDValue N1 = N->getOperand(1);
1776 SDValue CarryIn = N->getOperand(2);
1778 // fold (sube x, y, false) -> (subc x, y)
1779 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1780 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1785 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1786 /// elements are all the same constant or undefined.
1787 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1788 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1793 unsigned SplatBitSize;
1795 EVT EltVT = N->getValueType(0).getVectorElementType();
1796 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1798 EltVT.getSizeInBits() >= SplatBitSize);
1801 SDValue DAGCombiner::visitMUL(SDNode *N) {
1802 SDValue N0 = N->getOperand(0);
1803 SDValue N1 = N->getOperand(1);
1804 EVT VT = N0.getValueType();
1806 // fold (mul x, undef) -> 0
1807 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1808 return DAG.getConstant(0, VT);
1810 bool N0IsConst = false;
1811 bool N1IsConst = false;
1812 APInt ConstValue0, ConstValue1;
1814 if (VT.isVector()) {
1815 SDValue FoldedVOp = SimplifyVBinOp(N);
1816 if (FoldedVOp.getNode()) return FoldedVOp;
1818 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1819 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1821 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1822 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1824 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1825 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1829 // fold (mul c1, c2) -> c1*c2
1830 if (N0IsConst && N1IsConst)
1831 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1833 // canonicalize constant to RHS
1834 if (N0IsConst && !N1IsConst)
1835 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1836 // fold (mul x, 0) -> 0
1837 if (N1IsConst && ConstValue1 == 0)
1839 // We require a splat of the entire scalar bit width for non-contiguous
1842 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1843 // fold (mul x, 1) -> x
1844 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1846 // fold (mul x, -1) -> 0-x
1847 if (N1IsConst && ConstValue1.isAllOnesValue())
1848 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849 DAG.getConstant(0, VT), N0);
1850 // fold (mul x, (1 << c)) -> x << c
1851 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1852 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1853 DAG.getConstant(ConstValue1.logBase2(),
1854 getShiftAmountTy(N0.getValueType())));
1855 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1856 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1857 unsigned Log2Val = (-ConstValue1).logBase2();
1858 // FIXME: If the input is something that is easily negated (e.g. a
1859 // single-use add), we should put the negate there.
1860 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1861 DAG.getConstant(0, VT),
1862 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1863 DAG.getConstant(Log2Val,
1864 getShiftAmountTy(N0.getValueType()))));
1868 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1869 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1870 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1871 isa<ConstantSDNode>(N0.getOperand(1)))) {
1872 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1873 N1, N0.getOperand(1));
1874 AddToWorkList(C3.getNode());
1875 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1876 N0.getOperand(0), C3);
1879 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1882 SDValue Sh(0,0), Y(0,0);
1883 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1884 if (N0.getOpcode() == ISD::SHL &&
1885 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1886 isa<ConstantSDNode>(N0.getOperand(1))) &&
1887 N0.getNode()->hasOneUse()) {
1889 } else if (N1.getOpcode() == ISD::SHL &&
1890 isa<ConstantSDNode>(N1.getOperand(1)) &&
1891 N1.getNode()->hasOneUse()) {
1896 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1897 Sh.getOperand(0), Y);
1898 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1899 Mul, Sh.getOperand(1));
1903 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1904 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1905 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1906 isa<ConstantSDNode>(N0.getOperand(1))))
1907 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1908 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1909 N0.getOperand(0), N1),
1910 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1911 N0.getOperand(1), N1));
1914 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1915 if (RMUL.getNode() != 0)
1921 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1922 SDValue N0 = N->getOperand(0);
1923 SDValue N1 = N->getOperand(1);
1924 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1925 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1926 EVT VT = N->getValueType(0);
1929 if (VT.isVector()) {
1930 SDValue FoldedVOp = SimplifyVBinOp(N);
1931 if (FoldedVOp.getNode()) return FoldedVOp;
1934 // fold (sdiv c1, c2) -> c1/c2
1935 if (N0C && N1C && !N1C->isNullValue())
1936 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1937 // fold (sdiv X, 1) -> X
1938 if (N1C && N1C->getAPIntValue() == 1LL)
1940 // fold (sdiv X, -1) -> 0-X
1941 if (N1C && N1C->isAllOnesValue())
1942 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1943 DAG.getConstant(0, VT), N0);
1944 // If we know the sign bits of both operands are zero, strength reduce to a
1945 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1946 if (!VT.isVector()) {
1947 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1948 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1951 // fold (sdiv X, pow2) -> simple ops after legalize
1952 if (N1C && !N1C->isNullValue() &&
1953 (N1C->getAPIntValue().isPowerOf2() ||
1954 (-N1C->getAPIntValue()).isPowerOf2())) {
1955 // If dividing by powers of two is cheap, then don't perform the following
1957 if (TLI.isPow2DivCheap())
1960 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1962 // Splat the sign bit into the register
1963 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1964 DAG.getConstant(VT.getSizeInBits()-1,
1965 getShiftAmountTy(N0.getValueType())));
1966 AddToWorkList(SGN.getNode());
1968 // Add (N0 < 0) ? abs2 - 1 : 0;
1969 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1970 DAG.getConstant(VT.getSizeInBits() - lg2,
1971 getShiftAmountTy(SGN.getValueType())));
1972 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1973 AddToWorkList(SRL.getNode());
1974 AddToWorkList(ADD.getNode()); // Divide by pow2
1975 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1976 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1978 // If we're dividing by a positive value, we're done. Otherwise, we must
1979 // negate the result.
1980 if (N1C->getAPIntValue().isNonNegative())
1983 AddToWorkList(SRA.getNode());
1984 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1985 DAG.getConstant(0, VT), SRA);
1988 // if integer divide is expensive and we satisfy the requirements, emit an
1989 // alternate sequence.
1990 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1991 SDValue Op = BuildSDIV(N);
1992 if (Op.getNode()) return Op;
1996 if (N0.getOpcode() == ISD::UNDEF)
1997 return DAG.getConstant(0, VT);
1998 // X / undef -> undef
1999 if (N1.getOpcode() == ISD::UNDEF)
2005 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2006 SDValue N0 = N->getOperand(0);
2007 SDValue N1 = N->getOperand(1);
2008 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2010 EVT VT = N->getValueType(0);
2013 if (VT.isVector()) {
2014 SDValue FoldedVOp = SimplifyVBinOp(N);
2015 if (FoldedVOp.getNode()) return FoldedVOp;
2018 // fold (udiv c1, c2) -> c1/c2
2019 if (N0C && N1C && !N1C->isNullValue())
2020 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2021 // fold (udiv x, (1 << c)) -> x >>u c
2022 if (N1C && N1C->getAPIntValue().isPowerOf2())
2023 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2024 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2025 getShiftAmountTy(N0.getValueType())));
2026 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2027 if (N1.getOpcode() == ISD::SHL) {
2028 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2029 if (SHC->getAPIntValue().isPowerOf2()) {
2030 EVT ADDVT = N1.getOperand(1).getValueType();
2031 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2033 DAG.getConstant(SHC->getAPIntValue()
2036 AddToWorkList(Add.getNode());
2037 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2041 // fold (udiv x, c) -> alternate
2042 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2043 SDValue Op = BuildUDIV(N);
2044 if (Op.getNode()) return Op;
2048 if (N0.getOpcode() == ISD::UNDEF)
2049 return DAG.getConstant(0, VT);
2050 // X / undef -> undef
2051 if (N1.getOpcode() == ISD::UNDEF)
2057 SDValue DAGCombiner::visitSREM(SDNode *N) {
2058 SDValue N0 = N->getOperand(0);
2059 SDValue N1 = N->getOperand(1);
2060 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2061 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2062 EVT VT = N->getValueType(0);
2064 // fold (srem c1, c2) -> c1%c2
2065 if (N0C && N1C && !N1C->isNullValue())
2066 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2067 // If we know the sign bits of both operands are zero, strength reduce to a
2068 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2069 if (!VT.isVector()) {
2070 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2071 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2074 // If X/C can be simplified by the division-by-constant logic, lower
2075 // X%C to the equivalent of X-X/C*C.
2076 if (N1C && !N1C->isNullValue()) {
2077 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2078 AddToWorkList(Div.getNode());
2079 SDValue OptimizedDiv = combine(Div.getNode());
2080 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2081 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2083 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2084 AddToWorkList(Mul.getNode());
2090 if (N0.getOpcode() == ISD::UNDEF)
2091 return DAG.getConstant(0, VT);
2092 // X % undef -> undef
2093 if (N1.getOpcode() == ISD::UNDEF)
2099 SDValue DAGCombiner::visitUREM(SDNode *N) {
2100 SDValue N0 = N->getOperand(0);
2101 SDValue N1 = N->getOperand(1);
2102 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2103 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2104 EVT VT = N->getValueType(0);
2106 // fold (urem c1, c2) -> c1%c2
2107 if (N0C && N1C && !N1C->isNullValue())
2108 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2109 // fold (urem x, pow2) -> (and x, pow2-1)
2110 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2111 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2112 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2113 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2114 if (N1.getOpcode() == ISD::SHL) {
2115 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2116 if (SHC->getAPIntValue().isPowerOf2()) {
2118 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2119 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2121 AddToWorkList(Add.getNode());
2122 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2127 // If X/C can be simplified by the division-by-constant logic, lower
2128 // X%C to the equivalent of X-X/C*C.
2129 if (N1C && !N1C->isNullValue()) {
2130 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2131 AddToWorkList(Div.getNode());
2132 SDValue OptimizedDiv = combine(Div.getNode());
2133 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2134 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2136 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2137 AddToWorkList(Mul.getNode());
2143 if (N0.getOpcode() == ISD::UNDEF)
2144 return DAG.getConstant(0, VT);
2145 // X % undef -> undef
2146 if (N1.getOpcode() == ISD::UNDEF)
2152 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2153 SDValue N0 = N->getOperand(0);
2154 SDValue N1 = N->getOperand(1);
2155 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2156 EVT VT = N->getValueType(0);
2159 // fold (mulhs x, 0) -> 0
2160 if (N1C && N1C->isNullValue())
2162 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2163 if (N1C && N1C->getAPIntValue() == 1)
2164 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2165 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2166 getShiftAmountTy(N0.getValueType())));
2167 // fold (mulhs x, undef) -> 0
2168 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2169 return DAG.getConstant(0, VT);
2171 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2173 if (VT.isSimple() && !VT.isVector()) {
2174 MVT Simple = VT.getSimpleVT();
2175 unsigned SimpleSize = Simple.getSizeInBits();
2176 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2177 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2178 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2179 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2180 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2181 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2182 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2183 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2190 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2191 SDValue N0 = N->getOperand(0);
2192 SDValue N1 = N->getOperand(1);
2193 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2194 EVT VT = N->getValueType(0);
2197 // fold (mulhu x, 0) -> 0
2198 if (N1C && N1C->isNullValue())
2200 // fold (mulhu x, 1) -> 0
2201 if (N1C && N1C->getAPIntValue() == 1)
2202 return DAG.getConstant(0, N0.getValueType());
2203 // fold (mulhu x, undef) -> 0
2204 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2205 return DAG.getConstant(0, VT);
2207 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2209 if (VT.isSimple() && !VT.isVector()) {
2210 MVT Simple = VT.getSimpleVT();
2211 unsigned SimpleSize = Simple.getSizeInBits();
2212 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2213 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2214 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2215 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2216 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2217 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2218 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2219 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2226 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2227 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2228 /// that are being performed. Return true if a simplification was made.
2230 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2232 // If the high half is not needed, just compute the low half.
2233 bool HiExists = N->hasAnyUseOfValue(1);
2235 (!LegalOperations ||
2236 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2237 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2238 N->op_begin(), N->getNumOperands());
2239 return CombineTo(N, Res, Res);
2242 // If the low half is not needed, just compute the high half.
2243 bool LoExists = N->hasAnyUseOfValue(0);
2245 (!LegalOperations ||
2246 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2247 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2248 N->op_begin(), N->getNumOperands());
2249 return CombineTo(N, Res, Res);
2252 // If both halves are used, return as it is.
2253 if (LoExists && HiExists)
2256 // If the two computed results can be simplified separately, separate them.
2258 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2259 N->op_begin(), N->getNumOperands());
2260 AddToWorkList(Lo.getNode());
2261 SDValue LoOpt = combine(Lo.getNode());
2262 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2263 (!LegalOperations ||
2264 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2265 return CombineTo(N, LoOpt, LoOpt);
2269 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2270 N->op_begin(), N->getNumOperands());
2271 AddToWorkList(Hi.getNode());
2272 SDValue HiOpt = combine(Hi.getNode());
2273 if (HiOpt.getNode() && HiOpt != Hi &&
2274 (!LegalOperations ||
2275 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2276 return CombineTo(N, HiOpt, HiOpt);
2282 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2283 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2284 if (Res.getNode()) return Res;
2286 EVT VT = N->getValueType(0);
2289 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2291 if (VT.isSimple() && !VT.isVector()) {
2292 MVT Simple = VT.getSimpleVT();
2293 unsigned SimpleSize = Simple.getSizeInBits();
2294 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2295 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2296 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2297 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2298 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2299 // Compute the high part as N1.
2300 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2301 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2302 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2303 // Compute the low part as N0.
2304 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2305 return CombineTo(N, Lo, Hi);
2312 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2313 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2314 if (Res.getNode()) return Res;
2316 EVT VT = N->getValueType(0);
2319 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2321 if (VT.isSimple() && !VT.isVector()) {
2322 MVT Simple = VT.getSimpleVT();
2323 unsigned SimpleSize = Simple.getSizeInBits();
2324 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2325 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2326 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2327 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2328 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2329 // Compute the high part as N1.
2330 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2331 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2332 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2333 // Compute the low part as N0.
2334 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2335 return CombineTo(N, Lo, Hi);
2342 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2343 // (smulo x, 2) -> (saddo x, x)
2344 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2345 if (C2->getAPIntValue() == 2)
2346 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2347 N->getOperand(0), N->getOperand(0));
2352 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2353 // (umulo x, 2) -> (uaddo x, x)
2354 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2355 if (C2->getAPIntValue() == 2)
2356 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2357 N->getOperand(0), N->getOperand(0));
2362 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2363 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2364 if (Res.getNode()) return Res;
2369 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2370 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2371 if (Res.getNode()) return Res;
2376 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2377 /// two operands of the same opcode, try to simplify it.
2378 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2379 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2380 EVT VT = N0.getValueType();
2381 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2383 // Bail early if none of these transforms apply.
2384 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2386 // For each of OP in AND/OR/XOR:
2387 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2388 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2389 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2390 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2392 // do not sink logical op inside of a vector extend, since it may combine
2394 EVT Op0VT = N0.getOperand(0).getValueType();
2395 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2396 N0.getOpcode() == ISD::SIGN_EXTEND ||
2397 // Avoid infinite looping with PromoteIntBinOp.
2398 (N0.getOpcode() == ISD::ANY_EXTEND &&
2399 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2400 (N0.getOpcode() == ISD::TRUNCATE &&
2401 (!TLI.isZExtFree(VT, Op0VT) ||
2402 !TLI.isTruncateFree(Op0VT, VT)) &&
2403 TLI.isTypeLegal(Op0VT))) &&
2405 Op0VT == N1.getOperand(0).getValueType() &&
2406 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2407 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2408 N0.getOperand(0).getValueType(),
2409 N0.getOperand(0), N1.getOperand(0));
2410 AddToWorkList(ORNode.getNode());
2411 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2414 // For each of OP in SHL/SRL/SRA/AND...
2415 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2416 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2417 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2418 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2419 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2420 N0.getOperand(1) == N1.getOperand(1)) {
2421 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2422 N0.getOperand(0).getValueType(),
2423 N0.getOperand(0), N1.getOperand(0));
2424 AddToWorkList(ORNode.getNode());
2425 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2426 ORNode, N0.getOperand(1));
2429 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2430 // Only perform this optimization after type legalization and before
2431 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2432 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2433 // we don't want to undo this promotion.
2434 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2436 if ((N0.getOpcode() == ISD::BITCAST ||
2437 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2438 Level == AfterLegalizeTypes) {
2439 SDValue In0 = N0.getOperand(0);
2440 SDValue In1 = N1.getOperand(0);
2441 EVT In0Ty = In0.getValueType();
2442 EVT In1Ty = In1.getValueType();
2444 // If both incoming values are integers, and the original types are the
2446 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2447 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2448 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2449 AddToWorkList(Op.getNode());
2454 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2455 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2456 // If both shuffles use the same mask, and both shuffle within a single
2457 // vector, then it is worthwhile to move the swizzle after the operation.
2458 // The type-legalizer generates this pattern when loading illegal
2459 // vector types from memory. In many cases this allows additional shuffle
2461 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2462 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2463 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2464 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2465 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2467 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2468 "Inputs to shuffles are not the same type");
2470 unsigned NumElts = VT.getVectorNumElements();
2472 // Check that both shuffles use the same mask. The masks are known to be of
2473 // the same length because the result vector type is the same.
2474 bool SameMask = true;
2475 for (unsigned i = 0; i != NumElts; ++i) {
2476 int Idx0 = SVN0->getMaskElt(i);
2477 int Idx1 = SVN1->getMaskElt(i);
2485 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2486 N0.getOperand(0), N1.getOperand(0));
2487 AddToWorkList(Op.getNode());
2488 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2489 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2496 SDValue DAGCombiner::visitAND(SDNode *N) {
2497 SDValue N0 = N->getOperand(0);
2498 SDValue N1 = N->getOperand(1);
2499 SDValue LL, LR, RL, RR, CC0, CC1;
2500 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2501 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2502 EVT VT = N1.getValueType();
2503 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2506 if (VT.isVector()) {
2507 SDValue FoldedVOp = SimplifyVBinOp(N);
2508 if (FoldedVOp.getNode()) return FoldedVOp;
2510 // fold (and x, 0) -> 0, vector edition
2511 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2513 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2516 // fold (and x, -1) -> x, vector edition
2517 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2519 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2523 // fold (and x, undef) -> 0
2524 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2525 return DAG.getConstant(0, VT);
2526 // fold (and c1, c2) -> c1&c2
2528 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2529 // canonicalize constant to RHS
2531 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2532 // fold (and x, -1) -> x
2533 if (N1C && N1C->isAllOnesValue())
2535 // if (and x, c) is known to be zero, return 0
2536 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2537 APInt::getAllOnesValue(BitWidth)))
2538 return DAG.getConstant(0, VT);
2540 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2541 if (RAND.getNode() != 0)
2543 // fold (and (or x, C), D) -> D if (C & D) == D
2544 if (N1C && N0.getOpcode() == ISD::OR)
2545 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2546 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2548 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2549 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2550 SDValue N0Op0 = N0.getOperand(0);
2551 APInt Mask = ~N1C->getAPIntValue();
2552 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2553 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2554 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2555 N0.getValueType(), N0Op0);
2557 // Replace uses of the AND with uses of the Zero extend node.
2560 // We actually want to replace all uses of the any_extend with the
2561 // zero_extend, to avoid duplicating things. This will later cause this
2562 // AND to be folded.
2563 CombineTo(N0.getNode(), Zext);
2564 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2567 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2568 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2569 // already be zero by virtue of the width of the base type of the load.
2571 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2573 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2574 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2575 N0.getOpcode() == ISD::LOAD) {
2576 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2577 N0 : N0.getOperand(0) );
2579 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2580 // This can be a pure constant or a vector splat, in which case we treat the
2581 // vector as a scalar and use the splat value.
2582 APInt Constant = APInt::getNullValue(1);
2583 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2584 Constant = C->getAPIntValue();
2585 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2586 APInt SplatValue, SplatUndef;
2587 unsigned SplatBitSize;
2589 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2590 SplatBitSize, HasAnyUndefs);
2592 // Undef bits can contribute to a possible optimisation if set, so
2594 SplatValue |= SplatUndef;
2596 // The splat value may be something like "0x00FFFFFF", which means 0 for
2597 // the first vector value and FF for the rest, repeating. We need a mask
2598 // that will apply equally to all members of the vector, so AND all the
2599 // lanes of the constant together.
2600 EVT VT = Vector->getValueType(0);
2601 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2603 // If the splat value has been compressed to a bitlength lower
2604 // than the size of the vector lane, we need to re-expand it to
2606 if (BitWidth > SplatBitSize)
2607 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2608 SplatBitSize < BitWidth;
2609 SplatBitSize = SplatBitSize * 2)
2610 SplatValue |= SplatValue.shl(SplatBitSize);
2612 Constant = APInt::getAllOnesValue(BitWidth);
2613 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2614 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2618 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2619 // actually legal and isn't going to get expanded, else this is a false
2621 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2622 Load->getMemoryVT());
2624 // Resize the constant to the same size as the original memory access before
2625 // extension. If it is still the AllOnesValue then this AND is completely
2628 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2631 switch (Load->getExtensionType()) {
2632 default: B = false; break;
2633 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2635 case ISD::NON_EXTLOAD: B = true; break;
2638 if (B && Constant.isAllOnesValue()) {
2639 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2640 // preserve semantics once we get rid of the AND.
2641 SDValue NewLoad(Load, 0);
2642 if (Load->getExtensionType() == ISD::EXTLOAD) {
2643 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2644 Load->getValueType(0), SDLoc(Load),
2645 Load->getChain(), Load->getBasePtr(),
2646 Load->getOffset(), Load->getMemoryVT(),
2647 Load->getMemOperand());
2648 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2649 if (Load->getNumValues() == 3) {
2650 // PRE/POST_INC loads have 3 values.
2651 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2652 NewLoad.getValue(2) };
2653 CombineTo(Load, To, 3, true);
2655 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2659 // Fold the AND away, taking care not to fold to the old load node if we
2661 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2663 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2666 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2667 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2668 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2669 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2671 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2672 LL.getValueType().isInteger()) {
2673 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2674 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2675 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2676 LR.getValueType(), LL, RL);
2677 AddToWorkList(ORNode.getNode());
2678 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2680 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2681 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2682 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2683 LR.getValueType(), LL, RL);
2684 AddToWorkList(ANDNode.getNode());
2685 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2687 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2688 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2689 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2690 LR.getValueType(), LL, RL);
2691 AddToWorkList(ORNode.getNode());
2692 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2695 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2696 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2697 Op0 == Op1 && LL.getValueType().isInteger() &&
2698 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2699 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2700 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2701 cast<ConstantSDNode>(RR)->isNullValue()))) {
2702 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2703 LL, DAG.getConstant(1, LL.getValueType()));
2704 AddToWorkList(ADDNode.getNode());
2705 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2706 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2708 // canonicalize equivalent to ll == rl
2709 if (LL == RR && LR == RL) {
2710 Op1 = ISD::getSetCCSwappedOperands(Op1);
2713 if (LL == RL && LR == RR) {
2714 bool isInteger = LL.getValueType().isInteger();
2715 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2716 if (Result != ISD::SETCC_INVALID &&
2717 (!LegalOperations ||
2718 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2719 TLI.isOperationLegal(ISD::SETCC,
2720 getSetCCResultType(N0.getSimpleValueType())))))
2721 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2726 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2727 if (N0.getOpcode() == N1.getOpcode()) {
2728 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2729 if (Tmp.getNode()) return Tmp;
2732 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2733 // fold (and (sra)) -> (and (srl)) when possible.
2734 if (!VT.isVector() &&
2735 SimplifyDemandedBits(SDValue(N, 0)))
2736 return SDValue(N, 0);
2738 // fold (zext_inreg (extload x)) -> (zextload x)
2739 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2740 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2741 EVT MemVT = LN0->getMemoryVT();
2742 // If we zero all the possible extended bits, then we can turn this into
2743 // a zextload if we are running before legalize or the operation is legal.
2744 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2745 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2746 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2747 ((!LegalOperations && !LN0->isVolatile()) ||
2748 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2749 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2750 LN0->getChain(), LN0->getBasePtr(),
2751 MemVT, LN0->getMemOperand());
2753 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2754 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2757 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2758 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2760 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2761 EVT MemVT = LN0->getMemoryVT();
2762 // If we zero all the possible extended bits, then we can turn this into
2763 // a zextload if we are running before legalize or the operation is legal.
2764 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2765 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2766 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2767 ((!LegalOperations && !LN0->isVolatile()) ||
2768 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2769 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2770 LN0->getChain(), LN0->getBasePtr(),
2771 MemVT, LN0->getMemOperand());
2773 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2774 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2778 // fold (and (load x), 255) -> (zextload x, i8)
2779 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2780 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2781 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2782 (N0.getOpcode() == ISD::ANY_EXTEND &&
2783 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2784 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2785 LoadSDNode *LN0 = HasAnyExt
2786 ? cast<LoadSDNode>(N0.getOperand(0))
2787 : cast<LoadSDNode>(N0);
2788 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2789 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2790 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2791 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2792 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2793 EVT LoadedVT = LN0->getMemoryVT();
2795 if (ExtVT == LoadedVT &&
2796 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2797 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2800 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2801 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2802 LN0->getMemOperand());
2804 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2805 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2808 // Do not change the width of a volatile load.
2809 // Do not generate loads of non-round integer types since these can
2810 // be expensive (and would be wrong if the type is not byte sized).
2811 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2812 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813 EVT PtrType = LN0->getOperand(1).getValueType();
2815 unsigned Alignment = LN0->getAlignment();
2816 SDValue NewPtr = LN0->getBasePtr();
2818 // For big endian targets, we need to add an offset to the pointer
2819 // to load the correct bytes. For little endian systems, we merely
2820 // need to read fewer bytes from the same pointer.
2821 if (TLI.isBigEndian()) {
2822 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2823 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2824 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2825 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2826 NewPtr, DAG.getConstant(PtrOff, PtrType));
2827 Alignment = MinAlign(Alignment, PtrOff);
2830 AddToWorkList(NewPtr.getNode());
2832 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2834 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2835 LN0->getChain(), NewPtr,
2836 LN0->getPointerInfo(),
2837 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2838 Alignment, LN0->getTBAAInfo());
2840 CombineTo(LN0, Load, Load.getValue(1));
2841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2847 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2848 VT.getSizeInBits() <= 64) {
2849 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2850 APInt ADDC = ADDI->getAPIntValue();
2851 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2852 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2853 // immediate for an add, but it is legal if its top c2 bits are set,
2854 // transform the ADD so the immediate doesn't need to be materialized
2856 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2857 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2858 SRLI->getZExtValue());
2859 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2861 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2863 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2864 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2865 CombineTo(N0.getNode(), NewAdd);
2866 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2874 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2875 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2876 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2877 N0.getOperand(1), false);
2878 if (BSwap.getNode())
2885 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2887 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2888 bool DemandHighBits) {
2889 if (!LegalOperations)
2892 EVT VT = N->getValueType(0);
2893 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2895 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2898 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2899 bool LookPassAnd0 = false;
2900 bool LookPassAnd1 = false;
2901 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2903 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2905 if (N0.getOpcode() == ISD::AND) {
2906 if (!N0.getNode()->hasOneUse())
2908 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2909 if (!N01C || N01C->getZExtValue() != 0xFF00)
2911 N0 = N0.getOperand(0);
2912 LookPassAnd0 = true;
2915 if (N1.getOpcode() == ISD::AND) {
2916 if (!N1.getNode()->hasOneUse())
2918 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2919 if (!N11C || N11C->getZExtValue() != 0xFF)
2921 N1 = N1.getOperand(0);
2922 LookPassAnd1 = true;
2925 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2927 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2929 if (!N0.getNode()->hasOneUse() ||
2930 !N1.getNode()->hasOneUse())
2933 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2934 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2937 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2940 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2941 SDValue N00 = N0->getOperand(0);
2942 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2943 if (!N00.getNode()->hasOneUse())
2945 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2946 if (!N001C || N001C->getZExtValue() != 0xFF)
2948 N00 = N00.getOperand(0);
2949 LookPassAnd0 = true;
2952 SDValue N10 = N1->getOperand(0);
2953 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2954 if (!N10.getNode()->hasOneUse())
2956 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2957 if (!N101C || N101C->getZExtValue() != 0xFF00)
2959 N10 = N10.getOperand(0);
2960 LookPassAnd1 = true;
2966 // Make sure everything beyond the low halfword gets set to zero since the SRL
2967 // 16 will clear the top bits.
2968 unsigned OpSizeInBits = VT.getSizeInBits();
2969 if (DemandHighBits && OpSizeInBits > 16) {
2970 // If the left-shift isn't masked out then the only way this is a bswap is
2971 // if all bits beyond the low 8 are 0. In that case the entire pattern
2972 // reduces to a left shift anyway: leave it for other parts of the combiner.
2976 // However, if the right shift isn't masked out then it might be because
2977 // it's not needed. See if we can spot that too.
2978 if (!LookPassAnd1 &&
2979 !DAG.MaskedValueIsZero(
2980 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2984 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2985 if (OpSizeInBits > 16)
2986 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2987 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2991 /// isBSwapHWordElement - Return true if the specified node is an element
2992 /// that makes up a 32-bit packed halfword byteswap. i.e.
2993 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2994 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2995 if (!N.getNode()->hasOneUse())
2998 unsigned Opc = N.getOpcode();
2999 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3002 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3007 switch (N1C->getZExtValue()) {
3010 case 0xFF: Num = 0; break;
3011 case 0xFF00: Num = 1; break;
3012 case 0xFF0000: Num = 2; break;
3013 case 0xFF000000: Num = 3; break;
3016 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3017 SDValue N0 = N.getOperand(0);
3018 if (Opc == ISD::AND) {
3019 if (Num == 0 || Num == 2) {
3021 // (x >> 8) & 0xff0000
3022 if (N0.getOpcode() != ISD::SRL)
3024 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3025 if (!C || C->getZExtValue() != 8)
3028 // (x << 8) & 0xff00
3029 // (x << 8) & 0xff000000
3030 if (N0.getOpcode() != ISD::SHL)
3032 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3033 if (!C || C->getZExtValue() != 8)
3036 } else if (Opc == ISD::SHL) {
3038 // (x & 0xff0000) << 8
3039 if (Num != 0 && Num != 2)
3041 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3042 if (!C || C->getZExtValue() != 8)
3044 } else { // Opc == ISD::SRL
3045 // (x & 0xff00) >> 8
3046 // (x & 0xff000000) >> 8
3047 if (Num != 1 && Num != 3)
3049 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3050 if (!C || C->getZExtValue() != 8)
3057 Parts[Num] = N0.getOperand(0).getNode();
3061 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3062 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3063 /// => (rotl (bswap x), 16)
3064 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3065 if (!LegalOperations)
3068 EVT VT = N->getValueType(0);
3071 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3074 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3076 // (or (or (and), (and)), (or (and), (and)))
3077 // (or (or (or (and), (and)), (and)), (and))
3078 if (N0.getOpcode() != ISD::OR)
3080 SDValue N00 = N0.getOperand(0);
3081 SDValue N01 = N0.getOperand(1);
3083 if (N1.getOpcode() == ISD::OR &&
3084 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3085 // (or (or (and), (and)), (or (and), (and)))
3086 SDValue N000 = N00.getOperand(0);
3087 if (!isBSwapHWordElement(N000, Parts))
3090 SDValue N001 = N00.getOperand(1);
3091 if (!isBSwapHWordElement(N001, Parts))
3093 SDValue N010 = N01.getOperand(0);
3094 if (!isBSwapHWordElement(N010, Parts))
3096 SDValue N011 = N01.getOperand(1);
3097 if (!isBSwapHWordElement(N011, Parts))
3100 // (or (or (or (and), (and)), (and)), (and))
3101 if (!isBSwapHWordElement(N1, Parts))
3103 if (!isBSwapHWordElement(N01, Parts))
3105 if (N00.getOpcode() != ISD::OR)
3107 SDValue N000 = N00.getOperand(0);
3108 if (!isBSwapHWordElement(N000, Parts))
3110 SDValue N001 = N00.getOperand(1);
3111 if (!isBSwapHWordElement(N001, Parts))
3115 // Make sure the parts are all coming from the same node.
3116 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3119 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3120 SDValue(Parts[0],0));
3122 // Result of the bswap should be rotated by 16. If it's not legal, then
3123 // do (x << 16) | (x >> 16).
3124 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3125 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3126 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3127 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3128 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3129 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3130 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3131 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3134 SDValue DAGCombiner::visitOR(SDNode *N) {
3135 SDValue N0 = N->getOperand(0);
3136 SDValue N1 = N->getOperand(1);
3137 SDValue LL, LR, RL, RR, CC0, CC1;
3138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3140 EVT VT = N1.getValueType();
3143 if (VT.isVector()) {
3144 SDValue FoldedVOp = SimplifyVBinOp(N);
3145 if (FoldedVOp.getNode()) return FoldedVOp;
3147 // fold (or x, 0) -> x, vector edition
3148 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3150 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3153 // fold (or x, -1) -> -1, vector edition
3154 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3156 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3160 // fold (or x, undef) -> -1
3161 if (!LegalOperations &&
3162 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3163 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3164 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3166 // fold (or c1, c2) -> c1|c2
3168 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3169 // canonicalize constant to RHS
3171 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3172 // fold (or x, 0) -> x
3173 if (N1C && N1C->isNullValue())
3175 // fold (or x, -1) -> -1
3176 if (N1C && N1C->isAllOnesValue())
3178 // fold (or x, c) -> c iff (x & ~c) == 0
3179 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3182 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3183 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3184 if (BSwap.getNode() != 0)
3186 BSwap = MatchBSwapHWordLow(N, N0, N1);
3187 if (BSwap.getNode() != 0)
3191 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3192 if (ROR.getNode() != 0)
3194 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3195 // iff (c1 & c2) == 0.
3196 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3197 isa<ConstantSDNode>(N0.getOperand(1))) {
3198 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3199 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3200 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3201 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3202 N0.getOperand(0), N1),
3203 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3205 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3206 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3207 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3208 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3210 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3211 LL.getValueType().isInteger()) {
3212 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3213 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3214 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3215 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3216 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3217 LR.getValueType(), LL, RL);
3218 AddToWorkList(ORNode.getNode());
3219 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3221 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3222 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3223 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3224 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3225 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3226 LR.getValueType(), LL, RL);
3227 AddToWorkList(ANDNode.getNode());
3228 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3231 // canonicalize equivalent to ll == rl
3232 if (LL == RR && LR == RL) {
3233 Op1 = ISD::getSetCCSwappedOperands(Op1);
3236 if (LL == RL && LR == RR) {
3237 bool isInteger = LL.getValueType().isInteger();
3238 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3239 if (Result != ISD::SETCC_INVALID &&
3240 (!LegalOperations ||
3241 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3242 TLI.isOperationLegal(ISD::SETCC,
3243 getSetCCResultType(N0.getValueType())))))
3244 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3249 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3250 if (N0.getOpcode() == N1.getOpcode()) {
3251 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3252 if (Tmp.getNode()) return Tmp;
3255 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3256 if (N0.getOpcode() == ISD::AND &&
3257 N1.getOpcode() == ISD::AND &&
3258 N0.getOperand(1).getOpcode() == ISD::Constant &&
3259 N1.getOperand(1).getOpcode() == ISD::Constant &&
3260 // Don't increase # computations.
3261 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3262 // We can only do this xform if we know that bits from X that are set in C2
3263 // but not in C1 are already zero. Likewise for Y.
3264 const APInt &LHSMask =
3265 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3266 const APInt &RHSMask =
3267 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3269 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3270 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3271 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3272 N0.getOperand(0), N1.getOperand(0));
3273 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3274 DAG.getConstant(LHSMask | RHSMask, VT));
3278 // See if this is some rotate idiom.
3279 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3280 return SDValue(Rot, 0);
3282 // Simplify the operands using demanded-bits information.
3283 if (!VT.isVector() &&
3284 SimplifyDemandedBits(SDValue(N, 0)))
3285 return SDValue(N, 0);
3290 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3291 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3292 if (Op.getOpcode() == ISD::AND) {
3293 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3294 Mask = Op.getOperand(1);
3295 Op = Op.getOperand(0);
3301 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3309 // Return true if we can prove that Neg == OpSize - Pos. This means that
3310 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3312 // (or (shift1 X, Neg), (shift2 X, Pos))
3314 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3315 // shift1 by Neg. Note that the (or ...) then invokes undefined behavior
3316 // if Pos == 0 (and consequently Neg == OpSize).
3317 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3318 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3319 if (Neg.getOpcode() != ISD::SUB)
3321 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3324 SDValue NegOp1 = Neg.getOperand(1);
3326 // The condition we need to prove is now NegC - NegOp1 == OpSize - Pos.
3327 // Check whether the terms match directly.
3329 return NegC->getAPIntValue() == OpSize;
3331 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3332 // Then the condition we want to prove becomes:
3333 // NegC - NegOp1 == OpSize - (NegOp1 + PosC)
3334 // NegC == OpSize - PosC
3336 // Because NegC and PosC are APInts, this is easier to test as:
3337 // OpSize == NegC + PosC
3338 if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3339 ConstantSDNode *PosC = dyn_cast<ConstantSDNode>(Pos.getOperand(1));
3340 return PosC && OpSize == NegC->getAPIntValue() + PosC->getAPIntValue();
3346 // A subroutine of MatchRotate used once we have found an OR of two opposite
3347 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3348 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3349 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3350 // Neg with outer conversions stripped away.
3351 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3352 SDValue Neg, SDValue InnerPos,
3353 SDValue InnerNeg, unsigned PosOpcode,
3354 unsigned NegOpcode, SDLoc DL) {
3355 // fold (or (shl x, (*ext y)),
3356 // (srl x, (*ext (sub 32, y)))) ->
3357 // (rotl x, y) or (rotr x, (sub 32, y))
3359 // fold (or (shl x, (*ext (sub 32, y))),
3360 // (srl x, (*ext y))) ->
3361 // (rotr x, y) or (rotl x, (sub 32, y))
3362 EVT VT = Shifted.getValueType();
3363 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3364 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3365 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3366 HasPos ? Pos : Neg).getNode();
3369 // fold (or (shl (*ext x), (*ext y)),
3370 // (srl (*ext x), (*ext (sub 32, y)))) ->
3371 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3373 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3374 // (srl (*ext x), (*ext y))) ->
3375 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3376 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3377 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3378 SDValue InnerShifted = Shifted.getOperand(0);
3379 EVT InnerVT = InnerShifted.getValueType();
3380 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3381 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3382 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3383 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3384 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3385 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3393 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3394 // idioms for rotate, and if the target supports rotation instructions, generate
3396 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3397 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3398 EVT VT = LHS.getValueType();
3399 if (!TLI.isTypeLegal(VT)) return 0;
3401 // The target must have at least one rotate flavor.
3402 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3403 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3404 if (!HasROTL && !HasROTR) return 0;
3406 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3407 SDValue LHSShift; // The shift.
3408 SDValue LHSMask; // AND value if any.
3409 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3410 return 0; // Not part of a rotate.
3412 SDValue RHSShift; // The shift.
3413 SDValue RHSMask; // AND value if any.
3414 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3415 return 0; // Not part of a rotate.
3417 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3418 return 0; // Not shifting the same value.
3420 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3421 return 0; // Shifts must disagree.
3423 // Canonicalize shl to left side in a shl/srl pair.
3424 if (RHSShift.getOpcode() == ISD::SHL) {
3425 std::swap(LHS, RHS);
3426 std::swap(LHSShift, RHSShift);
3427 std::swap(LHSMask , RHSMask );
3430 unsigned OpSizeInBits = VT.getSizeInBits();
3431 SDValue LHSShiftArg = LHSShift.getOperand(0);
3432 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3433 SDValue RHSShiftArg = RHSShift.getOperand(0);
3434 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3436 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3437 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3438 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3439 RHSShiftAmt.getOpcode() == ISD::Constant) {
3440 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3441 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3442 if ((LShVal + RShVal) != OpSizeInBits)
3445 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3446 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3448 // If there is an AND of either shifted operand, apply it to the result.
3449 if (LHSMask.getNode() || RHSMask.getNode()) {
3450 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3452 if (LHSMask.getNode()) {
3453 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3454 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3456 if (RHSMask.getNode()) {
3457 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3458 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3461 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3464 return Rot.getNode();
3467 // If there is a mask here, and we have a variable shift, we can't be sure
3468 // that we're masking out the right stuff.
3469 if (LHSMask.getNode() || RHSMask.getNode())
3472 // If the shift amount is sign/zext/any-extended just peel it off.
3473 SDValue LExtOp0 = LHSShiftAmt;
3474 SDValue RExtOp0 = RHSShiftAmt;
3475 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3476 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3477 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3478 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3479 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3480 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3481 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3482 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3483 LExtOp0 = LHSShiftAmt.getOperand(0);
3484 RExtOp0 = RHSShiftAmt.getOperand(0);
3487 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3488 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3492 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3493 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3500 SDValue DAGCombiner::visitXOR(SDNode *N) {
3501 SDValue N0 = N->getOperand(0);
3502 SDValue N1 = N->getOperand(1);
3503 SDValue LHS, RHS, CC;
3504 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3506 EVT VT = N0.getValueType();
3509 if (VT.isVector()) {
3510 SDValue FoldedVOp = SimplifyVBinOp(N);
3511 if (FoldedVOp.getNode()) return FoldedVOp;
3513 // fold (xor x, 0) -> x, vector edition
3514 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3516 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3520 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3521 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3522 return DAG.getConstant(0, VT);
3523 // fold (xor x, undef) -> undef
3524 if (N0.getOpcode() == ISD::UNDEF)
3526 if (N1.getOpcode() == ISD::UNDEF)
3528 // fold (xor c1, c2) -> c1^c2
3530 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3531 // canonicalize constant to RHS
3533 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3534 // fold (xor x, 0) -> x
3535 if (N1C && N1C->isNullValue())
3538 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3539 if (RXOR.getNode() != 0)
3542 // fold !(x cc y) -> (x !cc y)
3543 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3544 bool isInt = LHS.getValueType().isInteger();
3545 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3548 if (!LegalOperations ||
3549 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3550 switch (N0.getOpcode()) {
3552 llvm_unreachable("Unhandled SetCC Equivalent!");
3554 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3555 case ISD::SELECT_CC:
3556 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3557 N0.getOperand(3), NotCC);
3562 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3563 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3564 N0.getNode()->hasOneUse() &&
3565 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3566 SDValue V = N0.getOperand(0);
3567 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3568 DAG.getConstant(1, V.getValueType()));
3569 AddToWorkList(V.getNode());
3570 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3573 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3574 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3575 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3576 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3577 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3578 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3579 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3580 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3581 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3582 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3585 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3586 if (N1C && N1C->isAllOnesValue() &&
3587 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3588 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3589 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3590 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3591 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3592 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3593 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3594 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3597 // fold (xor (and x, y), y) -> (and (not x), y)
3598 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3599 N0->getOperand(1) == N1) {
3600 SDValue X = N0->getOperand(0);
3601 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3602 AddToWorkList(NotX.getNode());
3603 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3605 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3606 if (N1C && N0.getOpcode() == ISD::XOR) {
3607 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3608 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3610 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3611 DAG.getConstant(N1C->getAPIntValue() ^
3612 N00C->getAPIntValue(), VT));
3614 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3615 DAG.getConstant(N1C->getAPIntValue() ^
3616 N01C->getAPIntValue(), VT));
3618 // fold (xor x, x) -> 0
3620 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3622 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3623 if (N0.getOpcode() == N1.getOpcode()) {
3624 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3625 if (Tmp.getNode()) return Tmp;
3628 // Simplify the expression using non-local knowledge.
3629 if (!VT.isVector() &&
3630 SimplifyDemandedBits(SDValue(N, 0)))
3631 return SDValue(N, 0);
3636 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3637 /// the shift amount is a constant.
3638 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3639 SDNode *LHS = N->getOperand(0).getNode();
3640 if (!LHS->hasOneUse()) return SDValue();
3642 // We want to pull some binops through shifts, so that we have (and (shift))
3643 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3644 // thing happens with address calculations, so it's important to canonicalize
3646 bool HighBitSet = false; // Can we transform this if the high bit is set?
3648 switch (LHS->getOpcode()) {
3649 default: return SDValue();
3652 HighBitSet = false; // We can only transform sra if the high bit is clear.
3655 HighBitSet = true; // We can only transform sra if the high bit is set.
3658 if (N->getOpcode() != ISD::SHL)
3659 return SDValue(); // only shl(add) not sr[al](add).
3660 HighBitSet = false; // We can only transform sra if the high bit is clear.
3664 // We require the RHS of the binop to be a constant as well.
3665 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3666 if (!BinOpCst) return SDValue();
3668 // FIXME: disable this unless the input to the binop is a shift by a constant.
3669 // If it is not a shift, it pessimizes some common cases like:
3671 // void foo(int *X, int i) { X[i & 1235] = 1; }
3672 // int bar(int *X, int i) { return X[i & 255]; }
3673 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3674 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3675 BinOpLHSVal->getOpcode() != ISD::SRA &&
3676 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3677 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3680 EVT VT = N->getValueType(0);
3682 // If this is a signed shift right, and the high bit is modified by the
3683 // logical operation, do not perform the transformation. The highBitSet
3684 // boolean indicates the value of the high bit of the constant which would
3685 // cause it to be modified for this operation.
3686 if (N->getOpcode() == ISD::SRA) {
3687 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3688 if (BinOpRHSSignSet != HighBitSet)
3692 // Fold the constants, shifting the binop RHS by the shift amount.
3693 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3695 LHS->getOperand(1), N->getOperand(1));
3697 // Create the new shift.
3698 SDValue NewShift = DAG.getNode(N->getOpcode(),
3699 SDLoc(LHS->getOperand(0)),
3700 VT, LHS->getOperand(0), N->getOperand(1));
3702 // Create the new binop.
3703 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3706 SDValue DAGCombiner::visitSHL(SDNode *N) {
3707 SDValue N0 = N->getOperand(0);
3708 SDValue N1 = N->getOperand(1);
3709 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3710 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3711 EVT VT = N0.getValueType();
3712 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3715 if (VT.isVector()) {
3716 SDValue FoldedVOp = SimplifyVBinOp(N);
3717 if (FoldedVOp.getNode()) return FoldedVOp;
3720 // fold (shl c1, c2) -> c1<<c2
3722 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3723 // fold (shl 0, x) -> 0
3724 if (N0C && N0C->isNullValue())
3726 // fold (shl x, c >= size(x)) -> undef
3727 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3728 return DAG.getUNDEF(VT);
3729 // fold (shl x, 0) -> x
3730 if (N1C && N1C->isNullValue())
3732 // fold (shl undef, x) -> 0
3733 if (N0.getOpcode() == ISD::UNDEF)
3734 return DAG.getConstant(0, VT);
3735 // if (shl x, c) is known to be zero, return 0
3736 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3737 APInt::getAllOnesValue(OpSizeInBits)))
3738 return DAG.getConstant(0, VT);
3739 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3740 if (N1.getOpcode() == ISD::TRUNCATE &&
3741 N1.getOperand(0).getOpcode() == ISD::AND &&
3742 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3743 SDValue N101 = N1.getOperand(0).getOperand(1);
3744 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3745 EVT TruncVT = N1.getValueType();
3746 SDValue N100 = N1.getOperand(0).getOperand(0);
3747 APInt TruncC = N101C->getAPIntValue();
3748 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3749 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3750 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3751 DAG.getNode(ISD::TRUNCATE,
3754 DAG.getConstant(TruncC, TruncVT)));
3758 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3759 return SDValue(N, 0);
3761 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3762 if (N1C && N0.getOpcode() == ISD::SHL &&
3763 N0.getOperand(1).getOpcode() == ISD::Constant) {
3764 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3765 uint64_t c2 = N1C->getZExtValue();
3766 if (c1 + c2 >= OpSizeInBits)
3767 return DAG.getConstant(0, VT);
3768 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3769 DAG.getConstant(c1 + c2, N1.getValueType()));
3772 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3773 // For this to be valid, the second form must not preserve any of the bits
3774 // that are shifted out by the inner shift in the first form. This means
3775 // the outer shift size must be >= the number of bits added by the ext.
3776 // As a corollary, we don't care what kind of ext it is.
3777 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3778 N0.getOpcode() == ISD::ANY_EXTEND ||
3779 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3780 N0.getOperand(0).getOpcode() == ISD::SHL &&
3781 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3783 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3784 uint64_t c2 = N1C->getZExtValue();
3785 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3786 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3787 if (c2 >= OpSizeInBits - InnerShiftSize) {
3788 if (c1 + c2 >= OpSizeInBits)
3789 return DAG.getConstant(0, VT);
3790 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3791 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3792 N0.getOperand(0)->getOperand(0)),
3793 DAG.getConstant(c1 + c2, N1.getValueType()));
3797 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3798 // Only fold this if the inner zext has no other uses to avoid increasing
3799 // the total number of instructions.
3800 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3801 N0.getOperand(0).getOpcode() == ISD::SRL &&
3802 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3804 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3805 if (c1 < VT.getSizeInBits()) {
3806 uint64_t c2 = N1C->getZExtValue();
3808 SDValue NewOp0 = N0.getOperand(0);
3809 EVT CountVT = NewOp0.getOperand(1).getValueType();
3810 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3811 NewOp0, DAG.getConstant(c2, CountVT));
3812 AddToWorkList(NewSHL.getNode());
3813 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3818 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3819 // (and (srl x, (sub c1, c2), MASK)
3820 // Only fold this if the inner shift has no other uses -- if it does, folding
3821 // this will increase the total number of instructions.
3822 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3823 N0.getOperand(1).getOpcode() == ISD::Constant) {
3824 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3825 if (c1 < VT.getSizeInBits()) {
3826 uint64_t c2 = N1C->getZExtValue();
3827 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3828 VT.getSizeInBits() - c1);
3831 Mask = Mask.shl(c2-c1);
3832 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3833 DAG.getConstant(c2-c1, N1.getValueType()));
3835 Mask = Mask.lshr(c1-c2);
3836 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3837 DAG.getConstant(c1-c2, N1.getValueType()));
3839 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3840 DAG.getConstant(Mask, VT));
3843 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3844 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3845 SDValue HiBitsMask =
3846 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3847 VT.getSizeInBits() -
3848 N1C->getZExtValue()),
3850 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3855 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3856 if (NewSHL.getNode())
3863 SDValue DAGCombiner::visitSRA(SDNode *N) {
3864 SDValue N0 = N->getOperand(0);
3865 SDValue N1 = N->getOperand(1);
3866 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3867 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3868 EVT VT = N0.getValueType();
3869 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3872 if (VT.isVector()) {
3873 SDValue FoldedVOp = SimplifyVBinOp(N);
3874 if (FoldedVOp.getNode()) return FoldedVOp;
3877 // fold (sra c1, c2) -> (sra c1, c2)
3879 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3880 // fold (sra 0, x) -> 0
3881 if (N0C && N0C->isNullValue())
3883 // fold (sra -1, x) -> -1
3884 if (N0C && N0C->isAllOnesValue())
3886 // fold (sra x, (setge c, size(x))) -> undef
3887 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3888 return DAG.getUNDEF(VT);
3889 // fold (sra x, 0) -> x
3890 if (N1C && N1C->isNullValue())
3892 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3894 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3895 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3896 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3898 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3899 ExtVT, VT.getVectorNumElements());
3900 if ((!LegalOperations ||
3901 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3902 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3903 N0.getOperand(0), DAG.getValueType(ExtVT));
3906 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3907 if (N1C && N0.getOpcode() == ISD::SRA) {
3908 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3909 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3910 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3911 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3912 DAG.getConstant(Sum, N1C->getValueType(0)));
3916 // fold (sra (shl X, m), (sub result_size, n))
3917 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3918 // result_size - n != m.
3919 // If truncate is free for the target sext(shl) is likely to result in better
3921 if (N0.getOpcode() == ISD::SHL) {
3922 // Get the two constanst of the shifts, CN0 = m, CN = n.
3923 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3925 // Determine what the truncate's result bitsize and type would be.
3927 EVT::getIntegerVT(*DAG.getContext(),
3928 OpSizeInBits - N1C->getZExtValue());
3929 // Determine the residual right-shift amount.
3930 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3932 // If the shift is not a no-op (in which case this should be just a sign
3933 // extend already), the truncated to type is legal, sign_extend is legal
3934 // on that type, and the truncate to that type is both legal and free,
3935 // perform the transform.
3936 if ((ShiftAmt > 0) &&
3937 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3938 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3939 TLI.isTruncateFree(VT, TruncVT)) {
3941 SDValue Amt = DAG.getConstant(ShiftAmt,
3942 getShiftAmountTy(N0.getOperand(0).getValueType()));
3943 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3944 N0.getOperand(0), Amt);
3945 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3947 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3948 N->getValueType(0), Trunc);
3953 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3954 if (N1.getOpcode() == ISD::TRUNCATE &&
3955 N1.getOperand(0).getOpcode() == ISD::AND &&
3956 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3957 SDValue N101 = N1.getOperand(0).getOperand(1);
3958 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3959 EVT TruncVT = N1.getValueType();
3960 SDValue N100 = N1.getOperand(0).getOperand(0);
3961 APInt TruncC = N101C->getAPIntValue();
3962 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3963 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3964 DAG.getNode(ISD::AND, SDLoc(N),
3966 DAG.getNode(ISD::TRUNCATE,
3969 DAG.getConstant(TruncC, TruncVT)));
3973 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3974 // if c1 is equal to the number of bits the trunc removes
3975 if (N0.getOpcode() == ISD::TRUNCATE &&
3976 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3977 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3978 N0.getOperand(0).hasOneUse() &&
3979 N0.getOperand(0).getOperand(1).hasOneUse() &&
3980 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3981 EVT LargeVT = N0.getOperand(0).getValueType();
3982 ConstantSDNode *LargeShiftAmt =
3983 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3985 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3986 LargeShiftAmt->getZExtValue()) {
3988 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3989 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3990 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3991 N0.getOperand(0).getOperand(0), Amt);
3992 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3996 // Simplify, based on bits shifted out of the LHS.
3997 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3998 return SDValue(N, 0);
4001 // If the sign bit is known to be zero, switch this to a SRL.
4002 if (DAG.SignBitIsZero(N0))
4003 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4006 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4007 if (NewSRA.getNode())
4014 SDValue DAGCombiner::visitSRL(SDNode *N) {
4015 SDValue N0 = N->getOperand(0);
4016 SDValue N1 = N->getOperand(1);
4017 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4018 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4019 EVT VT = N0.getValueType();
4020 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4023 if (VT.isVector()) {
4024 SDValue FoldedVOp = SimplifyVBinOp(N);
4025 if (FoldedVOp.getNode()) return FoldedVOp;
4028 // fold (srl c1, c2) -> c1 >>u c2
4030 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4031 // fold (srl 0, x) -> 0
4032 if (N0C && N0C->isNullValue())
4034 // fold (srl x, c >= size(x)) -> undef
4035 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4036 return DAG.getUNDEF(VT);
4037 // fold (srl x, 0) -> x
4038 if (N1C && N1C->isNullValue())
4040 // if (srl x, c) is known to be zero, return 0
4041 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4042 APInt::getAllOnesValue(OpSizeInBits)))
4043 return DAG.getConstant(0, VT);
4045 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4046 if (N1C && N0.getOpcode() == ISD::SRL &&
4047 N0.getOperand(1).getOpcode() == ISD::Constant) {
4048 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4049 uint64_t c2 = N1C->getZExtValue();
4050 if (c1 + c2 >= OpSizeInBits)
4051 return DAG.getConstant(0, VT);
4052 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4053 DAG.getConstant(c1 + c2, N1.getValueType()));
4056 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4057 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4058 N0.getOperand(0).getOpcode() == ISD::SRL &&
4059 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4061 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4062 uint64_t c2 = N1C->getZExtValue();
4063 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4064 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4065 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4066 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4067 if (c1 + OpSizeInBits == InnerShiftSize) {
4068 if (c1 + c2 >= InnerShiftSize)
4069 return DAG.getConstant(0, VT);
4070 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4071 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4072 N0.getOperand(0)->getOperand(0),
4073 DAG.getConstant(c1 + c2, ShiftCountVT)));
4077 // fold (srl (shl x, c), c) -> (and x, cst2)
4078 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4079 N0.getValueSizeInBits() <= 64) {
4080 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4081 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4082 DAG.getConstant(~0ULL >> ShAmt, VT));
4085 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4086 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4087 // Shifting in all undef bits?
4088 EVT SmallVT = N0.getOperand(0).getValueType();
4089 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4090 return DAG.getUNDEF(VT);
4092 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4093 uint64_t ShiftAmt = N1C->getZExtValue();
4094 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4096 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4097 AddToWorkList(SmallShift.getNode());
4098 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4099 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4100 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4101 DAG.getConstant(Mask, VT));
4105 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4106 // bit, which is unmodified by sra.
4107 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4108 if (N0.getOpcode() == ISD::SRA)
4109 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4112 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4113 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4114 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4115 APInt KnownZero, KnownOne;
4116 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4118 // If any of the input bits are KnownOne, then the input couldn't be all
4119 // zeros, thus the result of the srl will always be zero.
4120 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4122 // If all of the bits input the to ctlz node are known to be zero, then
4123 // the result of the ctlz is "32" and the result of the shift is one.
4124 APInt UnknownBits = ~KnownZero;
4125 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4127 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4128 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4129 // Okay, we know that only that the single bit specified by UnknownBits
4130 // could be set on input to the CTLZ node. If this bit is set, the SRL
4131 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4132 // to an SRL/XOR pair, which is likely to simplify more.
4133 unsigned ShAmt = UnknownBits.countTrailingZeros();
4134 SDValue Op = N0.getOperand(0);
4137 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4138 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4139 AddToWorkList(Op.getNode());
4142 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4143 Op, DAG.getConstant(1, VT));
4147 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4148 if (N1.getOpcode() == ISD::TRUNCATE &&
4149 N1.getOperand(0).getOpcode() == ISD::AND &&
4150 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4151 SDValue N101 = N1.getOperand(0).getOperand(1);
4152 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4153 EVT TruncVT = N1.getValueType();
4154 SDValue N100 = N1.getOperand(0).getOperand(0);
4155 APInt TruncC = N101C->getAPIntValue();
4156 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4157 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4158 DAG.getNode(ISD::AND, SDLoc(N),
4160 DAG.getNode(ISD::TRUNCATE,
4163 DAG.getConstant(TruncC, TruncVT)));
4167 // fold operands of srl based on knowledge that the low bits are not
4169 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4170 return SDValue(N, 0);
4173 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4174 if (NewSRL.getNode())
4178 // Attempt to convert a srl of a load into a narrower zero-extending load.
4179 SDValue NarrowLoad = ReduceLoadWidth(N);
4180 if (NarrowLoad.getNode())
4183 // Here is a common situation. We want to optimize:
4186 // %b = and i32 %a, 2
4187 // %c = srl i32 %b, 1
4188 // brcond i32 %c ...
4194 // %c = setcc eq %b, 0
4197 // However when after the source operand of SRL is optimized into AND, the SRL
4198 // itself may not be optimized further. Look for it and add the BRCOND into
4200 if (N->hasOneUse()) {
4201 SDNode *Use = *N->use_begin();
4202 if (Use->getOpcode() == ISD::BRCOND)
4204 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4205 // Also look pass the truncate.
4206 Use = *Use->use_begin();
4207 if (Use->getOpcode() == ISD::BRCOND)
4215 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4216 SDValue N0 = N->getOperand(0);
4217 EVT VT = N->getValueType(0);
4219 // fold (ctlz c1) -> c2
4220 if (isa<ConstantSDNode>(N0))
4221 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4225 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4226 SDValue N0 = N->getOperand(0);
4227 EVT VT = N->getValueType(0);
4229 // fold (ctlz_zero_undef c1) -> c2
4230 if (isa<ConstantSDNode>(N0))
4231 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4235 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4236 SDValue N0 = N->getOperand(0);
4237 EVT VT = N->getValueType(0);
4239 // fold (cttz c1) -> c2
4240 if (isa<ConstantSDNode>(N0))
4241 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4245 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4246 SDValue N0 = N->getOperand(0);
4247 EVT VT = N->getValueType(0);
4249 // fold (cttz_zero_undef c1) -> c2
4250 if (isa<ConstantSDNode>(N0))
4251 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4255 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4256 SDValue N0 = N->getOperand(0);
4257 EVT VT = N->getValueType(0);
4259 // fold (ctpop c1) -> c2
4260 if (isa<ConstantSDNode>(N0))
4261 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4265 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4266 SDValue N0 = N->getOperand(0);
4267 SDValue N1 = N->getOperand(1);
4268 SDValue N2 = N->getOperand(2);
4269 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4270 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4271 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4272 EVT VT = N->getValueType(0);
4273 EVT VT0 = N0.getValueType();
4275 // fold (select C, X, X) -> X
4278 // fold (select true, X, Y) -> X
4279 if (N0C && !N0C->isNullValue())
4281 // fold (select false, X, Y) -> Y
4282 if (N0C && N0C->isNullValue())
4284 // fold (select C, 1, X) -> (or C, X)
4285 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4286 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4287 // fold (select C, 0, 1) -> (xor C, 1)
4288 if (VT.isInteger() &&
4291 TLI.getBooleanContents(false) ==
4292 TargetLowering::ZeroOrOneBooleanContent)) &&
4293 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4296 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4297 N0, DAG.getConstant(1, VT0));
4298 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4299 N0, DAG.getConstant(1, VT0));
4300 AddToWorkList(XORNode.getNode());
4302 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4303 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4305 // fold (select C, 0, X) -> (and (not C), X)
4306 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4307 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4308 AddToWorkList(NOTNode.getNode());
4309 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4311 // fold (select C, X, 1) -> (or (not C), X)
4312 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4313 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4314 AddToWorkList(NOTNode.getNode());
4315 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4317 // fold (select C, X, 0) -> (and C, X)
4318 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4319 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4320 // fold (select X, X, Y) -> (or X, Y)
4321 // fold (select X, 1, Y) -> (or X, Y)
4322 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4323 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4324 // fold (select X, Y, X) -> (and X, Y)
4325 // fold (select X, Y, 0) -> (and X, Y)
4326 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4327 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4329 // If we can fold this based on the true/false value, do so.
4330 if (SimplifySelectOps(N, N1, N2))
4331 return SDValue(N, 0); // Don't revisit N.
4333 // fold selects based on a setcc into other things, such as min/max/abs
4334 if (N0.getOpcode() == ISD::SETCC) {
4336 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4337 // having to say they don't support SELECT_CC on every type the DAG knows
4338 // about, since there is no way to mark an opcode illegal at all value types
4339 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4340 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4341 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4342 N0.getOperand(0), N0.getOperand(1),
4343 N1, N2, N0.getOperand(2));
4344 return SimplifySelect(SDLoc(N), N0, N1, N2);
4351 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4354 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4356 // Split the inputs.
4357 SDValue Lo, Hi, LL, LH, RL, RH;
4358 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4359 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4361 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4362 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4364 return std::make_pair(Lo, Hi);
4367 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4368 SDValue N0 = N->getOperand(0);
4369 SDValue N1 = N->getOperand(1);
4370 SDValue N2 = N->getOperand(2);
4373 // Canonicalize integer abs.
4374 // vselect (setg[te] X, 0), X, -X ->
4375 // vselect (setgt X, -1), X, -X ->
4376 // vselect (setl[te] X, 0), -X, X ->
4377 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4378 if (N0.getOpcode() == ISD::SETCC) {
4379 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4380 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4382 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4384 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4385 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4386 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4387 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4388 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4389 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4390 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4393 EVT VT = LHS.getValueType();
4394 SDValue Shift = DAG.getNode(
4395 ISD::SRA, DL, VT, LHS,
4396 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4397 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4398 AddToWorkList(Shift.getNode());
4399 AddToWorkList(Add.getNode());
4400 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4404 // If the VSELECT result requires splitting and the mask is provided by a
4405 // SETCC, then split both nodes and its operands before legalization. This
4406 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4407 // and enables future optimizations (e.g. min/max pattern matching on X86).
4408 if (N0.getOpcode() == ISD::SETCC) {
4409 EVT VT = N->getValueType(0);
4411 // Check if any splitting is required.
4412 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4413 TargetLowering::TypeSplitVector)
4416 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4417 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4418 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4419 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4421 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4422 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4424 // Add the new VSELECT nodes to the work list in case they need to be split
4426 AddToWorkList(Lo.getNode());
4427 AddToWorkList(Hi.getNode());
4429 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4432 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4433 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4435 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4436 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4442 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4443 SDValue N0 = N->getOperand(0);
4444 SDValue N1 = N->getOperand(1);
4445 SDValue N2 = N->getOperand(2);
4446 SDValue N3 = N->getOperand(3);
4447 SDValue N4 = N->getOperand(4);
4448 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4450 // fold select_cc lhs, rhs, x, x, cc -> x
4454 // Determine if the condition we're dealing with is constant
4455 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4456 N0, N1, CC, SDLoc(N), false);
4457 if (SCC.getNode()) {
4458 AddToWorkList(SCC.getNode());
4460 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4461 if (!SCCC->isNullValue())
4462 return N2; // cond always true -> true val
4464 return N3; // cond always false -> false val
4467 // Fold to a simpler select_cc
4468 if (SCC.getOpcode() == ISD::SETCC)
4469 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4470 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4474 // If we can fold this based on the true/false value, do so.
4475 if (SimplifySelectOps(N, N2, N3))
4476 return SDValue(N, 0); // Don't revisit N.
4478 // fold select_cc into other things, such as min/max/abs
4479 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4482 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4483 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4484 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4488 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4489 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4490 // transformation. Returns true if extension are possible and the above
4491 // mentioned transformation is profitable.
4492 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4494 SmallVectorImpl<SDNode *> &ExtendNodes,
4495 const TargetLowering &TLI) {
4496 bool HasCopyToRegUses = false;
4497 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4498 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4499 UE = N0.getNode()->use_end();
4504 if (UI.getUse().getResNo() != N0.getResNo())
4506 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4507 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4508 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4509 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4510 // Sign bits will be lost after a zext.
4513 for (unsigned i = 0; i != 2; ++i) {
4514 SDValue UseOp = User->getOperand(i);
4517 if (!isa<ConstantSDNode>(UseOp))
4522 ExtendNodes.push_back(User);
4525 // If truncates aren't free and there are users we can't
4526 // extend, it isn't worthwhile.
4529 // Remember if this value is live-out.
4530 if (User->getOpcode() == ISD::CopyToReg)
4531 HasCopyToRegUses = true;
4534 if (HasCopyToRegUses) {
4535 bool BothLiveOut = false;
4536 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4538 SDUse &Use = UI.getUse();
4539 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4545 // Both unextended and extended values are live out. There had better be
4546 // a good reason for the transformation.
4547 return ExtendNodes.size();
4552 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4553 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4554 ISD::NodeType ExtType) {
4555 // Extend SetCC uses if necessary.
4556 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4557 SDNode *SetCC = SetCCs[i];
4558 SmallVector<SDValue, 4> Ops;
4560 for (unsigned j = 0; j != 2; ++j) {
4561 SDValue SOp = SetCC->getOperand(j);
4563 Ops.push_back(ExtLoad);
4565 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4568 Ops.push_back(SetCC->getOperand(2));
4569 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4570 &Ops[0], Ops.size()));
4574 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4575 SDValue N0 = N->getOperand(0);
4576 EVT VT = N->getValueType(0);
4578 // fold (sext c1) -> c1
4579 if (isa<ConstantSDNode>(N0))
4580 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4582 // fold (sext (sext x)) -> (sext x)
4583 // fold (sext (aext x)) -> (sext x)
4584 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4585 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4588 if (N0.getOpcode() == ISD::TRUNCATE) {
4589 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4590 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4591 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4592 if (NarrowLoad.getNode()) {
4593 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4594 if (NarrowLoad.getNode() != N0.getNode()) {
4595 CombineTo(N0.getNode(), NarrowLoad);
4596 // CombineTo deleted the truncate, if needed, but not what's under it.
4599 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4602 // See if the value being truncated is already sign extended. If so, just
4603 // eliminate the trunc/sext pair.
4604 SDValue Op = N0.getOperand(0);
4605 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4606 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4607 unsigned DestBits = VT.getScalarType().getSizeInBits();
4608 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4610 if (OpBits == DestBits) {
4611 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4612 // bits, it is already ready.
4613 if (NumSignBits > DestBits-MidBits)
4615 } else if (OpBits < DestBits) {
4616 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4617 // bits, just sext from i32.
4618 if (NumSignBits > OpBits-MidBits)
4619 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4621 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4622 // bits, just truncate to i32.
4623 if (NumSignBits > OpBits-MidBits)
4624 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4627 // fold (sext (truncate x)) -> (sextinreg x).
4628 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4629 N0.getValueType())) {
4630 if (OpBits < DestBits)
4631 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4632 else if (OpBits > DestBits)
4633 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4634 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4635 DAG.getValueType(N0.getValueType()));
4639 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4640 // None of the supported targets knows how to perform load and sign extend
4641 // on vectors in one instruction. We only perform this transformation on
4643 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4644 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4645 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4646 bool DoXform = true;
4647 SmallVector<SDNode*, 4> SetCCs;
4648 if (!N0.hasOneUse())
4649 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4651 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4652 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4654 LN0->getBasePtr(), N0.getValueType(),
4655 LN0->getMemOperand());
4656 CombineTo(N, ExtLoad);
4657 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4658 N0.getValueType(), ExtLoad);
4659 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4660 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4662 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4666 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4667 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4668 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4669 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4670 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4671 EVT MemVT = LN0->getMemoryVT();
4672 if ((!LegalOperations && !LN0->isVolatile()) ||
4673 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4674 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4676 LN0->getBasePtr(), MemVT,
4677 LN0->getMemOperand());
4678 CombineTo(N, ExtLoad);
4679 CombineTo(N0.getNode(),
4680 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4681 N0.getValueType(), ExtLoad),
4682 ExtLoad.getValue(1));
4683 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4687 // fold (sext (and/or/xor (load x), cst)) ->
4688 // (and/or/xor (sextload x), (sext cst))
4689 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4690 N0.getOpcode() == ISD::XOR) &&
4691 isa<LoadSDNode>(N0.getOperand(0)) &&
4692 N0.getOperand(1).getOpcode() == ISD::Constant &&
4693 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4694 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4695 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4696 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4697 bool DoXform = true;
4698 SmallVector<SDNode*, 4> SetCCs;
4699 if (!N0.hasOneUse())
4700 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4703 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4704 LN0->getChain(), LN0->getBasePtr(),
4706 LN0->getMemOperand());
4707 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4708 Mask = Mask.sext(VT.getSizeInBits());
4709 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4710 ExtLoad, DAG.getConstant(Mask, VT));
4711 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4712 SDLoc(N0.getOperand(0)),
4713 N0.getOperand(0).getValueType(), ExtLoad);
4715 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4716 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4718 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4723 if (N0.getOpcode() == ISD::SETCC) {
4724 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4725 // Only do this before legalize for now.
4726 if (VT.isVector() && !LegalOperations &&
4727 TLI.getBooleanContents(true) ==
4728 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4729 EVT N0VT = N0.getOperand(0).getValueType();
4730 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4731 // of the same size as the compared operands. Only optimize sext(setcc())
4732 // if this is the case.
4733 EVT SVT = getSetCCResultType(N0VT);
4735 // We know that the # elements of the results is the same as the
4736 // # elements of the compare (and the # elements of the compare result
4737 // for that matter). Check to see that they are the same size. If so,
4738 // we know that the element size of the sext'd result matches the
4739 // element size of the compare operands.
4740 if (VT.getSizeInBits() == SVT.getSizeInBits())
4741 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4743 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4745 // If the desired elements are smaller or larger than the source
4746 // elements we can use a matching integer vector type and then
4747 // truncate/sign extend
4748 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4749 if (SVT == MatchingVectorType) {
4750 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4751 N0.getOperand(0), N0.getOperand(1),
4752 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4753 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4757 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4758 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4760 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4762 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4763 NegOne, DAG.getConstant(0, VT),
4764 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4765 if (SCC.getNode()) return SCC;
4766 if (!VT.isVector() &&
4767 (!LegalOperations ||
4768 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4769 return DAG.getSelect(SDLoc(N), VT,
4770 DAG.getSetCC(SDLoc(N),
4771 getSetCCResultType(VT),
4772 N0.getOperand(0), N0.getOperand(1),
4773 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4774 NegOne, DAG.getConstant(0, VT));
4778 // fold (sext x) -> (zext x) if the sign bit is known zero.
4779 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4780 DAG.SignBitIsZero(N0))
4781 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4786 // isTruncateOf - If N is a truncate of some other value, return true, record
4787 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4788 // This function computes KnownZero to avoid a duplicated call to
4789 // ComputeMaskedBits in the caller.
4790 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4793 if (N->getOpcode() == ISD::TRUNCATE) {
4794 Op = N->getOperand(0);
4795 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4799 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4800 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4803 SDValue Op0 = N->getOperand(0);
4804 SDValue Op1 = N->getOperand(1);
4805 assert(Op0.getValueType() == Op1.getValueType());
4807 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4808 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4809 if (COp0 && COp0->isNullValue())
4811 else if (COp1 && COp1->isNullValue())
4816 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4818 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4824 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4825 SDValue N0 = N->getOperand(0);
4826 EVT VT = N->getValueType(0);
4828 // fold (zext c1) -> c1
4829 if (isa<ConstantSDNode>(N0))
4830 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4831 // fold (zext (zext x)) -> (zext x)
4832 // fold (zext (aext x)) -> (zext x)
4833 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4834 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4837 // fold (zext (truncate x)) -> (zext x) or
4838 // (zext (truncate x)) -> (truncate x)
4839 // This is valid when the truncated bits of x are already zero.
4840 // FIXME: We should extend this to work for vectors too.
4843 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4844 APInt TruncatedBits =
4845 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4846 APInt(Op.getValueSizeInBits(), 0) :
4847 APInt::getBitsSet(Op.getValueSizeInBits(),
4848 N0.getValueSizeInBits(),
4849 std::min(Op.getValueSizeInBits(),
4850 VT.getSizeInBits()));
4851 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4852 if (VT.bitsGT(Op.getValueType()))
4853 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4854 if (VT.bitsLT(Op.getValueType()))
4855 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4861 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4862 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4863 if (N0.getOpcode() == ISD::TRUNCATE) {
4864 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4865 if (NarrowLoad.getNode()) {
4866 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4867 if (NarrowLoad.getNode() != N0.getNode()) {
4868 CombineTo(N0.getNode(), NarrowLoad);
4869 // CombineTo deleted the truncate, if needed, but not what's under it.
4872 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4876 // fold (zext (truncate x)) -> (and x, mask)
4877 if (N0.getOpcode() == ISD::TRUNCATE &&
4878 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4880 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4881 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4882 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4883 if (NarrowLoad.getNode()) {
4884 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4885 if (NarrowLoad.getNode() != N0.getNode()) {
4886 CombineTo(N0.getNode(), NarrowLoad);
4887 // CombineTo deleted the truncate, if needed, but not what's under it.
4890 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4893 SDValue Op = N0.getOperand(0);
4894 if (Op.getValueType().bitsLT(VT)) {
4895 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4896 AddToWorkList(Op.getNode());
4897 } else if (Op.getValueType().bitsGT(VT)) {
4898 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4899 AddToWorkList(Op.getNode());
4901 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4902 N0.getValueType().getScalarType());
4905 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4906 // if either of the casts is not free.
4907 if (N0.getOpcode() == ISD::AND &&
4908 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4909 N0.getOperand(1).getOpcode() == ISD::Constant &&
4910 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4911 N0.getValueType()) ||
4912 !TLI.isZExtFree(N0.getValueType(), VT))) {
4913 SDValue X = N0.getOperand(0).getOperand(0);
4914 if (X.getValueType().bitsLT(VT)) {
4915 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4916 } else if (X.getValueType().bitsGT(VT)) {
4917 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4919 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4920 Mask = Mask.zext(VT.getSizeInBits());
4921 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4922 X, DAG.getConstant(Mask, VT));
4925 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4926 // None of the supported targets knows how to perform load and vector_zext
4927 // on vectors in one instruction. We only perform this transformation on
4929 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4930 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4931 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4932 bool DoXform = true;
4933 SmallVector<SDNode*, 4> SetCCs;
4934 if (!N0.hasOneUse())
4935 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4937 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4938 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4940 LN0->getBasePtr(), N0.getValueType(),
4941 LN0->getMemOperand());
4942 CombineTo(N, ExtLoad);
4943 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4944 N0.getValueType(), ExtLoad);
4945 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4947 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4953 // fold (zext (and/or/xor (load x), cst)) ->
4954 // (and/or/xor (zextload x), (zext cst))
4955 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4956 N0.getOpcode() == ISD::XOR) &&
4957 isa<LoadSDNode>(N0.getOperand(0)) &&
4958 N0.getOperand(1).getOpcode() == ISD::Constant &&
4959 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4960 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4961 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4962 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4963 bool DoXform = true;
4964 SmallVector<SDNode*, 4> SetCCs;
4965 if (!N0.hasOneUse())
4966 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4969 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4970 LN0->getChain(), LN0->getBasePtr(),
4972 LN0->getMemOperand());
4973 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4974 Mask = Mask.zext(VT.getSizeInBits());
4975 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4976 ExtLoad, DAG.getConstant(Mask, VT));
4977 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4978 SDLoc(N0.getOperand(0)),
4979 N0.getOperand(0).getValueType(), ExtLoad);
4981 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4982 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4984 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4989 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4990 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4991 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4992 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4993 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4994 EVT MemVT = LN0->getMemoryVT();
4995 if ((!LegalOperations && !LN0->isVolatile()) ||
4996 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4997 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4999 LN0->getBasePtr(), MemVT,
5000 LN0->getMemOperand());
5001 CombineTo(N, ExtLoad);
5002 CombineTo(N0.getNode(),
5003 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5005 ExtLoad.getValue(1));
5006 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5010 if (N0.getOpcode() == ISD::SETCC) {
5011 if (!LegalOperations && VT.isVector() &&
5012 N0.getValueType().getVectorElementType() == MVT::i1) {
5013 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5014 // Only do this before legalize for now.
5015 EVT N0VT = N0.getOperand(0).getValueType();
5016 EVT EltVT = VT.getVectorElementType();
5017 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5018 DAG.getConstant(1, EltVT));
5019 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5020 // We know that the # elements of the results is the same as the
5021 // # elements of the compare (and the # elements of the compare result
5022 // for that matter). Check to see that they are the same size. If so,
5023 // we know that the element size of the sext'd result matches the
5024 // element size of the compare operands.
5025 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5026 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5028 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5029 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5030 &OneOps[0], OneOps.size()));
5032 // If the desired elements are smaller or larger than the source
5033 // elements we can use a matching integer vector type and then
5034 // truncate/sign extend
5035 EVT MatchingElementType =
5036 EVT::getIntegerVT(*DAG.getContext(),
5037 N0VT.getScalarType().getSizeInBits());
5038 EVT MatchingVectorType =
5039 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5040 N0VT.getVectorNumElements());
5042 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5044 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5045 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5046 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5047 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5048 &OneOps[0], OneOps.size()));
5051 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5053 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5054 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5055 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5056 if (SCC.getNode()) return SCC;
5059 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5060 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5061 isa<ConstantSDNode>(N0.getOperand(1)) &&
5062 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5064 SDValue ShAmt = N0.getOperand(1);
5065 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5066 if (N0.getOpcode() == ISD::SHL) {
5067 SDValue InnerZExt = N0.getOperand(0);
5068 // If the original shl may be shifting out bits, do not perform this
5070 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5071 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5072 if (ShAmtVal > KnownZeroBits)
5078 // Ensure that the shift amount is wide enough for the shifted value.
5079 if (VT.getSizeInBits() >= 256)
5080 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5082 return DAG.getNode(N0.getOpcode(), DL, VT,
5083 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5090 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5091 SDValue N0 = N->getOperand(0);
5092 EVT VT = N->getValueType(0);
5094 // fold (aext c1) -> c1
5095 if (isa<ConstantSDNode>(N0))
5096 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5097 // fold (aext (aext x)) -> (aext x)
5098 // fold (aext (zext x)) -> (zext x)
5099 // fold (aext (sext x)) -> (sext x)
5100 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5101 N0.getOpcode() == ISD::ZERO_EXTEND ||
5102 N0.getOpcode() == ISD::SIGN_EXTEND)
5103 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5105 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5106 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5107 if (N0.getOpcode() == ISD::TRUNCATE) {
5108 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5109 if (NarrowLoad.getNode()) {
5110 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5111 if (NarrowLoad.getNode() != N0.getNode()) {
5112 CombineTo(N0.getNode(), NarrowLoad);
5113 // CombineTo deleted the truncate, if needed, but not what's under it.
5116 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5120 // fold (aext (truncate x))
5121 if (N0.getOpcode() == ISD::TRUNCATE) {
5122 SDValue TruncOp = N0.getOperand(0);
5123 if (TruncOp.getValueType() == VT)
5124 return TruncOp; // x iff x size == zext size.
5125 if (TruncOp.getValueType().bitsGT(VT))
5126 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5127 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5130 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5131 // if the trunc is not free.
5132 if (N0.getOpcode() == ISD::AND &&
5133 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5134 N0.getOperand(1).getOpcode() == ISD::Constant &&
5135 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5136 N0.getValueType())) {
5137 SDValue X = N0.getOperand(0).getOperand(0);
5138 if (X.getValueType().bitsLT(VT)) {
5139 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5140 } else if (X.getValueType().bitsGT(VT)) {
5141 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5143 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5144 Mask = Mask.zext(VT.getSizeInBits());
5145 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5146 X, DAG.getConstant(Mask, VT));
5149 // fold (aext (load x)) -> (aext (truncate (extload x)))
5150 // None of the supported targets knows how to perform load and any_ext
5151 // on vectors in one instruction. We only perform this transformation on
5153 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5154 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5155 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5156 bool DoXform = true;
5157 SmallVector<SDNode*, 4> SetCCs;
5158 if (!N0.hasOneUse())
5159 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5161 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5162 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5164 LN0->getBasePtr(), N0.getValueType(),
5165 LN0->getMemOperand());
5166 CombineTo(N, ExtLoad);
5167 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5168 N0.getValueType(), ExtLoad);
5169 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5170 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5172 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5176 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5177 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5178 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5179 if (N0.getOpcode() == ISD::LOAD &&
5180 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5182 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5183 EVT MemVT = LN0->getMemoryVT();
5184 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5185 VT, LN0->getChain(), LN0->getBasePtr(),
5186 MemVT, LN0->getMemOperand());
5187 CombineTo(N, ExtLoad);
5188 CombineTo(N0.getNode(),
5189 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5190 N0.getValueType(), ExtLoad),
5191 ExtLoad.getValue(1));
5192 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5195 if (N0.getOpcode() == ISD::SETCC) {
5196 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5197 // Only do this before legalize for now.
5198 if (VT.isVector() && !LegalOperations) {
5199 EVT N0VT = N0.getOperand(0).getValueType();
5200 // We know that the # elements of the results is the same as the
5201 // # elements of the compare (and the # elements of the compare result
5202 // for that matter). Check to see that they are the same size. If so,
5203 // we know that the element size of the sext'd result matches the
5204 // element size of the compare operands.
5205 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5206 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5208 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5209 // If the desired elements are smaller or larger than the source
5210 // elements we can use a matching integer vector type and then
5211 // truncate/sign extend
5213 EVT MatchingElementType =
5214 EVT::getIntegerVT(*DAG.getContext(),
5215 N0VT.getScalarType().getSizeInBits());
5216 EVT MatchingVectorType =
5217 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5218 N0VT.getVectorNumElements());
5220 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5222 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5223 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5227 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5229 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5230 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5231 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5239 /// GetDemandedBits - See if the specified operand can be simplified with the
5240 /// knowledge that only the bits specified by Mask are used. If so, return the
5241 /// simpler operand, otherwise return a null SDValue.
5242 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5243 switch (V.getOpcode()) {
5245 case ISD::Constant: {
5246 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5247 assert(CV != 0 && "Const value should be ConstSDNode.");
5248 const APInt &CVal = CV->getAPIntValue();
5249 APInt NewVal = CVal & Mask;
5251 return DAG.getConstant(NewVal, V.getValueType());
5256 // If the LHS or RHS don't contribute bits to the or, drop them.
5257 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5258 return V.getOperand(1);
5259 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5260 return V.getOperand(0);
5263 // Only look at single-use SRLs.
5264 if (!V.getNode()->hasOneUse())
5266 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5267 // See if we can recursively simplify the LHS.
5268 unsigned Amt = RHSC->getZExtValue();
5270 // Watch out for shift count overflow though.
5271 if (Amt >= Mask.getBitWidth()) break;
5272 APInt NewMask = Mask << Amt;
5273 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5274 if (SimplifyLHS.getNode())
5275 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5276 SimplifyLHS, V.getOperand(1));
5282 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5283 /// bits and then truncated to a narrower type and where N is a multiple
5284 /// of number of bits of the narrower type, transform it to a narrower load
5285 /// from address + N / num of bits of new type. If the result is to be
5286 /// extended, also fold the extension to form a extending load.
5287 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5288 unsigned Opc = N->getOpcode();
5290 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5291 SDValue N0 = N->getOperand(0);
5292 EVT VT = N->getValueType(0);
5295 // This transformation isn't valid for vector loads.
5299 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5301 if (Opc == ISD::SIGN_EXTEND_INREG) {
5302 ExtType = ISD::SEXTLOAD;
5303 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5304 } else if (Opc == ISD::SRL) {
5305 // Another special-case: SRL is basically zero-extending a narrower value.
5306 ExtType = ISD::ZEXTLOAD;
5308 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5309 if (!N01) return SDValue();
5310 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5311 VT.getSizeInBits() - N01->getZExtValue());
5313 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5316 unsigned EVTBits = ExtVT.getSizeInBits();
5318 // Do not generate loads of non-round integer types since these can
5319 // be expensive (and would be wrong if the type is not byte sized).
5320 if (!ExtVT.isRound())
5324 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5325 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5326 ShAmt = N01->getZExtValue();
5327 // Is the shift amount a multiple of size of VT?
5328 if ((ShAmt & (EVTBits-1)) == 0) {
5329 N0 = N0.getOperand(0);
5330 // Is the load width a multiple of size of VT?
5331 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5335 // At this point, we must have a load or else we can't do the transform.
5336 if (!isa<LoadSDNode>(N0)) return SDValue();
5338 // Because a SRL must be assumed to *need* to zero-extend the high bits
5339 // (as opposed to anyext the high bits), we can't combine the zextload
5340 // lowering of SRL and an sextload.
5341 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5344 // If the shift amount is larger than the input type then we're not
5345 // accessing any of the loaded bytes. If the load was a zextload/extload
5346 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5347 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5352 // If the load is shifted left (and the result isn't shifted back right),
5353 // we can fold the truncate through the shift.
5354 unsigned ShLeftAmt = 0;
5355 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5356 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5357 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5358 ShLeftAmt = N01->getZExtValue();
5359 N0 = N0.getOperand(0);
5363 // If we haven't found a load, we can't narrow it. Don't transform one with
5364 // multiple uses, this would require adding a new load.
5365 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5368 // Don't change the width of a volatile load.
5369 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5370 if (LN0->isVolatile())
5373 // Verify that we are actually reducing a load width here.
5374 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5377 // For the transform to be legal, the load must produce only two values
5378 // (the value loaded and the chain). Don't transform a pre-increment
5379 // load, for example, which produces an extra value. Otherwise the
5380 // transformation is not equivalent, and the downstream logic to replace
5381 // uses gets things wrong.
5382 if (LN0->getNumValues() > 2)
5385 // If the load that we're shrinking is an extload and we're not just
5386 // discarding the extension we can't simply shrink the load. Bail.
5387 // TODO: It would be possible to merge the extensions in some cases.
5388 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5389 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5392 EVT PtrType = N0.getOperand(1).getValueType();
5394 if (PtrType == MVT::Untyped || PtrType.isExtended())
5395 // It's not possible to generate a constant of extended or untyped type.
5398 // For big endian targets, we need to adjust the offset to the pointer to
5399 // load the correct bytes.
5400 if (TLI.isBigEndian()) {
5401 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5402 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5403 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5406 uint64_t PtrOff = ShAmt / 8;
5407 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5408 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5409 PtrType, LN0->getBasePtr(),
5410 DAG.getConstant(PtrOff, PtrType));
5411 AddToWorkList(NewPtr.getNode());
5414 if (ExtType == ISD::NON_EXTLOAD)
5415 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5416 LN0->getPointerInfo().getWithOffset(PtrOff),
5417 LN0->isVolatile(), LN0->isNonTemporal(),
5418 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5420 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5421 LN0->getPointerInfo().getWithOffset(PtrOff),
5422 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5423 NewAlign, LN0->getTBAAInfo());
5425 // Replace the old load's chain with the new load's chain.
5426 WorkListRemover DeadNodes(*this);
5427 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5429 // Shift the result left, if we've swallowed a left shift.
5430 SDValue Result = Load;
5431 if (ShLeftAmt != 0) {
5432 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5433 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5435 // If the shift amount is as large as the result size (but, presumably,
5436 // no larger than the source) then the useful bits of the result are
5437 // zero; we can't simply return the shortened shift, because the result
5438 // of that operation is undefined.
5439 if (ShLeftAmt >= VT.getSizeInBits())
5440 Result = DAG.getConstant(0, VT);
5442 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5443 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5446 // Return the new loaded value.
5450 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5451 SDValue N0 = N->getOperand(0);
5452 SDValue N1 = N->getOperand(1);
5453 EVT VT = N->getValueType(0);
5454 EVT EVT = cast<VTSDNode>(N1)->getVT();
5455 unsigned VTBits = VT.getScalarType().getSizeInBits();
5456 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5458 // fold (sext_in_reg c1) -> c1
5459 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5460 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5462 // If the input is already sign extended, just drop the extension.
5463 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5466 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5467 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5468 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5469 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5470 N0.getOperand(0), N1);
5472 // fold (sext_in_reg (sext x)) -> (sext x)
5473 // fold (sext_in_reg (aext x)) -> (sext x)
5474 // if x is small enough.
5475 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5476 SDValue N00 = N0.getOperand(0);
5477 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5478 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5479 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5482 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5483 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5484 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5486 // fold operands of sext_in_reg based on knowledge that the top bits are not
5488 if (SimplifyDemandedBits(SDValue(N, 0)))
5489 return SDValue(N, 0);
5491 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5492 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5493 SDValue NarrowLoad = ReduceLoadWidth(N);
5494 if (NarrowLoad.getNode())
5497 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5498 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5499 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5500 if (N0.getOpcode() == ISD::SRL) {
5501 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5502 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5503 // We can turn this into an SRA iff the input to the SRL is already sign
5505 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5506 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5507 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5508 N0.getOperand(0), N0.getOperand(1));
5512 // fold (sext_inreg (extload x)) -> (sextload x)
5513 if (ISD::isEXTLoad(N0.getNode()) &&
5514 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5515 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5516 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5517 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5518 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5519 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5521 LN0->getBasePtr(), EVT,
5522 LN0->getMemOperand());
5523 CombineTo(N, ExtLoad);
5524 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5525 AddToWorkList(ExtLoad.getNode());
5526 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5528 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5529 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5531 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5532 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5533 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5534 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5535 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5537 LN0->getBasePtr(), EVT,
5538 LN0->getMemOperand());
5539 CombineTo(N, ExtLoad);
5540 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5541 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5544 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5545 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5546 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5547 N0.getOperand(1), false);
5548 if (BSwap.getNode() != 0)
5549 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5553 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5554 // into a build_vector.
5555 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5556 SmallVector<SDValue, 8> Elts;
5557 unsigned NumElts = N0->getNumOperands();
5558 unsigned ShAmt = VTBits - EVTBits;
5560 for (unsigned i = 0; i != NumElts; ++i) {
5561 SDValue Op = N0->getOperand(i);
5562 if (Op->getOpcode() == ISD::UNDEF) {
5567 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5568 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5569 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5570 Op.getValueType()));
5573 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5579 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5580 SDValue N0 = N->getOperand(0);
5581 EVT VT = N->getValueType(0);
5582 bool isLE = TLI.isLittleEndian();
5585 if (N0.getValueType() == N->getValueType(0))
5587 // fold (truncate c1) -> c1
5588 if (isa<ConstantSDNode>(N0))
5589 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5590 // fold (truncate (truncate x)) -> (truncate x)
5591 if (N0.getOpcode() == ISD::TRUNCATE)
5592 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5593 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5594 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5595 N0.getOpcode() == ISD::SIGN_EXTEND ||
5596 N0.getOpcode() == ISD::ANY_EXTEND) {
5597 if (N0.getOperand(0).getValueType().bitsLT(VT))
5598 // if the source is smaller than the dest, we still need an extend
5599 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5601 if (N0.getOperand(0).getValueType().bitsGT(VT))
5602 // if the source is larger than the dest, than we just need the truncate
5603 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5604 // if the source and dest are the same type, we can drop both the extend
5605 // and the truncate.
5606 return N0.getOperand(0);
5609 // Fold extract-and-trunc into a narrow extract. For example:
5610 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5611 // i32 y = TRUNCATE(i64 x)
5613 // v16i8 b = BITCAST (v2i64 val)
5614 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5616 // Note: We only run this optimization after type legalization (which often
5617 // creates this pattern) and before operation legalization after which
5618 // we need to be more careful about the vector instructions that we generate.
5619 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5620 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5622 EVT VecTy = N0.getOperand(0).getValueType();
5623 EVT ExTy = N0.getValueType();
5624 EVT TrTy = N->getValueType(0);
5626 unsigned NumElem = VecTy.getVectorNumElements();
5627 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5629 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5630 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5632 SDValue EltNo = N0->getOperand(1);
5633 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5634 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5635 EVT IndexTy = TLI.getVectorIdxTy();
5636 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5638 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5639 NVT, N0.getOperand(0));
5641 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5643 DAG.getConstant(Index, IndexTy));
5647 // Fold a series of buildvector, bitcast, and truncate if possible.
5649 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5650 // (2xi32 (buildvector x, y)).
5651 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5652 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5653 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5654 N0.getOperand(0).hasOneUse()) {
5656 SDValue BuildVect = N0.getOperand(0);
5657 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5658 EVT TruncVecEltTy = VT.getVectorElementType();
5660 // Check that the element types match.
5661 if (BuildVectEltTy == TruncVecEltTy) {
5662 // Now we only need to compute the offset of the truncated elements.
5663 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5664 unsigned TruncVecNumElts = VT.getVectorNumElements();
5665 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5667 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5668 "Invalid number of elements");
5670 SmallVector<SDValue, 8> Opnds;
5671 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5672 Opnds.push_back(BuildVect.getOperand(i));
5674 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5679 // See if we can simplify the input to this truncate through knowledge that
5680 // only the low bits are being used.
5681 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5682 // Currently we only perform this optimization on scalars because vectors
5683 // may have different active low bits.
5684 if (!VT.isVector()) {
5686 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5687 VT.getSizeInBits()));
5688 if (Shorter.getNode())
5689 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5691 // fold (truncate (load x)) -> (smaller load x)
5692 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5693 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5694 SDValue Reduced = ReduceLoadWidth(N);
5695 if (Reduced.getNode())
5697 // Handle the case where the load remains an extending load even
5698 // after truncation.
5699 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5700 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5701 if (!LN0->isVolatile() &&
5702 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5703 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5704 VT, LN0->getChain(), LN0->getBasePtr(),
5706 LN0->getMemOperand());
5707 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5712 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5713 // where ... are all 'undef'.
5714 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5715 SmallVector<EVT, 8> VTs;
5718 unsigned NumDefs = 0;
5720 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5721 SDValue X = N0.getOperand(i);
5722 if (X.getOpcode() != ISD::UNDEF) {
5727 // Stop if more than one members are non-undef.
5730 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5731 VT.getVectorElementType(),
5732 X.getValueType().getVectorNumElements()));
5736 return DAG.getUNDEF(VT);
5739 assert(V.getNode() && "The single defined operand is empty!");
5740 SmallVector<SDValue, 8> Opnds;
5741 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5743 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5746 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5747 AddToWorkList(NV.getNode());
5748 Opnds.push_back(NV);
5750 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5751 &Opnds[0], Opnds.size());
5755 // Simplify the operands using demanded-bits information.
5756 if (!VT.isVector() &&
5757 SimplifyDemandedBits(SDValue(N, 0)))
5758 return SDValue(N, 0);
5763 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5764 SDValue Elt = N->getOperand(i);
5765 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5766 return Elt.getNode();
5767 return Elt.getOperand(Elt.getResNo()).getNode();
5770 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5771 /// if load locations are consecutive.
5772 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5773 assert(N->getOpcode() == ISD::BUILD_PAIR);
5775 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5776 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5777 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5778 LD1->getPointerInfo().getAddrSpace() !=
5779 LD2->getPointerInfo().getAddrSpace())
5781 EVT LD1VT = LD1->getValueType(0);
5783 if (ISD::isNON_EXTLoad(LD2) &&
5785 // If both are volatile this would reduce the number of volatile loads.
5786 // If one is volatile it might be ok, but play conservative and bail out.
5787 !LD1->isVolatile() &&
5788 !LD2->isVolatile() &&
5789 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5790 unsigned Align = LD1->getAlignment();
5791 unsigned NewAlign = TLI.getDataLayout()->
5792 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5794 if (NewAlign <= Align &&
5795 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5796 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5797 LD1->getBasePtr(), LD1->getPointerInfo(),
5798 false, false, false, Align);
5804 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5805 SDValue N0 = N->getOperand(0);
5806 EVT VT = N->getValueType(0);
5808 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5809 // Only do this before legalize, since afterward the target may be depending
5810 // on the bitconvert.
5811 // First check to see if this is all constant.
5813 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5815 bool isSimple = true;
5816 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5817 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5818 N0.getOperand(i).getOpcode() != ISD::Constant &&
5819 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5824 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5825 assert(!DestEltVT.isVector() &&
5826 "Element type of vector ValueType must not be vector!");
5828 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5831 // If the input is a constant, let getNode fold it.
5832 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5833 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5834 if (Res.getNode() != N) {
5835 if (!LegalOperations ||
5836 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5839 // Folding it resulted in an illegal node, and it's too late to
5840 // do that. Clean up the old node and forego the transformation.
5841 // Ideally this won't happen very often, because instcombine
5842 // and the earlier dagcombine runs (where illegal nodes are
5843 // permitted) should have folded most of them already.
5844 DAG.DeleteNode(Res.getNode());
5848 // (conv (conv x, t1), t2) -> (conv x, t2)
5849 if (N0.getOpcode() == ISD::BITCAST)
5850 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5853 // fold (conv (load x)) -> (load (conv*)x)
5854 // If the resultant load doesn't need a higher alignment than the original!
5855 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5856 // Do not change the width of a volatile load.
5857 !cast<LoadSDNode>(N0)->isVolatile() &&
5858 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5859 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5860 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861 unsigned Align = TLI.getDataLayout()->
5862 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5863 unsigned OrigAlign = LN0->getAlignment();
5865 if (Align <= OrigAlign) {
5866 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5867 LN0->getBasePtr(), LN0->getPointerInfo(),
5868 LN0->isVolatile(), LN0->isNonTemporal(),
5869 LN0->isInvariant(), OrigAlign,
5870 LN0->getTBAAInfo());
5872 CombineTo(N0.getNode(),
5873 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5874 N0.getValueType(), Load),
5880 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5881 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5882 // This often reduces constant pool loads.
5883 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5884 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5885 N0.getNode()->hasOneUse() && VT.isInteger() &&
5886 !VT.isVector() && !N0.getValueType().isVector()) {
5887 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5889 AddToWorkList(NewConv.getNode());
5891 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5892 if (N0.getOpcode() == ISD::FNEG)
5893 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5894 NewConv, DAG.getConstant(SignBit, VT));
5895 assert(N0.getOpcode() == ISD::FABS);
5896 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5897 NewConv, DAG.getConstant(~SignBit, VT));
5900 // fold (bitconvert (fcopysign cst, x)) ->
5901 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5902 // Note that we don't handle (copysign x, cst) because this can always be
5903 // folded to an fneg or fabs.
5904 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5905 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5906 VT.isInteger() && !VT.isVector()) {
5907 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5908 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5909 if (isTypeLegal(IntXVT)) {
5910 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5911 IntXVT, N0.getOperand(1));
5912 AddToWorkList(X.getNode());
5914 // If X has a different width than the result/lhs, sext it or truncate it.
5915 unsigned VTWidth = VT.getSizeInBits();
5916 if (OrigXWidth < VTWidth) {
5917 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5918 AddToWorkList(X.getNode());
5919 } else if (OrigXWidth > VTWidth) {
5920 // To get the sign bit in the right place, we have to shift it right
5921 // before truncating.
5922 X = DAG.getNode(ISD::SRL, SDLoc(X),
5923 X.getValueType(), X,
5924 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5925 AddToWorkList(X.getNode());
5926 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5927 AddToWorkList(X.getNode());
5930 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5931 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5932 X, DAG.getConstant(SignBit, VT));
5933 AddToWorkList(X.getNode());
5935 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5936 VT, N0.getOperand(0));
5937 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5938 Cst, DAG.getConstant(~SignBit, VT));
5939 AddToWorkList(Cst.getNode());
5941 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5945 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5946 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5947 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5948 if (CombineLD.getNode())
5955 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5956 EVT VT = N->getValueType(0);
5957 return CombineConsecutiveLoads(N, VT);
5960 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5961 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5962 /// destination element value type.
5963 SDValue DAGCombiner::
5964 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5965 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5967 // If this is already the right type, we're done.
5968 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5970 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5971 unsigned DstBitSize = DstEltVT.getSizeInBits();
5973 // If this is a conversion of N elements of one type to N elements of another
5974 // type, convert each element. This handles FP<->INT cases.
5975 if (SrcBitSize == DstBitSize) {
5976 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5977 BV->getValueType(0).getVectorNumElements());
5979 // Due to the FP element handling below calling this routine recursively,
5980 // we can end up with a scalar-to-vector node here.
5981 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5982 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5983 DAG.getNode(ISD::BITCAST, SDLoc(BV),
5984 DstEltVT, BV->getOperand(0)));
5986 SmallVector<SDValue, 8> Ops;
5987 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5988 SDValue Op = BV->getOperand(i);
5989 // If the vector element type is not legal, the BUILD_VECTOR operands
5990 // are promoted and implicitly truncated. Make that explicit here.
5991 if (Op.getValueType() != SrcEltVT)
5992 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5993 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5995 AddToWorkList(Ops.back().getNode());
5997 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5998 &Ops[0], Ops.size());
6001 // Otherwise, we're growing or shrinking the elements. To avoid having to
6002 // handle annoying details of growing/shrinking FP values, we convert them to
6004 if (SrcEltVT.isFloatingPoint()) {
6005 // Convert the input float vector to a int vector where the elements are the
6007 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6008 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6009 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6013 // Now we know the input is an integer vector. If the output is a FP type,
6014 // convert to integer first, then to FP of the right size.
6015 if (DstEltVT.isFloatingPoint()) {
6016 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6017 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6018 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6020 // Next, convert to FP elements of the same size.
6021 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6024 // Okay, we know the src/dst types are both integers of differing types.
6025 // Handling growing first.
6026 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6027 if (SrcBitSize < DstBitSize) {
6028 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6030 SmallVector<SDValue, 8> Ops;
6031 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6032 i += NumInputsPerOutput) {
6033 bool isLE = TLI.isLittleEndian();
6034 APInt NewBits = APInt(DstBitSize, 0);
6035 bool EltIsUndef = true;
6036 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6037 // Shift the previously computed bits over.
6038 NewBits <<= SrcBitSize;
6039 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6040 if (Op.getOpcode() == ISD::UNDEF) continue;
6043 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6044 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6048 Ops.push_back(DAG.getUNDEF(DstEltVT));
6050 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6053 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6054 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6055 &Ops[0], Ops.size());
6058 // Finally, this must be the case where we are shrinking elements: each input
6059 // turns into multiple outputs.
6060 bool isS2V = ISD::isScalarToVector(BV);
6061 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6062 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6063 NumOutputsPerInput*BV->getNumOperands());
6064 SmallVector<SDValue, 8> Ops;
6066 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6067 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6068 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6069 Ops.push_back(DAG.getUNDEF(DstEltVT));
6073 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6074 getAPIntValue().zextOrTrunc(SrcBitSize);
6076 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6077 APInt ThisVal = OpVal.trunc(DstBitSize);
6078 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6079 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6080 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6081 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6083 OpVal = OpVal.lshr(DstBitSize);
6086 // For big endian targets, swap the order of the pieces of each element.
6087 if (TLI.isBigEndian())
6088 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6091 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6092 &Ops[0], Ops.size());
6095 SDValue DAGCombiner::visitFADD(SDNode *N) {
6096 SDValue N0 = N->getOperand(0);
6097 SDValue N1 = N->getOperand(1);
6098 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6099 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6100 EVT VT = N->getValueType(0);
6103 if (VT.isVector()) {
6104 SDValue FoldedVOp = SimplifyVBinOp(N);
6105 if (FoldedVOp.getNode()) return FoldedVOp;
6108 // fold (fadd c1, c2) -> c1 + c2
6110 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6111 // canonicalize constant to RHS
6112 if (N0CFP && !N1CFP)
6113 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6114 // fold (fadd A, 0) -> A
6115 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6116 N1CFP->getValueAPF().isZero())
6118 // fold (fadd A, (fneg B)) -> (fsub A, B)
6119 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6120 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6121 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6122 GetNegatedExpression(N1, DAG, LegalOperations));
6123 // fold (fadd (fneg A), B) -> (fsub B, A)
6124 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6125 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6126 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6127 GetNegatedExpression(N0, DAG, LegalOperations));
6129 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6130 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6131 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6132 isa<ConstantFPSDNode>(N0.getOperand(1)))
6133 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6134 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6135 N0.getOperand(1), N1));
6137 // No FP constant should be created after legalization as Instruction
6138 // Selection pass has hard time in dealing with FP constant.
6140 // We don't need test this condition for transformation like following, as
6141 // the DAG being transformed implies it is legal to take FP constant as
6144 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6146 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6148 // If allow, fold (fadd (fneg x), x) -> 0.0
6149 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6150 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6151 return DAG.getConstantFP(0.0, VT);
6153 // If allow, fold (fadd x, (fneg x)) -> 0.0
6154 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6155 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6156 return DAG.getConstantFP(0.0, VT);
6158 // In unsafe math mode, we can fold chains of FADD's of the same value
6159 // into multiplications. This transform is not safe in general because
6160 // we are reducing the number of rounding steps.
6161 if (DAG.getTarget().Options.UnsafeFPMath &&
6162 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6164 if (N0.getOpcode() == ISD::FMUL) {
6165 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6166 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6168 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6169 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6170 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6172 DAG.getConstantFP(1.0, VT));
6173 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6177 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6178 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6179 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6181 DAG.getConstantFP(1.0, VT));
6182 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6186 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6187 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6188 N1.getOperand(0) == N1.getOperand(1) &&
6189 N0.getOperand(1) == N1.getOperand(0)) {
6190 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6192 DAG.getConstantFP(2.0, VT));
6193 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6194 N0.getOperand(1), NewCFP);
6197 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6198 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6199 N1.getOperand(0) == N1.getOperand(1) &&
6200 N0.getOperand(0) == N1.getOperand(0)) {
6201 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6203 DAG.getConstantFP(2.0, VT));
6204 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6205 N0.getOperand(0), NewCFP);
6209 if (N1.getOpcode() == ISD::FMUL) {
6210 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6211 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6213 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6214 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6215 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6217 DAG.getConstantFP(1.0, VT));
6218 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6222 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6223 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6224 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6226 DAG.getConstantFP(1.0, VT));
6227 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6232 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6233 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6234 N0.getOperand(0) == N0.getOperand(1) &&
6235 N1.getOperand(1) == N0.getOperand(0)) {
6236 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6238 DAG.getConstantFP(2.0, VT));
6239 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6240 N1.getOperand(1), NewCFP);
6243 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6244 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6245 N0.getOperand(0) == N0.getOperand(1) &&
6246 N1.getOperand(0) == N0.getOperand(0)) {
6247 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6249 DAG.getConstantFP(2.0, VT));
6250 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6251 N1.getOperand(0), NewCFP);
6255 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6256 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6257 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6258 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6259 (N0.getOperand(0) == N1))
6260 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6261 N1, DAG.getConstantFP(3.0, VT));
6264 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6265 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6266 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6267 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6268 N1.getOperand(0) == N0)
6269 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6270 N0, DAG.getConstantFP(3.0, VT));
6273 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6274 if (AllowNewFpConst &&
6275 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6276 N0.getOperand(0) == N0.getOperand(1) &&
6277 N1.getOperand(0) == N1.getOperand(1) &&
6278 N0.getOperand(0) == N1.getOperand(0))
6279 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6281 DAG.getConstantFP(4.0, VT));
6284 // FADD -> FMA combines:
6285 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6286 DAG.getTarget().Options.UnsafeFPMath) &&
6287 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6288 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6290 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6291 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6292 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6293 N0.getOperand(0), N0.getOperand(1), N1);
6295 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6296 // Note: Commutes FADD operands.
6297 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6298 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6299 N1.getOperand(0), N1.getOperand(1), N0);
6305 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6306 SDValue N0 = N->getOperand(0);
6307 SDValue N1 = N->getOperand(1);
6308 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6309 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6310 EVT VT = N->getValueType(0);
6314 if (VT.isVector()) {
6315 SDValue FoldedVOp = SimplifyVBinOp(N);
6316 if (FoldedVOp.getNode()) return FoldedVOp;
6319 // fold (fsub c1, c2) -> c1-c2
6321 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6322 // fold (fsub A, 0) -> A
6323 if (DAG.getTarget().Options.UnsafeFPMath &&
6324 N1CFP && N1CFP->getValueAPF().isZero())
6326 // fold (fsub 0, B) -> -B
6327 if (DAG.getTarget().Options.UnsafeFPMath &&
6328 N0CFP && N0CFP->getValueAPF().isZero()) {
6329 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6330 return GetNegatedExpression(N1, DAG, LegalOperations);
6331 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6332 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6334 // fold (fsub A, (fneg B)) -> (fadd A, B)
6335 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6336 return DAG.getNode(ISD::FADD, dl, VT, N0,
6337 GetNegatedExpression(N1, DAG, LegalOperations));
6339 // If 'unsafe math' is enabled, fold
6340 // (fsub x, x) -> 0.0 &
6341 // (fsub x, (fadd x, y)) -> (fneg y) &
6342 // (fsub x, (fadd y, x)) -> (fneg y)
6343 if (DAG.getTarget().Options.UnsafeFPMath) {
6345 return DAG.getConstantFP(0.0f, VT);
6347 if (N1.getOpcode() == ISD::FADD) {
6348 SDValue N10 = N1->getOperand(0);
6349 SDValue N11 = N1->getOperand(1);
6351 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6352 &DAG.getTarget().Options))
6353 return GetNegatedExpression(N11, DAG, LegalOperations);
6355 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6356 &DAG.getTarget().Options))
6357 return GetNegatedExpression(N10, DAG, LegalOperations);
6361 // FSUB -> FMA combines:
6362 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6363 DAG.getTarget().Options.UnsafeFPMath) &&
6364 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6365 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6367 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6368 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6369 return DAG.getNode(ISD::FMA, dl, VT,
6370 N0.getOperand(0), N0.getOperand(1),
6371 DAG.getNode(ISD::FNEG, dl, VT, N1));
6373 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6374 // Note: Commutes FSUB operands.
6375 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6376 return DAG.getNode(ISD::FMA, dl, VT,
6377 DAG.getNode(ISD::FNEG, dl, VT,
6379 N1.getOperand(1), N0);
6381 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6382 if (N0.getOpcode() == ISD::FNEG &&
6383 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6384 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6385 SDValue N00 = N0.getOperand(0).getOperand(0);
6386 SDValue N01 = N0.getOperand(0).getOperand(1);
6387 return DAG.getNode(ISD::FMA, dl, VT,
6388 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6389 DAG.getNode(ISD::FNEG, dl, VT, N1));
6396 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6397 SDValue N0 = N->getOperand(0);
6398 SDValue N1 = N->getOperand(1);
6399 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6400 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6401 EVT VT = N->getValueType(0);
6402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6405 if (VT.isVector()) {
6406 SDValue FoldedVOp = SimplifyVBinOp(N);
6407 if (FoldedVOp.getNode()) return FoldedVOp;
6410 // fold (fmul c1, c2) -> c1*c2
6412 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6413 // canonicalize constant to RHS
6414 if (N0CFP && !N1CFP)
6415 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6416 // fold (fmul A, 0) -> 0
6417 if (DAG.getTarget().Options.UnsafeFPMath &&
6418 N1CFP && N1CFP->getValueAPF().isZero())
6420 // fold (fmul A, 0) -> 0, vector edition.
6421 if (DAG.getTarget().Options.UnsafeFPMath &&
6422 ISD::isBuildVectorAllZeros(N1.getNode()))
6424 // fold (fmul A, 1.0) -> A
6425 if (N1CFP && N1CFP->isExactlyValue(1.0))
6427 // fold (fmul X, 2.0) -> (fadd X, X)
6428 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6429 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6430 // fold (fmul X, -1.0) -> (fneg X)
6431 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6432 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6433 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6435 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6436 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6437 &DAG.getTarget().Options)) {
6438 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6439 &DAG.getTarget().Options)) {
6440 // Both can be negated for free, check to see if at least one is cheaper
6442 if (LHSNeg == 2 || RHSNeg == 2)
6443 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6444 GetNegatedExpression(N0, DAG, LegalOperations),
6445 GetNegatedExpression(N1, DAG, LegalOperations));
6449 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6450 if (DAG.getTarget().Options.UnsafeFPMath &&
6451 N1CFP && N0.getOpcode() == ISD::FMUL &&
6452 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6453 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6454 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6455 N0.getOperand(1), N1));
6460 SDValue DAGCombiner::visitFMA(SDNode *N) {
6461 SDValue N0 = N->getOperand(0);
6462 SDValue N1 = N->getOperand(1);
6463 SDValue N2 = N->getOperand(2);
6464 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6465 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6466 EVT VT = N->getValueType(0);
6469 if (DAG.getTarget().Options.UnsafeFPMath) {
6470 if (N0CFP && N0CFP->isZero())
6472 if (N1CFP && N1CFP->isZero())
6475 if (N0CFP && N0CFP->isExactlyValue(1.0))
6476 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6477 if (N1CFP && N1CFP->isExactlyValue(1.0))
6478 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6480 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6481 if (N0CFP && !N1CFP)
6482 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6484 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6485 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6486 N2.getOpcode() == ISD::FMUL &&
6487 N0 == N2.getOperand(0) &&
6488 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6489 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6490 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6494 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6495 if (DAG.getTarget().Options.UnsafeFPMath &&
6496 N0.getOpcode() == ISD::FMUL && N1CFP &&
6497 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6498 return DAG.getNode(ISD::FMA, dl, VT,
6500 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6504 // (fma x, 1, y) -> (fadd x, y)
6505 // (fma x, -1, y) -> (fadd (fneg x), y)
6507 if (N1CFP->isExactlyValue(1.0))
6508 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6510 if (N1CFP->isExactlyValue(-1.0) &&
6511 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6512 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6513 AddToWorkList(RHSNeg.getNode());
6514 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6518 // (fma x, c, x) -> (fmul x, (c+1))
6519 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6520 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6521 DAG.getNode(ISD::FADD, dl, VT,
6522 N1, DAG.getConstantFP(1.0, VT)));
6524 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6525 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6526 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6527 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6528 DAG.getNode(ISD::FADD, dl, VT,
6529 N1, DAG.getConstantFP(-1.0, VT)));
6535 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6536 SDValue N0 = N->getOperand(0);
6537 SDValue N1 = N->getOperand(1);
6538 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6539 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6540 EVT VT = N->getValueType(0);
6541 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6544 if (VT.isVector()) {
6545 SDValue FoldedVOp = SimplifyVBinOp(N);
6546 if (FoldedVOp.getNode()) return FoldedVOp;
6549 // fold (fdiv c1, c2) -> c1/c2
6551 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6553 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6554 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6555 // Compute the reciprocal 1.0 / c2.
6556 APFloat N1APF = N1CFP->getValueAPF();
6557 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6558 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6559 // Only do the transform if the reciprocal is a legal fp immediate that
6560 // isn't too nasty (eg NaN, denormal, ...).
6561 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6562 (!LegalOperations ||
6563 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6564 // backend)... we should handle this gracefully after Legalize.
6565 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6566 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6567 TLI.isFPImmLegal(Recip, VT)))
6568 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6569 DAG.getConstantFP(Recip, VT));
6572 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6573 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6574 &DAG.getTarget().Options)) {
6575 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6576 &DAG.getTarget().Options)) {
6577 // Both can be negated for free, check to see if at least one is cheaper
6579 if (LHSNeg == 2 || RHSNeg == 2)
6580 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6581 GetNegatedExpression(N0, DAG, LegalOperations),
6582 GetNegatedExpression(N1, DAG, LegalOperations));
6589 SDValue DAGCombiner::visitFREM(SDNode *N) {
6590 SDValue N0 = N->getOperand(0);
6591 SDValue N1 = N->getOperand(1);
6592 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6593 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6594 EVT VT = N->getValueType(0);
6596 // fold (frem c1, c2) -> fmod(c1,c2)
6598 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6603 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6604 SDValue N0 = N->getOperand(0);
6605 SDValue N1 = N->getOperand(1);
6606 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6607 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6608 EVT VT = N->getValueType(0);
6610 if (N0CFP && N1CFP) // Constant fold
6611 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6614 const APFloat& V = N1CFP->getValueAPF();
6615 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6616 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6617 if (!V.isNegative()) {
6618 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6619 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6621 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6622 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6623 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6627 // copysign(fabs(x), y) -> copysign(x, y)
6628 // copysign(fneg(x), y) -> copysign(x, y)
6629 // copysign(copysign(x,z), y) -> copysign(x, y)
6630 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6631 N0.getOpcode() == ISD::FCOPYSIGN)
6632 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6633 N0.getOperand(0), N1);
6635 // copysign(x, abs(y)) -> abs(x)
6636 if (N1.getOpcode() == ISD::FABS)
6637 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6639 // copysign(x, copysign(y,z)) -> copysign(x, z)
6640 if (N1.getOpcode() == ISD::FCOPYSIGN)
6641 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6642 N0, N1.getOperand(1));
6644 // copysign(x, fp_extend(y)) -> copysign(x, y)
6645 // copysign(x, fp_round(y)) -> copysign(x, y)
6646 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6647 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6648 N0, N1.getOperand(0));
6653 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6654 SDValue N0 = N->getOperand(0);
6655 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6656 EVT VT = N->getValueType(0);
6657 EVT OpVT = N0.getValueType();
6659 // fold (sint_to_fp c1) -> c1fp
6661 // ...but only if the target supports immediate floating-point values
6662 (!LegalOperations ||
6663 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6664 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6666 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6667 // but UINT_TO_FP is legal on this target, try to convert.
6668 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6669 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6670 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6671 if (DAG.SignBitIsZero(N0))
6672 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6675 // The next optimizations are desireable only if SELECT_CC can be lowered.
6676 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6677 // having to say they don't support SELECT_CC on every type the DAG knows
6678 // about, since there is no way to mark an opcode illegal at all value types
6679 // (See also visitSELECT)
6680 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6681 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6682 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6684 (!LegalOperations ||
6685 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6687 { N0.getOperand(0), N0.getOperand(1),
6688 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6690 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6693 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6694 // (select_cc x, y, 1.0, 0.0,, cc)
6695 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6696 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6697 (!LegalOperations ||
6698 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6700 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6701 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6702 N0.getOperand(0).getOperand(2) };
6703 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6710 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6711 SDValue N0 = N->getOperand(0);
6712 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6713 EVT VT = N->getValueType(0);
6714 EVT OpVT = N0.getValueType();
6716 // fold (uint_to_fp c1) -> c1fp
6718 // ...but only if the target supports immediate floating-point values
6719 (!LegalOperations ||
6720 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6721 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6723 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6724 // but SINT_TO_FP is legal on this target, try to convert.
6725 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6726 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6727 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6728 if (DAG.SignBitIsZero(N0))
6729 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6732 // The next optimizations are desireable only if SELECT_CC can be lowered.
6733 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6734 // having to say they don't support SELECT_CC on every type the DAG knows
6735 // about, since there is no way to mark an opcode illegal at all value types
6736 // (See also visitSELECT)
6737 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6738 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6740 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6741 (!LegalOperations ||
6742 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6744 { N0.getOperand(0), N0.getOperand(1),
6745 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6747 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6754 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6755 SDValue N0 = N->getOperand(0);
6756 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6757 EVT VT = N->getValueType(0);
6759 // fold (fp_to_sint c1fp) -> c1
6761 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6766 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6767 SDValue N0 = N->getOperand(0);
6768 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6769 EVT VT = N->getValueType(0);
6771 // fold (fp_to_uint c1fp) -> c1
6773 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6778 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6779 SDValue N0 = N->getOperand(0);
6780 SDValue N1 = N->getOperand(1);
6781 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6782 EVT VT = N->getValueType(0);
6784 // fold (fp_round c1fp) -> c1fp
6786 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6788 // fold (fp_round (fp_extend x)) -> x
6789 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6790 return N0.getOperand(0);
6792 // fold (fp_round (fp_round x)) -> (fp_round x)
6793 if (N0.getOpcode() == ISD::FP_ROUND) {
6794 // This is a value preserving truncation if both round's are.
6795 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6796 N0.getNode()->getConstantOperandVal(1) == 1;
6797 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6798 DAG.getIntPtrConstant(IsTrunc));
6801 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6802 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6803 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6804 N0.getOperand(0), N1);
6805 AddToWorkList(Tmp.getNode());
6806 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6807 Tmp, N0.getOperand(1));
6813 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6814 SDValue N0 = N->getOperand(0);
6815 EVT VT = N->getValueType(0);
6816 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6817 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6819 // fold (fp_round_inreg c1fp) -> c1fp
6820 if (N0CFP && isTypeLegal(EVT)) {
6821 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6822 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6828 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6829 SDValue N0 = N->getOperand(0);
6830 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6831 EVT VT = N->getValueType(0);
6833 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6834 if (N->hasOneUse() &&
6835 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6838 // fold (fp_extend c1fp) -> c1fp
6840 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6842 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6844 if (N0.getOpcode() == ISD::FP_ROUND
6845 && N0.getNode()->getConstantOperandVal(1) == 1) {
6846 SDValue In = N0.getOperand(0);
6847 if (In.getValueType() == VT) return In;
6848 if (VT.bitsLT(In.getValueType()))
6849 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6850 In, N0.getOperand(1));
6851 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6854 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6855 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6856 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6857 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6858 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6859 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6861 LN0->getBasePtr(), N0.getValueType(),
6862 LN0->getMemOperand());
6863 CombineTo(N, ExtLoad);
6864 CombineTo(N0.getNode(),
6865 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6866 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6867 ExtLoad.getValue(1));
6868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6874 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6875 SDValue N0 = N->getOperand(0);
6876 EVT VT = N->getValueType(0);
6878 if (VT.isVector()) {
6879 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6880 if (FoldedVOp.getNode()) return FoldedVOp;
6883 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6884 &DAG.getTarget().Options))
6885 return GetNegatedExpression(N0, DAG, LegalOperations);
6887 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6888 // constant pool values.
6889 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6891 N0.getNode()->hasOneUse() &&
6892 N0.getOperand(0).getValueType().isInteger()) {
6893 SDValue Int = N0.getOperand(0);
6894 EVT IntVT = Int.getValueType();
6895 if (IntVT.isInteger() && !IntVT.isVector()) {
6896 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6897 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6898 AddToWorkList(Int.getNode());
6899 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6904 // (fneg (fmul c, x)) -> (fmul -c, x)
6905 if (N0.getOpcode() == ISD::FMUL) {
6906 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6908 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6910 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6917 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6918 SDValue N0 = N->getOperand(0);
6919 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6920 EVT VT = N->getValueType(0);
6922 // fold (fceil c1) -> fceil(c1)
6924 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6929 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6930 SDValue N0 = N->getOperand(0);
6931 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6932 EVT VT = N->getValueType(0);
6934 // fold (ftrunc c1) -> ftrunc(c1)
6936 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6941 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6942 SDValue N0 = N->getOperand(0);
6943 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6944 EVT VT = N->getValueType(0);
6946 // fold (ffloor c1) -> ffloor(c1)
6948 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6953 SDValue DAGCombiner::visitFABS(SDNode *N) {
6954 SDValue N0 = N->getOperand(0);
6955 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6956 EVT VT = N->getValueType(0);
6958 if (VT.isVector()) {
6959 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6960 if (FoldedVOp.getNode()) return FoldedVOp;
6963 // fold (fabs c1) -> fabs(c1)
6965 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6966 // fold (fabs (fabs x)) -> (fabs x)
6967 if (N0.getOpcode() == ISD::FABS)
6968 return N->getOperand(0);
6969 // fold (fabs (fneg x)) -> (fabs x)
6970 // fold (fabs (fcopysign x, y)) -> (fabs x)
6971 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6972 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6974 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6975 // constant pool values.
6976 if (!TLI.isFAbsFree(VT) &&
6977 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6978 N0.getOperand(0).getValueType().isInteger() &&
6979 !N0.getOperand(0).getValueType().isVector()) {
6980 SDValue Int = N0.getOperand(0);
6981 EVT IntVT = Int.getValueType();
6982 if (IntVT.isInteger() && !IntVT.isVector()) {
6983 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6984 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6985 AddToWorkList(Int.getNode());
6986 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6987 N->getValueType(0), Int);
6994 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6995 SDValue Chain = N->getOperand(0);
6996 SDValue N1 = N->getOperand(1);
6997 SDValue N2 = N->getOperand(2);
6999 // If N is a constant we could fold this into a fallthrough or unconditional
7000 // branch. However that doesn't happen very often in normal code, because
7001 // Instcombine/SimplifyCFG should have handled the available opportunities.
7002 // If we did this folding here, it would be necessary to update the
7003 // MachineBasicBlock CFG, which is awkward.
7005 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7007 if (N1.getOpcode() == ISD::SETCC &&
7008 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7009 N1.getOperand(0).getValueType())) {
7010 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7011 Chain, N1.getOperand(2),
7012 N1.getOperand(0), N1.getOperand(1), N2);
7015 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7016 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7017 (N1.getOperand(0).hasOneUse() &&
7018 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7020 if (N1.getOpcode() == ISD::TRUNCATE) {
7021 // Look pass the truncate.
7022 Trunc = N1.getNode();
7023 N1 = N1.getOperand(0);
7026 // Match this pattern so that we can generate simpler code:
7029 // %b = and i32 %a, 2
7030 // %c = srl i32 %b, 1
7031 // brcond i32 %c ...
7036 // %b = and i32 %a, 2
7037 // %c = setcc eq %b, 0
7040 // This applies only when the AND constant value has one bit set and the
7041 // SRL constant is equal to the log2 of the AND constant. The back-end is
7042 // smart enough to convert the result into a TEST/JMP sequence.
7043 SDValue Op0 = N1.getOperand(0);
7044 SDValue Op1 = N1.getOperand(1);
7046 if (Op0.getOpcode() == ISD::AND &&
7047 Op1.getOpcode() == ISD::Constant) {
7048 SDValue AndOp1 = Op0.getOperand(1);
7050 if (AndOp1.getOpcode() == ISD::Constant) {
7051 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7053 if (AndConst.isPowerOf2() &&
7054 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7056 DAG.getSetCC(SDLoc(N),
7057 getSetCCResultType(Op0.getValueType()),
7058 Op0, DAG.getConstant(0, Op0.getValueType()),
7061 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7062 MVT::Other, Chain, SetCC, N2);
7063 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7064 // will convert it back to (X & C1) >> C2.
7065 CombineTo(N, NewBRCond, false);
7066 // Truncate is dead.
7068 removeFromWorkList(Trunc);
7069 DAG.DeleteNode(Trunc);
7071 // Replace the uses of SRL with SETCC
7072 WorkListRemover DeadNodes(*this);
7073 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7074 removeFromWorkList(N1.getNode());
7075 DAG.DeleteNode(N1.getNode());
7076 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7082 // Restore N1 if the above transformation doesn't match.
7083 N1 = N->getOperand(1);
7086 // Transform br(xor(x, y)) -> br(x != y)
7087 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7088 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7089 SDNode *TheXor = N1.getNode();
7090 SDValue Op0 = TheXor->getOperand(0);
7091 SDValue Op1 = TheXor->getOperand(1);
7092 if (Op0.getOpcode() == Op1.getOpcode()) {
7093 // Avoid missing important xor optimizations.
7094 SDValue Tmp = visitXOR(TheXor);
7095 if (Tmp.getNode()) {
7096 if (Tmp.getNode() != TheXor) {
7097 DEBUG(dbgs() << "\nReplacing.8 ";
7099 dbgs() << "\nWith: ";
7100 Tmp.getNode()->dump(&DAG);
7102 WorkListRemover DeadNodes(*this);
7103 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7104 removeFromWorkList(TheXor);
7105 DAG.DeleteNode(TheXor);
7106 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7107 MVT::Other, Chain, Tmp, N2);
7110 // visitXOR has changed XOR's operands or replaced the XOR completely,
7112 return SDValue(N, 0);
7116 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7118 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7119 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7120 Op0.getOpcode() == ISD::XOR) {
7121 TheXor = Op0.getNode();
7125 EVT SetCCVT = N1.getValueType();
7127 SetCCVT = getSetCCResultType(SetCCVT);
7128 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7131 Equal ? ISD::SETEQ : ISD::SETNE);
7132 // Replace the uses of XOR with SETCC
7133 WorkListRemover DeadNodes(*this);
7134 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7135 removeFromWorkList(N1.getNode());
7136 DAG.DeleteNode(N1.getNode());
7137 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7138 MVT::Other, Chain, SetCC, N2);
7145 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7147 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7148 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7149 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7151 // If N is a constant we could fold this into a fallthrough or unconditional
7152 // branch. However that doesn't happen very often in normal code, because
7153 // Instcombine/SimplifyCFG should have handled the available opportunities.
7154 // If we did this folding here, it would be necessary to update the
7155 // MachineBasicBlock CFG, which is awkward.
7157 // Use SimplifySetCC to simplify SETCC's.
7158 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7159 CondLHS, CondRHS, CC->get(), SDLoc(N),
7161 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7163 // fold to a simpler setcc
7164 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7165 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7166 N->getOperand(0), Simp.getOperand(2),
7167 Simp.getOperand(0), Simp.getOperand(1),
7173 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7174 /// uses N as its base pointer and that N may be folded in the load / store
7175 /// addressing mode.
7176 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7178 const TargetLowering &TLI) {
7180 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7181 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7183 VT = Use->getValueType(0);
7184 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7185 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7187 VT = ST->getValue().getValueType();
7191 TargetLowering::AddrMode AM;
7192 if (N->getOpcode() == ISD::ADD) {
7193 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7196 AM.BaseOffs = Offset->getSExtValue();
7200 } else if (N->getOpcode() == ISD::SUB) {
7201 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7204 AM.BaseOffs = -Offset->getSExtValue();
7211 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7214 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7215 /// pre-indexed load / store when the base pointer is an add or subtract
7216 /// and it has other uses besides the load / store. After the
7217 /// transformation, the new indexed load / store has effectively folded
7218 /// the add / subtract in and all of its other uses are redirected to the
7219 /// new load / store.
7220 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7221 if (Level < AfterLegalizeDAG)
7227 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7228 if (LD->isIndexed())
7230 VT = LD->getMemoryVT();
7231 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7232 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7234 Ptr = LD->getBasePtr();
7235 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7236 if (ST->isIndexed())
7238 VT = ST->getMemoryVT();
7239 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7240 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7242 Ptr = ST->getBasePtr();
7248 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7249 // out. There is no reason to make this a preinc/predec.
7250 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7251 Ptr.getNode()->hasOneUse())
7254 // Ask the target to do addressing mode selection.
7257 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7258 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7261 // Backends without true r+i pre-indexed forms may need to pass a
7262 // constant base with a variable offset so that constant coercion
7263 // will work with the patterns in canonical form.
7264 bool Swapped = false;
7265 if (isa<ConstantSDNode>(BasePtr)) {
7266 std::swap(BasePtr, Offset);
7270 // Don't create a indexed load / store with zero offset.
7271 if (isa<ConstantSDNode>(Offset) &&
7272 cast<ConstantSDNode>(Offset)->isNullValue())
7275 // Try turning it into a pre-indexed load / store except when:
7276 // 1) The new base ptr is a frame index.
7277 // 2) If N is a store and the new base ptr is either the same as or is a
7278 // predecessor of the value being stored.
7279 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7280 // that would create a cycle.
7281 // 4) All uses are load / store ops that use it as old base ptr.
7283 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7284 // (plus the implicit offset) to a register to preinc anyway.
7285 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7290 SDValue Val = cast<StoreSDNode>(N)->getValue();
7291 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7295 // If the offset is a constant, there may be other adds of constants that
7296 // can be folded with this one. We should do this to avoid having to keep
7297 // a copy of the original base pointer.
7298 SmallVector<SDNode *, 16> OtherUses;
7299 if (isa<ConstantSDNode>(Offset))
7300 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7301 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7303 if (Use == Ptr.getNode())
7306 if (Use->isPredecessorOf(N))
7309 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7314 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7315 if (Op1.getNode() == BasePtr.getNode())
7316 std::swap(Op0, Op1);
7317 assert(Op0.getNode() == BasePtr.getNode() &&
7318 "Use of ADD/SUB but not an operand");
7320 if (!isa<ConstantSDNode>(Op1)) {
7325 // FIXME: In some cases, we can be smarter about this.
7326 if (Op1.getValueType() != Offset.getValueType()) {
7331 OtherUses.push_back(Use);
7335 std::swap(BasePtr, Offset);
7337 // Now check for #3 and #4.
7338 bool RealUse = false;
7340 // Caches for hasPredecessorHelper
7341 SmallPtrSet<const SDNode *, 32> Visited;
7342 SmallVector<const SDNode *, 16> Worklist;
7344 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7345 E = Ptr.getNode()->use_end(); I != E; ++I) {
7349 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7352 // If Ptr may be folded in addressing mode of other use, then it's
7353 // not profitable to do this transformation.
7354 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7363 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7364 BasePtr, Offset, AM);
7366 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7367 BasePtr, Offset, AM);
7370 DEBUG(dbgs() << "\nReplacing.4 ";
7372 dbgs() << "\nWith: ";
7373 Result.getNode()->dump(&DAG);
7375 WorkListRemover DeadNodes(*this);
7377 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7378 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7380 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7383 // Finally, since the node is now dead, remove it from the graph.
7387 std::swap(BasePtr, Offset);
7389 // Replace other uses of BasePtr that can be updated to use Ptr
7390 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7391 unsigned OffsetIdx = 1;
7392 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7394 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7395 BasePtr.getNode() && "Expected BasePtr operand");
7397 // We need to replace ptr0 in the following expression:
7398 // x0 * offset0 + y0 * ptr0 = t0
7400 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7402 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7403 // indexed load/store and the expresion that needs to be re-written.
7405 // Therefore, we have:
7406 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7408 ConstantSDNode *CN =
7409 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7411 APInt Offset0 = CN->getAPIntValue();
7412 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7414 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7415 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7416 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7417 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7419 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7421 APInt CNV = Offset0;
7422 if (X0 < 0) CNV = -CNV;
7423 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7424 else CNV = CNV - Offset1;
7426 // We can now generate the new expression.
7427 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7428 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7430 SDValue NewUse = DAG.getNode(Opcode,
7431 SDLoc(OtherUses[i]),
7432 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7433 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7434 removeFromWorkList(OtherUses[i]);
7435 DAG.DeleteNode(OtherUses[i]);
7438 // Replace the uses of Ptr with uses of the updated base value.
7439 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7440 removeFromWorkList(Ptr.getNode());
7441 DAG.DeleteNode(Ptr.getNode());
7446 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7447 /// add / sub of the base pointer node into a post-indexed load / store.
7448 /// The transformation folded the add / subtract into the new indexed
7449 /// load / store effectively and all of its uses are redirected to the
7450 /// new load / store.
7451 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7452 if (Level < AfterLegalizeDAG)
7458 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7459 if (LD->isIndexed())
7461 VT = LD->getMemoryVT();
7462 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7463 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7465 Ptr = LD->getBasePtr();
7466 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7467 if (ST->isIndexed())
7469 VT = ST->getMemoryVT();
7470 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7471 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7473 Ptr = ST->getBasePtr();
7479 if (Ptr.getNode()->hasOneUse())
7482 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7483 E = Ptr.getNode()->use_end(); I != E; ++I) {
7486 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7491 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7492 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7493 // Don't create a indexed load / store with zero offset.
7494 if (isa<ConstantSDNode>(Offset) &&
7495 cast<ConstantSDNode>(Offset)->isNullValue())
7498 // Try turning it into a post-indexed load / store except when
7499 // 1) All uses are load / store ops that use it as base ptr (and
7500 // it may be folded as addressing mmode).
7501 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7502 // nor a successor of N. Otherwise, if Op is folded that would
7505 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7509 bool TryNext = false;
7510 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7511 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7513 if (Use == Ptr.getNode())
7516 // If all the uses are load / store addresses, then don't do the
7518 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7519 bool RealUse = false;
7520 for (SDNode::use_iterator III = Use->use_begin(),
7521 EEE = Use->use_end(); III != EEE; ++III) {
7522 SDNode *UseUse = *III;
7523 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7538 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7539 SDValue Result = isLoad
7540 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7541 BasePtr, Offset, AM)
7542 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7543 BasePtr, Offset, AM);
7546 DEBUG(dbgs() << "\nReplacing.5 ";
7548 dbgs() << "\nWith: ";
7549 Result.getNode()->dump(&DAG);
7551 WorkListRemover DeadNodes(*this);
7553 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7554 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7556 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7559 // Finally, since the node is now dead, remove it from the graph.
7562 // Replace the uses of Use with uses of the updated base value.
7563 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7564 Result.getValue(isLoad ? 1 : 0));
7565 removeFromWorkList(Op);
7575 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7576 LoadSDNode *LD = cast<LoadSDNode>(N);
7577 SDValue Chain = LD->getChain();
7578 SDValue Ptr = LD->getBasePtr();
7580 // If load is not volatile and there are no uses of the loaded value (and
7581 // the updated indexed value in case of indexed loads), change uses of the
7582 // chain value into uses of the chain input (i.e. delete the dead load).
7583 if (!LD->isVolatile()) {
7584 if (N->getValueType(1) == MVT::Other) {
7586 if (!N->hasAnyUseOfValue(0)) {
7587 // It's not safe to use the two value CombineTo variant here. e.g.
7588 // v1, chain2 = load chain1, loc
7589 // v2, chain3 = load chain2, loc
7591 // Now we replace use of chain2 with chain1. This makes the second load
7592 // isomorphic to the one we are deleting, and thus makes this load live.
7593 DEBUG(dbgs() << "\nReplacing.6 ";
7595 dbgs() << "\nWith chain: ";
7596 Chain.getNode()->dump(&DAG);
7598 WorkListRemover DeadNodes(*this);
7599 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7601 if (N->use_empty()) {
7602 removeFromWorkList(N);
7606 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7610 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7611 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7612 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7613 DEBUG(dbgs() << "\nReplacing.7 ";
7615 dbgs() << "\nWith: ";
7616 Undef.getNode()->dump(&DAG);
7617 dbgs() << " and 2 other values\n");
7618 WorkListRemover DeadNodes(*this);
7619 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7620 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7621 DAG.getUNDEF(N->getValueType(1)));
7622 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7623 removeFromWorkList(N);
7625 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7630 // If this load is directly stored, replace the load value with the stored
7632 // TODO: Handle store large -> read small portion.
7633 // TODO: Handle TRUNCSTORE/LOADEXT
7634 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7635 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7636 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7637 if (PrevST->getBasePtr() == Ptr &&
7638 PrevST->getValue().getValueType() == N->getValueType(0))
7639 return CombineTo(N, Chain.getOperand(1), Chain);
7643 // Try to infer better alignment information than the load already has.
7644 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7645 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7646 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7648 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7649 LD->getValueType(0),
7650 Chain, Ptr, LD->getPointerInfo(),
7652 LD->isVolatile(), LD->isNonTemporal(), Align,
7654 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7659 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7660 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7662 // Walk up chain skipping non-aliasing memory nodes.
7663 SDValue BetterChain = FindBetterChain(N, Chain);
7665 // If there is a better chain.
7666 if (Chain != BetterChain) {
7669 // Replace the chain to void dependency.
7670 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7671 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7672 BetterChain, Ptr, LD->getMemOperand());
7674 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7675 LD->getValueType(0),
7676 BetterChain, Ptr, LD->getMemoryVT(),
7677 LD->getMemOperand());
7680 // Create token factor to keep old chain connected.
7681 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7682 MVT::Other, Chain, ReplLoad.getValue(1));
7684 // Make sure the new and old chains are cleaned up.
7685 AddToWorkList(Token.getNode());
7687 // Replace uses with load result and token factor. Don't add users
7689 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7693 // Try transforming N to an indexed load.
7694 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7695 return SDValue(N, 0);
7697 // Try to slice up N to more direct loads if the slices are mapped to
7698 // different register banks or pairing can take place.
7700 return SDValue(N, 0);
7706 /// \brief Helper structure used to slice a load in smaller loads.
7707 /// Basically a slice is obtained from the following sequence:
7708 /// Origin = load Ty1, Base
7709 /// Shift = srl Ty1 Origin, CstTy Amount
7710 /// Inst = trunc Shift to Ty2
7712 /// Then, it will be rewriten into:
7713 /// Slice = load SliceTy, Base + SliceOffset
7714 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7716 /// SliceTy is deduced from the number of bits that are actually used to
7718 struct LoadedSlice {
7719 /// \brief Helper structure used to compute the cost of a slice.
7721 /// Are we optimizing for code size.
7726 unsigned CrossRegisterBanksCopies;
7730 Cost(bool ForCodeSize = false)
7731 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7732 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7734 /// \brief Get the cost of one isolated slice.
7735 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7736 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7737 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7738 EVT TruncType = LS.Inst->getValueType(0);
7739 EVT LoadedType = LS.getLoadedType();
7740 if (TruncType != LoadedType &&
7741 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7745 /// \brief Account for slicing gain in the current cost.
7746 /// Slicing provide a few gains like removing a shift or a
7747 /// truncate. This method allows to grow the cost of the original
7748 /// load with the gain from this slice.
7749 void addSliceGain(const LoadedSlice &LS) {
7750 // Each slice saves a truncate.
7751 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7752 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7753 LS.Inst->getOperand(0).getValueType()))
7755 // If there is a shift amount, this slice gets rid of it.
7758 // If this slice can merge a cross register bank copy, account for it.
7759 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7760 ++CrossRegisterBanksCopies;
7763 Cost &operator+=(const Cost &RHS) {
7765 Truncates += RHS.Truncates;
7766 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7772 bool operator==(const Cost &RHS) const {
7773 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7774 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7775 ZExts == RHS.ZExts && Shift == RHS.Shift;
7778 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7780 bool operator<(const Cost &RHS) const {
7781 // Assume cross register banks copies are as expensive as loads.
7782 // FIXME: Do we want some more target hooks?
7783 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7784 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7785 // Unless we are optimizing for code size, consider the
7786 // expensive operation first.
7787 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7788 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7789 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7790 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7793 bool operator>(const Cost &RHS) const { return RHS < *this; }
7795 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7797 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7799 // The last instruction that represent the slice. This should be a
7800 // truncate instruction.
7802 // The original load instruction.
7804 // The right shift amount in bits from the original load.
7806 // The DAG from which Origin came from.
7807 // This is used to get some contextual information about legal types, etc.
7810 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7811 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7812 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7814 LoadedSlice(const LoadedSlice &LS)
7815 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7817 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7818 /// \return Result is \p BitWidth and has used bits set to 1 and
7819 /// not used bits set to 0.
7820 APInt getUsedBits() const {
7821 // Reproduce the trunc(lshr) sequence:
7822 // - Start from the truncated value.
7823 // - Zero extend to the desired bit width.
7825 assert(Origin && "No original load to compare against.");
7826 unsigned BitWidth = Origin->getValueSizeInBits(0);
7827 assert(Inst && "This slice is not bound to an instruction");
7828 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7829 "Extracted slice is bigger than the whole type!");
7830 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7831 UsedBits.setAllBits();
7832 UsedBits = UsedBits.zext(BitWidth);
7837 /// \brief Get the size of the slice to be loaded in bytes.
7838 unsigned getLoadedSize() const {
7839 unsigned SliceSize = getUsedBits().countPopulation();
7840 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7841 return SliceSize / 8;
7844 /// \brief Get the type that will be loaded for this slice.
7845 /// Note: This may not be the final type for the slice.
7846 EVT getLoadedType() const {
7847 assert(DAG && "Missing context");
7848 LLVMContext &Ctxt = *DAG->getContext();
7849 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7852 /// \brief Get the alignment of the load used for this slice.
7853 unsigned getAlignment() const {
7854 unsigned Alignment = Origin->getAlignment();
7855 unsigned Offset = getOffsetFromBase();
7857 Alignment = MinAlign(Alignment, Alignment + Offset);
7861 /// \brief Check if this slice can be rewritten with legal operations.
7862 bool isLegal() const {
7863 // An invalid slice is not legal.
7864 if (!Origin || !Inst || !DAG)
7867 // Offsets are for indexed load only, we do not handle that.
7868 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7871 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7873 // Check that the type is legal.
7874 EVT SliceType = getLoadedType();
7875 if (!TLI.isTypeLegal(SliceType))
7878 // Check that the load is legal for this type.
7879 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7882 // Check that the offset can be computed.
7883 // 1. Check its type.
7884 EVT PtrType = Origin->getBasePtr().getValueType();
7885 if (PtrType == MVT::Untyped || PtrType.isExtended())
7888 // 2. Check that it fits in the immediate.
7889 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7892 // 3. Check that the computation is legal.
7893 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7896 // Check that the zext is legal if it needs one.
7897 EVT TruncateType = Inst->getValueType(0);
7898 if (TruncateType != SliceType &&
7899 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7905 /// \brief Get the offset in bytes of this slice in the original chunk of
7907 /// \pre DAG != NULL.
7908 uint64_t getOffsetFromBase() const {
7909 assert(DAG && "Missing context.");
7911 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7912 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7913 uint64_t Offset = Shift / 8;
7914 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7915 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7916 "The size of the original loaded type is not a multiple of a"
7918 // If Offset is bigger than TySizeInBytes, it means we are loading all
7919 // zeros. This should have been optimized before in the process.
7920 assert(TySizeInBytes > Offset &&
7921 "Invalid shift amount for given loaded size");
7923 Offset = TySizeInBytes - Offset - getLoadedSize();
7927 /// \brief Generate the sequence of instructions to load the slice
7928 /// represented by this object and redirect the uses of this slice to
7929 /// this new sequence of instructions.
7930 /// \pre this->Inst && this->Origin are valid Instructions and this
7931 /// object passed the legal check: LoadedSlice::isLegal returned true.
7932 /// \return The last instruction of the sequence used to load the slice.
7933 SDValue loadSlice() const {
7934 assert(Inst && Origin && "Unable to replace a non-existing slice.");
7935 const SDValue &OldBaseAddr = Origin->getBasePtr();
7936 SDValue BaseAddr = OldBaseAddr;
7937 // Get the offset in that chunk of bytes w.r.t. the endianess.
7938 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7939 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7941 // BaseAddr = BaseAddr + Offset.
7942 EVT ArithType = BaseAddr.getValueType();
7943 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7944 DAG->getConstant(Offset, ArithType));
7947 // Create the type of the loaded slice according to its size.
7948 EVT SliceType = getLoadedType();
7950 // Create the load for the slice.
7951 SDValue LastInst = DAG->getLoad(
7952 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7953 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7954 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7955 // If the final type is not the same as the loaded type, this means that
7956 // we have to pad with zero. Create a zero extend for that.
7957 EVT FinalType = Inst->getValueType(0);
7958 if (SliceType != FinalType)
7960 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7964 /// \brief Check if this slice can be merged with an expensive cross register
7965 /// bank copy. E.g.,
7967 /// f = bitcast i32 i to float
7968 bool canMergeExpensiveCrossRegisterBankCopy() const {
7969 if (!Inst || !Inst->hasOneUse())
7971 SDNode *Use = *Inst->use_begin();
7972 if (Use->getOpcode() != ISD::BITCAST)
7974 assert(DAG && "Missing context");
7975 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7976 EVT ResVT = Use->getValueType(0);
7977 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7978 const TargetRegisterClass *ArgRC =
7979 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7980 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7983 // At this point, we know that we perform a cross-register-bank copy.
7984 // Check if it is expensive.
7985 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7986 // Assume bitcasts are cheap, unless both register classes do not
7987 // explicitly share a common sub class.
7988 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7991 // Check if it will be merged with the load.
7992 // 1. Check the alignment constraint.
7993 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7994 ResVT.getTypeForEVT(*DAG->getContext()));
7996 if (RequiredAlignment > getAlignment())
7999 // 2. Check that the load is a legal operation for that type.
8000 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8003 // 3. Check that we do not have a zext in the way.
8004 if (Inst->getValueType(0) != getLoadedType())
8012 /// \brief Sorts LoadedSlice according to their offset.
8013 struct LoadedSliceSorter {
8014 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8015 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8016 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8020 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8021 /// \p UsedBits looks like 0..0 1..1 0..0.
8022 static bool areUsedBitsDense(const APInt &UsedBits) {
8023 // If all the bits are one, this is dense!
8024 if (UsedBits.isAllOnesValue())
8027 // Get rid of the unused bits on the right.
8028 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8029 // Get rid of the unused bits on the left.
8030 if (NarrowedUsedBits.countLeadingZeros())
8031 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8032 // Check that the chunk of bits is completely used.
8033 return NarrowedUsedBits.isAllOnesValue();
8036 /// \brief Check whether or not \p First and \p Second are next to each other
8037 /// in memory. This means that there is no hole between the bits loaded
8038 /// by \p First and the bits loaded by \p Second.
8039 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8040 const LoadedSlice &Second) {
8041 assert(First.Origin == Second.Origin && First.Origin &&
8042 "Unable to match different memory origins.");
8043 APInt UsedBits = First.getUsedBits();
8044 assert((UsedBits & Second.getUsedBits()) == 0 &&
8045 "Slices are not supposed to overlap.");
8046 UsedBits |= Second.getUsedBits();
8047 return areUsedBitsDense(UsedBits);
8050 /// \brief Adjust the \p GlobalLSCost according to the target
8051 /// paring capabilities and the layout of the slices.
8052 /// \pre \p GlobalLSCost should account for at least as many loads as
8053 /// there is in the slices in \p LoadedSlices.
8054 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8055 LoadedSlice::Cost &GlobalLSCost) {
8056 unsigned NumberOfSlices = LoadedSlices.size();
8057 // If there is less than 2 elements, no pairing is possible.
8058 if (NumberOfSlices < 2)
8061 // Sort the slices so that elements that are likely to be next to each
8062 // other in memory are next to each other in the list.
8063 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8064 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8065 // First (resp. Second) is the first (resp. Second) potentially candidate
8066 // to be placed in a paired load.
8067 const LoadedSlice *First = NULL;
8068 const LoadedSlice *Second = NULL;
8069 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8070 // Set the beginning of the pair.
8073 Second = &LoadedSlices[CurrSlice];
8075 // If First is NULL, it means we start a new pair.
8076 // Get to the next slice.
8080 EVT LoadedType = First->getLoadedType();
8082 // If the types of the slices are different, we cannot pair them.
8083 if (LoadedType != Second->getLoadedType())
8086 // Check if the target supplies paired loads for this type.
8087 unsigned RequiredAlignment = 0;
8088 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8089 // move to the next pair, this type is hopeless.
8093 // Check if we meet the alignment requirement.
8094 if (RequiredAlignment > First->getAlignment())
8097 // Check that both loads are next to each other in memory.
8098 if (!areSlicesNextToEachOther(*First, *Second))
8101 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8102 --GlobalLSCost.Loads;
8103 // Move to the next pair.
8108 /// \brief Check the profitability of all involved LoadedSlice.
8109 /// Currently, it is considered profitable if there is exactly two
8110 /// involved slices (1) which are (2) next to each other in memory, and
8111 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8113 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8114 /// the elements themselves.
8116 /// FIXME: When the cost model will be mature enough, we can relax
8117 /// constraints (1) and (2).
8118 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8119 const APInt &UsedBits, bool ForCodeSize) {
8120 unsigned NumberOfSlices = LoadedSlices.size();
8121 if (StressLoadSlicing)
8122 return NumberOfSlices > 1;
8125 if (NumberOfSlices != 2)
8129 if (!areUsedBitsDense(UsedBits))
8133 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8134 // The original code has one big load.
8136 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8137 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8138 // Accumulate the cost of all the slices.
8139 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8140 GlobalSlicingCost += SliceCost;
8142 // Account as cost in the original configuration the gain obtained
8143 // with the current slices.
8144 OrigCost.addSliceGain(LS);
8147 // If the target supports paired load, adjust the cost accordingly.
8148 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8149 return OrigCost > GlobalSlicingCost;
8152 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8153 /// operations, split it in the various pieces being extracted.
8155 /// This sort of thing is introduced by SROA.
8156 /// This slicing takes care not to insert overlapping loads.
8157 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8158 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8159 if (Level < AfterLegalizeDAG)
8162 LoadSDNode *LD = cast<LoadSDNode>(N);
8163 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8164 !LD->getValueType(0).isInteger())
8167 // Keep track of already used bits to detect overlapping values.
8168 // In that case, we will just abort the transformation.
8169 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8171 SmallVector<LoadedSlice, 4> LoadedSlices;
8173 // Check if this load is used as several smaller chunks of bits.
8174 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8175 // of computation for each trunc.
8176 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8177 UI != UIEnd; ++UI) {
8178 // Skip the uses of the chain.
8179 if (UI.getUse().getResNo() != 0)
8185 // Check if this is a trunc(lshr).
8186 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8187 isa<ConstantSDNode>(User->getOperand(1))) {
8188 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8189 User = *User->use_begin();
8192 // At this point, User is a Truncate, iff we encountered, trunc or
8194 if (User->getOpcode() != ISD::TRUNCATE)
8197 // The width of the type must be a power of 2 and greater than 8-bits.
8198 // Otherwise the load cannot be represented in LLVM IR.
8199 // Moreover, if we shifted with a non-8-bits multiple, the slice
8200 // will be accross several bytes. We do not support that.
8201 unsigned Width = User->getValueSizeInBits(0);
8202 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8205 // Build the slice for this chain of computations.
8206 LoadedSlice LS(User, LD, Shift, &DAG);
8207 APInt CurrentUsedBits = LS.getUsedBits();
8209 // Check if this slice overlaps with another.
8210 if ((CurrentUsedBits & UsedBits) != 0)
8212 // Update the bits used globally.
8213 UsedBits |= CurrentUsedBits;
8215 // Check if the new slice would be legal.
8219 // Record the slice.
8220 LoadedSlices.push_back(LS);
8223 // Abort slicing if it does not seem to be profitable.
8224 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8229 // Rewrite each chain to use an independent load.
8230 // By construction, each chain can be represented by a unique load.
8232 // Prepare the argument for the new token factor for all the slices.
8233 SmallVector<SDValue, 8> ArgChains;
8234 for (SmallVectorImpl<LoadedSlice>::const_iterator
8235 LSIt = LoadedSlices.begin(),
8236 LSItEnd = LoadedSlices.end();
8237 LSIt != LSItEnd; ++LSIt) {
8238 SDValue SliceInst = LSIt->loadSlice();
8239 CombineTo(LSIt->Inst, SliceInst, true);
8240 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8241 SliceInst = SliceInst.getOperand(0);
8242 assert(SliceInst->getOpcode() == ISD::LOAD &&
8243 "It takes more than a zext to get to the loaded slice!!");
8244 ArgChains.push_back(SliceInst.getValue(1));
8247 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8248 &ArgChains[0], ArgChains.size());
8249 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8253 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8254 /// load is having specific bytes cleared out. If so, return the byte size
8255 /// being masked out and the shift amount.
8256 static std::pair<unsigned, unsigned>
8257 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8258 std::pair<unsigned, unsigned> Result(0, 0);
8260 // Check for the structure we're looking for.
8261 if (V->getOpcode() != ISD::AND ||
8262 !isa<ConstantSDNode>(V->getOperand(1)) ||
8263 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8266 // Check the chain and pointer.
8267 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8268 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8270 // The store should be chained directly to the load or be an operand of a
8272 if (LD == Chain.getNode())
8274 else if (Chain->getOpcode() != ISD::TokenFactor)
8275 return Result; // Fail.
8278 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8279 if (Chain->getOperand(i).getNode() == LD) {
8283 if (!isOk) return Result;
8286 // This only handles simple types.
8287 if (V.getValueType() != MVT::i16 &&
8288 V.getValueType() != MVT::i32 &&
8289 V.getValueType() != MVT::i64)
8292 // Check the constant mask. Invert it so that the bits being masked out are
8293 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8294 // follow the sign bit for uniformity.
8295 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8296 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8297 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8298 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8299 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8300 if (NotMaskLZ == 64) return Result; // All zero mask.
8302 // See if we have a continuous run of bits. If so, we have 0*1+0*
8303 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8306 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8307 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8308 NotMaskLZ -= 64-V.getValueSizeInBits();
8310 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8311 switch (MaskedBytes) {
8315 default: return Result; // All one mask, or 5-byte mask.
8318 // Verify that the first bit starts at a multiple of mask so that the access
8319 // is aligned the same as the access width.
8320 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8322 Result.first = MaskedBytes;
8323 Result.second = NotMaskTZ/8;
8328 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8329 /// provides a value as specified by MaskInfo. If so, replace the specified
8330 /// store with a narrower store of truncated IVal.
8332 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8333 SDValue IVal, StoreSDNode *St,
8335 unsigned NumBytes = MaskInfo.first;
8336 unsigned ByteShift = MaskInfo.second;
8337 SelectionDAG &DAG = DC->getDAG();
8339 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8340 // that uses this. If not, this is not a replacement.
8341 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8342 ByteShift*8, (ByteShift+NumBytes)*8);
8343 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8345 // Check that it is legal on the target to do this. It is legal if the new
8346 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8348 MVT VT = MVT::getIntegerVT(NumBytes*8);
8349 if (!DC->isTypeLegal(VT))
8352 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8353 // shifted by ByteShift and truncated down to NumBytes.
8355 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8356 DAG.getConstant(ByteShift*8,
8357 DC->getShiftAmountTy(IVal.getValueType())));
8359 // Figure out the offset for the store and the alignment of the access.
8361 unsigned NewAlign = St->getAlignment();
8363 if (DAG.getTargetLoweringInfo().isLittleEndian())
8364 StOffset = ByteShift;
8366 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8368 SDValue Ptr = St->getBasePtr();
8370 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8371 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8372 NewAlign = MinAlign(NewAlign, StOffset);
8375 // Truncate down to the new size.
8376 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8379 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8380 St->getPointerInfo().getWithOffset(StOffset),
8381 false, false, NewAlign).getNode();
8385 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8386 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8387 /// of the loaded bits, try narrowing the load and store if it would end up
8388 /// being a win for performance or code size.
8389 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8390 StoreSDNode *ST = cast<StoreSDNode>(N);
8391 if (ST->isVolatile())
8394 SDValue Chain = ST->getChain();
8395 SDValue Value = ST->getValue();
8396 SDValue Ptr = ST->getBasePtr();
8397 EVT VT = Value.getValueType();
8399 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8402 unsigned Opc = Value.getOpcode();
8404 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8405 // is a byte mask indicating a consecutive number of bytes, check to see if
8406 // Y is known to provide just those bytes. If so, we try to replace the
8407 // load + replace + store sequence with a single (narrower) store, which makes
8409 if (Opc == ISD::OR) {
8410 std::pair<unsigned, unsigned> MaskedLoad;
8411 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8412 if (MaskedLoad.first)
8413 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8414 Value.getOperand(1), ST,this))
8415 return SDValue(NewST, 0);
8417 // Or is commutative, so try swapping X and Y.
8418 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8419 if (MaskedLoad.first)
8420 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8421 Value.getOperand(0), ST,this))
8422 return SDValue(NewST, 0);
8425 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8426 Value.getOperand(1).getOpcode() != ISD::Constant)
8429 SDValue N0 = Value.getOperand(0);
8430 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8431 Chain == SDValue(N0.getNode(), 1)) {
8432 LoadSDNode *LD = cast<LoadSDNode>(N0);
8433 if (LD->getBasePtr() != Ptr ||
8434 LD->getPointerInfo().getAddrSpace() !=
8435 ST->getPointerInfo().getAddrSpace())
8438 // Find the type to narrow it the load / op / store to.
8439 SDValue N1 = Value.getOperand(1);
8440 unsigned BitWidth = N1.getValueSizeInBits();
8441 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8442 if (Opc == ISD::AND)
8443 Imm ^= APInt::getAllOnesValue(BitWidth);
8444 if (Imm == 0 || Imm.isAllOnesValue())
8446 unsigned ShAmt = Imm.countTrailingZeros();
8447 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8448 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8449 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8450 while (NewBW < BitWidth &&
8451 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8452 TLI.isNarrowingProfitable(VT, NewVT))) {
8453 NewBW = NextPowerOf2(NewBW);
8454 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8456 if (NewBW >= BitWidth)
8459 // If the lsb changed does not start at the type bitwidth boundary,
8460 // start at the previous one.
8462 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8463 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8464 std::min(BitWidth, ShAmt + NewBW));
8465 if ((Imm & Mask) == Imm) {
8466 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8467 if (Opc == ISD::AND)
8468 NewImm ^= APInt::getAllOnesValue(NewBW);
8469 uint64_t PtrOff = ShAmt / 8;
8470 // For big endian targets, we need to adjust the offset to the pointer to
8471 // load the correct bytes.
8472 if (TLI.isBigEndian())
8473 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8475 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8476 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8477 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8480 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8481 Ptr.getValueType(), Ptr,
8482 DAG.getConstant(PtrOff, Ptr.getValueType()));
8483 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8484 LD->getChain(), NewPtr,
8485 LD->getPointerInfo().getWithOffset(PtrOff),
8486 LD->isVolatile(), LD->isNonTemporal(),
8487 LD->isInvariant(), NewAlign,
8489 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8490 DAG.getConstant(NewImm, NewVT));
8491 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8493 ST->getPointerInfo().getWithOffset(PtrOff),
8494 false, false, NewAlign);
8496 AddToWorkList(NewPtr.getNode());
8497 AddToWorkList(NewLD.getNode());
8498 AddToWorkList(NewVal.getNode());
8499 WorkListRemover DeadNodes(*this);
8500 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8509 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8510 /// if the load value isn't used by any other operations, then consider
8511 /// transforming the pair to integer load / store operations if the target
8512 /// deems the transformation profitable.
8513 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8514 StoreSDNode *ST = cast<StoreSDNode>(N);
8515 SDValue Chain = ST->getChain();
8516 SDValue Value = ST->getValue();
8517 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8518 Value.hasOneUse() &&
8519 Chain == SDValue(Value.getNode(), 1)) {
8520 LoadSDNode *LD = cast<LoadSDNode>(Value);
8521 EVT VT = LD->getMemoryVT();
8522 if (!VT.isFloatingPoint() ||
8523 VT != ST->getMemoryVT() ||
8524 LD->isNonTemporal() ||
8525 ST->isNonTemporal() ||
8526 LD->getPointerInfo().getAddrSpace() != 0 ||
8527 ST->getPointerInfo().getAddrSpace() != 0)
8530 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8531 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8532 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8533 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8534 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8537 unsigned LDAlign = LD->getAlignment();
8538 unsigned STAlign = ST->getAlignment();
8539 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8540 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8541 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8544 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8545 LD->getChain(), LD->getBasePtr(),
8546 LD->getPointerInfo(),
8547 false, false, false, LDAlign);
8549 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8550 NewLD, ST->getBasePtr(),
8551 ST->getPointerInfo(),
8552 false, false, STAlign);
8554 AddToWorkList(NewLD.getNode());
8555 AddToWorkList(NewST.getNode());
8556 WorkListRemover DeadNodes(*this);
8557 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8565 /// Helper struct to parse and store a memory address as base + index + offset.
8566 /// We ignore sign extensions when it is safe to do so.
8567 /// The following two expressions are not equivalent. To differentiate we need
8568 /// to store whether there was a sign extension involved in the index
8570 /// (load (i64 add (i64 copyfromreg %c)
8571 /// (i64 signextend (add (i8 load %index)
8575 /// (load (i64 add (i64 copyfromreg %c)
8576 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8578 struct BaseIndexOffset {
8582 bool IsIndexSignExt;
8584 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8586 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8587 bool IsIndexSignExt) :
8588 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8590 bool equalBaseIndex(const BaseIndexOffset &Other) {
8591 return Other.Base == Base && Other.Index == Index &&
8592 Other.IsIndexSignExt == IsIndexSignExt;
8595 /// Parses tree in Ptr for base, index, offset addresses.
8596 static BaseIndexOffset match(SDValue Ptr) {
8597 bool IsIndexSignExt = false;
8599 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8600 // instruction, then it could be just the BASE or everything else we don't
8601 // know how to handle. Just use Ptr as BASE and give up.
8602 if (Ptr->getOpcode() != ISD::ADD)
8603 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8605 // We know that we have at least an ADD instruction. Try to pattern match
8606 // the simple case of BASE + OFFSET.
8607 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8608 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8609 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8613 // Inside a loop the current BASE pointer is calculated using an ADD and a
8614 // MUL instruction. In this case Ptr is the actual BASE pointer.
8615 // (i64 add (i64 %array_ptr)
8616 // (i64 mul (i64 %induction_var)
8617 // (i64 %element_size)))
8618 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8619 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8621 // Look at Base + Index + Offset cases.
8622 SDValue Base = Ptr->getOperand(0);
8623 SDValue IndexOffset = Ptr->getOperand(1);
8625 // Skip signextends.
8626 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8627 IndexOffset = IndexOffset->getOperand(0);
8628 IsIndexSignExt = true;
8631 // Either the case of Base + Index (no offset) or something else.
8632 if (IndexOffset->getOpcode() != ISD::ADD)
8633 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8635 // Now we have the case of Base + Index + offset.
8636 SDValue Index = IndexOffset->getOperand(0);
8637 SDValue Offset = IndexOffset->getOperand(1);
8639 if (!isa<ConstantSDNode>(Offset))
8640 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8642 // Ignore signextends.
8643 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8644 Index = Index->getOperand(0);
8645 IsIndexSignExt = true;
8646 } else IsIndexSignExt = false;
8648 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8649 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8653 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8654 /// is located in a sequence of memory operations connected by a chain.
8656 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8657 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8658 // Ptr to the mem node.
8659 LSBaseSDNode *MemNode;
8660 // Offset from the base ptr.
8661 int64_t OffsetFromBase;
8662 // What is the sequence number of this mem node.
8663 // Lowest mem operand in the DAG starts at zero.
8664 unsigned SequenceNum;
8667 /// Sorts store nodes in a link according to their offset from a shared
8669 struct ConsecutiveMemoryChainSorter {
8670 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8671 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8675 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8676 EVT MemVT = St->getMemoryVT();
8677 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8678 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8679 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8681 // Don't merge vectors into wider inputs.
8682 if (MemVT.isVector() || !MemVT.isSimple())
8685 // Perform an early exit check. Do not bother looking at stored values that
8686 // are not constants or loads.
8687 SDValue StoredVal = St->getValue();
8688 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8689 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8693 // Only look at ends of store sequences.
8694 SDValue Chain = SDValue(St, 1);
8695 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8698 // This holds the base pointer, index, and the offset in bytes from the base
8700 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8702 // We must have a base and an offset.
8703 if (!BasePtr.Base.getNode())
8706 // Do not handle stores to undef base pointers.
8707 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8710 // Save the LoadSDNodes that we find in the chain.
8711 // We need to make sure that these nodes do not interfere with
8712 // any of the store nodes.
8713 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8715 // Save the StoreSDNodes that we find in the chain.
8716 SmallVector<MemOpLink, 8> StoreNodes;
8718 // Walk up the chain and look for nodes with offsets from the same
8719 // base pointer. Stop when reaching an instruction with a different kind
8720 // or instruction which has a different base pointer.
8722 StoreSDNode *Index = St;
8724 // If the chain has more than one use, then we can't reorder the mem ops.
8725 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8728 // Find the base pointer and offset for this memory node.
8729 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8731 // Check that the base pointer is the same as the original one.
8732 if (!Ptr.equalBaseIndex(BasePtr))
8735 // Check that the alignment is the same.
8736 if (Index->getAlignment() != St->getAlignment())
8739 // The memory operands must not be volatile.
8740 if (Index->isVolatile() || Index->isIndexed())
8744 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8745 if (St->isTruncatingStore())
8748 // The stored memory type must be the same.
8749 if (Index->getMemoryVT() != MemVT)
8752 // We do not allow unaligned stores because we want to prevent overriding
8754 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8757 // We found a potential memory operand to merge.
8758 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8760 // Find the next memory operand in the chain. If the next operand in the
8761 // chain is a store then move up and continue the scan with the next
8762 // memory operand. If the next operand is a load save it and use alias
8763 // information to check if it interferes with anything.
8764 SDNode *NextInChain = Index->getChain().getNode();
8766 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8767 // We found a store node. Use it for the next iteration.
8770 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8771 if (Ldn->isVolatile()) {
8776 // Save the load node for later. Continue the scan.
8777 AliasLoadNodes.push_back(Ldn);
8778 NextInChain = Ldn->getChain().getNode();
8787 // Check if there is anything to merge.
8788 if (StoreNodes.size() < 2)
8791 // Sort the memory operands according to their distance from the base pointer.
8792 std::sort(StoreNodes.begin(), StoreNodes.end(),
8793 ConsecutiveMemoryChainSorter());
8795 // Scan the memory operations on the chain and find the first non-consecutive
8796 // store memory address.
8797 unsigned LastConsecutiveStore = 0;
8798 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8799 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8801 // Check that the addresses are consecutive starting from the second
8802 // element in the list of stores.
8804 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8805 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8810 // Check if this store interferes with any of the loads that we found.
8811 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8812 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8816 // We found a load that alias with this store. Stop the sequence.
8820 // Mark this node as useful.
8821 LastConsecutiveStore = i;
8824 // The node with the lowest store address.
8825 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8827 // Store the constants into memory as one consecutive store.
8829 unsigned LastLegalType = 0;
8830 unsigned LastLegalVectorType = 0;
8831 bool NonZero = false;
8832 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8833 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8834 SDValue StoredVal = St->getValue();
8836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8837 NonZero |= !C->isNullValue();
8838 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8839 NonZero |= !C->getConstantFPValue()->isNullValue();
8845 // Find a legal type for the constant store.
8846 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8847 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8848 if (TLI.isTypeLegal(StoreTy))
8849 LastLegalType = i+1;
8850 // Or check whether a truncstore is legal.
8851 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8852 TargetLowering::TypePromoteInteger) {
8853 EVT LegalizedStoredValueTy =
8854 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8855 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8856 LastLegalType = i+1;
8859 // Find a legal type for the vector store.
8860 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8861 if (TLI.isTypeLegal(Ty))
8862 LastLegalVectorType = i + 1;
8865 // We only use vectors if the constant is known to be zero and the
8866 // function is not marked with the noimplicitfloat attribute.
8867 if (NonZero || NoVectors)
8868 LastLegalVectorType = 0;
8870 // Check if we found a legal integer type to store.
8871 if (LastLegalType == 0 && LastLegalVectorType == 0)
8874 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8875 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8877 // Make sure we have something to merge.
8881 unsigned EarliestNodeUsed = 0;
8882 for (unsigned i=0; i < NumElem; ++i) {
8883 // Find a chain for the new wide-store operand. Notice that some
8884 // of the store nodes that we found may not be selected for inclusion
8885 // in the wide store. The chain we use needs to be the chain of the
8886 // earliest store node which is *used* and replaced by the wide store.
8887 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8888 EarliestNodeUsed = i;
8891 // The earliest Node in the DAG.
8892 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8893 SDLoc DL(StoreNodes[0].MemNode);
8897 // Find a legal type for the vector store.
8898 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8899 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8900 StoredVal = DAG.getConstant(0, Ty);
8902 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8903 APInt StoreInt(StoreBW, 0);
8905 // Construct a single integer constant which is made of the smaller
8907 bool IsLE = TLI.isLittleEndian();
8908 for (unsigned i = 0; i < NumElem ; ++i) {
8909 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8910 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8911 SDValue Val = St->getValue();
8912 StoreInt<<=ElementSizeBytes*8;
8913 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8914 StoreInt|=C->getAPIntValue().zext(StoreBW);
8915 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8916 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8918 assert(false && "Invalid constant element type");
8922 // Create the new Load and Store operations.
8923 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8924 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8927 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8928 FirstInChain->getBasePtr(),
8929 FirstInChain->getPointerInfo(),
8931 FirstInChain->getAlignment());
8933 // Replace the first store with the new store
8934 CombineTo(EarliestOp, NewStore);
8935 // Erase all other stores.
8936 for (unsigned i = 0; i < NumElem ; ++i) {
8937 if (StoreNodes[i].MemNode == EarliestOp)
8939 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8940 // ReplaceAllUsesWith will replace all uses that existed when it was
8941 // called, but graph optimizations may cause new ones to appear. For
8942 // example, the case in pr14333 looks like
8944 // St's chain -> St -> another store -> X
8946 // And the only difference from St to the other store is the chain.
8947 // When we change it's chain to be St's chain they become identical,
8948 // get CSEed and the net result is that X is now a use of St.
8949 // Since we know that St is redundant, just iterate.
8950 while (!St->use_empty())
8951 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8952 removeFromWorkList(St);
8959 // Below we handle the case of multiple consecutive stores that
8960 // come from multiple consecutive loads. We merge them into a single
8961 // wide load and a single wide store.
8963 // Look for load nodes which are used by the stored values.
8964 SmallVector<MemOpLink, 8> LoadNodes;
8966 // Find acceptable loads. Loads need to have the same chain (token factor),
8967 // must not be zext, volatile, indexed, and they must be consecutive.
8968 BaseIndexOffset LdBasePtr;
8969 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8970 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8971 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8974 // Loads must only have one use.
8975 if (!Ld->hasNUsesOfValue(1, 0))
8978 // Check that the alignment is the same as the stores.
8979 if (Ld->getAlignment() != St->getAlignment())
8982 // The memory operands must not be volatile.
8983 if (Ld->isVolatile() || Ld->isIndexed())
8986 // We do not accept ext loads.
8987 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8990 // The stored memory type must be the same.
8991 if (Ld->getMemoryVT() != MemVT)
8994 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8995 // If this is not the first ptr that we check.
8996 if (LdBasePtr.Base.getNode()) {
8997 // The base ptr must be the same.
8998 if (!LdPtr.equalBaseIndex(LdBasePtr))
9001 // Check that all other base pointers are the same as this one.
9005 // We found a potential memory operand to merge.
9006 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9009 if (LoadNodes.size() < 2)
9012 // Scan the memory operations on the chain and find the first non-consecutive
9013 // load memory address. These variables hold the index in the store node
9015 unsigned LastConsecutiveLoad = 0;
9016 // This variable refers to the size and not index in the array.
9017 unsigned LastLegalVectorType = 0;
9018 unsigned LastLegalIntegerType = 0;
9019 StartAddress = LoadNodes[0].OffsetFromBase;
9020 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9021 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9022 // All loads much share the same chain.
9023 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9026 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9027 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9029 LastConsecutiveLoad = i;
9031 // Find a legal type for the vector store.
9032 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9033 if (TLI.isTypeLegal(StoreTy))
9034 LastLegalVectorType = i + 1;
9036 // Find a legal type for the integer store.
9037 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9038 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9039 if (TLI.isTypeLegal(StoreTy))
9040 LastLegalIntegerType = i + 1;
9041 // Or check whether a truncstore and extload is legal.
9042 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9043 TargetLowering::TypePromoteInteger) {
9044 EVT LegalizedStoredValueTy =
9045 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9046 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9047 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9048 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9049 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9050 LastLegalIntegerType = i+1;
9054 // Only use vector types if the vector type is larger than the integer type.
9055 // If they are the same, use integers.
9056 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9057 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9059 // We add +1 here because the LastXXX variables refer to location while
9060 // the NumElem refers to array/index size.
9061 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9062 NumElem = std::min(LastLegalType, NumElem);
9067 // The earliest Node in the DAG.
9068 unsigned EarliestNodeUsed = 0;
9069 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9070 for (unsigned i=1; i<NumElem; ++i) {
9071 // Find a chain for the new wide-store operand. Notice that some
9072 // of the store nodes that we found may not be selected for inclusion
9073 // in the wide store. The chain we use needs to be the chain of the
9074 // earliest store node which is *used* and replaced by the wide store.
9075 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9076 EarliestNodeUsed = i;
9079 // Find if it is better to use vectors or integers to load and store
9083 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9085 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9086 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9089 SDLoc LoadDL(LoadNodes[0].MemNode);
9090 SDLoc StoreDL(StoreNodes[0].MemNode);
9092 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9093 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9094 FirstLoad->getChain(),
9095 FirstLoad->getBasePtr(),
9096 FirstLoad->getPointerInfo(),
9097 false, false, false,
9098 FirstLoad->getAlignment());
9100 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9101 FirstInChain->getBasePtr(),
9102 FirstInChain->getPointerInfo(), false, false,
9103 FirstInChain->getAlignment());
9105 // Replace one of the loads with the new load.
9106 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9107 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9108 SDValue(NewLoad.getNode(), 1));
9110 // Remove the rest of the load chains.
9111 for (unsigned i = 1; i < NumElem ; ++i) {
9112 // Replace all chain users of the old load nodes with the chain of the new
9114 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9115 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9118 // Replace the first store with the new store.
9119 CombineTo(EarliestOp, NewStore);
9120 // Erase all other stores.
9121 for (unsigned i = 0; i < NumElem ; ++i) {
9122 // Remove all Store nodes.
9123 if (StoreNodes[i].MemNode == EarliestOp)
9125 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9126 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9127 removeFromWorkList(St);
9134 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9135 StoreSDNode *ST = cast<StoreSDNode>(N);
9136 SDValue Chain = ST->getChain();
9137 SDValue Value = ST->getValue();
9138 SDValue Ptr = ST->getBasePtr();
9140 // If this is a store of a bit convert, store the input value if the
9141 // resultant store does not need a higher alignment than the original.
9142 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9143 ST->isUnindexed()) {
9144 unsigned OrigAlign = ST->getAlignment();
9145 EVT SVT = Value.getOperand(0).getValueType();
9146 unsigned Align = TLI.getDataLayout()->
9147 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9148 if (Align <= OrigAlign &&
9149 ((!LegalOperations && !ST->isVolatile()) ||
9150 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9151 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9152 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9153 ST->isNonTemporal(), OrigAlign,
9157 // Turn 'store undef, Ptr' -> nothing.
9158 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9161 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9162 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9163 // NOTE: If the original store is volatile, this transform must not increase
9164 // the number of stores. For example, on x86-32 an f64 can be stored in one
9165 // processor operation but an i64 (which is not legal) requires two. So the
9166 // transform should not be done in this case.
9167 if (Value.getOpcode() != ISD::TargetConstantFP) {
9169 switch (CFP->getSimpleValueType(0).SimpleTy) {
9170 default: llvm_unreachable("Unknown FP type");
9171 case MVT::f16: // We don't do this for these yet.
9177 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9178 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9179 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9180 bitcastToAPInt().getZExtValue(), MVT::i32);
9181 return DAG.getStore(Chain, SDLoc(N), Tmp,
9182 Ptr, ST->getMemOperand());
9186 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9187 !ST->isVolatile()) ||
9188 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9189 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9190 getZExtValue(), MVT::i64);
9191 return DAG.getStore(Chain, SDLoc(N), Tmp,
9192 Ptr, ST->getMemOperand());
9195 if (!ST->isVolatile() &&
9196 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9197 // Many FP stores are not made apparent until after legalize, e.g. for
9198 // argument passing. Since this is so common, custom legalize the
9199 // 64-bit integer store into two 32-bit stores.
9200 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9201 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9202 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9203 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9205 unsigned Alignment = ST->getAlignment();
9206 bool isVolatile = ST->isVolatile();
9207 bool isNonTemporal = ST->isNonTemporal();
9208 const MDNode *TBAAInfo = ST->getTBAAInfo();
9210 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9211 Ptr, ST->getPointerInfo(),
9212 isVolatile, isNonTemporal,
9213 ST->getAlignment(), TBAAInfo);
9214 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9215 DAG.getConstant(4, Ptr.getValueType()));
9216 Alignment = MinAlign(Alignment, 4U);
9217 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9218 Ptr, ST->getPointerInfo().getWithOffset(4),
9219 isVolatile, isNonTemporal,
9220 Alignment, TBAAInfo);
9221 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9230 // Try to infer better alignment information than the store already has.
9231 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9232 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9233 if (Align > ST->getAlignment())
9234 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9235 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9236 ST->isVolatile(), ST->isNonTemporal(), Align,
9241 // Try transforming a pair floating point load / store ops to integer
9242 // load / store ops.
9243 SDValue NewST = TransformFPLoadStorePair(N);
9244 if (NewST.getNode())
9247 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9248 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9250 // Walk up chain skipping non-aliasing memory nodes.
9251 SDValue BetterChain = FindBetterChain(N, Chain);
9253 // If there is a better chain.
9254 if (Chain != BetterChain) {
9257 // Replace the chain to avoid dependency.
9258 if (ST->isTruncatingStore()) {
9259 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9260 ST->getMemoryVT(), ST->getMemOperand());
9262 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9263 ST->getMemOperand());
9266 // Create token to keep both nodes around.
9267 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9268 MVT::Other, Chain, ReplStore);
9270 // Make sure the new and old chains are cleaned up.
9271 AddToWorkList(Token.getNode());
9273 // Don't add users to work list.
9274 return CombineTo(N, Token, false);
9278 // Try transforming N to an indexed store.
9279 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9280 return SDValue(N, 0);
9282 // FIXME: is there such a thing as a truncating indexed store?
9283 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9284 Value.getValueType().isInteger()) {
9285 // See if we can simplify the input to this truncstore with knowledge that
9286 // only the low bits are being used. For example:
9287 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9289 GetDemandedBits(Value,
9290 APInt::getLowBitsSet(
9291 Value.getValueType().getScalarType().getSizeInBits(),
9292 ST->getMemoryVT().getScalarType().getSizeInBits()));
9293 AddToWorkList(Value.getNode());
9294 if (Shorter.getNode())
9295 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9296 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9298 // Otherwise, see if we can simplify the operation with
9299 // SimplifyDemandedBits, which only works if the value has a single use.
9300 if (SimplifyDemandedBits(Value,
9301 APInt::getLowBitsSet(
9302 Value.getValueType().getScalarType().getSizeInBits(),
9303 ST->getMemoryVT().getScalarType().getSizeInBits())))
9304 return SDValue(N, 0);
9307 // If this is a load followed by a store to the same location, then the store
9309 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9310 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9311 ST->isUnindexed() && !ST->isVolatile() &&
9312 // There can't be any side effects between the load and store, such as
9314 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9315 // The store is dead, remove it.
9320 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9321 // truncating store. We can do this even if this is already a truncstore.
9322 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9323 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9324 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9325 ST->getMemoryVT())) {
9326 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9327 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9330 // Only perform this optimization before the types are legal, because we
9331 // don't want to perform this optimization on every DAGCombine invocation.
9333 bool EverChanged = false;
9336 // There can be multiple store sequences on the same chain.
9337 // Keep trying to merge store sequences until we are unable to do so
9338 // or until we merge the last store on the chain.
9339 bool Changed = MergeConsecutiveStores(ST);
9340 EverChanged |= Changed;
9341 if (!Changed) break;
9342 } while (ST->getOpcode() != ISD::DELETED_NODE);
9345 return SDValue(N, 0);
9348 return ReduceLoadOpStoreWidth(N);
9351 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9352 SDValue InVec = N->getOperand(0);
9353 SDValue InVal = N->getOperand(1);
9354 SDValue EltNo = N->getOperand(2);
9357 // If the inserted element is an UNDEF, just use the input vector.
9358 if (InVal.getOpcode() == ISD::UNDEF)
9361 EVT VT = InVec.getValueType();
9363 // If we can't generate a legal BUILD_VECTOR, exit
9364 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9367 // Check that we know which element is being inserted
9368 if (!isa<ConstantSDNode>(EltNo))
9370 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9372 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9373 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9375 SmallVector<SDValue, 8> Ops;
9376 // Do not combine these two vectors if the output vector will not replace
9377 // the input vector.
9378 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9379 Ops.append(InVec.getNode()->op_begin(),
9380 InVec.getNode()->op_end());
9381 } else if (InVec.getOpcode() == ISD::UNDEF) {
9382 unsigned NElts = VT.getVectorNumElements();
9383 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9388 // Insert the element
9389 if (Elt < Ops.size()) {
9390 // All the operands of BUILD_VECTOR must have the same type;
9391 // we enforce that here.
9392 EVT OpVT = Ops[0].getValueType();
9393 if (InVal.getValueType() != OpVT)
9394 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9395 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9396 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9400 // Return the new vector
9401 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9402 VT, &Ops[0], Ops.size());
9405 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9406 // (vextract (scalar_to_vector val, 0) -> val
9407 SDValue InVec = N->getOperand(0);
9408 EVT VT = InVec.getValueType();
9409 EVT NVT = N->getValueType(0);
9411 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9412 // Check if the result type doesn't match the inserted element type. A
9413 // SCALAR_TO_VECTOR may truncate the inserted element and the
9414 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9415 SDValue InOp = InVec.getOperand(0);
9416 if (InOp.getValueType() != NVT) {
9417 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9418 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9423 SDValue EltNo = N->getOperand(1);
9424 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9426 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9427 // We only perform this optimization before the op legalization phase because
9428 // we may introduce new vector instructions which are not backed by TD
9429 // patterns. For example on AVX, extracting elements from a wide vector
9430 // without using extract_subvector.
9431 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9432 && ConstEltNo && !LegalOperations) {
9433 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9434 int NumElem = VT.getVectorNumElements();
9435 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9436 // Find the new index to extract from.
9437 int OrigElt = SVOp->getMaskElt(Elt);
9439 // Extracting an undef index is undef.
9441 return DAG.getUNDEF(NVT);
9443 // Select the right vector half to extract from.
9444 if (OrigElt < NumElem) {
9445 InVec = InVec->getOperand(0);
9447 InVec = InVec->getOperand(1);
9451 EVT IndexTy = TLI.getVectorIdxTy();
9452 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9453 InVec, DAG.getConstant(OrigElt, IndexTy));
9456 // Perform only after legalization to ensure build_vector / vector_shuffle
9457 // optimizations have already been done.
9458 if (!LegalOperations) return SDValue();
9460 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9461 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9462 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9465 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9466 bool NewLoad = false;
9467 bool BCNumEltsChanged = false;
9468 EVT ExtVT = VT.getVectorElementType();
9471 // If the result of load has to be truncated, then it's not necessarily
9473 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9476 if (InVec.getOpcode() == ISD::BITCAST) {
9477 // Don't duplicate a load with other uses.
9478 if (!InVec.hasOneUse())
9481 EVT BCVT = InVec.getOperand(0).getValueType();
9482 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9484 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9485 BCNumEltsChanged = true;
9486 InVec = InVec.getOperand(0);
9487 ExtVT = BCVT.getVectorElementType();
9491 LoadSDNode *LN0 = NULL;
9492 const ShuffleVectorSDNode *SVN = NULL;
9493 if (ISD::isNormalLoad(InVec.getNode())) {
9494 LN0 = cast<LoadSDNode>(InVec);
9495 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9496 InVec.getOperand(0).getValueType() == ExtVT &&
9497 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9498 // Don't duplicate a load with other uses.
9499 if (!InVec.hasOneUse())
9502 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9503 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9504 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9506 // (load $addr+1*size)
9508 // Don't duplicate a load with other uses.
9509 if (!InVec.hasOneUse())
9512 // If the bit convert changed the number of elements, it is unsafe
9513 // to examine the mask.
9514 if (BCNumEltsChanged)
9517 // Select the input vector, guarding against out of range extract vector.
9518 unsigned NumElems = VT.getVectorNumElements();
9519 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9520 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9522 if (InVec.getOpcode() == ISD::BITCAST) {
9523 // Don't duplicate a load with other uses.
9524 if (!InVec.hasOneUse())
9527 InVec = InVec.getOperand(0);
9529 if (ISD::isNormalLoad(InVec.getNode())) {
9530 LN0 = cast<LoadSDNode>(InVec);
9531 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9535 // Make sure we found a non-volatile load and the extractelement is
9537 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9540 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9542 return DAG.getUNDEF(LVT);
9544 unsigned Align = LN0->getAlignment();
9546 // Check the resultant load doesn't need a higher alignment than the
9550 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9552 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9558 SDValue NewPtr = LN0->getBasePtr();
9559 unsigned PtrOff = 0;
9562 PtrOff = LVT.getSizeInBits() * Elt / 8;
9563 EVT PtrType = NewPtr.getValueType();
9564 if (TLI.isBigEndian())
9565 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9566 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9567 DAG.getConstant(PtrOff, PtrType));
9570 // The replacement we need to do here is a little tricky: we need to
9571 // replace an extractelement of a load with a load.
9572 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9573 // Note that this replacement assumes that the extractvalue is the only
9574 // use of the load; that's okay because we don't want to perform this
9575 // transformation in other cases anyway.
9578 if (NVT.bitsGT(LVT)) {
9579 // If the result type of vextract is wider than the load, then issue an
9580 // extending load instead.
9581 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9582 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9583 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9584 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9585 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9586 Align, LN0->getTBAAInfo());
9587 Chain = Load.getValue(1);
9589 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9590 LN0->getPointerInfo().getWithOffset(PtrOff),
9591 LN0->isVolatile(), LN0->isNonTemporal(),
9592 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9593 Chain = Load.getValue(1);
9594 if (NVT.bitsLT(LVT))
9595 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9597 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9599 WorkListRemover DeadNodes(*this);
9600 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9601 SDValue To[] = { Load, Chain };
9602 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9603 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9604 // worklist explicitly as well.
9605 AddToWorkList(Load.getNode());
9606 AddUsersToWorkList(Load.getNode()); // Add users too
9607 // Make sure to revisit this node to clean it up; it will usually be dead.
9609 return SDValue(N, 0);
9615 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9616 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9617 // We perform this optimization post type-legalization because
9618 // the type-legalizer often scalarizes integer-promoted vectors.
9619 // Performing this optimization before may create bit-casts which
9620 // will be type-legalized to complex code sequences.
9621 // We perform this optimization only before the operation legalizer because we
9622 // may introduce illegal operations.
9623 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9626 unsigned NumInScalars = N->getNumOperands();
9628 EVT VT = N->getValueType(0);
9630 // Check to see if this is a BUILD_VECTOR of a bunch of values
9631 // which come from any_extend or zero_extend nodes. If so, we can create
9632 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9633 // optimizations. We do not handle sign-extend because we can't fill the sign
9635 EVT SourceType = MVT::Other;
9636 bool AllAnyExt = true;
9638 for (unsigned i = 0; i != NumInScalars; ++i) {
9639 SDValue In = N->getOperand(i);
9640 // Ignore undef inputs.
9641 if (In.getOpcode() == ISD::UNDEF) continue;
9643 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9644 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9646 // Abort if the element is not an extension.
9647 if (!ZeroExt && !AnyExt) {
9648 SourceType = MVT::Other;
9652 // The input is a ZeroExt or AnyExt. Check the original type.
9653 EVT InTy = In.getOperand(0).getValueType();
9655 // Check that all of the widened source types are the same.
9656 if (SourceType == MVT::Other)
9659 else if (InTy != SourceType) {
9660 // Multiple income types. Abort.
9661 SourceType = MVT::Other;
9665 // Check if all of the extends are ANY_EXTENDs.
9666 AllAnyExt &= AnyExt;
9669 // In order to have valid types, all of the inputs must be extended from the
9670 // same source type and all of the inputs must be any or zero extend.
9671 // Scalar sizes must be a power of two.
9672 EVT OutScalarTy = VT.getScalarType();
9673 bool ValidTypes = SourceType != MVT::Other &&
9674 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9675 isPowerOf2_32(SourceType.getSizeInBits());
9677 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9678 // turn into a single shuffle instruction.
9682 bool isLE = TLI.isLittleEndian();
9683 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9684 assert(ElemRatio > 1 && "Invalid element size ratio");
9685 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9686 DAG.getConstant(0, SourceType);
9688 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9689 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9691 // Populate the new build_vector
9692 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9693 SDValue Cast = N->getOperand(i);
9694 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9695 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9696 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9698 if (Cast.getOpcode() == ISD::UNDEF)
9699 In = DAG.getUNDEF(SourceType);
9701 In = Cast->getOperand(0);
9702 unsigned Index = isLE ? (i * ElemRatio) :
9703 (i * ElemRatio + (ElemRatio - 1));
9705 assert(Index < Ops.size() && "Invalid index");
9709 // The type of the new BUILD_VECTOR node.
9710 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9711 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9712 "Invalid vector size");
9713 // Check if the new vector type is legal.
9714 if (!isTypeLegal(VecVT)) return SDValue();
9716 // Make the new BUILD_VECTOR.
9717 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9719 // The new BUILD_VECTOR node has the potential to be further optimized.
9720 AddToWorkList(BV.getNode());
9721 // Bitcast to the desired type.
9722 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9725 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9726 EVT VT = N->getValueType(0);
9728 unsigned NumInScalars = N->getNumOperands();
9731 EVT SrcVT = MVT::Other;
9732 unsigned Opcode = ISD::DELETED_NODE;
9733 unsigned NumDefs = 0;
9735 for (unsigned i = 0; i != NumInScalars; ++i) {
9736 SDValue In = N->getOperand(i);
9737 unsigned Opc = In.getOpcode();
9739 if (Opc == ISD::UNDEF)
9742 // If all scalar values are floats and converted from integers.
9743 if (Opcode == ISD::DELETED_NODE &&
9744 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9751 EVT InVT = In.getOperand(0).getValueType();
9753 // If all scalar values are typed differently, bail out. It's chosen to
9754 // simplify BUILD_VECTOR of integer types.
9755 if (SrcVT == MVT::Other)
9762 // If the vector has just one element defined, it's not worth to fold it into
9763 // a vectorized one.
9767 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9768 && "Should only handle conversion from integer to float.");
9769 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9771 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9773 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9776 SmallVector<SDValue, 8> Opnds;
9777 for (unsigned i = 0; i != NumInScalars; ++i) {
9778 SDValue In = N->getOperand(i);
9780 if (In.getOpcode() == ISD::UNDEF)
9781 Opnds.push_back(DAG.getUNDEF(SrcVT));
9783 Opnds.push_back(In.getOperand(0));
9785 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9786 &Opnds[0], Opnds.size());
9787 AddToWorkList(BV.getNode());
9789 return DAG.getNode(Opcode, dl, VT, BV);
9792 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9793 unsigned NumInScalars = N->getNumOperands();
9795 EVT VT = N->getValueType(0);
9797 // A vector built entirely of undefs is undef.
9798 if (ISD::allOperandsUndef(N))
9799 return DAG.getUNDEF(VT);
9801 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9805 V = reduceBuildVecConvertToConvertBuildVec(N);
9809 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9810 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9811 // at most two distinct vectors, turn this into a shuffle node.
9813 // May only combine to shuffle after legalize if shuffle is legal.
9814 if (LegalOperations &&
9815 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9818 SDValue VecIn1, VecIn2;
9819 for (unsigned i = 0; i != NumInScalars; ++i) {
9820 // Ignore undef inputs.
9821 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9823 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9824 // constant index, bail out.
9825 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9826 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9827 VecIn1 = VecIn2 = SDValue(0, 0);
9831 // We allow up to two distinct input vectors.
9832 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9833 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9836 if (VecIn1.getNode() == 0) {
9837 VecIn1 = ExtractedFromVec;
9838 } else if (VecIn2.getNode() == 0) {
9839 VecIn2 = ExtractedFromVec;
9842 VecIn1 = VecIn2 = SDValue(0, 0);
9847 // If everything is good, we can make a shuffle operation.
9848 if (VecIn1.getNode()) {
9849 SmallVector<int, 8> Mask;
9850 for (unsigned i = 0; i != NumInScalars; ++i) {
9851 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9856 // If extracting from the first vector, just use the index directly.
9857 SDValue Extract = N->getOperand(i);
9858 SDValue ExtVal = Extract.getOperand(1);
9859 if (Extract.getOperand(0) == VecIn1) {
9860 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9861 if (ExtIndex > VT.getVectorNumElements())
9864 Mask.push_back(ExtIndex);
9868 // Otherwise, use InIdx + VecSize
9869 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9870 Mask.push_back(Idx+NumInScalars);
9873 // We can't generate a shuffle node with mismatched input and output types.
9874 // Attempt to transform a single input vector to the correct type.
9875 if ((VT != VecIn1.getValueType())) {
9876 // We don't support shuffeling between TWO values of different types.
9877 if (VecIn2.getNode() != 0)
9880 // We only support widening of vectors which are half the size of the
9881 // output registers. For example XMM->YMM widening on X86 with AVX.
9882 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9885 // If the input vector type has a different base type to the output
9886 // vector type, bail out.
9887 if (VecIn1.getValueType().getVectorElementType() !=
9888 VT.getVectorElementType())
9891 // Widen the input vector by adding undef values.
9892 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9893 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9896 // If VecIn2 is unused then change it to undef.
9897 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9899 // Check that we were able to transform all incoming values to the same
9901 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9902 VecIn1.getValueType() != VT)
9905 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9906 if (!isTypeLegal(VT))
9909 // Return the new VECTOR_SHUFFLE node.
9913 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9919 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9920 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9921 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9922 // inputs come from at most two distinct vectors, turn this into a shuffle
9925 // If we only have one input vector, we don't need to do any concatenation.
9926 if (N->getNumOperands() == 1)
9927 return N->getOperand(0);
9929 // Check if all of the operands are undefs.
9930 EVT VT = N->getValueType(0);
9931 if (ISD::allOperandsUndef(N))
9932 return DAG.getUNDEF(VT);
9934 // Optimize concat_vectors where one of the vectors is undef.
9935 if (N->getNumOperands() == 2 &&
9936 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9937 SDValue In = N->getOperand(0);
9938 assert(In.getValueType().isVector() && "Must concat vectors");
9940 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9941 if (In->getOpcode() == ISD::BITCAST &&
9942 !In->getOperand(0)->getValueType(0).isVector()) {
9943 SDValue Scalar = In->getOperand(0);
9944 EVT SclTy = Scalar->getValueType(0);
9946 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
9949 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
9950 VT.getSizeInBits() / SclTy.getSizeInBits());
9951 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
9954 SDLoc dl = SDLoc(N);
9955 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
9956 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
9960 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9961 // nodes often generate nop CONCAT_VECTOR nodes.
9962 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9963 // place the incoming vectors at the exact same location.
9964 SDValue SingleSource = SDValue();
9965 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9967 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9968 SDValue Op = N->getOperand(i);
9970 if (Op.getOpcode() == ISD::UNDEF)
9973 // Check if this is the identity extract:
9974 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9977 // Find the single incoming vector for the extract_subvector.
9978 if (SingleSource.getNode()) {
9979 if (Op.getOperand(0) != SingleSource)
9982 SingleSource = Op.getOperand(0);
9984 // Check the source type is the same as the type of the result.
9985 // If not, this concat may extend the vector, so we can not
9986 // optimize it away.
9987 if (SingleSource.getValueType() != N->getValueType(0))
9991 unsigned IdentityIndex = i * PartNumElem;
9992 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9993 // The extract index must be constant.
9997 // Check that we are reading from the identity index.
9998 if (CS->getZExtValue() != IdentityIndex)
10002 if (SingleSource.getNode())
10003 return SingleSource;
10008 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10009 EVT NVT = N->getValueType(0);
10010 SDValue V = N->getOperand(0);
10012 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10014 // (extract_subvec (concat V1, V2, ...), i)
10017 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10019 if (V->getOperand(0).getValueType() != NVT)
10021 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10022 unsigned NumElems = NVT.getVectorNumElements();
10023 assert((Idx % NumElems) == 0 &&
10024 "IDX in concat is not a multiple of the result vector length.");
10025 return V->getOperand(Idx / NumElems);
10029 if (V->getOpcode() == ISD::BITCAST)
10030 V = V.getOperand(0);
10032 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10034 // Handle only simple case where vector being inserted and vector
10035 // being extracted are of same type, and are half size of larger vectors.
10036 EVT BigVT = V->getOperand(0).getValueType();
10037 EVT SmallVT = V->getOperand(1).getValueType();
10038 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10041 // Only handle cases where both indexes are constants with the same type.
10042 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10043 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10045 if (InsIdx && ExtIdx &&
10046 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10047 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10049 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10051 // indices are equal or bit offsets are equal => V1
10052 // otherwise => (extract_subvec V1, ExtIdx)
10053 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10054 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10055 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10056 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10057 DAG.getNode(ISD::BITCAST, dl,
10058 N->getOperand(0).getValueType(),
10059 V->getOperand(0)), N->getOperand(1));
10066 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10067 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10068 EVT VT = N->getValueType(0);
10069 unsigned NumElts = VT.getVectorNumElements();
10071 SDValue N0 = N->getOperand(0);
10072 SDValue N1 = N->getOperand(1);
10073 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10075 SmallVector<SDValue, 4> Ops;
10076 EVT ConcatVT = N0.getOperand(0).getValueType();
10077 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10078 unsigned NumConcats = NumElts / NumElemsPerConcat;
10080 // Look at every vector that's inserted. We're looking for exact
10081 // subvector-sized copies from a concatenated vector
10082 for (unsigned I = 0; I != NumConcats; ++I) {
10083 // Make sure we're dealing with a copy.
10084 unsigned Begin = I * NumElemsPerConcat;
10085 bool AllUndef = true, NoUndef = true;
10086 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10087 if (SVN->getMaskElt(J) >= 0)
10094 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10097 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10098 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10101 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10102 if (FirstElt < N0.getNumOperands())
10103 Ops.push_back(N0.getOperand(FirstElt));
10105 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10107 } else if (AllUndef) {
10108 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10109 } else { // Mixed with general masks and undefs, can't do optimization.
10114 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10118 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10119 EVT VT = N->getValueType(0);
10120 unsigned NumElts = VT.getVectorNumElements();
10122 SDValue N0 = N->getOperand(0);
10123 SDValue N1 = N->getOperand(1);
10125 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10127 // Canonicalize shuffle undef, undef -> undef
10128 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10129 return DAG.getUNDEF(VT);
10131 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10133 // Canonicalize shuffle v, v -> v, undef
10135 SmallVector<int, 8> NewMask;
10136 for (unsigned i = 0; i != NumElts; ++i) {
10137 int Idx = SVN->getMaskElt(i);
10138 if (Idx >= (int)NumElts) Idx -= NumElts;
10139 NewMask.push_back(Idx);
10141 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10145 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10146 if (N0.getOpcode() == ISD::UNDEF) {
10147 SmallVector<int, 8> NewMask;
10148 for (unsigned i = 0; i != NumElts; ++i) {
10149 int Idx = SVN->getMaskElt(i);
10151 if (Idx >= (int)NumElts)
10154 Idx = -1; // remove reference to lhs
10156 NewMask.push_back(Idx);
10158 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10162 // Remove references to rhs if it is undef
10163 if (N1.getOpcode() == ISD::UNDEF) {
10164 bool Changed = false;
10165 SmallVector<int, 8> NewMask;
10166 for (unsigned i = 0; i != NumElts; ++i) {
10167 int Idx = SVN->getMaskElt(i);
10168 if (Idx >= (int)NumElts) {
10172 NewMask.push_back(Idx);
10175 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10178 // If it is a splat, check if the argument vector is another splat or a
10179 // build_vector with all scalar elements the same.
10180 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10181 SDNode *V = N0.getNode();
10183 // If this is a bit convert that changes the element type of the vector but
10184 // not the number of vector elements, look through it. Be careful not to
10185 // look though conversions that change things like v4f32 to v2f64.
10186 if (V->getOpcode() == ISD::BITCAST) {
10187 SDValue ConvInput = V->getOperand(0);
10188 if (ConvInput.getValueType().isVector() &&
10189 ConvInput.getValueType().getVectorNumElements() == NumElts)
10190 V = ConvInput.getNode();
10193 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10194 assert(V->getNumOperands() == NumElts &&
10195 "BUILD_VECTOR has wrong number of operands");
10197 bool AllSame = true;
10198 for (unsigned i = 0; i != NumElts; ++i) {
10199 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10200 Base = V->getOperand(i);
10204 // Splat of <u, u, u, u>, return <u, u, u, u>
10205 if (!Base.getNode())
10207 for (unsigned i = 0; i != NumElts; ++i) {
10208 if (V->getOperand(i) != Base) {
10213 // Splat of <x, x, x, x>, return <x, x, x, x>
10219 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10220 Level < AfterLegalizeVectorOps &&
10221 (N1.getOpcode() == ISD::UNDEF ||
10222 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10223 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10224 SDValue V = partitionShuffleOfConcats(N, DAG);
10230 // If this shuffle node is simply a swizzle of another shuffle node,
10231 // and it reverses the swizzle of the previous shuffle then we can
10232 // optimize shuffle(shuffle(x, undef), undef) -> x.
10233 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10234 N1.getOpcode() == ISD::UNDEF) {
10236 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10238 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10239 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10242 // The incoming shuffle must be of the same type as the result of the
10243 // current shuffle.
10244 assert(OtherSV->getOperand(0).getValueType() == VT &&
10245 "Shuffle types don't match");
10247 for (unsigned i = 0; i != NumElts; ++i) {
10248 int Idx = SVN->getMaskElt(i);
10249 assert(Idx < (int)NumElts && "Index references undef operand");
10250 // Next, this index comes from the first value, which is the incoming
10251 // shuffle. Adopt the incoming index.
10253 Idx = OtherSV->getMaskElt(Idx);
10255 // The combined shuffle must map each index to itself.
10256 if (Idx >= 0 && (unsigned)Idx != i)
10260 return OtherSV->getOperand(0);
10266 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10267 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10268 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10269 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10270 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10271 EVT VT = N->getValueType(0);
10273 SDValue LHS = N->getOperand(0);
10274 SDValue RHS = N->getOperand(1);
10275 if (N->getOpcode() == ISD::AND) {
10276 if (RHS.getOpcode() == ISD::BITCAST)
10277 RHS = RHS.getOperand(0);
10278 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10279 SmallVector<int, 8> Indices;
10280 unsigned NumElts = RHS.getNumOperands();
10281 for (unsigned i = 0; i != NumElts; ++i) {
10282 SDValue Elt = RHS.getOperand(i);
10283 if (!isa<ConstantSDNode>(Elt))
10286 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10287 Indices.push_back(i);
10288 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10289 Indices.push_back(NumElts);
10294 // Let's see if the target supports this vector_shuffle.
10295 EVT RVT = RHS.getValueType();
10296 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10299 // Return the new VECTOR_SHUFFLE node.
10300 EVT EltVT = RVT.getVectorElementType();
10301 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10302 DAG.getConstant(0, EltVT));
10303 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10304 RVT, &ZeroOps[0], ZeroOps.size());
10305 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10306 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10307 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10314 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10315 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10316 assert(N->getValueType(0).isVector() &&
10317 "SimplifyVBinOp only works on vectors!");
10319 SDValue LHS = N->getOperand(0);
10320 SDValue RHS = N->getOperand(1);
10321 SDValue Shuffle = XformToShuffleWithZero(N);
10322 if (Shuffle.getNode()) return Shuffle;
10324 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10326 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10327 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10328 SmallVector<SDValue, 8> Ops;
10329 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10330 SDValue LHSOp = LHS.getOperand(i);
10331 SDValue RHSOp = RHS.getOperand(i);
10332 // If these two elements can't be folded, bail out.
10333 if ((LHSOp.getOpcode() != ISD::UNDEF &&
10334 LHSOp.getOpcode() != ISD::Constant &&
10335 LHSOp.getOpcode() != ISD::ConstantFP) ||
10336 (RHSOp.getOpcode() != ISD::UNDEF &&
10337 RHSOp.getOpcode() != ISD::Constant &&
10338 RHSOp.getOpcode() != ISD::ConstantFP))
10341 // Can't fold divide by zero.
10342 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10343 N->getOpcode() == ISD::FDIV) {
10344 if ((RHSOp.getOpcode() == ISD::Constant &&
10345 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10346 (RHSOp.getOpcode() == ISD::ConstantFP &&
10347 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10351 EVT VT = LHSOp.getValueType();
10352 EVT RVT = RHSOp.getValueType();
10354 // Integer BUILD_VECTOR operands may have types larger than the element
10355 // size (e.g., when the element type is not legal). Prior to type
10356 // legalization, the types may not match between the two BUILD_VECTORS.
10357 // Truncate one of the operands to make them match.
10358 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10359 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10361 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10365 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10367 if (FoldOp.getOpcode() != ISD::UNDEF &&
10368 FoldOp.getOpcode() != ISD::Constant &&
10369 FoldOp.getOpcode() != ISD::ConstantFP)
10371 Ops.push_back(FoldOp);
10372 AddToWorkList(FoldOp.getNode());
10375 if (Ops.size() == LHS.getNumOperands())
10376 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10377 LHS.getValueType(), &Ops[0], Ops.size());
10383 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10384 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10385 assert(N->getValueType(0).isVector() &&
10386 "SimplifyVUnaryOp only works on vectors!");
10388 SDValue N0 = N->getOperand(0);
10390 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10393 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10394 SmallVector<SDValue, 8> Ops;
10395 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10396 SDValue Op = N0.getOperand(i);
10397 if (Op.getOpcode() != ISD::UNDEF &&
10398 Op.getOpcode() != ISD::ConstantFP)
10400 EVT EltVT = Op.getValueType();
10401 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10402 if (FoldOp.getOpcode() != ISD::UNDEF &&
10403 FoldOp.getOpcode() != ISD::ConstantFP)
10405 Ops.push_back(FoldOp);
10406 AddToWorkList(FoldOp.getNode());
10409 if (Ops.size() != N0.getNumOperands())
10412 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10413 N0.getValueType(), &Ops[0], Ops.size());
10416 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10417 SDValue N1, SDValue N2){
10418 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10420 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10421 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10423 // If we got a simplified select_cc node back from SimplifySelectCC, then
10424 // break it down into a new SETCC node, and a new SELECT node, and then return
10425 // the SELECT node, since we were called with a SELECT node.
10426 if (SCC.getNode()) {
10427 // Check to see if we got a select_cc back (to turn into setcc/select).
10428 // Otherwise, just return whatever node we got back, like fabs.
10429 if (SCC.getOpcode() == ISD::SELECT_CC) {
10430 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10432 SCC.getOperand(0), SCC.getOperand(1),
10433 SCC.getOperand(4));
10434 AddToWorkList(SETCC.getNode());
10435 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10436 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10444 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10445 /// are the two values being selected between, see if we can simplify the
10446 /// select. Callers of this should assume that TheSelect is deleted if this
10447 /// returns true. As such, they should return the appropriate thing (e.g. the
10448 /// node) back to the top-level of the DAG combiner loop to avoid it being
10450 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10453 // Cannot simplify select with vector condition
10454 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10456 // If this is a select from two identical things, try to pull the operation
10457 // through the select.
10458 if (LHS.getOpcode() != RHS.getOpcode() ||
10459 !LHS.hasOneUse() || !RHS.hasOneUse())
10462 // If this is a load and the token chain is identical, replace the select
10463 // of two loads with a load through a select of the address to load from.
10464 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10465 // constants have been dropped into the constant pool.
10466 if (LHS.getOpcode() == ISD::LOAD) {
10467 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10468 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10470 // Token chains must be identical.
10471 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10472 // Do not let this transformation reduce the number of volatile loads.
10473 LLD->isVolatile() || RLD->isVolatile() ||
10474 // If this is an EXTLOAD, the VT's must match.
10475 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10476 // If this is an EXTLOAD, the kind of extension must match.
10477 (LLD->getExtensionType() != RLD->getExtensionType() &&
10478 // The only exception is if one of the extensions is anyext.
10479 LLD->getExtensionType() != ISD::EXTLOAD &&
10480 RLD->getExtensionType() != ISD::EXTLOAD) ||
10481 // FIXME: this discards src value information. This is
10482 // over-conservative. It would be beneficial to be able to remember
10483 // both potential memory locations. Since we are discarding
10484 // src value info, don't do the transformation if the memory
10485 // locations are not in the default address space.
10486 LLD->getPointerInfo().getAddrSpace() != 0 ||
10487 RLD->getPointerInfo().getAddrSpace() != 0 ||
10488 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10489 LLD->getBasePtr().getValueType()))
10492 // Check that the select condition doesn't reach either load. If so,
10493 // folding this will induce a cycle into the DAG. If not, this is safe to
10494 // xform, so create a select of the addresses.
10496 if (TheSelect->getOpcode() == ISD::SELECT) {
10497 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10498 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10499 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10501 // The loads must not depend on one another.
10502 if (LLD->isPredecessorOf(RLD) ||
10503 RLD->isPredecessorOf(LLD))
10505 Addr = DAG.getSelect(SDLoc(TheSelect),
10506 LLD->getBasePtr().getValueType(),
10507 TheSelect->getOperand(0), LLD->getBasePtr(),
10508 RLD->getBasePtr());
10509 } else { // Otherwise SELECT_CC
10510 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10511 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10513 if ((LLD->hasAnyUseOfValue(1) &&
10514 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10515 (RLD->hasAnyUseOfValue(1) &&
10516 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10519 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10520 LLD->getBasePtr().getValueType(),
10521 TheSelect->getOperand(0),
10522 TheSelect->getOperand(1),
10523 LLD->getBasePtr(), RLD->getBasePtr(),
10524 TheSelect->getOperand(4));
10528 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10529 Load = DAG.getLoad(TheSelect->getValueType(0),
10531 // FIXME: Discards pointer and TBAA info.
10532 LLD->getChain(), Addr, MachinePointerInfo(),
10533 LLD->isVolatile(), LLD->isNonTemporal(),
10534 LLD->isInvariant(), LLD->getAlignment());
10536 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10537 RLD->getExtensionType() : LLD->getExtensionType(),
10539 TheSelect->getValueType(0),
10540 // FIXME: Discards pointer and TBAA info.
10541 LLD->getChain(), Addr, MachinePointerInfo(),
10542 LLD->getMemoryVT(), LLD->isVolatile(),
10543 LLD->isNonTemporal(), LLD->getAlignment());
10546 // Users of the select now use the result of the load.
10547 CombineTo(TheSelect, Load);
10549 // Users of the old loads now use the new load's chain. We know the
10550 // old-load value is dead now.
10551 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10552 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10559 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10560 /// where 'cond' is the comparison specified by CC.
10561 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10562 SDValue N2, SDValue N3,
10563 ISD::CondCode CC, bool NotExtCompare) {
10564 // (x ? y : y) -> y.
10565 if (N2 == N3) return N2;
10567 EVT VT = N2.getValueType();
10568 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10569 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10570 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10572 // Determine if the condition we're dealing with is constant
10573 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10574 N0, N1, CC, DL, false);
10575 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10576 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10578 // fold select_cc true, x, y -> x
10579 if (SCCC && !SCCC->isNullValue())
10581 // fold select_cc false, x, y -> y
10582 if (SCCC && SCCC->isNullValue())
10585 // Check to see if we can simplify the select into an fabs node
10586 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10587 // Allow either -0.0 or 0.0
10588 if (CFP->getValueAPF().isZero()) {
10589 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10590 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10591 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10592 N2 == N3.getOperand(0))
10593 return DAG.getNode(ISD::FABS, DL, VT, N0);
10595 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10596 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10597 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10598 N2.getOperand(0) == N3)
10599 return DAG.getNode(ISD::FABS, DL, VT, N3);
10603 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10604 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10605 // in it. This is a win when the constant is not otherwise available because
10606 // it replaces two constant pool loads with one. We only do this if the FP
10607 // type is known to be legal, because if it isn't, then we are before legalize
10608 // types an we want the other legalization to happen first (e.g. to avoid
10609 // messing with soft float) and if the ConstantFP is not legal, because if
10610 // it is legal, we may not need to store the FP constant in a constant pool.
10611 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10612 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10613 if (TLI.isTypeLegal(N2.getValueType()) &&
10614 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10615 TargetLowering::Legal) &&
10616 // If both constants have multiple uses, then we won't need to do an
10617 // extra load, they are likely around in registers for other users.
10618 (TV->hasOneUse() || FV->hasOneUse())) {
10619 Constant *Elts[] = {
10620 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10621 const_cast<ConstantFP*>(TV->getConstantFPValue())
10623 Type *FPTy = Elts[0]->getType();
10624 const DataLayout &TD = *TLI.getDataLayout();
10626 // Create a ConstantArray of the two constants.
10627 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10628 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10629 TD.getPrefTypeAlignment(FPTy));
10630 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10632 // Get the offsets to the 0 and 1 element of the array so that we can
10633 // select between them.
10634 SDValue Zero = DAG.getIntPtrConstant(0);
10635 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10636 SDValue One = DAG.getIntPtrConstant(EltSize);
10638 SDValue Cond = DAG.getSetCC(DL,
10639 getSetCCResultType(N0.getValueType()),
10641 AddToWorkList(Cond.getNode());
10642 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10644 AddToWorkList(CstOffset.getNode());
10645 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10647 AddToWorkList(CPIdx.getNode());
10648 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10649 MachinePointerInfo::getConstantPool(), false,
10650 false, false, Alignment);
10655 // Check to see if we can perform the "gzip trick", transforming
10656 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10657 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10658 (N1C->isNullValue() || // (a < 0) ? b : 0
10659 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10660 EVT XType = N0.getValueType();
10661 EVT AType = N2.getValueType();
10662 if (XType.bitsGE(AType)) {
10663 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10664 // single-bit constant.
10665 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10666 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10667 ShCtV = XType.getSizeInBits()-ShCtV-1;
10668 SDValue ShCt = DAG.getConstant(ShCtV,
10669 getShiftAmountTy(N0.getValueType()));
10670 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10672 AddToWorkList(Shift.getNode());
10674 if (XType.bitsGT(AType)) {
10675 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10676 AddToWorkList(Shift.getNode());
10679 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10682 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10684 DAG.getConstant(XType.getSizeInBits()-1,
10685 getShiftAmountTy(N0.getValueType())));
10686 AddToWorkList(Shift.getNode());
10688 if (XType.bitsGT(AType)) {
10689 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10690 AddToWorkList(Shift.getNode());
10693 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10697 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10698 // where y is has a single bit set.
10699 // A plaintext description would be, we can turn the SELECT_CC into an AND
10700 // when the condition can be materialized as an all-ones register. Any
10701 // single bit-test can be materialized as an all-ones register with
10702 // shift-left and shift-right-arith.
10703 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10704 N0->getValueType(0) == VT &&
10705 N1C && N1C->isNullValue() &&
10706 N2C && N2C->isNullValue()) {
10707 SDValue AndLHS = N0->getOperand(0);
10708 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10709 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10710 // Shift the tested bit over the sign bit.
10711 APInt AndMask = ConstAndRHS->getAPIntValue();
10713 DAG.getConstant(AndMask.countLeadingZeros(),
10714 getShiftAmountTy(AndLHS.getValueType()));
10715 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10717 // Now arithmetic right shift it all the way over, so the result is either
10718 // all-ones, or zero.
10720 DAG.getConstant(AndMask.getBitWidth()-1,
10721 getShiftAmountTy(Shl.getValueType()));
10722 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10724 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10728 // fold select C, 16, 0 -> shl C, 4
10729 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10730 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10731 TargetLowering::ZeroOrOneBooleanContent) {
10733 // If the caller doesn't want us to simplify this into a zext of a compare,
10735 if (NotExtCompare && N2C->getAPIntValue() == 1)
10738 // Get a SetCC of the condition
10739 // NOTE: Don't create a SETCC if it's not legal on this target.
10740 if (!LegalOperations ||
10741 TLI.isOperationLegal(ISD::SETCC,
10742 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10744 // cast from setcc result type to select result type
10746 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10748 if (N2.getValueType().bitsLT(SCC.getValueType()))
10749 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10750 N2.getValueType());
10752 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10753 N2.getValueType(), SCC);
10755 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10756 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10757 N2.getValueType(), SCC);
10760 AddToWorkList(SCC.getNode());
10761 AddToWorkList(Temp.getNode());
10763 if (N2C->getAPIntValue() == 1)
10766 // shl setcc result by log2 n2c
10767 return DAG.getNode(
10768 ISD::SHL, DL, N2.getValueType(), Temp,
10769 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10770 getShiftAmountTy(Temp.getValueType())));
10774 // Check to see if this is the equivalent of setcc
10775 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10776 // otherwise, go ahead with the folds.
10777 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10778 EVT XType = N0.getValueType();
10779 if (!LegalOperations ||
10780 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10781 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10782 if (Res.getValueType() != VT)
10783 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10787 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10788 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10789 (!LegalOperations ||
10790 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10791 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10792 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10793 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10794 getShiftAmountTy(Ctlz.getValueType())));
10796 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10797 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10798 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10799 XType, DAG.getConstant(0, XType), N0);
10800 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10801 return DAG.getNode(ISD::SRL, DL, XType,
10802 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10803 DAG.getConstant(XType.getSizeInBits()-1,
10804 getShiftAmountTy(XType)));
10806 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10807 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10808 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10809 DAG.getConstant(XType.getSizeInBits()-1,
10810 getShiftAmountTy(N0.getValueType())));
10811 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10815 // Check to see if this is an integer abs.
10816 // select_cc setg[te] X, 0, X, -X ->
10817 // select_cc setgt X, -1, X, -X ->
10818 // select_cc setl[te] X, 0, -X, X ->
10819 // select_cc setlt X, 1, -X, X ->
10820 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10822 ConstantSDNode *SubC = NULL;
10823 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10824 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10825 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10826 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10827 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10828 (N1C->isOne() && CC == ISD::SETLT)) &&
10829 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10830 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10832 EVT XType = N0.getValueType();
10833 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10834 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10836 DAG.getConstant(XType.getSizeInBits()-1,
10837 getShiftAmountTy(N0.getValueType())));
10838 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10840 AddToWorkList(Shift.getNode());
10841 AddToWorkList(Add.getNode());
10842 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10849 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10850 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10851 SDValue N1, ISD::CondCode Cond,
10852 SDLoc DL, bool foldBooleans) {
10853 TargetLowering::DAGCombinerInfo
10854 DagCombineInfo(DAG, Level, false, this);
10855 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10858 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10859 /// return a DAG expression to select that will generate the same value by
10860 /// multiplying by a magic number. See:
10861 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10862 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10863 std::vector<SDNode*> Built;
10864 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10866 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10868 AddToWorkList(*ii);
10872 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10873 /// return a DAG expression to select that will generate the same value by
10874 /// multiplying by a magic number. See:
10875 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10876 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10877 std::vector<SDNode*> Built;
10878 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10880 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10882 AddToWorkList(*ii);
10886 /// FindBaseOffset - Return true if base is a frame index, which is known not
10887 // to alias with anything but itself. Provides base object and offset as
10889 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10890 const GlobalValue *&GV, const void *&CV) {
10891 // Assume it is a primitive operation.
10892 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10894 // If it's an adding a simple constant then integrate the offset.
10895 if (Base.getOpcode() == ISD::ADD) {
10896 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10897 Base = Base.getOperand(0);
10898 Offset += C->getZExtValue();
10902 // Return the underlying GlobalValue, and update the Offset. Return false
10903 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10904 // by multiple nodes with different offsets.
10905 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10906 GV = G->getGlobal();
10907 Offset += G->getOffset();
10911 // Return the underlying Constant value, and update the Offset. Return false
10912 // for ConstantSDNodes since the same constant pool entry may be represented
10913 // by multiple nodes with different offsets.
10914 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10915 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10916 : (const void *)C->getConstVal();
10917 Offset += C->getOffset();
10920 // If it's any of the following then it can't alias with anything but itself.
10921 return isa<FrameIndexSDNode>(Base);
10924 /// isAlias - Return true if there is any possibility that the two addresses
10926 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10927 const Value *SrcValue1, int SrcValueOffset1,
10928 unsigned SrcValueAlign1,
10929 const MDNode *TBAAInfo1,
10930 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10931 const Value *SrcValue2, int SrcValueOffset2,
10932 unsigned SrcValueAlign2,
10933 const MDNode *TBAAInfo2) const {
10934 // If they are the same then they must be aliases.
10935 if (Ptr1 == Ptr2) return true;
10937 // If they are both volatile then they cannot be reordered.
10938 if (IsVolatile1 && IsVolatile2) return true;
10940 // Gather base node and offset information.
10941 SDValue Base1, Base2;
10942 int64_t Offset1, Offset2;
10943 const GlobalValue *GV1, *GV2;
10944 const void *CV1, *CV2;
10945 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10946 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10948 // If they have a same base address then check to see if they overlap.
10949 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10950 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10952 // It is possible for different frame indices to alias each other, mostly
10953 // when tail call optimization reuses return address slots for arguments.
10954 // To catch this case, look up the actual index of frame indices to compute
10955 // the real alias relationship.
10956 if (isFrameIndex1 && isFrameIndex2) {
10957 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10958 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10959 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10960 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10963 // Otherwise, if we know what the bases are, and they aren't identical, then
10964 // we know they cannot alias.
10965 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10968 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10969 // compared to the size and offset of the access, we may be able to prove they
10970 // do not alias. This check is conservative for now to catch cases created by
10971 // splitting vector types.
10972 if ((SrcValueAlign1 == SrcValueAlign2) &&
10973 (SrcValueOffset1 != SrcValueOffset2) &&
10974 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10975 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10976 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10978 // There is no overlap between these relatively aligned accesses of similar
10979 // size, return no alias.
10980 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10984 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10985 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10986 if (UseAA && SrcValue1 && SrcValue2) {
10987 // Use alias analysis information.
10988 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10989 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10990 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10991 AliasAnalysis::AliasResult AAResult =
10992 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10993 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10994 if (AAResult == AliasAnalysis::NoAlias)
10998 // Otherwise we have to assume they alias.
11002 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11003 SDValue Ptr0, Ptr1;
11004 int64_t Size0, Size1;
11005 bool IsVolatile0, IsVolatile1;
11006 const Value *SrcValue0, *SrcValue1;
11007 int SrcValueOffset0, SrcValueOffset1;
11008 unsigned SrcValueAlign0, SrcValueAlign1;
11009 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11010 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11011 SrcValueAlign0, SrcTBAAInfo0);
11012 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11013 SrcValueAlign1, SrcTBAAInfo1);
11014 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11015 SrcValueAlign0, SrcTBAAInfo0,
11016 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11017 SrcValueAlign1, SrcTBAAInfo1);
11020 /// FindAliasInfo - Extracts the relevant alias information from the memory
11021 /// node. Returns true if the operand was a nonvolatile load.
11022 bool DAGCombiner::FindAliasInfo(SDNode *N,
11023 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11024 const Value *&SrcValue,
11025 int &SrcValueOffset,
11026 unsigned &SrcValueAlign,
11027 const MDNode *&TBAAInfo) const {
11028 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11030 Ptr = LS->getBasePtr();
11031 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11032 IsVolatile = LS->isVolatile();
11033 SrcValue = LS->getSrcValue();
11034 SrcValueOffset = LS->getSrcValueOffset();
11035 SrcValueAlign = LS->getOriginalAlignment();
11036 TBAAInfo = LS->getTBAAInfo();
11037 return isa<LoadSDNode>(LS) && !IsVolatile;
11040 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11041 /// looking for aliasing nodes and adding them to the Aliases vector.
11042 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11043 SmallVectorImpl<SDValue> &Aliases) {
11044 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11045 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11047 // Get alias information for node.
11051 const Value *SrcValue;
11052 int SrcValueOffset;
11053 unsigned SrcValueAlign;
11054 const MDNode *SrcTBAAInfo;
11055 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11056 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11059 Chains.push_back(OriginalChain);
11060 unsigned Depth = 0;
11062 // Look at each chain and determine if it is an alias. If so, add it to the
11063 // aliases list. If not, then continue up the chain looking for the next
11065 while (!Chains.empty()) {
11066 SDValue Chain = Chains.back();
11069 // For TokenFactor nodes, look at each operand and only continue up the
11070 // chain until we find two aliases. If we've seen two aliases, assume we'll
11071 // find more and revert to original chain since the xform is unlikely to be
11074 // FIXME: The depth check could be made to return the last non-aliasing
11075 // chain we found before we hit a tokenfactor rather than the original
11077 if (Depth > 6 || Aliases.size() == 2) {
11079 Aliases.push_back(OriginalChain);
11083 // Don't bother if we've been before.
11084 if (!Visited.insert(Chain.getNode()))
11087 switch (Chain.getOpcode()) {
11088 case ISD::EntryToken:
11089 // Entry token is ideal chain operand, but handled in FindBetterChain.
11094 // Get alias information for Chain.
11098 const Value *OpSrcValue;
11099 int OpSrcValueOffset;
11100 unsigned OpSrcValueAlign;
11101 const MDNode *OpSrcTBAAInfo;
11102 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11103 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11107 // If chain is alias then stop here.
11108 if (!(IsLoad && IsOpLoad) &&
11109 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11110 SrcValueAlign, SrcTBAAInfo,
11111 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11112 OpSrcValueAlign, OpSrcTBAAInfo)) {
11113 Aliases.push_back(Chain);
11115 // Look further up the chain.
11116 Chains.push_back(Chain.getOperand(0));
11122 case ISD::TokenFactor:
11123 // We have to check each of the operands of the token factor for "small"
11124 // token factors, so we queue them up. Adding the operands to the queue
11125 // (stack) in reverse order maintains the original order and increases the
11126 // likelihood that getNode will find a matching token factor (CSE.)
11127 if (Chain.getNumOperands() > 16) {
11128 Aliases.push_back(Chain);
11131 for (unsigned n = Chain.getNumOperands(); n;)
11132 Chains.push_back(Chain.getOperand(--n));
11137 // For all other instructions we will just have to take what we can get.
11138 Aliases.push_back(Chain);
11144 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11145 /// for a better chain (aliasing node.)
11146 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11147 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11149 // Accumulate all the aliases to this node.
11150 GatherAllAliases(N, OldChain, Aliases);
11152 // If no operands then chain to entry token.
11153 if (Aliases.size() == 0)
11154 return DAG.getEntryNode();
11156 // If a single operand then chain to it. We don't need to revisit it.
11157 if (Aliases.size() == 1)
11160 // Construct a custom tailored token factor.
11161 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11162 &Aliases[0], Aliases.size());
11165 // SelectionDAG::Combine - This is the entry point for the file.
11167 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11168 CodeGenOpt::Level OptLevel) {
11169 /// run - This is the main entry point to this class.
11171 DAGCombiner(*this, AA, OptLevel).Run(Level);